1 // Parse /etc/group files and serialize them
3 // Copyright (C) 2019 Simon Ruderich
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU Affero General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU Affero General Public License for more details.
15 // You should have received a copy of the GNU Affero General Public License
16 // along with this program. If not, see <https://www.gnu.org/licenses/>.
31 "github.com/pkg/errors"
34 // Version written in SerializeGroups()
35 const GroupVersion = 1
44 // Go does not support slices in map keys; therefore, use this separate struct
45 type GroupKey struct {
49 Members string // "," separated
52 func toKey(g Group) GroupKey {
57 Members: strings.Join(g.Members, ","),
61 // ParseGroups parses a file in the format of /etc/group and returns all
62 // entries as slice of Group structs.
63 func ParseGroups(r io.Reader) ([]Group, error) {
66 s := bufio.NewReader(r)
68 t, err := s.ReadString('\n')
76 x := strings.Split(t, ":")
78 return nil, fmt.Errorf("invalid line %q", t)
81 gid, err := strconv.ParseUint(x[2], 10, 64)
83 return nil, errors.Wrapf(err, "invalid gid in line %q", t)
86 // ReadString() contains the delimiter
87 x[3] = strings.TrimSuffix(x[3], "\n")
90 // No members must result in empty slice, not slice with the
93 members = strings.Split(x[3], ",")
95 res = append(res, Group{
106 func SerializeGroup(g Group) ([]byte, error) {
107 le := binary.LittleEndian
109 // Concatenate all (NUL-terminated) strings and store the offsets
110 var mems bytes.Buffer
111 var mems_off []uint16
112 for _, m := range g.Members {
113 mems_off = append(mems_off, uint16(mems.Len()))
114 mems.Write([]byte(m))
117 var data bytes.Buffer
118 data.Write([]byte(g.Name))
120 offPasswd := uint16(data.Len())
121 data.Write([]byte(g.Passwd))
123 alignBufferTo(&data, 2) // align the following uint16
124 offMemOff := uint16(data.Len())
125 // Offsets for group members
126 offMem := offMemOff + 2*uint16(len(mems_off))
127 for _, o := range mems_off {
128 tmp := make([]byte, 2)
129 le.PutUint16(tmp, offMem+o)
132 // And the group members concatenated as above
133 data.Write(mems.Bytes())
134 // Ensure the offsets can fit the length of this entry
135 if data.Len() > math.MaxUint16 {
136 return nil, fmt.Errorf("group too large to serialize: %v, %v",
139 size := uint16(data.Len())
141 var res bytes.Buffer // serialized result
143 id := make([]byte, 8)
145 le.PutUint64(id, g.Gid)
148 off := make([]byte, 2)
150 le.PutUint16(off, offPasswd)
153 le.PutUint16(off, offMemOff)
156 le.PutUint16(off, uint16(len(g.Members)))
159 le.PutUint16(off, size)
162 res.Write(data.Bytes())
163 // We must pad each entry so that all uint64 at the beginning of the
164 // struct are 8 byte aligned
165 alignBufferTo(&res, 8)
167 return res.Bytes(), nil
170 func SerializeGroups(w io.Writer, grs []Group) error {
171 // Serialize groups and store offsets
172 var data bytes.Buffer
173 offsets := make(map[GroupKey]uint64)
174 for _, g := range grs {
175 // TODO: warn about duplicate entries
176 offsets[toKey(g)] = uint64(data.Len())
177 x, err := SerializeGroup(g)
184 // Copy to prevent sorting from modifying the argument
185 sorted := make([]Group, len(grs))
188 le := binary.LittleEndian
189 tmp := make([]byte, 8)
191 // Create index "sorted" in input order, used when iterating over all
192 // passwd entries (getgrent_r); keeping the original order makes
194 var indexOrig bytes.Buffer
195 for _, g := range grs {
196 le.PutUint64(tmp, offsets[toKey(g)])
200 // Create index sorted after id
201 var indexId bytes.Buffer
202 sort.Slice(sorted, func(i, j int) bool {
203 return sorted[i].Gid < sorted[j].Gid
205 for _, g := range sorted {
206 le.PutUint64(tmp, offsets[toKey(g)])
210 // Create index sorted after name
211 var indexName bytes.Buffer
212 sort.Slice(sorted, func(i, j int) bool {
213 return sorted[i].Name < sorted[j].Name
215 for _, g := range sorted {
216 le.PutUint64(tmp, offsets[toKey(g)])
221 if len(grs)*8 != indexOrig.Len() ||
222 indexOrig.Len() != indexId.Len() ||
223 indexId.Len() != indexName.Len() {
224 return fmt.Errorf("indexes have inconsistent length")
230 w.Write([]byte("NSS-CASH"))
232 le.PutUint64(tmp, GroupVersion)
235 le.PutUint64(tmp, uint64(len(grs)))
239 le.PutUint64(tmp, offset)
242 offset += uint64(indexOrig.Len())
243 le.PutUint64(tmp, offset)
246 offset += uint64(indexId.Len())
247 le.PutUint64(tmp, offset)
250 offset += uint64(indexName.Len())
251 le.PutUint64(tmp, offset)
254 _, err := indexOrig.WriteTo(w)
258 _, err = indexId.WriteTo(w)
262 _, err = indexName.WriteTo(w)
266 _, err = data.WriteTo(w)