]> granicus.if.org Git - shadow/blob - src/chgpasswd.c
* src/chgpasswd.c: Add splint annotations.
[shadow] / src / chgpasswd.c
1 /*
2  * Copyright (c) 1990 - 1994, Julianne Frances Haugh
3  * Copyright (c) 2006       , Tomasz Kłoczko
4  * Copyright (c) 2006       , Jonas Meurer
5  * Copyright (c) 2007 - 2011, Nicolas François
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. The name of the copyright holders or contributors may not be used to
17  *    endorse or promote products derived from this software without
18  *    specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
23  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT
24  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31  */
32
33 #include <config.h>
34
35 #ident "$Id$"
36
37 #include <fcntl.h>
38 #include <getopt.h>
39 #include <pwd.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #ifdef ACCT_TOOLS_SETUID
43 #ifdef USE_PAM
44 #include "pam_defs.h"
45 #endif                          /* USE_PAM */
46 #endif                          /* ACCT_TOOLS_SETUID */
47 #include "defines.h"
48 #include "nscd.h"
49 #include "prototypes.h"
50 #include "groupio.h"
51 #ifdef  SHADOWGRP
52 #include "sgroupio.h"
53 #endif
54 /*@-exitarg@*/
55 #include "exitcodes.h"
56
57 /*
58  * Global variables
59  */
60 const char *Prog;
61 static bool cflg   = false;
62 static bool eflg   = false;
63 static bool md5flg = false;
64 #ifdef USE_SHA_CRYPT
65 static bool sflg   = false;
66 #endif
67
68 static /*@null@*//*@observer@*/const char *crypt_method = NULL;
69 #ifdef USE_SHA_CRYPT
70 static long sha_rounds = 5000;
71 #endif
72
73 #ifdef SHADOWGRP
74 static bool is_shadow_grp;
75 static bool sgr_locked = false;
76 #endif
77 static bool gr_locked = false;
78
79 /* local function prototypes */
80 static void fail_exit (int code);
81 static /*@noreturn@*/void usage (int status);
82 static void process_flags (int argc, char **argv);
83 static void check_flags (void);
84 static void check_perms (void);
85 static void open_files (void);
86 static void close_files (void);
87
88 /*
89  * fail_exit - exit with a failure code after unlocking the files
90  */
91 static void fail_exit (int code)
92 {
93         if (gr_locked) {
94                 if (gr_unlock () == 0) {
95                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
96                         SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
97                         /* continue */
98                 }
99         }
100
101 #ifdef  SHADOWGRP
102         if (sgr_locked) {
103                 if (sgr_unlock () == 0) {
104                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
105                         SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
106                         /* continue */
107                 }
108         }
109 #endif
110
111         exit (code);
112 }
113
114 /*
115  * usage - display usage message and exit
116  */
117 static /*@noreturn@*/void usage (int status)
118 {
119         FILE *usageout = (E_SUCCESS != status) ? stderr : stdout;
120         (void) fprintf (usageout,
121                         _("Usage: %s [options]\n"
122                           "\n"
123                           "Options:\n"),
124                         Prog);
125         (void) fprintf (usageout,
126                         _("  -c, --crypt-method <METHOD>   the crypt method (one of %s)\n"),
127 #ifndef USE_SHA_CRYPT
128                         "NONE DES MD5"
129 #else                           /* USE_SHA_CRYPT */
130                         "NONE DES MD5 SHA256 SHA512"
131 #endif                          /* USE_SHA_CRYPT */
132                        );
133         (void) fputs (_("  -e, --encrypted               supplied passwords are encrypted\n"), usageout);
134         (void) fputs (_("  -h, --help                    display this help message and exit\n"), usageout);
135         (void) fputs (_("  -m, --md5                     encrypt the clear text password using\n"
136                         "                                the MD5 algorithm\n"),
137                       usageout);
138 #ifdef USE_SHA_CRYPT
139         (void) fputs (_("  -s, --sha-rounds              number of SHA rounds for the SHA*\n"
140                         "                                crypt algorithms\n"),
141                       usageout);
142 #endif                          /* USE_SHA_CRYPT */
143         (void) fputs ("\n", usageout);
144
145         exit (status);
146 }
147
148 /*
149  * process_flags - parse the command line options
150  *
151  *      It will not return if an error is encountered.
152  */
153 static void process_flags (int argc, char **argv)
154 {
155         int option_index = 0;
156         int c;
157         static struct option long_options[] = {
158                 {"crypt-method", required_argument, NULL, 'c'},
159                 {"encrypted", no_argument, NULL, 'e'},
160                 {"help", no_argument, NULL, 'h'},
161                 {"md5", no_argument, NULL, 'm'},
162 #ifdef USE_SHA_CRYPT
163                 {"sha-rounds", required_argument, NULL, 's'},
164 #endif
165                 {NULL, 0, NULL, '\0'}
166         };
167
168         while ((c = getopt_long (argc, argv,
169 #ifdef USE_SHA_CRYPT
170                                  "c:ehms:",
171 #else
172                                  "c:ehm",
173 #endif
174                                  long_options, &option_index)) != -1) {
175                 switch (c) {
176                 case 'c':
177                         cflg = true;
178                         crypt_method = optarg;
179                         break;
180                 case 'e':
181                         eflg = true;
182                         break;
183                 case 'h':
184                         usage (E_SUCCESS);
185                         /*@notreached@*/break;
186                 case 'm':
187                         md5flg = true;
188                         break;
189 #ifdef USE_SHA_CRYPT
190                 case 's':
191                         sflg = true;
192                         if (getlong(optarg, &sha_rounds) == 0) {
193                                 fprintf (stderr,
194                                          _("%s: invalid numeric argument '%s'\n"),
195                                          Prog, optarg);
196                                 usage (E_USAGE);
197                         }
198                         break;
199 #endif
200                 default:
201                         usage (E_USAGE);
202                         /*@notreached@*/break;
203                 }
204         }
205
206         /* validate options */
207         check_flags ();
208 }
209
210 /*
211  * check_flags - check flags and parameters consistency
212  *
213  *      It will not return if an error is encountered.
214  */
215 static void check_flags (void)
216 {
217 #ifdef USE_SHA_CRYPT
218         if (sflg && !cflg) {
219                 fprintf (stderr,
220                          _("%s: %s flag is only allowed with the %s flag\n"),
221                          Prog, "-s", "-c");
222                 usage (E_USAGE);
223         }
224 #endif
225
226         if ((eflg && (md5flg || cflg)) ||
227             (md5flg && cflg)) {
228                 fprintf (stderr,
229                          _("%s: the -c, -e, and -m flags are exclusive\n"),
230                          Prog);
231                 usage (E_USAGE);
232         }
233
234         if (cflg) {
235                 if (   (0 != strcmp (crypt_method, "DES"))
236                     && (0 != strcmp (crypt_method, "MD5"))
237                     && (0 != strcmp (crypt_method, "NONE"))
238 #ifdef USE_SHA_CRYPT
239                     && (0 != strcmp (crypt_method, "SHA256"))
240                     && (0 != strcmp (crypt_method, "SHA512"))
241 #endif
242                     ) {
243                         fprintf (stderr,
244                                  _("%s: unsupported crypt method: %s\n"),
245                                  Prog, crypt_method);
246                         usage (E_USAGE);
247                 }
248         }
249 }
250
251 /*
252  * check_perms - check if the caller is allowed to add a group
253  *
254  *      With PAM support, the setuid bit can be set on chgpasswd to allow
255  *      non-root users to groups.
256  *      Without PAM support, only users who can write in the group databases
257  *      can add groups.
258  *
259  *      It will not return if the user is not allowed.
260  */
261 static void check_perms (void)
262 {
263 #ifdef ACCT_TOOLS_SETUID
264 #ifdef USE_PAM
265         pam_handle_t *pamh = NULL;
266         int retval;
267         struct passwd *pampw;
268
269         pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
270         if (NULL == pampw) {
271                 fprintf (stderr,
272                          _("%s: Cannot determine your user name.\n"),
273                          Prog);
274                 exit (1);
275         }
276
277         retval = pam_start ("chgpasswd", pampw->pw_name, &conv, &pamh);
278
279         if (PAM_SUCCESS == retval) {
280                 retval = pam_authenticate (pamh, 0);
281         }
282
283         if (PAM_SUCCESS == retval) {
284                 retval = pam_acct_mgmt (pamh, 0);
285         }
286
287         if (NULL != pamh) {
288                 (void) pam_end (pamh, retval);
289         }
290         if (PAM_SUCCESS != retval) {
291                 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
292                 exit (1);
293         }
294 #endif                          /* USE_PAM */
295 #endif                          /* ACCT_TOOLS_SETUID */
296 }
297
298 /*
299  * open_files - lock and open the group databases
300  */
301 static void open_files (void)
302 {
303         /*
304          * Lock the group file and open it for reading and writing. This will
305          * bring all of the entries into memory where they may be updated.
306          */
307         if (gr_lock () == 0) {
308                 fprintf (stderr,
309                          _("%s: cannot lock %s; try again later.\n"),
310                          Prog, gr_dbname ());
311                 fail_exit (1);
312         }
313         gr_locked = true;
314         if (gr_open (O_RDWR) == 0) {
315                 fprintf (stderr,
316                          _("%s: cannot open %s\n"), Prog, gr_dbname ());
317                 fail_exit (1);
318         }
319
320 #ifdef SHADOWGRP
321         /* Do the same for the shadowed database, if it exist */
322         if (is_shadow_grp) {
323                 if (sgr_lock () == 0) {
324                         fprintf (stderr,
325                                  _("%s: cannot lock %s; try again later.\n"),
326                                  Prog, sgr_dbname ());
327                         fail_exit (1);
328                 }
329                 sgr_locked = true;
330                 if (sgr_open (O_RDWR) == 0) {
331                         fprintf (stderr, _("%s: cannot open %s\n"),
332                                  Prog, sgr_dbname ());
333                         fail_exit (1);
334                 }
335         }
336 #endif
337 }
338
339 /*
340  * close_files - close and unlock the group databases
341  */
342 static void close_files (void)
343 {
344 #ifdef SHADOWGRP
345         if (is_shadow_grp) {
346                 if (sgr_close () == 0) {
347                         fprintf (stderr,
348                                  _("%s: failure while writing changes to %s\n"),
349                                  Prog, sgr_dbname ());
350                         SYSLOG ((LOG_ERR, "failure while writing changes to %s", sgr_dbname ()));
351                         fail_exit (1);
352                 }
353                 if (sgr_unlock () == 0) {
354                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
355                         SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
356                         /* continue */
357                 }
358                 sgr_locked = false;
359         }
360 #endif
361
362         if (gr_close () == 0) {
363                 fprintf (stderr,
364                          _("%s: failure while writing changes to %s\n"),
365                          Prog, gr_dbname ());
366                 SYSLOG ((LOG_ERR, "failure while writing changes to %s", gr_dbname ()));
367                 fail_exit (1);
368         }
369         if (gr_unlock () == 0) {
370                 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
371                 SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
372                 /* continue */
373         }
374         gr_locked = false;
375 }
376
377 int main (int argc, char **argv)
378 {
379         char buf[BUFSIZ];
380         char *name;
381         char *newpwd;
382         char *cp;
383
384 #ifdef  SHADOWGRP
385         const struct sgrp *sg;
386         struct sgrp newsg;
387 #endif
388
389         const struct group *gr;
390         struct group newgr;
391         int errors = 0;
392         int line = 0;
393
394         Prog = Basename (argv[0]);
395
396         (void) setlocale (LC_ALL, "");
397         (void) bindtextdomain (PACKAGE, LOCALEDIR);
398         (void) textdomain (PACKAGE);
399
400         process_flags (argc, argv);
401
402         OPENLOG ("chgpasswd");
403
404         check_perms ();
405
406 #ifdef SHADOWGRP
407         is_shadow_grp = sgr_file_present ();
408 #endif
409
410         open_files ();
411
412         /*
413          * Read each line, separating the group name from the password. The
414          * group entry for each group will be looked up in the appropriate
415          * file (gshadow or group) and the password changed.
416          */
417         while (fgets (buf, (int) sizeof buf, stdin) != (char *) 0) {
418                 line++;
419                 cp = strrchr (buf, '\n');
420                 if (NULL != cp) {
421                         *cp = '\0';
422                 } else {
423                         fprintf (stderr, _("%s: line %d: line too long\n"),
424                                  Prog, line);
425                         errors++;
426                         continue;
427                 }
428
429                 /*
430                  * The group's name is the first field. It is separated from
431                  * the password with a ":" character which is replaced with a
432                  * NUL to give the new password. The new password will then
433                  * be encrypted in the normal fashion with a new salt
434                  * generated, unless the '-e' is given, in which case it is
435                  * assumed to already be encrypted.
436                  */
437
438                 name = buf;
439                 cp = strchr (name, ':');
440                 if (NULL != cp) {
441                         *cp = '\0';
442                         cp++;
443                 } else {
444                         fprintf (stderr,
445                                  _("%s: line %d: missing new password\n"),
446                                  Prog, line);
447                         errors++;
448                         continue;
449                 }
450                 newpwd = cp;
451                 if (   (!eflg)
452                     && (   (NULL == crypt_method)
453                         || (0 != strcmp (crypt_method, "NONE")))) {
454                         void *arg = NULL;
455                         if (md5flg) {
456                                 crypt_method = "MD5";
457                         }
458 #ifdef USE_SHA_CRYPT
459                         if (sflg) {
460                                 arg = &sha_rounds;
461                         }
462 #endif
463                         cp = pw_encrypt (newpwd,
464                                          crypt_make_salt (crypt_method, arg));
465                 }
466
467                 /*
468                  * Get the group file entry for this group. The group must
469                  * already exist.
470                  */
471                 gr = gr_locate (name);
472                 if (NULL == gr) {
473                         fprintf (stderr,
474                                  _("%s: line %d: group '%s' does not exist\n"), Prog,
475                                  line, name);
476                         errors++;
477                         continue;
478                 }
479 #ifdef SHADOWGRP
480                 if (is_shadow_grp) {
481                         /* The gshadow entry should be updated if the
482                          * group entry has a password set to 'x'.
483                          * But on the other hand, if there is already both
484                          * a group and a gshadow password, it's preferable
485                          * to update both.
486                          */
487                         sg = sgr_locate (name);
488
489                         if (   (NULL == sg)
490                             && (strcmp (gr->gr_passwd,
491                                         SHADOW_PASSWD_STRING) == 0)) {
492                                 static char *empty = NULL;
493                                 /* If the password is set to 'x' in
494                                  * group, but there are no entries in
495                                  * gshadow, create one.
496                                  */
497                                 newsg.sg_name   = name;
498                                 /* newsg.sg_passwd = NULL; will be set later */
499                                 newsg.sg_adm    = &empty;
500                                 newsg.sg_mem    = dup_list (gr->gr_mem);
501                                 sg = &newsg;
502                         }
503                 } else {
504                         sg = NULL;
505                 }
506 #endif
507
508                 /*
509                  * The freshly encrypted new password is merged into the
510                  * group's entry.
511                  */
512 #ifdef SHADOWGRP
513                 if (NULL != sg) {
514                         newsg = *sg;
515                         newsg.sg_passwd = cp;
516                 }
517                 if (   (NULL == sg)
518                     || (strcmp (gr->gr_passwd, SHADOW_PASSWD_STRING) != 0))
519 #endif
520                 {
521                         newgr = *gr;
522                         newgr.gr_passwd = cp;
523                 }
524
525                 /* 
526                  * The updated group file entry is then put back and will
527                  * be written to the group file later, after all the
528                  * other entries have been updated as well.
529                  */
530 #ifdef SHADOWGRP
531                 if (NULL != sg) {
532                         if (sgr_update (&newsg) == 0) {
533                                 fprintf (stderr,
534                                          _("%s: line %d: failed to prepare the new %s entry '%s'\n"),
535                                          Prog, line, sgr_dbname (), newsg.sg_name);
536                                 errors++;
537                                 continue;
538                         }
539                 }
540                 if (   (NULL == sg)
541                     || (strcmp (gr->gr_passwd, SHADOW_PASSWD_STRING) != 0))
542 #endif
543                 {
544                         if (gr_update (&newgr) == 0) {
545                                 fprintf (stderr,
546                                          _("%s: line %d: failed to prepare the new %s entry '%s'\n"),
547                                          Prog, line, gr_dbname (), newgr.gr_name);
548                                 errors++;
549                                 continue;
550                         }
551                 }
552         }
553
554         /*
555          * Any detected errors will cause the entire set of changes to be
556          * aborted. Unlocking the group file will cause all of the
557          * changes to be ignored. Otherwise the file is closed, causing the
558          * changes to be written out all at once, and then unlocked
559          * afterwards.
560          */
561         if (0 != errors) {
562                 fprintf (stderr,
563                          _("%s: error detected, changes ignored\n"), Prog);
564                 fail_exit (1);
565         }
566
567         close_files ();
568
569         nscd_flush_cache ("group");
570
571         return (0);
572 }
573