Revert "jailsetup.sh: replace sshd even if it's busy"
[girocco.git] / Girocco / User.pm
blob1e312bffc0ada628d603349c940217e5ccbccc13
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 system "rm -f '$Girocco::Config::chroot/etc/sshkeys/$self->{name}'";
52 system "rm -f '$Girocco::Config::chroot/etc/sshcerts/${Girocco::Config::nickname}_$self->{name}'_user_*.pem";
53 system "rm -f '$Girocco::Config::chroot/etc/sshactive/$self->{name}'";
54 system "rm -f '$Girocco::Config::chroot/etc/sshactive/$self->{name}',*";
57 sub _passwd_add {
58 use POSIX qw(strftime);
59 my $self = shift;
60 my (undef, undef, $gid) = getgrnam($Girocco::Config::owning_group||'');
61 my $owngroupid = $gid ? $gid : 65534;
62 Girocco::User->load($self->{name}) and die "User $self->{name} already exists";
63 $self->{uuid} = $self->_gen_uuid;
64 my ($S,$M,$H,$d,$m,$y) = gmtime(time());
65 $self->{creationtime} = strftime("%Y%m%d_%H%M%S", $S, $M, $H, $d, $m, $y, -1, -1, -1);
66 my $email_uuid_etc = join ',', $self->{email}, $self->{uuid}, $self->{creationtime};
67 filedb_atomic_append(jailed_file('/etc/passwd'),
68 join(':', $self->{name}, 'x', '\i', $owngroupid, $email_uuid_etc, '/', '/bin/git-shell-verify'),
69 $self->{name});
70 $self->_remove_ssh_leftovers;
73 sub _passwd_update {
74 my $self = shift;
75 filedb_atomic_edit(jailed_file('/etc/passwd'),
76 sub {
77 $_ = $_[0];
78 chomp;
79 if ($self->{name} eq (split /:/)[0]) {
80 # preserve all but login name and first 2 fields of comment field
81 # creating a uuid (field 2 of comment field) if one is not already present
82 my @fields=split(/:/, $_, -1);
83 $fields[0] = $self->{name};
84 my @subfields = split(',', $fields[4]||'', -1);
85 $self->{uuid} = $subfields[1] || '';
86 $self->{uuid} or $self->{uuid} = $self->_gen_uuid;
87 $subfields[0] = $self->{email};
88 $subfields[1] = $self->{uuid};
89 $fields[4] = join(',', @subfields);
90 return join(':', @fields)."\n";
91 } else {
92 return "$_\n";
95 $self->{name}
99 sub _passwd_remove {
100 my $self = shift;
101 $self->_remove_ssh_leftovers;
102 filedb_atomic_edit(jailed_file('/etc/passwd'),
103 sub {
104 $self->{name} ne (split /:/)[0] and return $_;
106 $self->{name}
110 sub _sshkey_path {
111 my $self = shift;
112 '/etc/sshkeys/'.$self->{name};
115 sub _sshkey_load {
116 my $self = shift;
117 open F, '<', jailed_file($self->_sshkey_path) or die "sshkey load failed: $!";
118 my @keys = ();
119 my $auth = '';
120 my $authtype = '';
121 while (<F>) {
122 chomp;
123 if (/^ssh-(?:dss|rsa) /) {
124 push @keys, $_;
125 } elsif (/^# ([A-Z]+)AUTH ([0-9a-f]+) (\d+)/) {
126 my $expire = $3;
127 $auth = $2 unless (time >= $expire);
128 $authtype = $1 if $auth;
131 close F;
132 my $keys = join("\n", @keys); chomp $keys;
133 ($keys, $auth, $authtype);
136 sub _trimkeys {
137 my $keys = shift;
138 my @lines = ();
139 foreach (split /\r\n|\r|\n/, $keys) {
140 next if /^[ \t]*$/ || /^[ \t]*#/;
141 push(@lines, $_);
143 return join("\n", @lines);
146 sub _sshkey_save {
147 my $self = shift;
148 $self->{keys} = _trimkeys($self->{keys} || '');
149 open F, '>', jailed_file($self->_sshkey_path) or die "sshkey save failed: $!";
150 if (defined($self->{auth}) && $self->{auth}) {
151 my $expire = time + 24 * 3600;
152 my $typestr = $self->{authtype} ? uc($self->{authtype}) : 'REPO';
153 print F "# ${typestr}AUTH $self->{auth} $expire\n";
155 print F $self->{keys};
156 print F "\n" if $self->{keys};
157 close F;
158 chmod 0664, jailed_file($self->_sshkey_path);
161 # private constructor, do not use
162 sub _new {
163 my $class = shift;
164 my ($name) = @_;
165 Girocco::User::valid_name($name) or die "refusing to create user with invalid name ($name)!";
166 my $proj = { name => $name };
168 bless $proj, $class;
171 # public constructor #0
172 # creates a virtual user not connected to disk record
173 # you can conjure() it later to disk
174 sub ghost {
175 my $class = shift;
176 my ($name) = @_;
177 my $self = $class->_new($name);
178 $self;
181 # public constructor #1
182 sub load {
183 my $class = shift;
184 my ($name) = @_;
186 open F, '<', jailed_file("/etc/passwd") or die "user load failed: $!";
187 while (<F>) {
188 chomp;
189 @_ = split /:/;
190 next unless (shift eq $name);
192 my $self = $class->_new($name);
194 my $email_uuid_etc;
195 (undef, $self->{uid}, undef, $email_uuid_etc) = @_;
196 ($self->{keys}, $self->{auth}, $self->{authtype}) = $self->_sshkey_load;
197 ($self->{email}, $self->{uuid}, $self->{creationtime}) = split ',', $email_uuid_etc;
199 close F;
200 $self->{uuid} or $self->_passwd_update;
201 return $self;
203 close F;
204 undef;
207 # public constructor #2
208 sub load_by_uid {
209 my $class = shift;
210 my ($uid) = @_;
212 open F, '<', jailed_file("/etc/passwd") or die "user load failed: $!";
213 while (<F>) {
214 chomp;
215 @_ = split /:/;
216 next unless ($_[2] eq $uid);
218 my $self = $class->_new($_[0]);
220 my $email_uuid_etc;
221 (undef, undef, $self->{uid}, undef, $email_uuid_etc) = @_;
222 ($self->{keys}, $self->{auth}, $self->{authtype}) = $self->_sshkey_load;
223 ($self->{email}, $self->{uuid}, $self->{creationtime}) = split ',', $email_uuid_etc;
225 close F;
226 $self->{uuid} or $self->_passwd_update;
227 return $self;
229 close F;
230 undef;
233 # $user may not be in sane state if this returns false!
234 sub cgi_fill {
235 my $self = shift;
236 my ($gcgi) = @_;
237 my $cgi = $gcgi->cgi;
239 $self->{name} = $gcgi->wparam('name');
240 Girocco::User::valid_name($self->{name})
241 or $gcgi->err("Name contains invalid characters.");
243 length($self->{name}) <= 64
244 or $gcgi->err("Your user name is longer than 64 characters. Do you really need that much?");
246 $self->{email} = $gcgi->wparam('email');
247 valid_email($self->{email})
248 or $gcgi->err("Your email sure looks weird...?");
249 length($self->{email}) <= 96
250 or $gcgi->err("Your email is longer than 96 characters. Do you really need that much?");
252 $self->keys_fill($gcgi);
255 sub update_email {
256 my $self = shift;
257 my $gcgi = shift;
258 my $email = shift || '';
260 if (valid_email($email)) {
261 $self->{email} = $email;
262 $self->_passwd_update;
263 } else {
264 $gcgi->err("Your email sure looks weird...?");
267 not $gcgi->err_check;
270 sub _checkkey {
271 my $key = shift;
272 my ($type, $bits, $fingerprint, $comment) = sshpub_validate($key);
273 return $type ? 1 : 0;
276 sub keys_fill {
277 my $self = shift;
278 my ($gcgi) = @_;
279 my $cgi = $gcgi->cgi;
281 $self->{keys} = _trimkeys($cgi->param('keys'));
282 length($self->{keys}) <= 4096
283 or $gcgi->err("The list of keys is more than 4kb. Do you really need that much?");
284 foreach my $key (split /\r?\n/, $self->{keys}) {
285 my ($type, $bits, $fingerprint, $comment);
286 ($type, $bits, $fingerprint, $comment) = sshpub_validate($key)
287 if $key =~ /^ssh-(?:dss|rsa) [0-9A-Za-z+\/=]+ \S+@\S+$/;
288 if (!$type) {
289 my $keyval = CGI::escapeHTML($key);
290 my $dsablurb = '';
291 $dsablurb = ' or ssh-dss' unless $Girocco::Config::disable_dsa;
292 $gcgi->err(<<EOT);
293 Your ssh key ("$keyval") appears to have an invalid format
294 (does not start with ssh-rsa$dsablurb or does not end with <tt>\@</tt>-identifier) -
295 maybe your browser has split a single key onto multiple lines?
297 } elsif ($Girocco::Config::disable_dsa && $type eq 'ssh-dss') {
298 my $keyval = CGI::escapeHTML($key);
299 $gcgi->err(<<EOT);
300 Your ssh key ("$keyval") appears to be of type dsa but only rsa keys are
301 supported - please generate an rsa key (starts with ssh-rsa) and try again
303 } elsif ($Girocco::Config::min_key_length && $bits < $Girocco::Config::min_key_length) {
304 my $keyval = CGI::escapeHTML($key);
305 $gcgi->err(<<EOT);
306 Your ssh key ("$keyval") appears to have only $bits bit(s) but at least
307 $Girocco::Config::min_key_length are required - please generate a longer key
312 not $gcgi->err_check;
315 sub keys_save {
316 my $self = shift;
318 $self->_sshkey_save;
321 sub keys_html_list {
322 my $self = shift;
323 my @keys = split(/\r?\n/, $self->{keys});
324 return '' if !@keys;
325 my $html = "<ol>\n";
326 my %types = ('ssh-dss' => 'DSA', 'ssh-rsa' => 'RSA');
327 my $line = 0;
328 foreach (@keys) {
329 ++$line;
330 my ($type, $bits, $fingerprint, $comment) = sshpub_validate($_);
331 next unless $type && $types{$type};
332 my $euser = CGI::escapeHTML(CGI::Util::escape($self->{name}));
333 $html .= "<li>$bits <tt>$fingerprint</tt> ($types{$type}) $comment";
334 $html .= "<br /><a target=\"_blank\" ".
335 "href=\"@{[url_path($Girocco::Config::webadmurl)]}/usercert.cgi/$euser/$line/".
336 $Girocco::Config::nickname."_${euser}_user_$line.pem\">".
337 "download https push user authentication certificate</a> <sup>".
338 "<a target=\"_blank\" href=\"@{[url_path($Girocco::Config::htmlurl)]}/httpspush.html\">".
339 "(learn more)</a></sup>"
340 if $type eq 'ssh-rsa' && $Girocco::Config::httpspushurl &&
341 $Girocco::Config::clientcert &&
342 $Girocco::Config::clientkey;
343 $html .= "</li>\n";
345 $html .= "</ol>\n";
346 return $html;
349 sub gen_auth {
350 my $self = shift;
351 my ($type) = @_;
352 $type = 'REPO' unless $type && $type =~ /^[A-Z]+$/;
354 $self->{authtype} = $type;
355 $self->{auth} = sha1_hex(time . $$ . rand() . $self->{keys});
356 $self->_sshkey_save;
357 $self->{auth};
360 sub del_auth {
361 my $self = shift;
363 delete $self->{auth};
364 delete $self->{authtype};
367 sub get_projects {
368 my $self = shift;
370 return @{$self->{projects}} if defined($self->{projects});
371 my @projects = filedb_atomic_grep(jailed_file('/etc/group'),
372 sub {
373 $_ = $_[0];
374 chomp;
375 my ($group, $users) = (split /:/)[0,3];
376 $group if $users && $users =~ /(^|,)\Q$self->{name}\E(,|$)/;
379 $self->{projects} = \@projects;
380 @{$self->{projects}};
383 sub conjure {
384 my $self = shift;
386 $self->_passwd_add;
387 $self->_sshkey_save;
390 sub remove {
391 my $self = shift;
393 require Girocco::Project;
394 foreach ($self->get_projects) {
395 if (Girocco::Project::does_exist($_)) {
396 my $project = Girocco::Project->load($_);
397 $project->update if $project->remove_user($self->{name});
401 $self->_passwd_remove;
404 ### static methods
406 sub valid_name {
407 $_ = $_[0];
408 /^[a-zA-Z0-9][a-zA-Z0-9+._-]*$/;
411 sub does_exist {
412 my ($name) = @_;
413 Girocco::User::valid_name($name) or die "tried to query for user with invalid name $name!";
414 (-e jailed_file("/etc/sshkeys/$name"));
417 sub resolve_uid {
418 my ($name) = @_;
419 $Girocco::Config::chrooted and undef; # TODO for ACLs within chroot
420 scalar(getpwnam($name));