recyclebin: /srv/git-recyclebin -> /srv/git/_recyclebin
[girocco.git] / Girocco / User.pm
blob2ba9ec293c93658b5e2333ca39a679f827600de5
1 package Girocco::User;
3 use strict;
4 use warnings;
6 use Digest::MD5 qw(md5);
8 use Girocco::Config;
9 use Girocco::CGI;
10 use Girocco::Util;
11 use Girocco::SSHUtil;
13 BEGIN {
14 eval {
15 require Digest::SHA;
16 Digest::SHA->import(
17 qw(sha1_hex)
18 );1} ||
19 eval {
20 require Digest::SHA1;
21 Digest::SHA1->import(
22 qw(sha1_hex)
23 );1} ||
24 eval {
25 require Digest::SHA::PurePerl;
26 Digest::SHA::PurePerl->import(
27 qw(sha1_hex)
28 );1} ||
29 die "One of Digest::SHA or Digest::SHA1 or Digest::SHA::PurePerl "
30 . "must be available\n";
33 sub _gen_uuid {
34 my $self = shift;
36 $self->{uuid} = '' unless $self->{uuid};
37 my @md5;
39 no warnings;
40 @md5 = unpack('C*', md5(time . $$ . rand() . join(':',%$self)));
42 $md5[6] = 0x40 | ($md5[6] & 0x0F); # Version 4 -- random
43 $md5[8] = 0x80 | ($md5[8] & 0x3F); # RFC 4122 specification
44 return sprintf(
45 '%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x',
46 @md5);
49 sub _remove_ssh_leftovers {
50 my $self = shift;
51 my @files;
52 system('rm', '-f', "$Girocco::Config::chroot/etc/sshkeys/$self->{name}");
53 @files = glob("'$Girocco::Config::chroot/etc/sshcerts/${Girocco::Config::nickname}_$self->{name}'_user_*.pem");
54 system('rm', '-f', @files) if @files;
55 system('rm', '-f', "$Girocco::Config::chroot/etc/sshactive/$self->{name}");
56 @files = glob("'$Girocco::Config::chroot/etc/sshactive/$self->{name}',*");
57 system('rm', '-f', @files) if @files;
60 sub _passwd_add {
61 use POSIX qw(strftime);
62 my $self = shift;
63 my (undef, undef, $gid) = getgrnam($Girocco::Config::owning_group||'');
64 my $owngroupid = $gid ? $gid : 65534;
65 Girocco::User->load($self->{name}) and die "User $self->{name} already exists";
66 $self->{uuid} = $self->_gen_uuid;
67 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
68 $self->{creationtime} = strftime("%Y%m%d_%H%M%S", $S, $M, $H, $d, $m, $y, -1, -1, -1);
69 my $email_uuid_etc = join ',', $self->{email}, $self->{uuid}, $self->{creationtime};
70 filedb_atomic_append(jailed_file('/etc/passwd'),
71 join(':', $self->{name}, 'x', '\i', $owngroupid, $email_uuid_etc, '/', '/bin/git-shell-verify'),
72 $self->{name});
73 $self->_remove_ssh_leftovers;
76 sub _passwd_update {
77 my $self = shift;
78 filedb_atomic_edit(jailed_file('/etc/passwd'),
79 sub {
80 $_ = $_[0];
81 chomp;
82 if ($self->{name} eq (split /:/)[0]) {
83 # preserve all but login name and first 2 fields of comment field
84 # creating a uuid (field 2 of comment field) if one is not already present
85 my @fields=split(/:/, $_, -1);
86 $fields[0] = $self->{name};
87 my @subfields = split(',', $fields[4]||'', -1);
88 $self->{uuid} = $subfields[1] || '';
89 $self->{uuid} or $self->{uuid} = $self->_gen_uuid;
90 $subfields[0] = $self->{email};
91 $subfields[1] = $self->{uuid};
92 $fields[4] = join(',', @subfields);
93 return join(':', @fields)."\n";
94 } else {
95 return "$_\n";
98 $self->{name}
102 sub _passwd_remove {
103 my $self = shift;
104 $self->_remove_ssh_leftovers;
105 filedb_atomic_edit(jailed_file('/etc/passwd'),
106 sub {
107 $self->{name} ne (split /:/)[0] and return $_;
109 $self->{name}
113 sub _sshkey_path {
114 my $self = shift;
115 '/etc/sshkeys/'.$self->{name};
118 sub _sshkey_load {
119 my $self = shift;
120 open F, '<', jailed_file($self->_sshkey_path) or die "sshkey load failed: $!";
121 my @keys = ();
122 my $auth = '';
123 my $authtype = '';
124 while (<F>) {
125 chomp;
126 if (/^(?:no-pty )?(ssh-(?:dss|rsa) .*)$/) {
127 push @keys, $1;
128 } elsif (/^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
129 my $expire = $3;
130 $auth = $2 unless (time >= $expire);
131 $authtype = $1 if $auth;
134 close F;
135 my $keys = join("\n", @keys); chomp $keys;
136 ($keys, $auth, $authtype);
139 sub _trimkeys {
140 my $keys = shift;
141 my @lines = ();
142 foreach (split /\r\n|\r|\n/, $keys) {
143 next if /^[ \t]*$/ || /^[ \t]*#/;
144 push(@lines, $_);
146 return join("\n", @lines);
149 sub _sshkey_save {
150 my $self = shift;
151 $self->{keys} = _trimkeys($self->{keys} || '');
152 open F, '>', jailed_file($self->_sshkey_path) or die "sshkey save failed: $!";
153 if (defined($self->{auth}) && $self->{auth}) {
154 my $expire = time + 24 * 3600;
155 my $typestr = $self->{authtype} ? uc($self->{authtype}) : 'REPO';
156 print F "# ${typestr}AUTH $self->{auth} $expire\n";
158 print F map("no-pty $_\n", split(/\n/, $self->{keys}));
159 close F;
160 chmod 0664, jailed_file($self->_sshkey_path);
163 # private constructor, do not use
164 sub _new {
165 my $class = shift;
166 my ($name) = @_;
167 Girocco::User::valid_name($name) or die "refusing to create user with invalid name ($name)!";
168 my $proj = { name => $name };
170 bless $proj, $class;
173 # public constructor #0
174 # creates a virtual user not connected to disk record
175 # you can conjure() it later to disk
176 sub ghost {
177 my $class = shift;
178 my ($name) = @_;
179 my $self = $class->_new($name);
180 $self;
183 # public constructor #1
184 sub load {
185 my $class = shift;
186 my ($name) = @_;
188 open F, '<', jailed_file("/etc/passwd") or die "user load failed: $!";
189 while (<F>) {
190 chomp;
191 @_ = split /:/;
192 next unless (shift eq $name);
194 my $self = $class->_new($name);
196 my $email_uuid_etc;
197 (undef, $self->{uid}, undef, $email_uuid_etc) = @_;
198 ($self->{keys}, $self->{auth}, $self->{authtype}) = $self->_sshkey_load;
199 ($self->{email}, $self->{uuid}, $self->{creationtime}) = split ',', $email_uuid_etc;
201 close F;
202 $self->{uuid} or !valid_email($self->{email}) or $self->_passwd_update;
203 return $self;
205 close F;
206 undef;
209 # public constructor #2
210 sub load_by_uid {
211 my $class = shift;
212 my ($uid) = @_;
214 open F, '<', jailed_file("/etc/passwd") or die "user load failed: $!";
215 while (<F>) {
216 chomp;
217 @_ = split /:/;
218 next unless ($_[2] eq $uid);
220 my $self = $class->_new($_[0]);
222 my $email_uuid_etc;
223 (undef, undef, $self->{uid}, undef, $email_uuid_etc) = @_;
224 ($self->{keys}, $self->{auth}, $self->{authtype}) = $self->_sshkey_load;
225 ($self->{email}, $self->{uuid}, $self->{creationtime}) = split ',', $email_uuid_etc;
227 close F;
228 $self->{uuid} or $self->_passwd_update;
229 return $self;
231 close F;
232 undef;
235 # $user may not be in sane state if this returns false!
236 sub cgi_fill {
237 my $self = shift;
238 my ($gcgi) = @_;
239 my $cgi = $gcgi->cgi;
241 $self->{name} = $gcgi->wparam('name');
242 Girocco::User::valid_name($self->{name})
243 or $gcgi->err("Name contains invalid characters.");
245 length($self->{name}) <= 64
246 or $gcgi->err("Your user name is longer than 64 characters. Do you really need that much?");
248 $self->{email} = $gcgi->wparam('email');
249 valid_email($self->{email})
250 or $gcgi->err("Your email sure looks weird...?");
251 length($self->{email}) <= 96
252 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
254 $self->keys_fill($gcgi);
257 sub update_email {
258 my $self = shift;
259 my $gcgi = shift;
260 my $email = shift || '';
262 if (valid_email($email)) {
263 $self->{email} = $email;
264 $self->_passwd_update;
265 } else {
266 $gcgi->err("Your email sure looks weird...?");
269 not $gcgi->err_check;
272 sub _checkkey {
273 my $key = shift;
274 my ($type, $bits, $fingerprint, $comment) = sshpub_validate($key);
275 return $type ? 1 : 0;
278 sub keys_fill {
279 my $self = shift;
280 my ($gcgi) = @_;
281 my $cgi = $gcgi->cgi;
283 $self->{keys} = _trimkeys($cgi->param('keys'));
284 length($self->{keys}) <= 4096
285 or $gcgi->err("The list of keys is more than 4kb. Do you really need that much?");
286 foreach my $key (split /\r?\n/, $self->{keys}) {
287 my ($type, $bits, $fingerprint, $comment);
288 ($type, $bits, $fingerprint, $comment) = sshpub_validate($key)
289 if $key =~ /^ssh-(?:dss|rsa) [0-9A-Za-z+\/=]+ \S+@\S+$/;
290 if (!$type) {
291 my $keyval = CGI::escapeHTML($key);
292 my $dsablurb = '';
293 $dsablurb = ' or ssh-dss' unless $Girocco::Config::disable_dsa;
294 $gcgi->err(<<EOT);
295 Your ssh key ("$keyval") appears to have an invalid format
296 (does not start with ssh-rsa$dsablurb or does not end with <tt>\@</tt>-identifier) -
297 maybe your browser has split a single key onto multiple lines?
299 } elsif ($Girocco::Config::disable_dsa && $type eq 'ssh-dss') {
300 my $keyval = CGI::escapeHTML($key);
301 $gcgi->err(<<EOT);
302 Your ssh key ("$keyval") appears to be of type dsa but only rsa keys are
303 supported - please generate an rsa key (starts with ssh-rsa) and try again
305 } elsif ($Girocco::Config::min_key_length && $bits < $Girocco::Config::min_key_length) {
306 my $keyval = CGI::escapeHTML($key);
307 $gcgi->err(<<EOT);
308 Your ssh key ("$keyval") appears to have only $bits bit(s) but at least
309 $Girocco::Config::min_key_length are required - please generate a longer key
314 not $gcgi->err_check;
317 sub keys_save {
318 my $self = shift;
320 $self->_sshkey_save;
323 sub keys_html_list {
324 my $self = shift;
325 my @keys = split(/\r?\n/, $self->{keys});
326 return '' if !@keys;
327 my $html = "<ol>\n";
328 my %types = ('ssh-dss' => 'DSA', 'ssh-rsa' => 'RSA');
329 my $line = 0;
330 foreach (@keys) {
331 ++$line;
332 my ($type, $bits, $fingerprint, $comment) = sshpub_validate($_);
333 next unless $type && $types{$type};
334 my $euser = CGI::escapeHTML(CGI::Util::escape($self->{name}));
335 $html .= "<li>$bits <tt>$fingerprint</tt> ($types{$type}) $comment";
336 $html .= "<br /><a target=\"_blank\" ".
337 "href=\"@{[url_path($Girocco::Config::webadmurl)]}/usercert.cgi/$euser/$line/".
338 $Girocco::Config::nickname."_${euser}_user_$line.pem\">".
339 "download https push user authentication certificate</a> <sup>".
340 "<a target=\"_blank\" href=\"@{[url_path($Girocco::Config::htmlurl)]}/httpspush.html\">".
341 "(learn more)</a></sup>"
342 if $type eq 'ssh-rsa' && $Girocco::Config::httpspushurl &&
343 $Girocco::Config::clientcert &&
344 $Girocco::Config::clientkey;
345 $html .= "</li>\n";
347 $html .= "</ol>\n";
348 return $html;
351 sub gen_auth {
352 my $self = shift;
353 my ($type) = @_;
354 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
356 $self->{authtype} = $type;
357 $self->{auth} = sha1_hex(time . $$ . rand() . $self->{keys});
358 $self->_sshkey_save;
359 $self->{auth};
362 sub del_auth {
363 my $self = shift;
365 delete $self->{auth};
366 delete $self->{authtype};
369 sub get_projects {
370 my $self = shift;
372 return @{$self->{projects}} if defined($self->{projects});
373 my @projects = filedb_atomic_grep(jailed_file('/etc/group'),
374 sub {
375 $_ = $_[0];
376 chomp;
377 my ($group, $users) = (split /:/)[0,3];
378 $group if $users && $users =~ /(^|,)\Q$self->{name}\E(,|$)/;
381 $self->{projects} = \@projects;
382 @{$self->{projects}};
385 sub conjure {
386 my $self = shift;
388 $self->_passwd_add;
389 $self->_sshkey_save;
392 sub remove {
393 my $self = shift;
395 require Girocco::Project;
396 foreach ($self->get_projects) {
397 if (Girocco::Project::does_exist($_)) {
398 my $project = Girocco::Project->load($_);
399 $project->update if $project->remove_user($self->{name});
403 $self->_passwd_remove;
406 ### static methods
408 # Note that 'mob' and 'everyone' are NOT reserved names per se, but they are
409 # names with special semantics and they should be allowed in project membership
410 # lists so they are therefore NOT included in the reservedusernames list.
411 # 'git' and 'lock' are reserved so that the personal mob names 'mob.git' and
412 # 'mob.lock' are not needed as they would be invalid.
413 our %reservedusernames = (
414 root => 1,
415 sshd => 1,
416 _sshd => 1,
417 nobody => 1,
418 lc($Girocco::Config::cgi_user) => 1,
419 lc($Girocco::Config::mirror_user) => 1,
420 git => 1,
421 lock => 1,
424 sub valid_name {
425 $_ = $_[0];
426 /^[a-zA-Z0-9][a-zA-Z0-9+._-]*$/
427 and (not m#\.\.#)
428 and (not m#\.$#)
429 and (not m#\.git$#i)
430 and (not m#\.lock$#i)
431 and (not m#^mob[._]#i)
432 and !exists($reservedusernames{lc($_)});
435 sub does_exist {
436 my ($name) = @_;
437 Girocco::User::valid_name($name) or die "tried to query for user with invalid name $name!";
438 (-e jailed_file("/etc/sshkeys/$name"));
441 sub resolve_uid {
442 my ($name) = @_;
443 $Girocco::Config::chrooted and undef; # TODO for ACLs within chroot
444 scalar(getpwnam($name));