Debian Codegraph @

contrib/ftpasswd

raw ◀ ▶
1 Debian patch touch this file
1 #!/usr/bin/env perl
2 # ---------------------------------------------------------------------------
3 # Copyright (C) 2000-2021 TJ Saunders <[email protected]>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
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 General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA.
18 #
19 # Based on MacGuyver's genuser.pl script, this script generates password
20 # files suitable for use with proftpd's AuthUserFile directive, in passwd(5)
21 # format, or AuthGroupFile, in group(5) format. The idea is somewhat similar
22 # to Apache's htpasswd program.
23 # ---------------------------------------------------------------------------
24
25 use strict;
26
27 use Fcntl qw(:flock);
28 use File::Basename qw(basename);
29 use Getopt::Long;
30
31 # turn off auto abbreviation
32 $Getopt::Long::auto_abbrev = 0;
33
34 my $program = basename($0);
35 my $default_passwd_file = "./ftpd.passwd";
36 my $default_group_file = "./ftpd.group";
37 my $shell_file = "/etc/shells";
•38 #my $default_cracklib_dict = "/usr/lib/cracklib_dict";
39 my $default_cracklib_dict = "/var/cache/cracklib";
40 my $cracklib_dict;
41 my $output_file;
42 my $version = "1.3.0";
43
44 my @data;
45
46 my %opts = ();
47 GetOptions(\%opts,
48 'add-member=s',
49 'change-home',
50 'change-password',
51 'delete-group',
52 'delete-member=s',
53 'delete-user',
54 'des',
55 'enable-group-passwd',
56 'file=s',
57 'F|force',
58 'gecos=s',
59 'gid=n',
60 'group',
61 'hash',
62 'h|help',
63 'home=s',
64 'l|lock',
65 'md5',
66 'm|member=s@',
67 'name=s',
68 'not-previous-password',
69 'not-system-password',
70 'passwd',
71 'sha256',
72 'sha512',
73 'shell=s',
74 'stdin',
75 'uid=n',
76 'u|unlock',
77 'use-cracklib:s',
78 'version',
79 );
80
81 usage() if (defined($opts{'h'}));
82
83 version() if (defined($opts{'version'}));
84
85 # Per Bug#4171, check if we are on a Linux system, AND it has the
86 # /proc/sys/crypto/fips_enabled file, AND that entry says that FIPS mode is
87 # enabled. If these conditions are met, then neither DES nor MD5 will work.
88 #
89 # If either --des or --md5 are specified, OR if no hash is specified, we
90 # need to check.
91 if ((defined($opts{'des'}) || defined($opts{'md5'}))) {
92 if (open(my $fh, "< /proc/sys/crypto/fips_enabled")) {
93 my $fips_enabled = <$fh>;
94 close($fh);
95
96 chomp($fips_enabled);
97 if ($fips_enabled) {
98 die "$program: FIPS mode enabled on your system (see /proc/sys/crypto/fips_enabled), thus --des and --md5 will not be supported. Use --sha256 or --sha512.\n"
99 }
100 }
101 }
102
103 # check if "use-cracklib" was given as an option, and whether a path
104 # to other dictionary files was given.
105 if (defined($opts{'use-cracklib'})) {
106
107 # make sure that Crypt::Cracklib is installed before trying to use
108 # it later
109 eval { require Crypt::Cracklib };
110 die "$program: --use-cracklib requires Crypt::Cracklib to be installed\n" if $@;
111
112 if ($opts{'use-cracklib'} ne "") {
113 $cracklib_dict = $opts{'use-cracklib'};
114
115 } else {
116 $cracklib_dict = $default_cracklib_dict;
117 }
118 }
119
120 # Make sure that the given --home path exists, and is a directory.
121 if (exists($opts{'home'})) {
122 my $path = $opts{'home'};
123 unless (-e $path) {
124 die "$program: --home $path does not exist\n";
125 }
126
127 unless (-d $path) {
128 die "$program: --home $path is not a directory\n";
129 }
130 }
131
132 # make sure that both passwd and group modes haven't been simultaneously
133 # requested
134 if ((exists($opts{'passwd'}) && exists($opts{'group'})) ||
135 (exists($opts{'passwd'}) && exists($opts{'hash'})) ||
136 (exists($opts{'group'}) && exists($opts{'hash'}))) {
137 die "$program: please use *one*: --passwd, --group, or --hash\n";
138
139 } elsif (defined($opts{'passwd'})) {
140
141 # determine to which file to write the passwd entry
142 if (defined($opts{'file'})) {
143 $output_file = $opts{'file'};
144 print STDOUT "$program: using alternate file: $output_file\n"
145
146 } else {
147 $output_file = $default_passwd_file;
148 }
149
150 # make sure that the required arguments are present
151 die "$program: --passwd: missing required argument: --name\n"
152 unless (defined($opts{'name'}));
153
154 # check for and handle the --delete-user option.
155 if (defined($opts{'delete-user'})) {
156 open_output_file();
157
158 my ($pass, $uid, $gid, $gecos, $home, $shell) = find_passwd_entry(name =>
159 $opts{'name'});
160
161 handle_passwd_entry(name => $opts{'name'}, uid => $uid, gid => $gid,
162 gecos => $gecos, home => $home, shell => $shell,
163 delete_user => $opts{'delete-user'});
164
165 close_output_file();
166
167 # done
168 exit 0;
169 }
170
171 # check for and handle the --lock option.
172 if (defined($opts{'l'})) {
173 open_output_file();
174
175 my ($pass, $uid, $gid, $gecos, $home, $shell) = find_passwd_entry(name =>
176 $opts{'name'});
177
178 my $new_passwd = $pass;
179
180 # If this password is already "locked", leave it alone
181 if ($new_passwd !~ /^!/) {
182 $new_passwd = '!' . $new_passwd;
183 }
184
185 handle_passwd_entry(name => $opts{'name'}, uid => $uid, gid => $gid,
186 gecos => $gecos, home => $home, shell => $shell,
187 new_passwd => $new_passwd);
188
189 close_output_file();
190
191 # done
192 exit 0;
193 }
194
195 # check for and handle the --unlock option.
196 if (defined($opts{'u'})) {
197 open_output_file();
198
199 my ($pass, $uid, $gid, $gecos, $home, $shell) = find_passwd_entry(name =>
200 $opts{'name'});
201
202 my $new_passwd = $pass;
203 $new_passwd =~ s/^!+//;
204
205 handle_passwd_entry(name => $opts{'name'}, uid => $uid, gid => $gid,
206 gecos => $gecos, home => $home, shell => $shell,
207 new_passwd => $new_passwd);
208
209 close_output_file();
210
211 # done
212 exit 0;
213 }
214
215 # now check for the --change-password option. If present, lookup
216 # the given name in the password file, and reuse all the information
217 # except for the password
218 if (defined($opts{'change-password'})) {
219 open_output_file();
220
221 my ($pass, $uid, $gid, $gecos, $home, $shell) = find_passwd_entry(name =>
222 $opts{'name'});
223
224 handle_passwd_entry(name => $opts{'name'}, uid => $uid, gid => $gid,
225 gecos => $gecos, home => $home, shell => $shell);
226
227 close_output_file();
228
229 # done
230 exit 0;
231 }
232
233 # Now check for the --change-home option. If present, lookup the given name
234 # in the password file, and reuse all the information except for the home.
235 if (defined($opts{'change-home'})) {
236 if (!defined($opts{'home'})) {
237 die "$program: --change-home requires use of --home\n";
238 }
239
240 open_output_file();
241
242 my ($pass, $uid, $gid, $gecos, $home, $shell) = find_passwd_entry(name =>
243 $opts{'name'});
244
245 # We trick this function into not prompting for a password by acting
246 # as if we are handling a new password.
247 handle_passwd_entry(name => $opts{'name'}, uid => $uid, gid => $gid,
248 gecos => $gecos, home => $opts{'home'}, shell => $shell,
249 new_passwd => $pass);
250
251 close_output_file();
252
253 # done
254 exit 0;
255 }
256
257 # check for the --not-system-password option. If present, make sure that
258 # a) the script is running with root privs, and b) perl on the system is
259 # such that getpwnam() will return the system password
260 if (defined($opts{'not-system-password'})) {
261 die "$program: must be user root for system password check\n"
262 unless ($> == 0);
263 }
264
265 die "$program: --passwd: missing required argument: --home\n"
266 unless (defined($opts{'home'}));
267
268 die "$program: --passwd: missing required argument: --shell\n"
269 unless (defined($opts{'shell'}));
270
271 die "$program: --passwd: missing required argument: --uid\n"
272 unless (defined($opts{'uid'}));
273
274 # As per Flying Hamster's suggestion, have $opts{'gid'} default to --uid
275 # if none are specified on the command-line via --gid
276 unless (defined($opts{'gid'})) {
277 $opts{'gid'} = $opts{'uid'};
278 warn "$program: --passwd: missing --gid argument: default gid set to uid\n";
279 }
280
281 open_output_file();
282
283 handle_passwd_entry(name => $opts{'name'}, uid => $opts{'uid'},
284 gid => $opts{'gid'}, gecos => $opts{'gecos'}, home => $opts{'home'},
285 shell => $opts{'shell'}, delete_user => $opts{'delete-user'});
286
287 close_output_file();
288
289 # NOTE: if this process is not running as root, then the file generated
290 # is not owned by root. Issue a warning reminding the user to make the
291 # generated file mode 0400, owned by root, before using it.
292
293 } elsif (defined($opts{'group'})) {
294
295 # determine to which file to write the group entry
296 if (defined($opts{'file'})) {
297 $output_file = $opts{'file'};
298 print STDOUT "$program: using alternate file: $output_file\n";
299
300 } else {
301 $output_file = $default_group_file;
302 }
303
304 # check for and handle the --delete-group option.
305 if (defined($opts{'delete-group'})) {
306 open_output_file();
307
308 handle_group_entry(
309 name => $opts{'name'},
310 delete_group => $opts{'delete-group'}
311 );
312
313 close_output_file();
314
315 # done
316 exit 0;
317 }
318
319 # make sure the required options are present
320 if (!defined($opts{'add-member'}) &&
321 !defined($opts{'delete-member'})) {
322 die "$program: --group: missing required argument: --gid\n"
323 unless (defined($opts{'gid'}));
324 }
325
326 die "$program: --group: missing required argument: --name\n"
327 unless (defined($opts{'name'}));
328
329 open_output_file();
330
331 handle_group_entry(
332 gid => $opts{'gid'},
333 members => $opts{'m'},
334 name => $opts{'name'},
335 add_user => $opts{'add-member'},
336 delete_group => $opts{'delete-group'},
337 delete_user => $opts{'delete-member'}
338 );
339
340 close_output_file();
341
342 } elsif (defined($opts{'hash'})) {
343 print STDOUT "$program: ", get_passwd(), "\n";
344
345 } else {
346 die "$program: missing required --passwd or --group\n$program: use $program --help for details on usage\n\n";
347 }
348
349 # done
350 exit 0;
351
352 # ----------------------------------------------------------------------------
353 sub check_shell {
354 my %args = @_;
355
356 my $shell = $args{'shell'};
357 my $result = 0;
358
359 # check the given shell against the list in /etc/shells. If not present
360 # there, issue a message recognizing this, and suggesting that
361 # RequireValidShell be set to off, and that any necessary PAM modules be
362 # adjusted.
363
364 unless (open(SHELLS, "< $shell_file")) {
365 warn "$program: unable to open $shell_file: $!\n";
366 warn "$program: skipping check of $shell_file\n";
367 return;
368 }
369
370 while(my $line = <SHELLS>) {
371 chomp($line);
372
373 if ($line eq $shell) {
374 $result = 1;
375 last;
376 }
377 }
378
379 close(SHELLS);
380
381 unless ($result) {
382 print STDOUT "\n$program: $shell is not among the valid system shells. Use of\n";
383 print STDOUT "$program: \"RequireValidShell off\" may be required, and the PAM\n";
384 print STDOUT "$program: module configuration may need to be adjusted.\n\n";
385 }
386
387 return $result;
388 }
389
390 # ----------------------------------------------------------------------------
391 sub close_output_file {
392 my %args = @_;
393
394 if (open(my $fh, "> $output_file")) {
395 if (flock($fh, LOCK_EX|LOCK_NB)) {
396 # flush the data to the file
397 foreach my $line (@data) {
398 print $fh "$line\n";
399 }
400
401 # set the permissions appropriately, ie 0440, before closing the file
402 unless (chmod(0440, $output_file)) {
403 flock($fh, LOCK_UN);
404 die("$program: unable to set permissions on $output_file: $!");
405 }
406
407 flock($fh, LOCK_UN);
408
409 unless (close($fh)) {
410 die("$program: unable to close $output_file: $!\n");
411 }
412
413 } else {
414 close($fh);
415 die("$program: unable to write $output_file: Locked (in use) by another process\n");
416 }
417
418 } else {
419 die("$program: unable to open $output_file: $!\n");
420 }
421 }
422
423 # ----------------------------------------------------------------------------
424 sub find_passwd_entry {
425 my %args = @_;
426
427 my $name = $args{'name'};
428 my ($pass, $uid, $gid, $gecos, $home, $shell);
429 my $found = 0;
430
431 # given a name, find the corresponding entry in the passwd file
432 foreach my $line (@data) {
433 next unless $line =~ /^$name:/;
434
435 my @fields = split(':', $line);
436
437 $pass = $fields[1];
438 $uid = $fields[2];
439 $gid = $fields[3];
440 $gecos = $fields[4];
441 $home = $fields[5];
442 $shell = $fields[6];
443
444 $found = 1;
445
446 last;
447 }
448
449 unless ($found) {
450 print STDOUT "$program: error: no such user $name in $output_file\n";
451
452 # Restore the file permissions.
453 unless (chmod(0440, $output_file)) {
454 print STDERR "$program: unable to set permissions on $output_file: $!";
455 }
456
457 exit 1;
458 }
459
460 return ($pass, $uid, $gid, $gecos, $home, $shell);
461 }
462
463 # ----------------------------------------------------------------------------
464 sub get_salt {
465 my $salt;
466
467 # The determination of with encryption algorithm to use is done via
468 # the salt. The format and nature of the salt is how crypt(3) knows
469 # how to do its thing. By default, generate a salt that triggers MD5.
470
471 if (defined($opts{'des'})) {
472 # DES salt
473 $salt = join '', ('.', '/', 0..9, 'A'..'Z', 'a'..'z')[rand 64, rand 64];
474
475 } elsif (defined($opts{'md5'})) {
476 # MD5 salt (16 characters)
477 $salt = join '', (0..9, 'A'..'Z', 'a'..'z')
478 [rand 62, rand 62, rand 62, rand 62,
479 rand 62, rand 62, rand 62, rand 62,
480 rand 62, rand 62, rand 62, rand 62,
481 rand 62, rand 62, rand 62, rand 62];
482 $salt = '$1$' . $salt;
483
484 } elsif (defined($opts{'sha512'})) {
485 # SHA-512 salt (16 characters)
486 $salt = join '', (0..9, 'A'..'Z', 'a'..'z')
487 [rand 62, rand 62, rand 62, rand 62,
488 rand 62, rand 62, rand 62, rand 62,
489 rand 62, rand 62, rand 62, rand 62,
490 rand 62, rand 62, rand 62, rand 62];
491 $salt = '$6$' . $salt;
492
493 } else {
494 # SHA-256 salt (16 characters)
495 $salt = join '', (0..9, 'A'..'Z', 'a'..'z')
496 [rand 62, rand 62, rand 62, rand 62,
497 rand 62, rand 62, rand 62, rand 62,
498 rand 62, rand 62, rand 62, rand 62,
499 rand 62, rand 62, rand 62, rand 62];
500 $salt = '$5$' . $salt;
501 }
502
503 return $salt;
504 }
505
506 # ----------------------------------------------------------------------------
507 sub get_passwd {
508 my %args = @_;
509 my $name = $args{'name'};
510 my ($passwd, $passwd2);
511
512 # If using a DES salt, print an informative message about the 8 character
513 # limit of relevant password characters.
514
515 if (defined($opts{'des'}) && !defined($opts{'stdin'})) {
516 print STDOUT "\nPlease be aware that only the first 8 characters of a DES password are\nrelevant. Use the --md5, --sha256, or --sha512 options as they do not have\nthis limitation.\n";
517 }
518
519 if (defined($opts{'stdin'})) {
520
521 # simply read in the password from stdin, as from a script
522 chomp($passwd = <STDIN>);
523
524 } else {
525
526 # Install a SIGINT handler, for cases where Ctrl-C may be used to abort
527 # the prompt.
528 $SIG{INT} = sub {
529 # Restore the file permissions.
530 unless (chmod(0440, $output_file)) {
531 print STDERR "$program: unable to set permissions on $output_file: $!";
532 }
533
534 # Restore the terminal echo behavior, too.
535 system "stty echo";
536
537 exit 1;
538 };
539
540 # Prompt for the password to be used
541 system "stty -echo";
542 print STDOUT "\nPassword: ";
543
544 # Open the tty for reading (is this portable?)
545 open(TTY, "/dev/tty") or die "$program: unable to open /dev/tty: $!\n";
546 chomp($passwd = <TTY>);
547 print STDOUT "\n";
548 system "stty echo";
549
550 # Prompt again, to make sure the user typed in the password correctly
551 system "stty -echo";
552 print STDOUT "Re-type password: ";
553 chomp($passwd2 = <TTY>);
554 print STDOUT "\n\n";
555 system "stty echo";
556 close(TTY);
557
558 # Restore default SIGINT handling
559 $SIG{INT} = 'DEFAULT';
560
561 if ($passwd2 ne $passwd) {
562 print STDOUT "Passwords do not match. Please try again.\n";
563 return get_passwd(name => $name);
564 }
565 }
566
567 if (defined($name) && defined($opts{'change-password'})) {
568
569 # retrieve the user's current password from the file and compare
570 my ($curpasswd, @junk) = find_passwd_entry(name => $name);
571
572 my $hash = crypt($passwd, $curpasswd);
573
574 if ($hash eq $curpasswd) {
575 if (defined($opts{'stdin'})) {
576 # cannot prompt again if automated. Simply print an error message
577 # and exit.
578 print STDOUT "$program: error: password matches current password\n";
579
580 # Restore the file permissions.
581 unless (chmod(0440, $output_file)) {
582 print STDERR "$program: unable to set permissions on $output_file: $!";
583 }
584
585 exit 2;
586
587 } else {
588 print STDOUT "Please use a password that is different from your current password.\n";
589 return get_passwd(name => $name);
590 }
591 }
592 }
593
594 if (defined($name) && defined($opts{'not-previous-password'})) {
595 # retrieve the user's current passwd and compare
596 my ($currpasswd) = find_passwd_entry(name => $name);
597
598 my $hash = crypt($passwd, $currpasswd);
599
600 if (($hash && $currpasswd) && $hash eq $currpasswd) {
601 if (defined($opts{'stdin'})) {
602
603 # cannot prompt again if automated. Simply print an error message
604 # and exit.
605 print STDOUT "$program: error: password matches previous password\n";
606
607 # Restore the file permissions.
608 unless (chmod(0440, $output_file)) {
609 print STDERR "$program: unable to set permissions on $output_file: $!";
610 }
611
612 exit 4;
613
614 } else {
615 print STDOUT "Please use a password that is different from your previous password.\n";
616 return get_passwd(name => $name);
617 }
618 }
619 }
620
621 if (defined($name) && defined($opts{'not-system-password'})) {
622 # retrieve the user's system passwd (from /etc/shadow) and compare
623 my $syspasswd = get_syspasswd(user => $name);
624
625 my $hash = crypt($passwd, $syspasswd);
626
627 if (($hash && $syspasswd) && $hash eq $syspasswd) {
628 if (defined($opts{'stdin'})) {
629 # Cannot prompt again if automated. Simply print an error message
630 # and exit.
631 print STDOUT "$program: error: password matches system password\n";
632
633 # Restore the file permissions.
634 unless (chmod(0440, $output_file)) {
635 print STDERR "$program: unable to set permissions on $output_file: $!";
636 }
637
638 exit 4;
639
640 } else {
641 print STDOUT "Please use a password that is different from your system password.\n";
642 return get_passwd(name => $name);
643 }
644 }
645 }
646
647 return "" if ($args{'allow_blank'} and $passwd eq "");
648
649 # check for BAD passwords, BLANK passwords, etc, if requested
650 if (defined($opts{'use-cracklib'})) {
651 require Crypt::Cracklib;
652 if (!Crypt::Cracklib::check($passwd, $cracklib_dict)) {
653 print STDOUT "Bad password: ", Crypt::Cracklib::fascist_check($passwd,
654 $cracklib_dict), "\n";
655 return get_passwd(name => $name);
656 }
657 }
658
659 my $salt = get_salt();
660
661 my $hash = crypt($passwd, $salt);
662
663 # Check that the crypt() implementation properly supports use of the MD5
664 # (or other non-DES algorithm), if specified.
665 if (!defined($opts{'des'})) {
666 if (defined($opts{'md5'})) {
667 # if the first three characters of the hash are not "$1$", the crypt()
668 # implementation doesn't support MD5. Some crypt()s will happily use
669 # "$1" as a salt even though this is not a valid DES salt. Humf.
670 #
671 # Perl doesn't treat strings as arrays of characters, so extracting the
672 # first three characters is a little more convoluted (I'm accustomed to
673 # C's strncmp(3) for this now).
674
675 my @string = split('', $hash);
676 my $prefix = $string[0] . $string[1] . $string[2];
677
678 if ($prefix ne '$1$') {
679 print STDOUT "You requested MD5 passwords but your system does not support it. Defaulting to DES passwords.\n\n";
680 }
681
682 } elsif (defined($opts{'sha256'})) {
683 # if the first three characters of the hash are not "$5$", the crypt()
684 # implementation doesn't support SHA-256. Some crypt()s will happily use
685 # "$5" as a salt even though this is not a valid DES salt. Humf.
686 #
687 # Perl doesn't treat strings as arrays of characters, so extracting the
688 # first three characters is a little more convoluted (I'm accustomed to
689 # C's strncmp(3) for this now).
690
691 my @string = split('', $hash);
692 my $prefix = $string[0] . $string[1] . $string[2];
693
694 if ($prefix ne '$5$') {
695 print STDOUT "You requested SHA-256 passwords but your system does not support it. Defaulting to DES passwords.\n\n";
696 }
697
698 } elsif (defined($opts{'sha512'})) {
699 # if the first three characters of the hash are not "$6$", the crypt()
700 # implementation doesn't support SHA-512. Some crypt()s will happily use
701 # "$6" as a salt even though this is not a valid DES salt. Humf.
702 #
703 # Perl doesn't treat strings as arrays of characters, so extracting the
704 # first three characters is a little more convoluted (I'm accustomed to
705 # C's strncmp(3) for this now).
706
707 my @string = split('', $hash);
708 my $prefix = $string[0] . $string[1] . $string[2];
709
710 if ($prefix ne '$6$') {
711 print STDOUT "You requested SHA-512 passwords but your system does not support it. Defaulting to DES passwords.\n\n";
712 }
713 }
714 }
715
716 return $hash;
717 }
718
719 # ----------------------------------------------------------------------------
720 sub get_syspasswd {
721 my %args = @_;
722
723 my $user = $args{'user'};
724
725 # test the shadow password support on this system. Some systems, such
726 # as the BSDs, use "transparent shadowing", where the real passwd will
727 # be returned via getpwnam() only if the process has root privs (effective
728 # UID of zero). That check has already been performed. However, other
729 # systems still may not return the password via getpwnam() (such as Linux).
730 # These other systems use a shadow password library of functions, and require
731 # other work to retrieve the password. On these systems, the retrieved
732 # password will be "x".
733
734 my $syspasswd = (getpwnam($user))[1];
735
736 if ($syspasswd eq "" || $syspasswd eq "x") {
737
738 # do the retrieval the hard way: open up /etc/shadow and iterate
739 # through each line. Yuck. *sigh*. Thanks to Micah Anderson
740 # for working out this issue.
741
742 open(SHADOW, "< /etc/shadow") or
743 die "$program: unable to access shadow file: $!\n";
744
745 while (chomp(my $line = <SHADOW>)) {
746 next unless $line =~ /^$user/;
747 $syspasswd = (split(':', $line))[1];
748 last;
749 }
750 close(SHADOW);
751
752 # if the password is still "x", you have problems
753 if ($syspasswd eq "x") {
754 die "$program: unable to retrieve shadow password.\nContact your system
755 administrator.\n";
756 }
757 }
758
759 return $syspasswd;
760 }
761
762 # ----------------------------------------------------------------------------
763 sub handle_group_entry {
764 my %args = @_;
765
766 my $gid = $args{'gid'};
767 my $name = $args{'name'};
768 my $delete_group = $args{'delete_group'};
769 my $delete_user = $args{'delete_user'};
770 my $add_user = $args{'add_user'};
771 my $passwd;
772
773 my $members = "";
774 $members = join(',', @{$args{'members'}}) if (defined($args{'members'}));
775
776 # check to see whether we should update the fields for this group (because
777 # it already exists), or to create a new entry
778
779 my $found = 0;
780 my $index = 0;
781 for ($index = 0; $index <= $#data; $index++) {
782 my @entry = split(':', $data[$index]);
783
784 if ($name eq $entry[0]) {
785 $found = 1;
786
787 # If we have not been given an explicit password, reuse the existing one.
788 $passwd = $entry[1] unless $passwd;
789
790 # If we have not been given an explicit GID, reuse the existing one.
791 $gid = $entry[2] unless $gid;
792
793 # If we have not been given explicit members, reuse the existing ones.
794 $members = $entry[3] if $members eq '';
795
796 last;
797 }
798 }
799
800 unless ($found) {
801 print STDOUT "$program: creating group entry for group $name\n";
802
803 } else {
804 print STDOUT "$program: updating group entry for group $name\n";
805 }
806
807 # if present, add the members given to the group. If none, just leave that
808 # field blank
809
810 # prompt for the group password, if requested
811 if (defined($opts{'enable-group-passwd'})) {
812 $passwd = get_passwd(name => $name, allow_blank => 1);
813
814 } else {
815 $passwd = "x";
816 }
817
818 # remove the entry to be updated
819 splice(@data, $index, 1);
820
821 if ($delete_group) {
822 print STDOUT "$program: entry deleted\n";
823 return;
824 }
825
826 if ($delete_user) {
827 $members =~ s/$delete_user//g;
828 $members =~ s/,,/,/g;
829 $members =~ s/^,//g;
830 $members =~ s/,$//g;
831 }
832
833 if ($add_user) {
834 if (length($members) > 0) {
835 $members .= ",$add_user";
836
837 } else {
838 $members = $add_user;
839 }
840 }
841
842 # Ensure that we have a sorted list of unique members
843 my $uniq_members = { map { $_ => 1 } split(',', $members) };
844 my $names = join(',', sort { $a <=> $b } keys(%$uniq_members));
845
846 # format: $name:$passwd:$gid:$members
847 push(@data, "$name:$passwd:$gid:$names");
848
849 # always sort by GIDs before printing out the file
850 @data = map { $_->[0] }
851 sort {
852 $a->[3] <=> $b->[3]
853 }
854 map { [ $_, (split /:/)[0, 1, 2, 3] ] }
855 @data;
856
857 if ($delete_group) {
858 print STDOUT "$program: entry deleted\n";
859
860 } elsif ($found) {
861 print STDOUT "$program: entry updated\n";
862
863 } else {
864 print STDOUT "$program: entry created\n";
865 }
866 }
867
868 # ----------------------------------------------------------------------------
869 sub handle_passwd_entry {
870 my %args = @_;
871
872 my $name = $args{'name'};
873 my $uid = $args{'uid'};
874 my $gid = $args{'gid'};
875 my $gecos = $args{'gecos'};
876 my $home = $args{'home'};
877 my $shell = $args{'shell'};
878 my $delete_user = $args{'delete_user'};
879 my $new_passwd = $args{'new_passwd'};
880
881 # Trim any trailing slashes in $home.
882 $home =~ s/(.*)\/$/$1/ if ($home =~ /\/$/);
883
884 # Make sure the given home directory is NOT a relative path (what a
885 # horrible idea).
886
887 unless ($home =~ /^\//) {
888 print STDOUT "$program: error: relative path given for home directory\n";
889 exit 8;
890 }
891
892 # check to see whether we should update the fields for this user (because
893 # they already exist), or create a new entry
894
895 my $found = 0;
896 my $index = 0;
897 for ($index = 0; $index <= $#data; $index++) {
898 my @entry = split(':', $data[$index]);
899
900 if ($name eq $entry[0]) {
901 $found = 1;
902 last;
903 }
904 }
905
906 unless ($found) {
907 print STDOUT "$program: creating passwd entry for user $name\n";
908
909 } else {
910 print STDOUT "$program: updating passwd entry for user $name\n";
911 }
912
913 my $passwd;
914
915 if (!$delete_user) {
916 if (!$new_passwd) {
917 # check the requested shell against the list in /etc/shells
918 check_shell(shell => $shell);
919
920 # prompt the user for the password
921 $passwd = get_passwd(name => $name);
922
923 } else {
924 $passwd = $new_passwd;
925 }
926 }
927
928 # remove the entry to be updated
929 splice(@data, $index, 1);
930
931 if ($delete_user) {
932 print STDOUT "$program: entry deleted\n";
933 return;
934 }
935
936 # format: $name:$passwd:$uid:$gid:$gecos:$home:$shell
937 push(@data, "$name:$passwd:$uid:$gid:$gecos:$home:$shell");
938
939 # always sort by UIDs before printing out the file
940 @data = map { $_->[0] }
941 sort {
942 $a->[3] <=> $b->[3]
943 }
944 map { [ $_, (split /:/)[0, 1, 2, 3, 4, 5, 6] ] }
945 @data;
946
947 if ($delete_user) {
948 print STDOUT "$program: entry deleted\n";
949
950 } elsif ($found) {
951 print STDOUT "$program: entry updated\n";
952
953 } else {
954 print STDOUT "$program: entry created\n";
955 }
956 }
957
958 # ----------------------------------------------------------------------------
959 sub open_output_file {
960 my %args = @_;
961
962 # open $output_file, paying attention to the --force command-line option
963 # If the file already exists, slurp up its contents for later updating.
964
965 if (-f $output_file) {
966 # make sure we can write/update the file first
967 unless (chmod(0644, $output_file)) {
968 die "$program: unable to set permissions on $output_file to 0644: $!\n";
969 }
970
971 if (open(my $fh, "< $output_file")) {
972 if (flock($fh, LOCK_SH|LOCK_NB)) {
973 chomp(@data = <$fh>);
974 flock($fh, LOCK_UN);
975 close($fh);
976
977 } else {
978 close($fh);
979 die("$program: unable to read $output_file: Locked (in use) by another process\n");
980 }
981
982
983 } else {
984 die("$program: unable to open $output_file: $!\n");
985 }
986 }
987
988 # if the --force option was given, just zero out any data that might have
989 # been read in, effectively erasing whatever contents there were. A new
990 # file is generated, anyway -- it's just a question of what data goes into
991 # it
992
993 @data = () if (defined($opts{'F'}));
994 }
995
996 # ----------------------------------------------------------------------------
997 sub usage {
998
999 print STDOUT <<END_OF_USAGE;
1000
1001 usage: $program [--help] [--hash|--group|--passwd]
1002
1003 REQUIRED: --passwd, --group, or --hash. These specify whether $program is to
1004 operate on a passwd(5) format file, on a group(5) format file, or simply
1005 to generate a password hash, respectively.
1006
1007 If used with --passwd, $program creates a file in the passwd(5) format,
1008 suitable for use with proftpd's AuthUserFile configuration directive.
1009 You will be prompted for the password to use of the user, which will be
1010 encrypted, and written out as the encrypted string. New entries are
1011 appended to the file by default.
1012
1013 By default, using --passwd will write output to "$default_passwd_file".
1014
1015 Error exit values:
1016
1017 To make it easier for wrapper scripts to interact with $program, $program
1018 will exit with the following error values for the reasons described:
1019
1020 1 no such user
1021 2 password matches current password
1022 4 password matches system password
1023 8 relative path given for home directory
1024
1025 Options:
1026
1027 --file Write output to specified file, rather than "$default_passwd_file".
1028
1029 -F If the file to be used already exists, delete it and write a
1030 --force new one. By default, new entries will be appended to the file.
1031
1032 --gecos Descriptive string for the given user (usually the user's
1033 full name).
1034
1035 --gid Primary group ID for this user (optional, will default to
1036 given --uid value if absent).
1037
1038 -h Displays this message.
1039 --help
1040
1041 --home Home directory for the user (required).
1042
1043 --des Use the DES algorithm for encrypting passwords. The default
1044 is the MD5 algorithm.
1045
1046 --md5 Use the MD5 algorithm for encrypting passwords. This is the
1047 default.
1048
1049 --name Name of the user account (required). If the name does not
1050 exist in the specified output-file, an entry will be created
1051 for her. Otherwise, the given fields will be updated.
1052
1053 --shell Shell for the user (required). Recommended: /bin/false
1054
1055 --uid Numerical user ID (required)
1056
1057 --change-home
1058
1059 Update only the home directory field for a user. This option
1060 requires that the --name and --passwd options be used, but no
1061 others.
1062
1063 --change-password
1064
1065 Update only the password field for a user. This option
1066 requires that the --name and --passwd options be used, but
1067 no others. This also double-checks the given password against
1068 the user's current password in the existing passwd file, and
1069 requests that a new password be given if the entered password
1070 is the same as the current password.
1071
1072 --delete-user
1073
1074 Remove the entry for the given user name from the file.
1075
1076 -l Lock the password of the named account. This option disables a
1077 --lock password by changing it to a value which matches no possible
1078 encrypted value (it adds a '!' at the beginning of the
1079 password).
1080
1081 --not-previous-password
1082
1083 Double-checks the given password against the previous password
1084 for the user, and requests that a new password be given if
1085 the entered password is the same as the previous password.
1086
1087 --not-system-password
1088
1089 Double-checks the given password against the system password
1090 for the user, and requests that a new password be given if
1091 the entered password is the same as the system password. This
1092 helps to enforce different passwords for different types of
1093 access.
1094
1095 --sha256 Use the SHA-256 algorithm for encrypting passwords.
1096
1097 --sha512 Use the SHA-512 algorithm for encrypting passwords.
1098
1099 --stdin
1100 Read the password directly from standard in rather than
1101 prompting for it. This is useful for writing scripts that
1102 automate use of $program.
1103
1104 -u Unlock the password of the named account. This option
1105 --unlock re-enables a password by changing the password back to its
1106 previous value (to the value before using the -l option).
1107
1108 --use-cracklib
1109
1110 Causes $program to use Alec Muffet's cracklib routines in
1111 order to determine and prevent the use of bad or weak
1112 passwords. The optional path to this option specifies
1113 the path to the dictionary files to use -- default path
1114 is "$default_cracklib_dict". This requires the Perl
1115 Crypt::Cracklib module to be installed on your system.
1116
1117 --version
1118 Displays the version of $program.
1119
1120 If used with --group, $program creates a file in the group(5) format,
1121 suitable for use with proftpd's AuthGroupFile configuration directive.
1122
1123 By default, using --group will write output to "$default_group_file".
1124
1125 Options:
1126
1127 --add-member
1128
1129 Add the named member to the given group name from the file.
1130 Example:
1131
1132 \$ ftpasswd --group --file=... --name=ftpd --add-member=bob
1133
1134 --delete-group
1135
1136 Remove the entry for the given group name from the file.
1137
1138 --enable-group-passwd
1139
1140 Prompt for a group password. This is disabled by default,
1141 as group passwords are not usually a good idea at all.
1142
1143 --file Write output to specified file, rather than "$default_group_file".
1144
1145 -F If the file be used already exists, delete it and write a new
1146 --force one. By default, new entries will be appended to the file.
1147
1148 --gid Numerical group ID (required).
1149
1150 -h
1151 --help Displays this message.
1152
1153 -m
1154 --member User name to be a member of the group. This argument may be
1155 used multiple times to specify the full list of users to be
1156 members of this group.
1157
1158 --des Use the DES algorithm for encrypting passwords. The default
1159 is the SHA256 algorithm.
1160
1161 --md5 Use the MD5 algorithm for encrypting passwords.
1162
1163 --name Name of the group (required). If the name does not exist in
1164 the specified output-file, an entry will be created for them.
1165 Otherwise, the given fields will be updated.
1166
1167 --sha256 Use the SHA-256 algorithm for encrypting passwords. This is the
1168 default.
1169
1170 --sha512 Use the SHA-512 algorithm for encrypting passwords.
1171
1172 --stdin
1173 Read the password directly from standard in rather than
1174 prompting for it. This is useful for writing scripts that
1175 automate use of $program.
1176
1177 --use-cracklib
1178
1179 Causes $program to use Alec Muffet's cracklib routines in
1180 order to determine and prevent the use of bad or weak
1181 passwords. The optional path to this option specifies
1182 the path to the dictionary files to use -- default path
1183 is "$default_cracklib_dict". This requires the Perl
1184 Crypt::Cracklib module to be installed on your system.
1185
1186 --version
1187 Displays the version of $program.
1188
1189 If used with --hash, $program generates a hash of a password, as would
1190 appear in an AuthUserFile. The hash is written to standard out.
1191 This hash is suitable for use with proftpd's UserPassword directive.
1192
1193 Options:
1194
1195 --des Use the DES algorithm for encrypting passwords. The default
1196 is the MD5 algorithm.
1197
1198 --md5 Use the MD5 algorithm for encrypting passwords. This is the
1199 default.
1200
1201 --sha256 Use the SHA-256 algorithm for encrypting passwords.
1202
1203 --sha512 Use the SHA-512 algorithm for encrypting passwords.
1204
1205 --stdin
1206 Read the password directly from standard in rather than
1207 prompting for it. This is useful for writing scripts that
1208 automate use of $program.
1209
1210 --use-cracklib
1211
1212 Causes $program to use Alec Muffet's cracklib routines in
1213 order to determine and prevent the use of bad or weak
1214 passwords. The optional path to this option specifies
1215 the path to the dictionary files to use -- default path
1216 is "$default_cracklib_dict". This requires the Perl
1217 Crypt::Cracklib module to be installed on your system.
1218
1219 --version
1220 Displays the version of $program.
1221
1222 END_OF_USAGE
1223
1224 exit 0;
1225 }
1226
1227 # ---------------------------------------------------------------------------
1228 sub version {
1229 print STDOUT "$version\n";
1230
1231 exit 0;
1232 }
1233
1234 # ---------------------------------------------------------------------------
1235