Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion docs/content/schedules/systemd.md
Original file line number Diff line number Diff line change
Expand Up @@ -260,11 +260,20 @@ ExecStart={{ .CommandLine }}
{{ end -}}
{{ if .IOSchedulingPriority }}IOSchedulingPriority={{ .IOSchedulingPriority }}
{{ end -}}
{{ if .User }}User={{ .User }}
{{ end -}}
{{ range .Environment -}}
Environment="{{ . }}"
{{ end -}}
{{ if .EnvironmentFile }}EnvironmentFile={{ .EnvironmentFile }}
{{ end -}}
```

{{% notice style="warning" %}}
The environment captured with `capture-environment` can contain secrets, so it is not written in the unit file: any user can read `Environment=` values with `systemctl show`. It is saved in a file only readable by the owner of the unit, in the service drop-in folder.
If you use your own unit template, add the `EnvironmentFile=` line above, otherwise the service doesn't get the captured environment.
{{% /notice %}}

### Default timer file

```ini
Expand Down Expand Up @@ -293,4 +302,5 @@ These are available for both the unit and timer templates:
* OnCalendar *array of strings*
* SystemdProfile *string*
* Nice *integer*
* Environment *array of strings*
* Environment *array of strings* (generated variables only, e.g. `HOME`)
* EnvironmentFile *string* (file holding the captured environment, empty when nothing is captured)
9 changes: 8 additions & 1 deletion schedule/handler_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ package schedule
import (
"bytes"
"context"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path"
Expand Down Expand Up @@ -343,7 +345,12 @@ func (h *HandlerLaunchd) createPlistFile(launchdJob *darwin.LaunchdJob, permissi
_ = h.fs.Chown(dir, user.Uid, user.Gid)
}
}
file, err := h.fs.Create(filename)
// the plist can contain the captured environment (secrets): only its owner can read it.
// A new file gets the right permission, and O_EXCL doesn't follow a symlink
if err = h.fs.Remove(filename); err != nil && !errors.Is(err, fs.ErrNotExist) {
return "", err
}
file, err := h.fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return "", err
}
Expand Down
23 changes: 23 additions & 0 deletions schedule/handler_darwin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,29 @@ func TestCreateSystemPlist(t *testing.T) {
assert.NoError(t, err)
}

func TestCreatePlistOnlyReadableByOwner(t *testing.T) {
handler := NewHandler(SchedulerLaunchd{}).(*HandlerLaunchd)
handler.fs = afero.NewMemMapFs()

launchdJob := &darwin.LaunchdJob{
Label: "TestCreatePlistOnlyReadableByOwner",
EnvironmentVariables: map[string]string{"RESTIC_PASSWORD": "secret"},
}
for _, permission := range []Permission{PermissionSystem, PermissionUserBackground} {
filename, err := getFilename(launchdJob.Label, permission)
require.NoError(t, err)
// a file from a previous version is replaced
require.NoError(t, afero.WriteFile(handler.fs, filename, []byte("old"), 0o644))

_, err = handler.createPlistFile(launchdJob, permission)
require.NoError(t, err)

info, err := handler.fs.Stat(filename)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
}

func TestReadingLaunchdScheduled(t *testing.T) {
calendarEvent := calendar.NewEvent(func(e *calendar.Event) {
_ = e.Second.AddValue(0)
Expand Down
136 changes: 136 additions & 0 deletions systemd/environment_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
//go:build !darwin && !windows && !openbsd && !netbsd && !freebsd

package systemd

import (
"errors"
"os"
"path/filepath"
"strings"
"testing"

"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

const (
testServiceFile = "resticprofile-backup@profile-name.service"
testEnvironmentFile = "resticprofile-backup@profile-name.service.d/resticprofile.env"
)

func testEnvironmentConfig(environment ...string) Config {
return Config{
CommandLine: "commandLine",
WorkingDirectory: "workdir",
Title: "name",
SubTitle: "backup",
Schedules: []string{"daily"},
UnitType: SystemUnit,
Environment: environment,
}
}

func TestGenerateEnvironmentFile(t *testing.T) {
t.Setenv("SUDO_USER", "")

fs := afero.NewMemMapFs()
unit := Unit{fs: fs, user: testSudoUser}
serviceFile := filepath.Join(GetSystemDir(), testServiceFile)
environmentFile := filepath.Join(GetSystemDir(), testEnvironmentFile)

// a file from a previous version is replaced
require.NoError(t, afero.WriteFile(fs, environmentFile, []byte("old"), 0o644))

config := testEnvironmentConfig(
"RESTICPROFILE_SCHEDULE_ID=profiles.yaml:backup@name",
"RESTIC_PASSWORD=pa$$ \"w`o\\rd'%h\nnext line",
"HOME=/captured",
)
require.NoError(t, unit.Generate(config))

service, err := afero.ReadFile(fs, serviceFile)
require.NoError(t, err)
assert.Contains(t, string(service), "Environment=\"HOME=/root\"\nEnvironmentFile="+environmentFile+"\n")
assert.NotContains(t, string(service), "RESTIC")

info, err := fs.Stat(environmentFile)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())

content, err := afero.ReadFile(fs, environmentFile)
require.NoError(t, err)
assert.Equal(t, "RESTICPROFILE_SCHEDULE_ID=\"profiles.yaml:backup@name\"\n"+
"RESTIC_PASSWORD=\"pa\\$\\$ \\\"w\\`o\\\\rd'%h\nnext line\"\n", string(content))

// the generated HOME keeps precedence over the captured one
read, err := unit.Read(testServiceFile, SystemUnit)
require.NoError(t, err)
assert.Equal(t, []string{"HOME=/root", config.Environment[0], config.Environment[1]}, read.Environment)

// nothing captured: no file
require.NoError(t, unit.Generate(testEnvironmentConfig()))
service, err = afero.ReadFile(fs, serviceFile)
require.NoError(t, err)
assert.NotContains(t, string(service), "EnvironmentFile")
_, err = fs.Stat(environmentFile)
assert.ErrorIs(t, err, os.ErrNotExist)
}

func TestEnvironmentFileDoesNotFollowSymlink(t *testing.T) {
root := t.TempDir()
target := filepath.Join(root, "target")
require.NoError(t, os.WriteFile(target, []byte("unchanged"), 0o644))

link := filepath.Join(root, GetSystemDir(), testEnvironmentFile)
require.NoError(t, os.MkdirAll(filepath.Dir(link), 0o755))
require.NoError(t, os.Symlink(target, link))

unit := Unit{fs: afero.NewBasePathFs(afero.NewOsFs(), root), user: testSudoUser}
require.NoError(t, unit.Generate(testEnvironmentConfig("RESTIC_PASSWORD=secret")))

content, err := os.ReadFile(target)
require.NoError(t, err)
assert.Equal(t, "unchanged", string(content))

info, err := os.Lstat(link)
require.NoError(t, err)
assert.True(t, info.Mode().IsRegular())
assert.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}

type failingRenameFs struct{ afero.Fs }

func (failingRenameFs) Rename(string, string) error { return errors.New("rename failed") }

func TestEnvironmentFileKeptOnFailure(t *testing.T) {
t.Parallel()

fs := afero.NewMemMapFs()
environmentFile := filepath.Join(GetSystemDir(), testEnvironmentFile)
require.NoError(t, afero.WriteFile(fs, environmentFile, []byte("old"), 0o600))

unit := Unit{fs: failingRenameFs{fs}, user: testSudoUser}
require.Error(t, unit.writeEnvironmentFile(environmentFile, []string{"RESTIC_PASSWORD=secret"}))

content, err := afero.ReadFile(fs, environmentFile)
require.NoError(t, err)
assert.Equal(t, "old", string(content))

// no temporary file left behind
entries, err := afero.ReadDir(fs, filepath.Dir(environmentFile))
require.NoError(t, err)
assert.Len(t, entries, 1)
}

func TestParseEnvironmentFile(t *testing.T) {
t.Parallel()

environment := []string{"A=", "B=plain", "C=\\ \" ` $ ' %h \n end"}
content := ""
for _, env := range environment {
name, value, _ := strings.Cut(env, "=")
content += name + "=" + quoteEnvironmentValue(value) + "\n"
}
assert.Equal(t, environment, parseEnvironmentFile(content))
}
81 changes: 77 additions & 4 deletions systemd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package systemd

import (
"bytes"
"errors"
"fmt"
"io"
"io/fs"
Expand All @@ -21,8 +22,9 @@ import (
)

const (
defaultPermission = 0o644
systemdSystemDir = "/etc/systemd/system/"
defaultPermission = 0o644
environmentFileName = "resticprofile.env"
systemdSystemDir = "/etc/systemd/system/"

systemdUnitDefaultTmpl = `[Unit]
Description={{ .JobDescription }}
Expand All @@ -45,6 +47,8 @@ ExecStart={{ .CommandLine }}
{{ range .Environment -}}
Environment="{{ . }}"
{{ end -}}
{{ if .EnvironmentFile }}EnvironmentFile={{ .EnvironmentFile }}
{{ end -}}
`

systemdTimerDefaultTmpl = `[Unit]
Expand Down Expand Up @@ -83,6 +87,7 @@ type templateInfo struct {
SystemdProfile string
Nice int
Environment []string
EnvironmentFile string
AfterNetworkOnline bool
CPUSchedulingPolicy string
IOSchedulingClass int
Expand Down Expand Up @@ -139,8 +144,7 @@ func (u Unit) Generate(config Config) error {
}
}

environment := slices.Clone(config.Environment)

var environment []string
if config.UnitType == SystemUnit && config.User == "" {
// permission = system
environment = append(environment, fmt.Sprintf("HOME=%s", u.user.SudoHomeDir))
Expand All @@ -152,6 +156,17 @@ func (u Unit) Generate(config Config) error {
environment = append(environment, fmt.Sprintf("HOME=%s", u.user.UserHomeDir))
}

// Any user can read Environment= ("systemctl show"): the captured environment, which can contain secrets,
// goes to a file only readable by the owner of the unit. Generated variables keep precedence.
capturedEnvironment := collect.All(config.Environment, func(env string) bool {
return !slices.ContainsFunc(environment, func(generated string) bool { return envName(generated) == envName(env) })
})
environmentFilePath := filepath.Join(systemdUserDir, GetServiceFileDropInDir(config.Title, config.SubTitle), environmentFileName)
environmentFile := ""
if len(capturedEnvironment) > 0 {
environmentFile = environmentFilePath
}

policy := ""
if config.Priority == constants.SchedulePriorityBackground {
policy = "idle"
Expand All @@ -168,6 +183,7 @@ func (u Unit) Generate(config Config) error {
SystemdProfile: systemdProfile,
Nice: config.Nice,
Environment: environment,
EnvironmentFile: environmentFile,
CPUSchedulingPolicy: policy,
IOSchedulingClass: config.IOSchedulingClass,
IOSchedulingPriority: config.IOSchedulingPriority,
Expand All @@ -180,6 +196,9 @@ func (u Unit) Generate(config Config) error {
if err != nil {
return err
}
if environmentFile != "" && !strings.Contains(systemdUnitTmpl, ".EnvironmentFile") {
clog.Warningf("unit template %q doesn't use {{ .EnvironmentFile }}: the service won't get the captured environment", config.UnitFile)
}
unitTmpl, err := templates.New("systemd.unit").Parse(systemdUnitTmpl)
if err != nil {
return err
Expand Down Expand Up @@ -221,6 +240,11 @@ func (u Unit) Generate(config Config) error {
_ = u.fs.Chown(filePathName, u.user.Uid, u.user.Gid)
}

// written before the drop-ins, which change the owner of the folder content for user units
if err = u.writeEnvironmentFile(environmentFilePath, capturedEnvironment); err != nil {
return err
}

existingFiles := collect.All(config.DropInFiles, u.DropInFileExists)

dropIns := map[string][]string{
Expand Down Expand Up @@ -301,3 +325,52 @@ func (u Unit) loadTemplate(filename, defaultTmpl string) (string, error) {
}
return output.String(), nil
}

// writeEnvironmentFile saves the environment in a file only readable by its owner, or removes the file when there's no environment
func (u Unit) writeEnvironmentFile(filename string, environment []string) error {
if len(environment) == 0 {
if err := u.fs.Remove(filename); err != nil && !errors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
dir := filepath.Dir(filename)
if err := u.fs.MkdirAll(dir, 0o755); err != nil {
return err
}
content := strings.Builder{}
for _, env := range environment {
name, value, _ := strings.Cut(env, "=")
content.WriteString(name + "=" + quoteEnvironmentValue(value) + "\n")
}
clog.Debugf("writing %v", filename)
// the temporary file is created with 0600 permission, and the rename replaces a symlink instead of following it.
// the previous file stays in place until the new one is complete.
file, err := afero.TempFile(u.fs, dir, "."+filepath.Base(filename)+"-*")
if err != nil {
return err
}
_, err = file.WriteString(content.String())
if closeErr := file.Close(); err == nil {
err = closeErr
}
if err == nil {
err = u.fs.Rename(file.Name(), filename)
}
if err != nil {
_ = u.fs.Remove(file.Name())
}
return err
}

// environmentValueEscaper escapes the only sequences systemd interprets in a double-quoted environment file value
var environmentValueEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`, "`", "\\`", `$`, `\$`)

func quoteEnvironmentValue(value string) string {
return `"` + environmentValueEscaper.Replace(value) + `"`
}

func envName(env string) string {
name, _, _ := strings.Cut(env, "=")
return name
}
Loading
Loading