Debian Codegraph @

user/user.go

raw symbols SCIP
1 package user
2
3 import (
4 "bufio"
5 "bytes"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "strconv"
11 "strings"
12 )
13
14 const (
15 minID = 0
16 maxID = 1<<31 - 1 // for 32-bit systems compatibility
17 )
18
19 var (
20 // ErrNoPasswdEntries is returned if no matching entries were found in /etc/group.
21 ErrNoPasswdEntries = errors.New("no matching entries in passwd file")
22 // ErrNoGroupEntries is returned if no matching entries were found in /etc/passwd.
23 ErrNoGroupEntries = errors.New("no matching entries in group file")
24 // ErrRange is returned if a UID or GID is outside of the valid range.
25 ErrRange = fmt.Errorf("uids and gids must be in range %d-%d", minID, maxID)
26 )
27
28 type User struct {
29 Name string
30 Pass string
31 Uid int
32 Gid int
33 Gecos string
34 Home string
35 Shell string
36 }
37
38 type Group struct {
39 Name string
40 Pass string
41 Gid int
42 List []string
43 }
44
45 // SubID represents an entry in /etc/sub{u,g}id
46 type SubID struct {
47 Name string
48 SubID int64
49 Count int64
50 }
51
52 // IDMap represents an entry in /proc/PID/{u,g}id_map
53 type IDMap struct {
54 ID int64
55 ParentID int64
56 Count int64
57 }
58
59 func parseLine(line []byte, v ...any) {
60 parseParts(bytes.Split(line, []byte(":")), v...)
61 }
62
63 func parseParts(parts [][]byte, v ...any) {
64 if len(parts) == 0 {
65 return
66 }
67
68 for i, p := range parts {
69 // Ignore cases where we don't have enough fields to populate the arguments.
70 // Some configuration files like to misbehave.
71 if len(v) <= i {
72 break
73 }
74
75 // Use the type of the argument to figure out how to parse it, scanf() style.
76 // This is legit.
77 switch e := v[i].(type) {
78 case *string:
79 *e = string(p)
80 case *int:
81 // "numbers", with conversion errors ignored because of some misbehaving configuration files.
82 *e, _ = strconv.Atoi(string(p))
83 case *int64:
84 *e, _ = strconv.ParseInt(string(p), 10, 64)
85 case *[]string:
86 // Comma-separated lists.
87 if len(p) != 0 {
88 *e = strings.Split(string(p), ",")
89 } else {
90 *e = []string{}
91 }
92 default:
93 // Someone goof'd when writing code using this function. Scream so they can hear us.
94 panic(fmt.Sprintf("parseLine only accepts {*string, *int, *int64, *[]string} as arguments! %#v is not a pointer!", e))
95 }
96 }
97 }
98
99 func ParsePasswdFile(path string) ([]User, error) {
100 passwd, err := os.Open(path)
101 if err != nil {
102 return nil, err
103 }
104 defer passwd.Close()
105 return ParsePasswd(passwd)
106 }
107
108 func ParsePasswd(passwd io.Reader) ([]User, error) {
109 return ParsePasswdFilter(passwd, nil)
110 }
111
112 func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) {
113 passwd, err := os.Open(path)
114 if err != nil {
115 return nil, err
116 }
117 defer passwd.Close()
118 return ParsePasswdFilter(passwd, filter)
119 }
120
121 func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) {
122 if r == nil {
123 return nil, errors.New("nil source for passwd-formatted data")
124 }
125
126 var (
127 s = bufio.NewScanner(r)
128 out = []User{}
129 )
130
131 for s.Scan() {
132 line := bytes.TrimSpace(s.Bytes())
133 if len(line) == 0 {
134 continue
135 }
136
137 // see: man 5 passwd
138 // name:password:UID:GID:GECOS:directory:shell
139 // Name:Pass:Uid:Gid:Gecos:Home:Shell
140 // root:x:0:0:root:/root:/bin/bash
141 // adm:x:3:4:adm:/var/adm:/bin/false
142 p := User{}
143 parseLine(line, &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell)
144
145 if filter == nil || filter(p) {
146 out = append(out, p)
147 }
148 }
149 if err := s.Err(); err != nil {
150 return nil, err
151 }
152
153 return out, nil
154 }
155
156 func ParseGroupFile(path string) ([]Group, error) {
157 group, err := os.Open(path)
158 if err != nil {
159 return nil, err
160 }
161
162 defer group.Close()
163 return ParseGroup(group)
164 }
165
166 func ParseGroup(group io.Reader) ([]Group, error) {
167 return ParseGroupFilter(group, nil)
168 }
169
170 func ParseGroupFileFilter(path string, filter func(Group) bool) ([]Group, error) {
171 group, err := os.Open(path)
172 if err != nil {
173 return nil, err
174 }
175 defer group.Close()
176 return ParseGroupFilter(group, filter)
177 }
178
179 func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) {
180 if r == nil {
181 return nil, errors.New("nil source for group-formatted data")
182 }
183 rd := bufio.NewReader(r)
184 out := []Group{}
185
186 // Read the file line-by-line.
187 for {
188 var (
189 isPrefix bool
190 wholeLine []byte
191 err error
192 )
193
194 // Read the next line. We do so in chunks (as much as reader's
195 // buffer is able to keep), check if we read enough columns
196 // already on each step and store final result in wholeLine.
197 for {
198 var line []byte
199 line, isPrefix, err = rd.ReadLine()
200 if err != nil {
201 // We should return no error if EOF is reached
202 // without a match.
203 if err == io.EOF {
204 err = nil
205 }
206 return out, err
207 }
208
209 // Simple common case: line is short enough to fit in a
210 // single reader's buffer.
211 if !isPrefix && len(wholeLine) == 0 {
212 wholeLine = line
213 break
214 }
215
216 wholeLine = append(wholeLine, line...)
217
218 // Check if we read the whole line already.
219 if !isPrefix {
220 break
221 }
222 }
223
224 // There's no spec for /etc/passwd or /etc/group, but we try to follow
225 // the same rules as the glibc parser, which allows comments and blank
226 // space at the beginning of a line.
227 wholeLine = bytes.TrimSpace(wholeLine)
228 if len(wholeLine) == 0 || wholeLine[0] == '#' {
229 continue
230 }
231
232 // see: man 5 group
233 // group_name:password:GID:user_list
234 // Name:Pass:Gid:List
235 // root:x:0:root
236 // adm:x:4:root,adm,daemon
237 p := Group{}
238 parseLine(wholeLine, &p.Name, &p.Pass, &p.Gid, &p.List)
239
240 if filter == nil || filter(p) {
241 out = append(out, p)
242 }
243 }
244 }
245
246 type ExecUser struct {
247 Uid int
248 Gid int
249 Sgids []int
250 Home string
251 }
252
253 // GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the
254 // given file paths and uses that data as the arguments to GetExecUser. If the
255 // files cannot be opened for any reason, the error is ignored and a nil
256 // io.Reader is passed instead.
257 func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) {
258 var passwd, group io.Reader
259
260 if passwdFile, err := os.Open(passwdPath); err == nil {
261 passwd = passwdFile
262 defer passwdFile.Close()
263 }
264
265 if groupFile, err := os.Open(groupPath); err == nil {
266 group = groupFile
267 defer groupFile.Close()
268 }
269
270 return GetExecUser(userSpec, defaults, passwd, group)
271 }
272
273 // GetExecUser parses a user specification string (using the passwd and group
274 // readers as sources for /etc/passwd and /etc/group data, respectively). In
275 // the case of blank fields or missing data from the sources, the values in
276 // defaults is used.
277 //
278 // GetExecUser will return an error if a user or group literal could not be
279 // found in any entry in passwd and group respectively.
280 //
281 // Examples of valid user specifications are:
282 // - ""
283 // - "user"
284 // - "uid"
285 // - "user:group"
286 // - "uid:gid
287 // - "user:gid"
288 // - "uid:group"
289 //
290 // It should be noted that if you specify a numeric user or group id, they will
291 // not be evaluated as usernames (only the metadata will be filled). So attempting
292 // to parse a user with user.Name = "1337" will produce the user with a UID of
293 // 1337.
294 func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) {
295 if defaults == nil {
296 defaults = new(ExecUser)
297 }
298
299 // Copy over defaults.
300 user := &ExecUser{
301 Uid: defaults.Uid,
302 Gid: defaults.Gid,
303 Sgids: defaults.Sgids,
304 Home: defaults.Home,
305 }
306
307 // Sgids slice *cannot* be nil.
308 if user.Sgids == nil {
309 user.Sgids = []int{}
310 }
311
312 // Allow for userArg to have either "user" syntax, or optionally "user:group" syntax
313 var userArg, groupArg string
314 parseLine([]byte(userSpec), &userArg, &groupArg)
315
316 // Convert userArg and groupArg to be numeric, so we don't have to execute
317 // Atoi *twice* for each iteration over lines.
318 uidArg, uidErr := strconv.Atoi(userArg)
319 gidArg, gidErr := strconv.Atoi(groupArg)
320
321 // Find the matching user.
322 users, err := ParsePasswdFilter(passwd, func(u User) bool {
323 if userArg == "" {
324 // Default to current state of the user.
325 return u.Uid == user.Uid
326 }
327
328 if uidErr == nil {
329 // If the userArg is numeric, always treat it as a UID.
330 return uidArg == u.Uid
331 }
332
333 return u.Name == userArg
334 })
335
336 // If we can't find the user, we have to bail.
337 if err != nil && passwd != nil {
338 if userArg == "" {
339 userArg = strconv.Itoa(user.Uid)
340 }
341 return nil, fmt.Errorf("unable to find user %s: %w", userArg, err)
342 }
343
344 var matchedUserName string
345 if len(users) > 0 {
346 // First match wins, even if there's more than one matching entry.
347 matchedUserName = users[0].Name
348 user.Uid = users[0].Uid
349 user.Gid = users[0].Gid
350 user.Home = users[0].Home
351 } else if userArg != "" {
352 // If we can't find a user with the given username, the only other valid
353 // option is if it's a numeric username with no associated entry in passwd.
354
355 if uidErr != nil {
356 // Not numeric.
357 return nil, fmt.Errorf("unable to find user %s: %w", userArg, ErrNoPasswdEntries)
358 }
359 user.Uid = uidArg
360
361 // Must be inside valid uid range.
362 if user.Uid < minID || user.Uid > maxID {
363 return nil, ErrRange
364 }
365
366 // Okay, so it's numeric. We can just roll with this.
367 }
368
369 // On to the groups. If we matched a username, we need to do this because of
370 // the supplementary group IDs.
371 if groupArg != "" || matchedUserName != "" {
372 groups, err := ParseGroupFilter(group, func(g Group) bool {
373 // If the group argument isn't explicit, we'll just search for it.
374 if groupArg == "" {
375 // Check if user is a member of this group.
376 for _, u := range g.List {
377 if u == matchedUserName {
378 return true
379 }
380 }
381 return false
382 }
383
384 if gidErr == nil {
385 // If the groupArg is numeric, always treat it as a GID.
386 return gidArg == g.Gid
387 }
388
389 return g.Name == groupArg
390 })
391 if err != nil && group != nil {
392 return nil, fmt.Errorf("unable to find groups for spec %v: %w", matchedUserName, err)
393 }
394
395 // Only start modifying user.Gid if it is in explicit form.
396 if groupArg != "" {
397 if len(groups) > 0 {
398 // First match wins, even if there's more than one matching entry.
399 user.Gid = groups[0].Gid
400 } else {
401 // If we can't find a group with the given name, the only other valid
402 // option is if it's a numeric group name with no associated entry in group.
403
404 if gidErr != nil {
405 // Not numeric.
406 return nil, fmt.Errorf("unable to find group %s: %w", groupArg, ErrNoGroupEntries)
407 }
408 user.Gid = gidArg
409
410 // Must be inside valid gid range.
411 if user.Gid < minID || user.Gid > maxID {
412 return nil, ErrRange
413 }
414
415 // Okay, so it's numeric. We can just roll with this.
416 }
417 } else if len(groups) > 0 {
418 // Supplementary group ids only make sense if in the implicit form.
419 user.Sgids = make([]int, len(groups))
420 for i, group := range groups {
421 user.Sgids[i] = group.Gid
422 }
423 }
424 }
425
426 return user, nil
427 }
428
429 // GetAdditionalGroups looks up a list of groups by name or group id
430 // against the given /etc/group formatted data. If a group name cannot
431 // be found, an error will be returned. If a group id cannot be found,
432 // or the given group data is nil, the id will be returned as-is
433 // provided it is in the legal range.
434 func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) {
435 groups := []Group{}
436 if group != nil {
437 var err error
438 groups, err = ParseGroupFilter(group, func(g Group) bool {
439 for _, ag := range additionalGroups {
440 if g.Name == ag || strconv.Itoa(g.Gid) == ag {
441 return true
442 }
443 }
444 return false
445 })
446 if err != nil {
447 return nil, fmt.Errorf("unable to find additional groups %v: %w", additionalGroups, err)
448 }
449 }
450
451 gidMap := make(map[int]struct{})
452 for _, ag := range additionalGroups {
453 var found bool
454 for _, g := range groups {
455 // if we found a matched group either by name or gid, take the
456 // first matched as correct
457 if g.Name == ag || strconv.Itoa(g.Gid) == ag {
458 if _, ok := gidMap[g.Gid]; !ok {
459 gidMap[g.Gid] = struct{}{}
460 found = true
461 break
462 }
463 }
464 }
465 // we asked for a group but didn't find it. let's check to see
466 // if we wanted a numeric group
467 if !found {
468 gid, err := strconv.ParseInt(ag, 10, 64)
469 if err != nil {
470 // Not a numeric ID either.
471 return nil, fmt.Errorf("unable to find group %s: %w", ag, ErrNoGroupEntries)
472 }
473 // Ensure gid is inside gid range.
474 if gid < minID || gid > maxID {
475 return nil, ErrRange
476 }
477 gidMap[int(gid)] = struct{}{}
478 }
479 }
480 gids := []int{}
481 for gid := range gidMap {
482 gids = append(gids, gid)
483 }
484 return gids, nil
485 }
486
487 // GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups
488 // that opens the groupPath given and gives it as an argument to
489 // GetAdditionalGroups.
490 func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) {
491 var group io.Reader
492
493 if groupFile, err := os.Open(groupPath); err == nil {
494 group = groupFile
495 defer groupFile.Close()
496 }
497 return GetAdditionalGroups(additionalGroups, group)
498 }
499
500 func ParseSubIDFile(path string) ([]SubID, error) {
501 subid, err := os.Open(path)
502 if err != nil {
503 return nil, err
504 }
505 defer subid.Close()
506 return ParseSubID(subid)
507 }
508
509 func ParseSubID(subid io.Reader) ([]SubID, error) {
510 return ParseSubIDFilter(subid, nil)
511 }
512
513 func ParseSubIDFileFilter(path string, filter func(SubID) bool) ([]SubID, error) {
514 subid, err := os.Open(path)
515 if err != nil {
516 return nil, err
517 }
518 defer subid.Close()
519 return ParseSubIDFilter(subid, filter)
520 }
521
522 func ParseSubIDFilter(r io.Reader, filter func(SubID) bool) ([]SubID, error) {
523 if r == nil {
524 return nil, errors.New("nil source for subid-formatted data")
525 }
526
527 var (
528 s = bufio.NewScanner(r)
529 out = []SubID{}
530 )
531
532 for s.Scan() {
533 line := bytes.TrimSpace(s.Bytes())
534 if len(line) == 0 {
535 continue
536 }
537
538 // see: man 5 subuid
539 p := SubID{}
540 parseLine(line, &p.Name, &p.SubID, &p.Count)
541
542 if filter == nil || filter(p) {
543 out = append(out, p)
544 }
545 }
546 if err := s.Err(); err != nil {
547 return nil, err
548 }
549
550 return out, nil
551 }
552
553 func ParseIDMapFile(path string) ([]IDMap, error) {
554 r, err := os.Open(path)
555 if err != nil {
556 return nil, err
557 }
558 defer r.Close()
559 return ParseIDMap(r)
560 }
561
562 func ParseIDMap(r io.Reader) ([]IDMap, error) {
563 return ParseIDMapFilter(r, nil)
564 }
565
566 func ParseIDMapFileFilter(path string, filter func(IDMap) bool) ([]IDMap, error) {
567 r, err := os.Open(path)
568 if err != nil {
569 return nil, err
570 }
571 defer r.Close()
572 return ParseIDMapFilter(r, filter)
573 }
574
575 func ParseIDMapFilter(r io.Reader, filter func(IDMap) bool) ([]IDMap, error) {
576 if r == nil {
577 return nil, errors.New("nil source for idmap-formatted data")
578 }
579
580 var (
581 s = bufio.NewScanner(r)
582 out = []IDMap{}
583 )
584
585 for s.Scan() {
586 line := bytes.TrimSpace(s.Bytes())
587 if len(line) == 0 {
588 continue
589 }
590
591 // see: man 7 user_namespaces
592 p := IDMap{}
593 parseParts(bytes.Fields(line), &p.ID, &p.ParentID, &p.Count)
594
595 if filter == nil || filter(p) {
596 out = append(out, p)
597 }
598 }
599 if err := s.Err(); err != nil {
600 return nil, err
601 }
602
603 return out, nil
604 }