Welcome to mirror list, hosted at ThFree Co, Russian Federation.

daemon.go - gitlab.com/gitlab-org/gitlab-pages.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 11fa3e9e0fd4469ddb69ab6ec70b4de979341b13 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
package main

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"os/signal"
	"strings"
	"syscall"

	"github.com/kardianos/osext"
	log "github.com/sirupsen/logrus"

	"gitlab.com/gitlab-org/gitlab-pages/internal/jail"
)

const (
	daemonRunProgram = "gitlab-pages-unprivileged"

	pagesRootInChroot = "/pages"
)

func daemonMain() {
	if os.Args[0] != daemonRunProgram {
		return
	}

	// Validate that a working directory is valid
	// https://man7.org/linux/man-pages/man2/getcwd.2.html
	wd, err := os.Getwd()
	if err != nil {
		fatal(err, "could not get current working directory")
	} else if strings.HasPrefix(wd, "(unreachable)") {
		fatal(os.ErrPermission, "could not get current working directory")
	}

	log.WithFields(log.Fields{
		"uid": syscall.Getuid(),
		"gid": syscall.Getgid(),
		"wd":  wd,
	}).Info("starting the daemon as unprivileged user")

	// read the configuration from the pipe "ExtraFiles"
	var config appConfig
	if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&config); err != nil {
		fatal(err, "could not decode app config")
	}
	runApp(config)
	os.Exit(0)
}

func daemonReexec(uid, gid uint, args ...string) (cmd *exec.Cmd, err error) {
	path, err := osext.Executable()
	if err != nil {
		return
	}

	cmd = &exec.Cmd{
		Path:   path,
		Args:   args,
		Env:    os.Environ(),
		Stdin:  os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
		SysProcAttr: &syscall.SysProcAttr{
			Credential: &syscall.Credential{
				Uid: uint32(uid),
				Gid: uint32(gid),
			},
			Setsid: true,
		},
	}
	return
}

func daemonUpdateFd(cmd *exec.Cmd, fd uintptr) (childFd uintptr) {
	file := os.NewFile(fd, "[socket]")

	// we add 3 since, we have a 3 predefined FDs
	childFd = uintptr(3 + len(cmd.ExtraFiles))
	cmd.ExtraFiles = append(cmd.ExtraFiles, file)

	return
}

func daemonUpdateFds(cmd *exec.Cmd, fds []uintptr) {
	for idx, fd := range fds {
		fds[idx] = daemonUpdateFd(cmd, fd)
	}
}

func killProcess(cmd *exec.Cmd) {
	if cmd.Process != nil {
		cmd.Process.Kill()
	}
	cmd.Wait()
	for _, file := range cmd.ExtraFiles {
		file.Close()
	}
}

func passSignals(cmd *exec.Cmd) {
	if cmd.Process == nil {
		return
	}

	s := make(chan os.Signal)
	signal.Notify(s, syscall.SIGTERM, os.Interrupt, os.Kill)

	go func() {
		for cmd.Process != nil {
			cmd.Process.Signal(<-s)
		}
	}()
}

func chrootDaemon(cmd *exec.Cmd) (*jail.Jail, error) {
	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	chroot := jail.Into(wd)

	// Generate a probabilistically-unique suffix for the copy of the pages
	// binary being placed into the chroot
	suffix := make([]byte, 16)
	if _, err := rand.Read(suffix); err != nil {
		return nil, err
	}

	tempExecutablePath := fmt.Sprintf("/.daemon.%x", suffix)

	if err := chroot.CopyTo(tempExecutablePath, cmd.Path); err != nil {
		return nil, err
	}

	// Update command to use chroot
	cmd.SysProcAttr.Chroot = chroot.Path()
	cmd.Path = tempExecutablePath
	cmd.Dir = "/"

	return chroot, nil
}

func jailCopyCertDir(cage *jail.Jail, sslCertDir, jailCertsDir string) error {
	log.WithFields(log.Fields{
		"ssl-cert-dir": sslCertDir,
	}).Debug("Copying certs from SSL_CERT_DIR")

	entries, err := ioutil.ReadDir(sslCertDir)
	if err != nil {
		return fmt.Errorf("failed to read SSL_CERT_DIR: %+v", err)
	}

	for _, fi := range entries {
		// Copy only regular files and symlinks
		mode := fi.Mode()
		if !(mode.IsRegular() || mode&os.ModeSymlink != 0) {
			continue
		}

		err = cage.CopyTo(jailCertsDir+"/"+fi.Name(), sslCertDir+"/"+fi.Name())
		if err != nil {
			log.WithError(err).Errorf("failed to copy cert: %q", fi.Name())
			// Go on and try to copy other files. We don't want the whole
			// startup process to fail due to a single failure here.
		}
	}

	return nil
}

func jailDaemonCerts(cmd *exec.Cmd, cage *jail.Jail) error {
	sslCertFile := os.Getenv("SSL_CERT_FILE")
	sslCertDir := os.Getenv("SSL_CERT_DIR")
	if sslCertFile == "" && sslCertDir == "" {
		log.Warn("Neither SSL_CERT_FILE nor SSL_CERT_DIR environment variable is set. HTTPS requests will fail.")
		return nil
	}

	// This assumes cage.MkDir("/etc") has already been called
	cage.MkDir("/etc/ssl", 0755)

	// Copy SSL_CERT_FILE inside the jail
	if sslCertFile != "" {
		jailCertsFile := "/etc/ssl/ca-bundle.pem"
		err := cage.CopyTo(jailCertsFile, sslCertFile)
		if err != nil {
			return fmt.Errorf("failed to copy SSL_CERT_FILE: %+v", err)
		}
		cmd.Env = append(cmd.Env, "SSL_CERT_FILE="+jailCertsFile)
	}

	// Copy all files and symlinks from SSL_CERT_DIR into the jail
	if sslCertDir != "" {
		jailCertsDir := "/etc/ssl/certs"
		cage.MkDir(jailCertsDir, 0755)
		err := jailCopyCertDir(cage, sslCertDir, jailCertsDir)
		if err != nil {
			return err
		}
		cmd.Env = append(cmd.Env, "SSL_CERT_DIR="+jailCertsDir)
	}

	return nil
}

func jailDaemon(cmd *exec.Cmd) (*jail.Jail, error) {
	cage := jail.CreateTimestamped("gitlab-pages", 0755)

	wd, err := os.Getwd()
	if err != nil {
		return nil, err
	}

	// Add /dev/urandom and /dev/random inside the jail. This is required to
	// support Linux versions < 3.17, which do not have the getrandom() syscall
	cage.MkDir("/dev", 0755)
	if err := cage.CharDev("/dev/urandom"); err != nil {
		return nil, err
	}

	if err := cage.CharDev("/dev/random"); err != nil {
		return nil, err
	}

	// Add gitlab-pages inside the jail
	err = cage.CopyTo("/gitlab-pages", cmd.Path)
	if err != nil {
		return nil, err
	}

	// Add /etc/resolv.conf inside the jail
	cage.MkDir("/etc", 0755)
	err = cage.Copy("/etc/resolv.conf")
	if err != nil {
		return nil, err
	}

	// Add certificates inside the jail
	err = jailDaemonCerts(cmd, cage)
	if err != nil {
		return nil, err
	}

	// Bind mount shared folder
	cage.MkDir(pagesRootInChroot, 0755)
	cage.Bind(pagesRootInChroot, wd)

	// Update command to use chroot
	cmd.SysProcAttr.Chroot = cage.Path()
	cmd.Path = "/gitlab-pages"
	cmd.Dir = pagesRootInChroot

	return cage, nil
}

func daemonize(config appConfig, uid, gid uint, inPlace bool) error {
	log.WithFields(log.Fields{
		"uid":      uid,
		"gid":      gid,
		"in-place": inPlace,
	}).Info("running the daemon as unprivileged user")

	cmd, err := daemonReexec(uid, gid, daemonRunProgram)
	if err != nil {
		return err
	}
	defer killProcess(cmd)

	// Run daemon in chroot environment
	var wrapper *jail.Jail
	if inPlace {
		wrapper, err = chrootDaemon(cmd)
	} else {
		wrapper, err = jailDaemon(cmd)
	}
	if err != nil {
		log.WithError(err).Print("chroot failed")
		return err
	}
	defer wrapper.Dispose()

	// Unshare mount namespace
	// 1. If this fails, in a worst case changes to mounts will propagate to other processes
	// 2. Ensures that jail mount is not propagated to the parent mount namespace
	//    to avoid populating `tmp` directory with old mounts
	_ = wrapper.Unshare()

	if err := wrapper.Build(); err != nil {
		log.WithError(err).Print("chroot build failed")
		return err
	}

	// Create a pipe to pass the configuration
	configReader, configWriter, err := os.Pipe()
	if err != nil {
		return err
	}
	defer configWriter.Close()
	cmd.ExtraFiles = append(cmd.ExtraFiles, configReader)

	updateFds(&config, cmd)

	// Start the process
	if err := cmd.Start(); err != nil {
		log.WithError(err).Error("start failed")
		return err
	}

	// Write the configuration
	if err := json.NewEncoder(configWriter).Encode(config); err != nil {
		return err
	}
	configWriter.Close()

	// Pass through signals
	passSignals(cmd)

	// Wait for process to exit
	return cmd.Wait()
}

func updateFds(config *appConfig, cmd *exec.Cmd) {
	for _, fds := range [][]uintptr{
		config.ListenHTTP,
		config.ListenHTTPS,
		config.ListenProxy,
	} {
		daemonUpdateFds(cmd, fds)
	}

	for _, fdPtr := range []*uintptr{
		&config.ListenMetrics,
	} {
		if *fdPtr != 0 {
			*fdPtr = daemonUpdateFd(cmd, *fdPtr)
		}
	}
}