File: fakeroot.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (370 lines) | stat: -rw-r--r-- 9,422 bytes parent folder | download | duplicates (2)
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Copyright (c) 2019-2021, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package fakeroot

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"syscall"

	specs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/sylabs/singularity/v4/internal/pkg/util/user"
	"github.com/sylabs/singularity/v4/pkg/util/fs/lock"
)

const (
	// SubUIDFile is the default path to the subuid file.
	SubUIDFile = "/etc/subuid"
	// SubGIDFile is the default path to the subgid file.
	SubGIDFile = "/etc/subgid"
	// validRangeCount is the valid fakeroot range count.
	validRangeCount = uint32(65536)
	// StartMax is the maximum possible range start.
	startMax = uint32(4294967296 - 131072)
	// StartMin is the minimum possible range start.
	startMin = uint32(65536)
	// disabledPrefix is the character prefix marking an entry as disabled.
	disabledPrefix = '!'
	// fieldSeparator is the character separating entry's fields.
	fieldSeparator = ":"
	// minFields is the minimum number of fields for a valid entry.
	minFields = 3
	// maxUID is the highest UID.
	maxUID = ^uint32(0)
)

// Entry represents an entry line of subuid/subgid configuration file.
type Entry struct {
	line     string
	UID      uint32
	Start    uint32
	Count    uint32
	disabled bool
	invalid  bool
}

// Config holds all entries found in the corresponding configuration
// file and manages its configuration.
type Config struct {
	entries       []*Entry
	file          *os.File
	readOnly      bool
	requireUpdate bool
	getUserFn     func(string) (*user.User, error)
}

// GetUserFn defines the user lookup function prototype.
type GetUserFn func(string) (*user.User, error)

// GetConfig parses a subuid/subgid configuration file and returns
// a Config holding all mapping entries, it allows to pass a custom
// function getUserFn used to lookup in a custom user database, if
// there is no custom function, the default one is used.
func GetConfig(filename string, edit bool, getUserFn GetUserFn) (*Config, error) {
	var err error

	config := &Config{
		readOnly:  !edit,
		getUserFn: user.GetPwNam,
	}

	// mainly for mocking
	if getUserFn != nil {
		config.getUserFn = getUserFn
	}

	flags := os.O_RDONLY
	if !config.readOnly {
		flags = os.O_CREATE | os.O_RDWR
		umask := syscall.Umask(0)
		defer syscall.Umask(umask)
	}

	config.file, err = os.OpenFile(filename, flags, 0o644)
	if err != nil {
		return nil, fmt.Errorf("failed to open: %s: %s", filename, err)
	}

	config.entries = make([]*Entry, 0)

	scanner := bufio.NewScanner(config.file)
	for scanner.Scan() {
		config.parseEntry(scanner.Text())
	}

	return config, nil
}

// parseEntry parses a line and adds an entry.
func (c *Config) parseEntry(line string) {
	e := new(Entry)
	e.line = line

	fields := strings.Split(line, fieldSeparator)
	// entry doesn't have the right number of fields,
	// don't add it to the list of entries that need to be removed
	// from the file during the close operation
	if len(fields) < minFields {
		return
	}

	defer func() {
		c.entries = append(c.entries, e)
	}()

	start, err := strconv.ParseUint(fields[1], 10, 32)
	if err != nil {
		e.invalid = true
	} else {
		e.Start = uint32(start)
	}

	count, err := strconv.ParseUint(fields[2], 10, 32)
	if err != nil || count == 0 {
		e.invalid = true
	} else {
		e.Count = uint32(count)
	}

	username := fields[0]

	// include disabled users
	if username[0] == disabledPrefix {
		username = username[1:]
		e.disabled = true
	}

	uid, err := strconv.ParseUint(username, 10, 32)
	if err == nil {
		e.UID = uint32(uid)
	} else {
		// try with username, if there is an error
		// we still consider the entry as valid and
		// just associate it with the maximal UID
		u, err := c.getUserFn(username)
		if err != nil {
			e.UID = maxUID
		} else {
			e.UID = u.UID
		}
	}
}

// Close closes the configuration file handle, if there is any pending
// updates and the configuration was opened for writing, all entries
// are written before into the configuration file before closing it.
func (c *Config) Close() error {
	defer c.file.Close()

	if !c.requireUpdate || c.readOnly {
		return nil
	}

	var buf bytes.Buffer
	filename := c.file.Name()

	for _, entry := range c.entries {
		buf.WriteString(entry.line + "\n")
	}

	fd, err := lock.Exclusive(filename)
	if err != nil {
		return fmt.Errorf("error while acquiring lock in %s: %s", filename, err)
	}
	defer lock.Release(fd)

	if err := c.file.Truncate(0); err != nil {
		return fmt.Errorf("error while truncating %s to 0: %s", filename, err)
	}
	if _, err := c.file.Seek(0, io.SeekStart); err != nil {
		return fmt.Errorf("error while resetting file offset: %s", err)
	}
	if _, err := c.file.Write(buf.Bytes()); err != nil {
		return fmt.Errorf("error while writing configuration file %s: %s", filename, err)
	}

	return nil
}

// AddUser adds a user mapping entry, it will automatically
// find the first available range. It doesn't return any error
// if the user is already present and ignores the operation.
func (c *Config) AddUser(username string) error {
	_, err := c.GetUserEntry(username)
	if err == nil {
		return nil
	}

	u, err := c.getUserFn(username)
	if err != nil {
		return fmt.Errorf("could not retrieve user information for %s: %s", username, err)
	}
	for i := startMax; i >= startMin; i -= validRangeCount {
		current := i
		available := true
		for _, entry := range c.entries {
			if entry.invalid {
				continue
			}
			start := entry.Start
			end := entry.Start + entry.Count - 1
			if current >= start && current <= end {
				available = false
				break
			}
		}
		if available {
			c.requireUpdate = true
			line := fmt.Sprintf("%d:%d:%d", u.UID, current, validRangeCount)
			c.entries = append(
				c.entries,
				&Entry{
					UID:      u.UID,
					Start:    current,
					Count:    validRangeCount,
					disabled: false,
					line:     line,
				})
			return nil
		}
	}
	return fmt.Errorf("no range available")
}

// RemoveUser removes a user mapping entry. It returns an error
// if there is no entry for the user.
func (c *Config) RemoveUser(username string) error {
	e, err := c.GetUserEntry(username)
	if err != nil {
		return err
	}
	for i, entry := range c.entries {
		if entry.invalid {
			continue
		} else if entry == e {
			c.requireUpdate = true
			c.entries = append(c.entries[:i], c.entries[i+1:]...)
			break
		}
	}
	return nil
}

// EnableUser enables a previously disabled user mapping entry.
// It returns an error if there is no entry for the user but will
// ignore the operation if the user entry is already enabled.
func (c *Config) EnableUser(username string) error {
	e, err := c.GetUserEntry(username)
	if err != nil {
		return err
	}
	e.disabled = false
	if e.line[0] == disabledPrefix {
		c.requireUpdate = true
		e.line = e.line[1:]
	}
	return nil
}

// DisableUser disables a user entry mapping entry. It returns an
// error if there is no entry for the user but will ignore the
// operation if the user entry is already disabled.
func (c *Config) DisableUser(username string) error {
	e, err := c.GetUserEntry(username)
	if err != nil {
		return err
	}
	e.disabled = true
	if e.line[0] != disabledPrefix {
		c.requireUpdate = true
		e.line = fmt.Sprintf("%c%s", disabledPrefix, e.line)
	}
	return nil
}

// GetUserEntry returns a user entry associated to a user and returns
// an error if there is no entry for this user.
func (c *Config) GetUserEntry(username string) (*Entry, error) {
	var largeRangeEntries []*Entry
	entryCount := 0

	u, err := c.getUserFn(username)
	if err != nil {
		return nil, fmt.Errorf("could not retrieve user information for %s: %s", username, err)
	}
	for _, entry := range c.entries {
		if entry.invalid {
			continue
		}
		if entry.UID == u.UID {
			if entry.Count == validRangeCount {
				return entry, nil
			} else if entry.Count > validRangeCount {
				largeRangeEntries = append(largeRangeEntries, entry)
				continue
			}
			entryCount++
		}
	}
	var largestEntry *Entry

	for _, e := range largeRangeEntries {
		if largestEntry == nil {
			largestEntry = e
		} else if e.Count > largestEntry.Count {
			largestEntry = e
		}
	}
	if largestEntry != nil {
		return largestEntry, nil
	}

	if entryCount > 0 {
		return nil, fmt.Errorf(
			"mapping entries for user %s found in %s but all with a range count lower than %d",
			username, c.file.Name(), validRangeCount,
		)
	}
	return nil, fmt.Errorf("no mapping entry found in %s for %s", c.file.Name(), username)
}

// getPwUID is also used for mocking purpose
var (
	getPwUID = user.GetPwUID
	getPwNam = user.GetPwNam
)

// GetIDRange determines UID/GID mappings based on configuration
// file provided in path.
func GetIDRange(path string, uid uint32) (*specs.LinuxIDMapping, error) {
	config, err := GetConfig(path, false, getPwNam)
	if err != nil {
		return nil, err
	}
	defer config.Close()

	userinfo, err := getPwUID(uid)
	if err != nil {
		return nil, fmt.Errorf("could not retrieve user with UID %d: %s", uid, err)
	}
	e, err := config.GetUserEntry(userinfo.Name)
	if err != nil {
		return nil, err
	}
	if e.disabled {
		return nil, fmt.Errorf("your fakeroot mapping has been disabled by the administrator")
	}
	return &specs.LinuxIDMapping{
		ContainerID: 1,
		HostID:      e.Start,
		Size:        e.Count,
	}, nil
}