1use strict;
2use warnings;
3use File::Path qw(make_path);
4use File::Slurp;
5use Getopt::Long;
6use JSON;
7use Time::Piece;
8
9# Keep track of deleted uids and gids.
10my $uidMapFile = "/var/lib/nixos/uid-map";
11my $uidMap = -e $uidMapFile ? decode_json(read_file($uidMapFile)) : {};
12
13my $gidMapFile = "/var/lib/nixos/gid-map";
14my $gidMap = -e $gidMapFile ? decode_json(read_file($gidMapFile)) : {};
15
16my $is_dry = ($ENV{'NIXOS_ACTION'} // "") eq "dry-activate";
17GetOptions("dry-activate" => \$is_dry);
18make_path("/var/lib/nixos", { mode => 0755 }) unless $is_dry;
19
20sub updateFile {
21 my ($path, $contents, $perms) = @_;
22 return if $is_dry;
23 write_file($path, { atomic => 1, binmode => ':utf8', perms => $perms // 0644 }, $contents) or die;
24}
25
26# Converts an ISO date to number of days since 1970-01-01
27sub dateToDays {
28 my ($date) = @_;
29 my $time = Time::Piece->strptime($date, "%Y-%m-%d");
30 return $time->epoch / 60 / 60 / 24;
31}
32
33sub nscdInvalidate {
34 system("nscd", "--invalidate", $_[0]) unless $is_dry;
35}
36
37sub hashPassword {
38 my ($password) = @_;
39 my $salt = "";
40 my @chars = ('.', '/', 0..9, 'A'..'Z', 'a'..'z');
41 $salt .= $chars[rand 64] for (1..8);
42 return crypt($password, '$6$' . $salt . '$');
43}
44
45sub dry_print {
46 if ($is_dry) {
47 print STDERR ("$_[1] $_[2]\n")
48 } else {
49 print STDERR ("$_[0] $_[2]\n")
50 }
51}
52
53
54# Functions for allocating free GIDs/UIDs. FIXME: respect ID ranges in
55# /etc/login.defs.
56sub allocId {
57 my ($used, $prevUsed, $idMin, $idMax, $up, $getid) = @_;
58 my $id = $up ? $idMin : $idMax;
59 while ($id >= $idMin && $id <= $idMax) {
60 if (!$used->{$id} && !$prevUsed->{$id} && !defined &$getid($id)) {
61 $used->{$id} = 1;
62 return $id;
63 }
64 $used->{$id} = 1;
65 if ($up) { $id++; } else { $id--; }
66 }
67 die "$0: out of free UIDs or GIDs\n";
68}
69
70my (%gidsUsed, %uidsUsed, %gidsPrevUsed, %uidsPrevUsed);
71
72sub allocGid {
73 my ($name) = @_;
74 my $prevGid = $gidMap->{$name};
75 if (defined $prevGid && !defined $gidsUsed{$prevGid}) {
76 dry_print("reviving", "would revive", "group '$name' with GID $prevGid");
77 $gidsUsed{$prevGid} = 1;
78 return $prevGid;
79 }
80 return allocId(\%gidsUsed, \%gidsPrevUsed, 400, 999, 0, sub { my ($gid) = @_; getgrgid($gid) });
81}
82
83sub allocUid {
84 my ($name, $isSystemUser) = @_;
85 my ($min, $max, $up) = $isSystemUser ? (400, 999, 0) : (1000, 29999, 1);
86 my $prevUid = $uidMap->{$name};
87 if (defined $prevUid && $prevUid >= $min && $prevUid <= $max && !defined $uidsUsed{$prevUid}) {
88 dry_print("reviving", "would revive", "user '$name' with UID $prevUid");
89 $uidsUsed{$prevUid} = 1;
90 return $prevUid;
91 }
92 return allocId(\%uidsUsed, \%uidsPrevUsed, $min, $max, $up, sub { my ($uid) = @_; getpwuid($uid) });
93}
94
95# Read the declared users/groups
96my $spec = decode_json(read_file($ARGV[0]));
97
98# Don't allocate UIDs/GIDs that are manually assigned.
99foreach my $g (@{$spec->{groups}}) {
100 $gidsUsed{$g->{gid}} = 1 if defined $g->{gid};
101}
102
103foreach my $u (@{$spec->{users}}) {
104 $uidsUsed{$u->{uid}} = 1 if defined $u->{uid};
105}
106
107# Likewise for previously used but deleted UIDs/GIDs.
108$uidsPrevUsed{$_} = 1 foreach values %{$uidMap};
109$gidsPrevUsed{$_} = 1 foreach values %{$gidMap};
110
111
112# Read the current /etc/group.
113sub parseGroup {
114 chomp;
115 my @f = split(':', $_, -4);
116 my $gid = $f[2] eq "" ? undef : int($f[2]);
117 $gidsUsed{$gid} = 1 if defined $gid;
118 return ($f[0], { name => $f[0], password => $f[1], gid => $gid, members => $f[3] });
119}
120
121my %groupsCur = -f "/etc/group" ? map { parseGroup } read_file("/etc/group", { binmode => ":utf8" }) : ();
122
123# Read the current /etc/passwd.
124sub parseUser {
125 chomp;
126 my @f = split(':', $_, -7);
127 my $uid = $f[2] eq "" ? undef : int($f[2]);
128 $uidsUsed{$uid} = 1 if defined $uid;
129 return ($f[0], { name => $f[0], fakePassword => $f[1], uid => $uid,
130 gid => $f[3], description => $f[4], home => $f[5], shell => $f[6] });
131}
132my %usersCur = -f "/etc/passwd" ? map { parseUser } read_file("/etc/passwd", { binmode => ":utf8" }) : ();
133
134# Read the groups that were created declaratively (i.e. not by groups)
135# in the past. These must be removed if they are no longer in the
136# current spec.
137my $declGroupsFile = "/var/lib/nixos/declarative-groups";
138my %declGroups;
139$declGroups{$_} = 1 foreach split / /, -e $declGroupsFile ? read_file($declGroupsFile, { binmode => ":utf8" }) : "";
140
141# Idem for the users.
142my $declUsersFile = "/var/lib/nixos/declarative-users";
143my %declUsers;
144$declUsers{$_} = 1 foreach split / /, -e $declUsersFile ? read_file($declUsersFile, { binmode => ":utf8" }) : "";
145
146
147# Generate a new /etc/group containing the declared groups.
148my %groupsOut;
149foreach my $g (@{$spec->{groups}}) {
150 my $name = $g->{name};
151 my $existing = $groupsCur{$name};
152
153 my %members = map { ($_, 1) } @{$g->{members}};
154
155 if (defined $existing) {
156 $g->{gid} = $existing->{gid} if !defined $g->{gid};
157 if ($g->{gid} != $existing->{gid}) {
158 dry_print("warning: not applying", "warning: would not apply", "GID change of group ‘$name’ ($existing->{gid} -> $g->{gid}) in /etc/group");
159 $g->{gid} = $existing->{gid};
160 }
161 $g->{password} = $existing->{password}; # do we want this?
162 if ($spec->{mutableUsers}) {
163 # Merge in non-declarative group members.
164 foreach my $uname (split /,/, $existing->{members} // "") {
165 $members{$uname} = 1 if !defined $declUsers{$uname};
166 }
167 }
168 } else {
169 $g->{gid} = allocGid($name) if !defined $g->{gid};
170 $g->{password} = "x";
171 }
172
173 $g->{members} = join ",", sort(keys(%members));
174 $groupsOut{$name} = $g;
175
176 $gidMap->{$name} = $g->{gid};
177}
178
179# Update the persistent list of declarative groups.
180updateFile($declGroupsFile, join(" ", sort(keys %groupsOut)));
181
182# Merge in the existing /etc/group.
183foreach my $name (keys %groupsCur) {
184 my $g = $groupsCur{$name};
185 next if defined $groupsOut{$name};
186 if (!$spec->{mutableUsers} || defined $declGroups{$name}) {
187 dry_print("removing group", "would remove group", "‘$name’");
188 } else {
189 $groupsOut{$name} = $g;
190 }
191}
192
193
194# Rewrite /etc/group. FIXME: acquire lock.
195my @lines = map { join(":", $_->{name}, $_->{password}, $_->{gid}, $_->{members}) . "\n" }
196 (sort { $a->{gid} <=> $b->{gid} } values(%groupsOut));
197updateFile($gidMapFile, to_json($gidMap, {canonical => 1}));
198updateFile("/etc/group", \@lines);
199nscdInvalidate("group");
200
201# Generate a new /etc/passwd containing the declared users.
202my %usersOut;
203foreach my $u (@{$spec->{users}}) {
204 my $name = $u->{name};
205
206 # Resolve the gid of the user.
207 if ($u->{group} =~ /^[0-9]$/) {
208 $u->{gid} = $u->{group};
209 } elsif (defined $groupsOut{$u->{group}}) {
210 $u->{gid} = $groupsOut{$u->{group}}->{gid} // die;
211 } else {
212 warn "warning: user ‘$name’ has unknown group ‘$u->{group}’\n";
213 $u->{gid} = 65534;
214 }
215
216 my $existing = $usersCur{$name};
217 if (defined $existing) {
218 $u->{uid} = $existing->{uid} if !defined $u->{uid};
219 if ($u->{uid} != $existing->{uid}) {
220 dry_print("warning: not applying", "warning: would not apply", "UID change of user ‘$name’ ($existing->{uid} -> $u->{uid}) in /etc/passwd");
221 $u->{uid} = $existing->{uid};
222 }
223 } else {
224 $u->{uid} = allocUid($name, $u->{isSystemUser}) if !defined $u->{uid};
225
226 if (!defined $u->{hashedPassword}) {
227 if (defined $u->{initialPassword}) {
228 $u->{hashedPassword} = hashPassword($u->{initialPassword});
229 } elsif (defined $u->{initialHashedPassword}) {
230 $u->{hashedPassword} = $u->{initialHashedPassword};
231 }
232 }
233 }
234
235 # Ensure home directory incl. ownership and permissions.
236 if ($u->{createHome} and !$is_dry) {
237 make_path($u->{home}, { mode => oct($u->{homeMode}) }) if ! -e $u->{home};
238 chown $u->{uid}, $u->{gid}, $u->{home};
239 chmod oct($u->{homeMode}), $u->{home};
240 }
241
242 if (defined $u->{hashedPasswordFile}) {
243 if (-e $u->{hashedPasswordFile}) {
244 $u->{hashedPassword} = read_file($u->{hashedPasswordFile});
245 chomp $u->{hashedPassword};
246 } else {
247 warn "warning: password file ‘$u->{hashedPasswordFile}’ does not exist\n";
248 }
249 } elsif (defined $u->{password}) {
250 $u->{hashedPassword} = hashPassword($u->{password});
251 }
252
253 if (!defined $u->{shell}) {
254 if (defined $existing) {
255 $u->{shell} = $existing->{shell};
256 } else {
257 warn "warning: no declarative or previous shell for ‘$name’, setting shell to nologin\n";
258 $u->{shell} = "/run/current-system/sw/bin/nologin";
259 }
260 }
261
262 $u->{fakePassword} = $existing->{fakePassword} // "x";
263 $usersOut{$name} = $u;
264
265 $uidMap->{$name} = $u->{uid};
266}
267
268# Update the persistent list of declarative users.
269updateFile($declUsersFile, join(" ", sort(keys %usersOut)));
270
271# Merge in the existing /etc/passwd.
272foreach my $name (keys %usersCur) {
273 my $u = $usersCur{$name};
274 next if defined $usersOut{$name};
275 if (!$spec->{mutableUsers} || defined $declUsers{$name}) {
276 dry_print("removing user", "would remove user", "‘$name’");
277 } else {
278 $usersOut{$name} = $u;
279 }
280}
281
282# Rewrite /etc/passwd. FIXME: acquire lock.
283@lines = map { join(":", $_->{name}, $_->{fakePassword}, $_->{uid}, $_->{gid}, $_->{description}, $_->{home}, $_->{shell}) . "\n" }
284 (sort { $a->{uid} <=> $b->{uid} } (values %usersOut));
285updateFile($uidMapFile, to_json($uidMap, {canonical => 1}));
286updateFile("/etc/passwd", \@lines);
287nscdInvalidate("passwd");
288
289
290# Rewrite /etc/shadow to add new accounts or remove dead ones.
291my @shadowNew;
292my %shadowSeen;
293
294foreach my $line (-f "/etc/shadow" ? read_file("/etc/shadow", { binmode => ":utf8" }) : ()) {
295 chomp $line;
296 # struct name copied from `man 3 shadow`
297 my ($sp_namp, $sp_pwdp, $sp_lstch, $sp_min, $sp_max, $sp_warn, $sp_inact, $sp_expire, $sp_flag) = split(':', $line, -9);
298 my $u = $usersOut{$sp_namp};;
299 next if !defined $u;
300 $sp_pwdp = "!" if !$spec->{mutableUsers};
301 $sp_pwdp = $u->{hashedPassword} if defined $u->{hashedPassword} && !$spec->{mutableUsers}; # FIXME
302 $sp_expire = dateToDays($u->{expires}) if defined $u->{expires};
303 chomp $sp_pwdp;
304 push @shadowNew, join(":", $sp_namp, $sp_pwdp, $sp_lstch, $sp_min, $sp_max, $sp_warn, $sp_inact, $sp_expire, $sp_flag) . "\n";
305 $shadowSeen{$sp_namp} = 1;
306}
307
308foreach my $u (values %usersOut) {
309 next if defined $shadowSeen{$u->{name}};
310 my $hashedPassword = "!";
311 $hashedPassword = $u->{hashedPassword} if defined $u->{hashedPassword};
312 my $expires = "";
313 $expires = dateToDays($u->{expires}) if defined $u->{expires};
314 # FIXME: set correct value for sp_lstchg.
315 push @shadowNew, join(":", $u->{name}, $hashedPassword, "1::::", $expires, "") . "\n";
316}
317
318updateFile("/etc/shadow", \@shadowNew, 0640);
319{
320 my $uid = getpwnam "root";
321 my $gid = getgrnam "shadow";
322 my $path = "/etc/shadow";
323 (chown($uid, $gid, $path) || die "Failed to change ownership of $path: $!") unless $is_dry;
324}
325
326# Rewrite /etc/subuid & /etc/subgid to include default container mappings
327
328my $subUidMapFile = "/var/lib/nixos/auto-subuid-map";
329my $subUidMap = -e $subUidMapFile ? decode_json(read_file($subUidMapFile)) : {};
330
331my (%subUidsUsed, %subUidsPrevUsed);
332
333$subUidsPrevUsed{$_} = 1 foreach values %{$subUidMap};
334
335sub allocSubUid {
336 my ($name, @rest) = @_;
337
338 # TODO: No upper bounds?
339 my ($min, $max, $up) = (100000, 100000 * 100, 1);
340 my $prevId = $subUidMap->{$name};
341 if (defined $prevId && !defined $subUidsUsed{$prevId}) {
342 $subUidsUsed{$prevId} = 1;
343 return $prevId;
344 }
345
346 my $id = allocId(\%subUidsUsed, \%subUidsPrevUsed, $min, $max, $up, sub { my ($uid) = @_; getpwuid($uid) });
347 my $offset = $id - 100000;
348 my $count = $offset * 65536;
349 my $subordinate = 100000 + $count;
350 return $subordinate;
351}
352
353my @subGids;
354my @subUids;
355foreach my $u (values %usersOut) {
356 my $name = $u->{name};
357
358 foreach my $range (@{$u->{subUidRanges}}) {
359 my $value = join(":", ($name, $range->{startUid}, $range->{count}));
360 push @subUids, $value;
361 }
362
363 foreach my $range (@{$u->{subGidRanges}}) {
364 my $value = join(":", ($name, $range->{startGid}, $range->{count}));
365 push @subGids, $value;
366 }
367
368 if($u->{autoSubUidGidRange}) {
369 my $subordinate = allocSubUid($name);
370 $subUidMap->{$name} = $subordinate;
371 my $value = join(":", ($name, $subordinate, 65536));
372 push @subUids, $value;
373 push @subGids, $value;
374 }
375}
376
377updateFile("/etc/subuid", join("\n", @subUids) . "\n");
378updateFile("/etc/subgid", join("\n", @subGids) . "\n");
379updateFile($subUidMapFile, encode_json($subUidMap) . "\n");