]> granicus.if.org Git - shadow/blob - src/useradd.c
* src/useradd.c, src/usermod.c, libmisc/getgr_nam_gid.c,
[shadow] / src / useradd.c
1 /*
2  * Copyright (c) 1991 - 1994, Julianne Frances Haugh
3  * Copyright (c) 1996 - 2000, Marek Michałkiewicz
4  * Copyright (c) 2000 - 2006, Tomasz Kłoczko
5  * Copyright (c) 2007 - 2009, 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 <assert.h>
38 #include <ctype.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <getopt.h>
42 #include <grp.h>
43 #include <lastlog.h>
44 #include <pwd.h>
45 #ifdef ACCT_TOOLS_SETUID
46 #ifdef USE_PAM
47 #include "pam_defs.h"
48 #endif                          /* USE_PAM */
49 #endif                          /* ACCT_TOOLS_SETUID */
50 #include <stdio.h>
51 #include <sys/stat.h>
52 #include <sys/types.h>
53 #include <time.h>
54 #include "chkname.h"
55 #include "defines.h"
56 #include "faillog.h"
57 #include "getdef.h"
58 #include "groupio.h"
59 #include "nscd.h"
60 #include "prototypes.h"
61 #include "pwauth.h"
62 #include "pwio.h"
63 #ifdef  SHADOWGRP
64 #include "sgroupio.h"
65 #endif
66 #include "shadowio.h"
67
68 #ifndef SKEL_DIR
69 #define SKEL_DIR "/etc/skel"
70 #endif
71 #ifndef USER_DEFAULTS_FILE
72 #define USER_DEFAULTS_FILE "/etc/default/useradd"
73 #define NEW_USER_FILE "/etc/default/nuaddXXXXXX"
74 #endif
75 /*
76  * Needed for MkLinux DR1/2/2.1 - J.
77  */
78 #ifndef LASTLOG_FILE
79 #define LASTLOG_FILE "/var/log/lastlog"
80 #endif
81 /*
82  * Global variables
83  */
84 char *Prog;
85
86 /*
87  * These defaults are used if there is no defaults file.
88  */
89 static gid_t def_group = 100;
90 static const char *def_gname = "other";
91 static const char *def_home = "/home";
92 static const char *def_shell = "";
93 static const char *def_template = SKEL_DIR;
94 static const char *def_create_mail_spool = "no";
95
96 static long def_inactive = -1;
97 static const char *def_expire = "";
98
99 static char def_file[] = USER_DEFAULTS_FILE;
100
101 #define VALID(s)        (strcspn (s, ":\n") == strlen (s))
102
103 static const char *user_name = "";
104 static const char *user_pass = "!";
105 static uid_t user_id;
106 static gid_t user_gid;
107 static const char *user_comment = "";
108 static const char *user_home = "";
109 static const char *user_shell = "";
110 static const char *create_mail_spool = "";
111
112 static long user_expire = -1;
113 static bool is_shadow_pwd;
114
115 #ifdef SHADOWGRP
116 static bool is_shadow_grp;
117 static bool sgr_locked = false;
118 #endif
119 static bool pw_locked = false;
120 static bool gr_locked = false;
121 static bool spw_locked = false;
122 static char **user_groups;      /* NULL-terminated list */
123 static long sys_ngroups;
124 static bool do_grp_update = false;      /* group files need to be updated */
125
126 static bool
127     bflg = false,               /* new default root of home directory */
128     cflg = false,               /* comment (GECOS) field for new account */
129     dflg = false,               /* home directory for new account */
130     Dflg = false,               /* set/show new user default values */
131     eflg = false,               /* days since 1970-01-01 when account is locked */
132     fflg = false,               /* days until account with expired password is locked */
133     gflg = false,               /* primary group ID for new account */
134     Gflg = false,               /* secondary group set for new account */
135     kflg = false,               /* specify a directory to fill new user directory */
136     lflg = false,               /* do not add user to lastlog/faillog databases */
137     mflg = false,               /* create user's home directory if it doesn't exist */
138     Mflg = false,               /* do not create user's home directory even if CREATE_HOME is set */
139     Nflg = false,               /* do not create a group having the same name as the user, but add the user to def_group (or the group specified with -g) */
140     oflg = false,               /* permit non-unique user ID to be specified with -u */
141     rflg = false,               /* create a system account */
142     sflg = false,               /* shell program for new account */
143     uflg = false,               /* specify user ID for new account */
144     Uflg = false;               /* create a group having the same name as the user */
145
146 static bool home_added = false;
147
148 /*
149  * exit status values
150  */
151 #define E_SUCCESS       0       /* success */
152 #define E_PW_UPDATE     1       /* can't update password file */
153 #define E_USAGE         2       /* invalid command syntax */
154 #define E_BAD_ARG       3       /* invalid argument to option */
155 #define E_UID_IN_USE    4       /* UID already in use (and no -o) */
156 #define E_NOTFOUND      6       /* specified group doesn't exist */
157 #define E_NAME_IN_USE   9       /* username already in use */
158 #define E_GRP_UPDATE    10      /* can't update group file */
159 #define E_HOMEDIR       12      /* can't create home directory */
160 #define E_MAIL_SPOOL    13      /* can't create mail spool */
161
162 #define DGROUP                  "GROUP="
163 #define HOME                    "HOME="
164 #define SHELL                   "SHELL="
165 #define INACT                   "INACTIVE="
166 #define EXPIRE                  "EXPIRE="
167 #define SKEL                    "SKEL="
168 #define CREATE_MAIL_SPOOL       "CREATE_MAIL_SPOOL="
169
170 /* local function prototypes */
171 static void fail_exit (int);
172 static void get_defaults (void);
173 static void show_defaults (void);
174 static int set_defaults (void);
175 static int get_groups (char *);
176 static void usage (void);
177 static void new_pwent (struct passwd *);
178
179 static long scale_age (long);
180 static void new_spent (struct spwd *);
181 static void grp_update (void);
182
183 static void process_flags (int argc, char **argv);
184 static void close_files (void);
185 static void open_files (void);
186 static void faillog_reset (uid_t);
187 static void lastlog_reset (uid_t);
188 static void usr_update (void);
189 static void create_home (void);
190 static void create_mail (void);
191
192 /*
193  * fail_exit - undo as much as possible
194  */
195 static void fail_exit (int code)
196 {
197         if (home_added) {
198                 rmdir (user_home);
199         }
200
201         if (spw_locked) {
202                 if (spw_unlock () == 0) {
203                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
204                         SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
205 #ifdef WITH_AUDIT
206                         audit_logger (AUDIT_ADD_USER, Prog,
207                                       "unlocking shadow file",
208                                       user_name, AUDIT_NO_ID,
209                                       SHADOW_AUDIT_FAILURE);
210 #endif
211                         /* continue */
212                 }
213         }
214         if (pw_locked) {
215                 if (pw_unlock () == 0) {
216                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
217                         SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
218 #ifdef WITH_AUDIT
219                         audit_logger (AUDIT_ADD_USER, Prog,
220                                       "unlocking passwd file",
221                                       user_name, AUDIT_NO_ID,
222                                       SHADOW_AUDIT_FAILURE);
223 #endif
224                         /* continue */
225                 }
226         }
227         if (gr_locked) {
228                 if (gr_unlock () == 0) {
229                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
230                         SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
231 #ifdef WITH_AUDIT
232                         audit_logger (AUDIT_ADD_USER, Prog,
233                                       "unlocking group file",
234                                       user_name, AUDIT_NO_ID,
235                                       SHADOW_AUDIT_FAILURE);
236 #endif
237                         /* continue */
238                 }
239         }
240 #ifdef  SHADOWGRP
241         if (sgr_locked) {
242                 if (sgr_unlock () == 0) {
243                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
244                         SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
245 #ifdef WITH_AUDIT
246                         audit_logger (AUDIT_ADD_USER, Prog,
247                                       "unlocking gshadow file",
248                                       user_name, AUDIT_NO_ID,
249                                       SHADOW_AUDIT_FAILURE);
250 #endif
251                         /* continue */
252                 }
253         }
254 #endif
255
256 #ifdef WITH_AUDIT
257         audit_logger (AUDIT_ADD_USER, Prog,
258                       "adding user",
259                       user_name, AUDIT_NO_ID,
260                       SHADOW_AUDIT_FAILURE);
261 #endif
262         SYSLOG ((LOG_INFO, "failed adding user '%s', data deleted", user_name));
263         exit (code);
264 }
265
266 #define MATCH(x,y) (strncmp((x),(y),strlen(y)) == 0)
267
268 /*
269  * get_defaults - read the defaults file
270  *
271  *      get_defaults() reads the defaults file for this command. It sets the
272  *      various values from the file, or uses built-in default values if the
273  *      file does not exist.
274  */
275 static void get_defaults (void)
276 {
277         FILE *fp;
278         char buf[1024];
279         char *cp, *ep;
280
281         /*
282          * Open the defaults file for reading.
283          */
284
285         fp = fopen (def_file, "r");
286         if (NULL == fp) {
287                 return;
288         }
289
290         /*
291          * Read the file a line at a time. Only the lines that have relevant
292          * values are used, everything else can be ignored.
293          */
294         while (fgets (buf, (int) sizeof buf, fp) == buf) {
295                 cp = strrchr (buf, '\n');
296                 if (NULL != cp) {
297                         *cp = '\0';
298                 }
299
300                 cp = strchr (buf, '=');
301                 if (NULL == cp) {
302                         continue;
303                 }
304
305                 cp++;
306
307                 /*
308                  * Primary GROUP identifier
309                  */
310                 if (MATCH (buf, DGROUP)) {
311                         const struct group *grp = getgr_nam_gid (cp);
312                         if (NULL == grp) {
313                                 fprintf (stderr,
314                                          _("%s: group '%s' does not exist\n"),
315                                          Prog, cp);
316                                 fprintf (stderr,
317                                          _("%s: the %s configuration in %s will be ignored\n"),
318                                          Prog, DGROUP, def_file);
319                         } else {
320                                 def_group = grp->gr_gid;
321                                 def_gname = xstrdup (grp->gr_name);
322                         }
323                 }
324
325                 /*
326                  * Default HOME filesystem
327                  */
328                 else if (MATCH (buf, HOME)) {
329                         def_home = xstrdup (cp);
330                 }
331
332                 /*
333                  * Default Login Shell command
334                  */
335                 else if (MATCH (buf, SHELL)) {
336                         def_shell = xstrdup (cp);
337                 }
338
339                 /*
340                  * Default Password Inactive value
341                  */
342                 else if (MATCH (buf, INACT)) {
343                         if (   (getlong (cp, &def_inactive) == 0)
344                             || (def_inactive < -1)) {
345                                 fprintf (stderr,
346                                          _("%s: invalid numeric argument '%s'\n"),
347                                          Prog, optarg);
348                                 fprintf (stderr,
349                                          _("%s: the %s configuration in %s will be ignored\n"),
350                                          Prog, INACT, def_file);
351                                 def_inactive = -1;
352                         }
353                 }
354
355                 /*
356                  * Default account expiration date
357                  */
358                 else if (MATCH (buf, EXPIRE)) {
359                         def_expire = xstrdup (cp);
360                 }
361
362                 /*
363                  * Default Skeleton information
364                  */
365                 else if (MATCH (buf, SKEL)) {
366                         if ('\0' == *cp) {
367                                 cp = SKEL_DIR;  /* XXX warning: const */
368                         }
369
370                         def_template = xstrdup (cp);
371                 }
372
373                 /*
374                  * Create by default user mail spool or not ?
375                  */
376                 else if (MATCH (buf, CREATE_MAIL_SPOOL)) {
377                         if (*cp == '\0') {
378                                 cp = CREATE_MAIL_SPOOL; /* XXX warning: const */
379                         }
380
381                         def_create_mail_spool = xstrdup (cp);
382                 }
383         }
384 }
385
386 /*
387  * show_defaults - show the contents of the defaults file
388  *
389  *      show_defaults() displays the values that are used from the default
390  *      file and the built-in values.
391  */
392 static void show_defaults (void)
393 {
394         printf ("GROUP=%u\n", (unsigned int) def_group);
395         printf ("HOME=%s\n", def_home);
396         printf ("INACTIVE=%ld\n", def_inactive);
397         printf ("EXPIRE=%s\n", def_expire);
398         printf ("SHELL=%s\n", def_shell);
399         printf ("SKEL=%s\n", def_template);
400         printf ("CREATE_MAIL_SPOOL=%s\n", def_create_mail_spool);
401 }
402
403 /*
404  * set_defaults - write new defaults file
405  *
406  *      set_defaults() re-writes the defaults file using the values that
407  *      are currently set. Duplicated lines are pruned, missing lines are
408  *      added, and unrecognized lines are copied as is.
409  */
410 static int set_defaults (void)
411 {
412         FILE *ifp;
413         FILE *ofp;
414         char buf[1024];
415         static char new_file[] = NEW_USER_FILE;
416         char *cp;
417         int ofd;
418         bool out_group = false;
419         bool out_home = false;
420         bool out_inactive = false;
421         bool out_expire = false;
422         bool out_shell = false;
423         bool out_skel = false;
424         bool out_create_mail_spool = false;
425
426         /*
427          * Create a temporary file to copy the new output to.
428          */
429         ofd = mkstemp (new_file);
430         if (-1 == ofd) {
431                 fprintf (stderr,
432                          _("%s: cannot create new defaults file\n"),
433                          Prog);
434                 return -1;
435         }
436
437         ofp = fdopen (ofd, "w");
438         if (NULL == ofp) {
439                 fprintf (stderr,
440                          _("%s: cannot open new defaults file\n"),
441                          Prog);
442                 return -1;
443         }
444
445         /*
446          * Open the existing defaults file and copy the lines to the
447          * temporary file, using any new values. Each line is checked
448          * to insure that it is not output more than once.
449          */
450         ifp = fopen (def_file, "r");
451         if (NULL == ifp) {
452                 fprintf (ofp, "# useradd defaults file\n");
453                 goto skip;
454         }
455
456         while (fgets (buf, (int) sizeof buf, ifp) == buf) {
457                 cp = strrchr (buf, '\n');
458                 if (NULL != cp) {
459                         *cp = '\0';
460                 }
461
462                 if (!out_group && MATCH (buf, DGROUP)) {
463                         fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
464                         out_group = true;
465                 } else if (!out_home && MATCH (buf, HOME)) {
466                         fprintf (ofp, HOME "%s\n", def_home);
467                         out_home = true;
468                 } else if (!out_inactive && MATCH (buf, INACT)) {
469                         fprintf (ofp, INACT "%ld\n", def_inactive);
470                         out_inactive = true;
471                 } else if (!out_expire && MATCH (buf, EXPIRE)) {
472                         fprintf (ofp, EXPIRE "%s\n", def_expire);
473                         out_expire = true;
474                 } else if (!out_shell && MATCH (buf, SHELL)) {
475                         fprintf (ofp, SHELL "%s\n", def_shell);
476                         out_shell = true;
477                 } else if (!out_skel && MATCH (buf, SKEL)) {
478                         fprintf (ofp, SKEL "%s\n", def_template);
479                         out_skel = true;
480                 } else if (!out_create_mail_spool
481                            && MATCH (buf, CREATE_MAIL_SPOOL)) {
482                         fprintf (ofp,
483                                  CREATE_MAIL_SPOOL "%s\n",
484                                  def_create_mail_spool);
485                         out_create_mail_spool = true;
486                 } else
487                         fprintf (ofp, "%s\n", buf);
488         }
489         (void) fclose (ifp);
490
491       skip:
492         /*
493          * Check each line to insure that every line was output. This
494          * causes new values to be added to a file which did not previously
495          * have an entry for that value.
496          */
497         if (!out_group)
498                 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
499         if (!out_home)
500                 fprintf (ofp, HOME "%s\n", def_home);
501         if (!out_inactive)
502                 fprintf (ofp, INACT "%ld\n", def_inactive);
503         if (!out_expire)
504                 fprintf (ofp, EXPIRE "%s\n", def_expire);
505         if (!out_shell)
506                 fprintf (ofp, SHELL "%s\n", def_shell);
507         if (!out_skel)
508                 fprintf (ofp, SKEL "%s\n", def_template);
509
510         if (!out_create_mail_spool)
511                 fprintf (ofp, CREATE_MAIL_SPOOL "%s\n", def_create_mail_spool);
512
513         /*
514          * Flush and close the file. Check for errors to make certain
515          * the new file is intact.
516          */
517         (void) fflush (ofp);
518         if (   (ferror (ofp) != 0)
519             || (fsync (fileno (ofp)) != 0)
520             || (fclose (ofp) != 0)) {
521                 unlink (new_file);
522                 return -1;
523         }
524
525         /*
526          * Rename the current default file to its backup name.
527          */
528         snprintf (buf, sizeof buf, "%s-", def_file);
529         if ((rename (def_file, buf) != 0) && (ENOENT != errno)) {
530                 snprintf (buf, sizeof buf, _("%s: rename: %s"), Prog, def_file);
531                 perror (buf);
532                 unlink (new_file);
533                 return -1;
534         }
535
536         /*
537          * Rename the new default file to its correct name.
538          */
539         if (rename (new_file, def_file) != 0) {
540                 snprintf (buf, sizeof buf, _("%s: rename: %s"), Prog, new_file);
541                 perror (buf);
542                 return -1;
543         }
544 #ifdef WITH_AUDIT
545         audit_logger (AUDIT_USYS_CONFIG, Prog,
546                       "changing useradd defaults",
547                       NULL, AUDIT_NO_ID,
548                       SHADOW_AUDIT_SUCCESS);
549 #endif
550         SYSLOG ((LOG_INFO,
551                  "useradd defaults: GROUP=%u, HOME=%s, SHELL=%s, INACTIVE=%ld, "
552                  "EXPIRE=%s, SKEL=%s, CREATE_MAIL_SPOOL=%s",
553                  (unsigned int) def_group, def_home, def_shell,
554                  def_inactive, def_expire, def_template,
555                  def_create_mail_spool));
556         return 0;
557 }
558
559 /*
560  * get_groups - convert a list of group names to an array of group IDs
561  *
562  *      get_groups() takes a comma-separated list of group names and
563  *      converts it to a NULL-terminated array. Any unknown group
564  *      names are reported as errors.
565  */
566 static int get_groups (char *list)
567 {
568         char *cp;
569         const struct group *grp;
570         int errors = 0;
571         int ngroups = 0;
572
573         if ('\0' == *list) {
574                 return 0;
575         }
576
577         /*
578          * So long as there is some data to be converted, strip off
579          * each name and look it up. A mix of numerical and string
580          * values for group identifiers is permitted.
581          */
582         do {
583                 /*
584                  * Strip off a single name from the list
585                  */
586                 cp = strchr (list, ',');
587                 if (NULL != cp) {
588                         *cp++ = '\0';
589                 }
590
591                 /*
592                  * Names starting with digits are treated as numerical
593                  * GID values, otherwise the string is looked up as is.
594                  */
595                 grp = getgr_nam_gid (list);
596
597                 /*
598                  * There must be a match, either by GID value or by
599                  * string name.
600                  */
601                 if (NULL == grp) {
602                         fprintf (stderr,
603                                  _("%s: group '%s' does not exist\n"),
604                                  Prog, list);
605                         errors++;
606                 }
607                 list = cp;
608
609                 /*
610                  * If the group doesn't exist, don't dump core...
611                  * Instead, try the next one.  --marekm
612                  */
613                 if (NULL == grp) {
614                         continue;
615                 }
616
617 #ifdef  USE_NIS
618                 /*
619                  * Don't add this group if they are an NIS group. Tell
620                  * the user to go to the server for this group.
621                  */
622                 if (__isgrNIS ()) {
623                         fprintf (stderr,
624                                  _("%s: group '%s' is a NIS group.\n"),
625                                  Prog, grp->gr_name);
626                         continue;
627                 }
628 #endif
629
630                 if (ngroups == sys_ngroups) {
631                         fprintf (stderr,
632                                  _("%s: too many groups specified (max %d).\n"),
633                                  Prog, ngroups);
634                         break;
635                 }
636
637                 /*
638                  * Add the group name to the user's list of groups.
639                  */
640                 user_groups[ngroups++] = xstrdup (grp->gr_name);
641         } while (NULL != list);
642
643         user_groups[ngroups] = (char *) 0;
644
645         /*
646          * Any errors in finding group names are fatal
647          */
648         if (0 != errors) {
649                 return -1;
650         }
651
652         return 0;
653 }
654
655 /*
656  * usage - display usage message and exit
657  */
658 static void usage (void)
659 {
660         fputs (_("Usage: useradd [options] LOGIN\n"
661                  "\n"
662                  "Options:\n"
663                  "  -b, --base-dir BASE_DIR       base directory for the new user account\n"
664                  "                                home directory\n"
665                  "  -c, --comment COMMENT         set the GECOS field for the new user account\n"
666                  "  -d, --home-dir HOME_DIR       home directory for the new user account\n"
667                  "  -D, --defaults                print or save modified default useradd\n"
668                  "                                configuration\n"
669                  "  -e, --expiredate EXPIRE_DATE  set account expiration date to EXPIRE_DATE\n"
670                  "  -f, --inactive INACTIVE       set password inactive after expiration\n"
671                  "                                to INACTIVE\n"
672                  "  -g, --gid GROUP               force use GROUP for the new user account\n"
673                  "  -G, --groups GROUPS           list of supplementary groups for the new\n"
674                  "                                user account\n"
675                  "  -h, --help                    display this help message and exit\n"
676                  "  -k, --skel SKEL_DIR           specify an alternative skel directory\n"
677                  "  -K, --key KEY=VALUE           overrides /etc/login.defs defaults\n"
678                  "  -l, --no-log-init             do not add the user to the lastlog and\n"
679                  "                                faillog databases\n"
680                  "  -m, --create-home             create home directory for the new user\n"
681                  "                                account\n"
682                  "  -M, --no-create-home          do not create user's home directory\n"
683                  "                                (overrides /etc/login.defs)\n"
684                  "  -N, --no-user-group           do not create a group with the same name as\n"
685                  "                                the user\n"
686                  "  -o, --non-unique              allow create user with duplicate\n"
687                  "                                (non-unique) UID\n"
688                  "  -p, --password PASSWORD       use encrypted password for the new user\n"
689                  "                                account\n"
690                  "  -r, --system                  create a system account\n"
691                  "  -s, --shell SHELL             the login shell for the new user account\n"
692                  "  -u, --uid UID                 force use the UID for the new user account\n"
693                  "  -U, --user-group              create a group with the same name as the user\n"
694                  "\n"), stderr);
695         exit (E_USAGE);
696 }
697
698 /*
699  * new_pwent - initialize the values in a password file entry
700  *
701  *      new_pwent() takes all of the values that have been entered and
702  *      fills in a (struct passwd) with them.
703  */
704 static void new_pwent (struct passwd *pwent)
705 {
706         memzero (pwent, sizeof *pwent);
707         pwent->pw_name = (char *) user_name;
708         if (is_shadow_pwd) {
709                 pwent->pw_passwd = (char *) SHADOW_PASSWD_STRING;
710         } else {
711                 pwent->pw_passwd = (char *) user_pass;
712         }
713
714         pwent->pw_uid = user_id;
715         pwent->pw_gid = user_gid;
716         pwent->pw_gecos = (char *) user_comment;
717         pwent->pw_dir = (char *) user_home;
718         pwent->pw_shell = (char *) user_shell;
719 }
720
721 static long scale_age (long x)
722 {
723         if (x <= 0) {
724                 return x;
725         }
726
727         return x * (DAY / SCALE);
728 }
729
730 /*
731  * new_spent - initialize the values in a shadow password file entry
732  *
733  *      new_spent() takes all of the values that have been entered and
734  *      fills in a (struct spwd) with them.
735  */
736 static void new_spent (struct spwd *spent)
737 {
738         memzero (spent, sizeof *spent);
739         spent->sp_namp = (char *) user_name;
740         spent->sp_pwdp = (char *) user_pass;
741         spent->sp_lstchg = (long) time ((time_t *) 0) / SCALE;
742         if (0 == spent->sp_lstchg) {
743                 /* Better disable aging than requiring a password change */
744                 spent->sp_lstchg = -1;
745         }
746         if (!rflg) {
747                 spent->sp_min = scale_age (getdef_num ("PASS_MIN_DAYS", -1));
748                 spent->sp_max = scale_age (getdef_num ("PASS_MAX_DAYS", -1));
749                 spent->sp_warn = scale_age (getdef_num ("PASS_WARN_AGE", -1));
750                 spent->sp_inact = scale_age (def_inactive);
751                 spent->sp_expire = scale_age (user_expire);
752         } else {
753                 spent->sp_min = scale_age (-1);
754                 spent->sp_max = scale_age (-1);
755                 spent->sp_warn = scale_age (-1);
756                 spent->sp_inact = scale_age (-1);
757                 spent->sp_expire = scale_age (-1);
758         }
759         spent->sp_flag = SHADOW_SP_FLAG_UNSET;
760 }
761
762 /*
763  * grp_update - add user to secondary group set
764  *
765  *      grp_update() takes the secondary group set given in user_groups
766  *      and adds the user to each group given by that set.
767  *
768  *      The group files are opened and locked in open_files().
769  *
770  *      close_files() should be called afterwards to commit the changes
771  *      and unlocking the group files.
772  */
773 static void grp_update (void)
774 {
775         const struct group *grp;
776         struct group *ngrp;
777
778 #ifdef  SHADOWGRP
779         const struct sgrp *sgrp;
780         struct sgrp *nsgrp;
781 #endif
782
783         /*
784          * Scan through the entire group file looking for the groups that
785          * the user is a member of.
786          */
787         for (gr_rewind (), grp = gr_next (); NULL != grp; grp = gr_next ()) {
788
789                 /*
790                  * See if the user specified this group as one of their
791                  * concurrent groups.
792                  */
793                 if (!is_on_list (user_groups, grp->gr_name)) {
794                         continue;
795                 }
796
797                 /*
798                  * Make a copy - gr_update() will free() everything
799                  * from the old entry, and we need it later.
800                  */
801                 ngrp = __gr_dup (grp);
802                 if (NULL == ngrp) {
803                         fprintf (stderr,
804                                  _("%s: Out of memory. Cannot update %s.\n"),
805                                  Prog, gr_dbname ());
806                         SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", gr_dbname (), user_name));
807 #ifdef WITH_AUDIT
808                         audit_logger (AUDIT_ADD_USER, Prog,
809                                       "adding user to group",
810                                       user_name, AUDIT_NO_ID,
811                                       SHADOW_AUDIT_FAILURE);
812 #endif
813                         fail_exit (E_GRP_UPDATE);       /* XXX */
814                 }
815
816                 /* 
817                  * Add the username to the list of group members and
818                  * update the group entry to reflect the change.
819                  */
820                 ngrp->gr_mem = add_list (ngrp->gr_mem, user_name);
821                 if (gr_update (ngrp) == 0) {
822                         fprintf (stderr,
823                                  _("%s: failed to prepare the new %s entry '%s'\n"),
824                                  Prog, gr_dbname (), ngrp->gr_name);
825                         SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", gr_dbname (), user_name));
826 #ifdef WITH_AUDIT
827                         audit_logger (AUDIT_ADD_USER, Prog,
828                                       "adding user to group",
829                                       user_name, AUDIT_NO_ID,
830                                       SHADOW_AUDIT_FAILURE);
831 #endif
832                         fail_exit (E_GRP_UPDATE);
833                 }
834 #ifdef WITH_AUDIT
835                 audit_logger (AUDIT_ADD_USER, Prog,
836                               "adding user to group",
837                               user_name, AUDIT_NO_ID,
838                               SHADOW_AUDIT_SUCCESS);
839 #endif
840                 SYSLOG ((LOG_INFO,
841                          "add '%s' to group '%s'",
842                          user_name, ngrp->gr_name));
843         }
844
845 #ifdef  SHADOWGRP
846         if (!is_shadow_grp)
847                 return;
848
849         /*
850          * Scan through the entire shadow group file looking for the groups
851          * that the user is a member of. The administrative list isn't
852          * modified.
853          */
854         for (sgr_rewind (), sgrp = sgr_next (); NULL != sgrp; sgrp = sgr_next ()) {
855
856                 /*
857                  * See if the user specified this group as one of their
858                  * concurrent groups.
859                  */
860                 if (gr_locate (sgrp->sg_name) == NULL) {
861                         continue;
862                 }
863
864                 if (!is_on_list (user_groups, sgrp->sg_name)) {
865                         continue;
866                 }
867
868                 /*
869                  * Make a copy - sgr_update() will free() everything
870                  * from the old entry, and we need it later.
871                  */
872                 nsgrp = __sgr_dup (sgrp);
873                 if (NULL == nsgrp) {
874                         fprintf (stderr,
875                                  _("%s: Out of memory. Cannot update %s.\n"),
876                                  Prog, sgr_dbname ());
877                         SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", sgr_dbname (), user_name));
878 #ifdef WITH_AUDIT
879                         audit_logger (AUDIT_ADD_USER, Prog,
880                                       "adding user to shadow group",
881                                       user_name, AUDIT_NO_ID,
882                                       SHADOW_AUDIT_FAILURE);
883 #endif
884                         fail_exit (E_GRP_UPDATE);       /* XXX */
885                 }
886
887                 /* 
888                  * Add the username to the list of group members and
889                  * update the group entry to reflect the change.
890                  */
891                 nsgrp->sg_mem = add_list (nsgrp->sg_mem, user_name);
892                 if (sgr_update (nsgrp) == 0) {
893                         fprintf (stderr,
894                                  _("%s: failed to prepare the new %s entry '%s'\n"),
895                                  Prog, sgr_dbname (), nsgrp->sg_name);
896                         SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", sgr_dbname (), user_name));
897 #ifdef WITH_AUDIT
898                         audit_logger (AUDIT_ADD_USER, Prog,
899                                       "adding user to shadow group",
900                                       user_name, AUDIT_NO_ID,
901                                       SHADOW_AUDIT_FAILURE);
902 #endif
903                         fail_exit (E_GRP_UPDATE);
904                 }
905 #ifdef WITH_AUDIT
906                 audit_logger (AUDIT_ADD_USER, Prog,
907                               "adding user to shadow group",
908                               user_name, AUDIT_NO_ID,
909                               SHADOW_AUDIT_SUCCESS);
910 #endif
911                 SYSLOG ((LOG_INFO,
912                          "add '%s' to shadow group '%s'",
913                          user_name, nsgrp->sg_name));
914         }
915 #endif                          /* SHADOWGRP */
916 }
917
918 /*
919  * process_flags - perform command line argument setting
920  *
921  *      process_flags() interprets the command line arguments and sets
922  *      the values that the user will be created with accordingly. The
923  *      values are checked for sanity.
924  */
925 static void process_flags (int argc, char **argv)
926 {
927         const struct group *grp;
928         bool anyflag = false;
929         char *cp;
930
931         {
932                 /*
933                  * Parse the command line options.
934                  */
935                 int c;
936                 static struct option long_options[] = {
937                         {"base-dir", required_argument, NULL, 'b'},
938                         {"comment", required_argument, NULL, 'c'},
939                         {"home-dir", required_argument, NULL, 'd'},
940                         {"defaults", no_argument, NULL, 'D'},
941                         {"expiredate", required_argument, NULL, 'e'},
942                         {"inactive", required_argument, NULL, 'f'},
943                         {"gid", required_argument, NULL, 'g'},
944                         {"groups", required_argument, NULL, 'G'},
945                         {"help", no_argument, NULL, 'h'},
946                         {"skel", required_argument, NULL, 'k'},
947                         {"key", required_argument, NULL, 'K'},
948                         {"create-home", no_argument, NULL, 'm'},
949                         {"no-create-home", no_argument, NULL, 'M'},
950                         {"no-log-init", no_argument, NULL, 'l'},
951                         {"no-user-group", no_argument, NULL, 'N'},
952                         {"non-unique", no_argument, NULL, 'o'},
953                         {"password", required_argument, NULL, 'p'},
954                         {"system", no_argument, NULL, 'r'},
955                         {"shell", required_argument, NULL, 's'},
956                         {"uid", required_argument, NULL, 'u'},
957                         {"user-group", no_argument, NULL, 'U'},
958                         {NULL, 0, NULL, '\0'}
959                 };
960                 while ((c = getopt_long (argc, argv,
961                                          "b:c:d:De:f:g:G:k:K:lmMNop:rs:u:U",
962                                          long_options, NULL)) != -1) {
963                         switch (c) {
964                         case 'b':
965                                 if (   ( !VALID (optarg) )
966                                     || ( optarg[0] != '/' )) {
967                                         fprintf (stderr,
968                                                  _("%s: invalid base directory '%s'\n"),
969                                                  Prog, optarg);
970                                         exit (E_BAD_ARG);
971                                 }
972                                 def_home = optarg;
973                                 bflg = true;
974                                 break;
975                         case 'c':
976                                 if (!VALID (optarg)) {
977                                         fprintf (stderr,
978                                                  _("%s: invalid comment '%s'\n"),
979                                                  Prog, optarg);
980                                         exit (E_BAD_ARG);
981                                 }
982                                 user_comment = optarg;
983                                 cflg = true;
984                                 break;
985                         case 'd':
986                                 if (   ( !VALID (optarg) )
987                                     || ( optarg[0] != '/' )) {
988                                         fprintf (stderr,
989                                                  _("%s: invalid home directory '%s'\n"),
990                                                  Prog, optarg);
991                                         exit (E_BAD_ARG);
992                                 }
993                                 user_home = optarg;
994                                 dflg = true;
995                                 break;
996                         case 'D':
997                                 if (anyflag) {
998                                         usage ();
999                                 }
1000                                 Dflg = true;
1001                                 break;
1002                         case 'e':
1003                                 if ('\0' != *optarg) {
1004                                         user_expire = strtoday (optarg);
1005                                         if (user_expire == -1) {
1006                                                 fprintf (stderr,
1007                                                          _("%s: invalid date '%s'\n"),
1008                                                          Prog, optarg);
1009                                                 exit (E_BAD_ARG);
1010                                         }
1011                                 } else {
1012                                         user_expire = -1;
1013                                 }
1014
1015                                 /*
1016                                  * -e "" is allowed - it's a no-op without /etc/shadow
1017                                  */
1018                                 if (('\0' != *optarg) && !is_shadow_pwd) {
1019                                         fprintf (stderr,
1020                                                  _("%s: shadow passwords required for -e\n"),
1021                                                  Prog);
1022                                         exit (E_USAGE);
1023                                 }
1024                                 if (Dflg) {
1025                                         def_expire = optarg;
1026                                 }
1027                                 eflg = true;
1028                                 break;
1029                         case 'f':
1030                                 if (   (getlong (optarg, &def_inactive) == 0)
1031                                     || (def_inactive < -1)) {
1032                                         fprintf (stderr,
1033                                                  _("%s: invalid numeric argument '%s'\n"),
1034                                                  Prog, optarg);
1035                                         usage ();
1036                                 }
1037                                 /*
1038                                  * -f -1 is allowed
1039                                  * it's a no-op without /etc/shadow
1040                                  */
1041                                 if ((-1 != def_inactive) && !is_shadow_pwd) {
1042                                         fprintf (stderr,
1043                                                  _("%s: shadow passwords required for -f\n"),
1044                                                  Prog);
1045                                         exit (E_USAGE);
1046                                 }
1047                                 fflg = true;
1048                                 break;
1049                         case 'g':
1050                                 grp = getgr_nam_gid (optarg);
1051                                 if (NULL == grp) {
1052                                         fprintf (stderr,
1053                                                  _("%s: group '%s' does not exist\n"),
1054                                                  Prog, optarg);
1055                                         exit (E_NOTFOUND);
1056                                 }
1057                                 if (Dflg) {
1058                                         def_group = grp->gr_gid;
1059                                         def_gname = optarg;
1060                                 } else {
1061                                         user_gid = grp->gr_gid;
1062                                 }
1063                                 gflg = true;
1064                                 break;
1065                         case 'G':
1066                                 if (get_groups (optarg) != 0) {
1067                                         exit (E_NOTFOUND);
1068                                 }
1069                                 if (NULL != user_groups[0]) {
1070                                         do_grp_update = true;
1071                                 }
1072                                 Gflg = true;
1073                                 break;
1074                         case 'h':
1075                                 usage ();
1076                                 break;
1077                         case 'k':
1078                                 def_template = optarg;
1079                                 kflg = true;
1080                                 break;
1081                         case 'K':
1082                                 /*
1083                                  * override login.defs defaults (-K name=value)
1084                                  * example: -K UID_MIN=100 -K UID_MAX=499
1085                                  * note: -K UID_MIN=10,UID_MAX=499 doesn't work yet
1086                                  */
1087                                 cp = strchr (optarg, '=');
1088                                 if (NULL == cp) {
1089                                         fprintf (stderr,
1090                                                  _("%s: -K requires KEY=VALUE\n"),
1091                                                  Prog);
1092                                         exit (E_BAD_ARG);
1093                                 }
1094                                 /* terminate name, point to value */
1095                                 *cp = '\0';
1096                                 cp++;
1097                                 if (putdef_str (optarg, cp) < 0) {
1098                                         exit (E_BAD_ARG);
1099                                 }
1100                                 break;
1101                         case 'l':
1102                                 lflg = true;
1103                                 break;
1104                         case 'm':
1105                                 mflg = true;
1106                                 break;
1107                         case 'M':
1108                                 Mflg = true;
1109                                 break;
1110                         case 'N':
1111                                 Nflg = true;
1112                                 break;
1113                         case 'o':
1114                                 oflg = true;
1115                                 break;
1116                         case 'p':       /* set encrypted password */
1117                                 if (!VALID (optarg)) {
1118                                         fprintf (stderr,
1119                                                  _("%s: invalid field '%s'\n"),
1120                                                  Prog, optarg);
1121                                         exit (E_BAD_ARG);
1122                                 }
1123                                 user_pass = optarg;
1124                                 break;
1125                         case 'r':
1126                                 rflg = true;
1127                                 break;
1128                         case 's':
1129                                 if (   ( !VALID (optarg) )
1130                                     || (   ('\0' != optarg[0])
1131                                         && ('/'  != optarg[0])
1132                                         && ('*'  != optarg[0]) )) {
1133                                         fprintf (stderr,
1134                                                  _("%s: invalid shell '%s'\n"),
1135                                                  Prog, optarg);
1136                                         exit (E_BAD_ARG);
1137                                 }
1138                                 user_shell = optarg;
1139                                 def_shell = optarg;
1140                                 sflg = true;
1141                                 break;
1142                         case 'u':
1143                                 if (   (get_uid (optarg, &user_id) == 0)
1144                                     || (user_id == (gid_t)-1)) {
1145                                         fprintf (stderr,
1146                                                  _("%s: invalid user ID '%s'\n"),
1147                                                  Prog, optarg);
1148                                         exit (E_BAD_ARG);
1149                                 }
1150                                 uflg = true;
1151                                 break;
1152                         case 'U':
1153                                 Uflg = true;
1154                                 break;
1155                         default:
1156                                 usage ();
1157                         }
1158                         anyflag = true;
1159                 }
1160         }
1161
1162         if (!gflg && !Nflg && !Uflg) {
1163                 /* Get the settings from login.defs */
1164                 Uflg = getdef_bool ("USERGROUPS_ENAB");
1165         }
1166
1167         /*
1168          * Certain options are only valid in combination with others.
1169          * Check it here so that they can be specified in any order.
1170          */
1171         if (oflg && !uflg) {
1172                 fprintf (stderr,
1173                          _("%s: %s flag is only allowed with the %s flag\n"),
1174                          Prog, "-o", "-u");
1175                 usage ();
1176         }
1177         if (kflg && !mflg) {
1178                 fprintf (stderr,
1179                          _("%s: %s flag is only allowed with the %s flag\n"),
1180                          Prog, "-k", "-m");
1181                 usage ();
1182         }
1183         if (Uflg && gflg) {
1184                 fprintf (stderr,
1185                          _("%s: options %s and %s conflict\n"),
1186                          Prog, "-U", "-g");
1187                 usage ();
1188         }
1189         if (Uflg && Nflg) {
1190                 fprintf (stderr,
1191                          _("%s: options %s and %s conflict\n"),
1192                          Prog, "-U", "-N");
1193                 usage ();
1194         }
1195         if (mflg && Mflg) {
1196                 fprintf (stderr,
1197                          _("%s: options %s and %s conflict\n"),
1198                          Prog, "-m", "-M");
1199                 usage ();
1200         }
1201
1202         /*
1203          * Either -D or username is required. Defaults can be set with -D
1204          * for the -b, -e, -f, -g, -s options only.
1205          */
1206         if (Dflg) {
1207                 if (optind != argc) {
1208                         usage ();
1209                 }
1210
1211                 if (uflg || oflg || Gflg || dflg || cflg || mflg) {
1212                         usage ();
1213                 }
1214         } else {
1215                 if (optind != argc - 1) {
1216                         usage ();
1217                 }
1218
1219                 user_name = argv[optind];
1220                 if (!is_valid_user_name (user_name)) {
1221                         fprintf (stderr,
1222                                  _("%s: invalid user name '%s'\n"),
1223                                  Prog, user_name);
1224 #ifdef WITH_AUDIT
1225                         audit_logger (AUDIT_ADD_USER, Prog,
1226                                       "adding user",
1227                                       user_name, AUDIT_NO_ID,
1228                                       SHADOW_AUDIT_FAILURE);
1229 #endif
1230                         exit (E_BAD_ARG);
1231                 }
1232                 if (!dflg) {
1233                         char *uh;
1234
1235                         uh = xmalloc (strlen (def_home) +
1236                                       strlen (user_name) + 2);
1237                         sprintf (uh, "%s/%s", def_home, user_name);
1238                         user_home = uh;
1239                 }
1240         }
1241
1242         if (!eflg) {
1243                 user_expire = strtoday (def_expire);
1244         }
1245
1246         if (!gflg) {
1247                 user_gid = def_group;
1248         }
1249
1250         if (!sflg) {
1251                 user_shell = def_shell;
1252         }
1253
1254         create_mail_spool = def_create_mail_spool;
1255
1256         if (!rflg) {
1257                 /* for system accounts defaults are ignored and we
1258                  * do not create a home dir */
1259                 if (getdef_bool("CREATE_HOME")) {
1260                         mflg = true;
1261                 }
1262         }
1263
1264         if (Mflg) {
1265                 /* absolutely sure that we do not create home dirs */
1266                 mflg = false;
1267         }
1268 }
1269
1270 /*
1271  * close_files - close all of the files that were opened
1272  *
1273  *      close_files() closes all of the files that were opened for this
1274  *      new user. This causes any modified entries to be written out.
1275  */
1276 static void close_files (void)
1277 {
1278         if (pw_close () == 0) {
1279                 fprintf (stderr, _("%s: failure while writing changes to %s\n"), Prog, pw_dbname ());
1280                 SYSLOG ((LOG_ERR, "failure while writing changes to %s", pw_dbname ()));
1281                 fail_exit (E_PW_UPDATE);
1282         }
1283         if (is_shadow_pwd && (spw_close () == 0)) {
1284                 fprintf (stderr,
1285                          _("%s: failure while writing changes to %s\n"), Prog, spw_dbname ());
1286                 SYSLOG ((LOG_ERR, "failure while writing changes to %s", spw_dbname ()));
1287                 fail_exit (E_PW_UPDATE);
1288         }
1289         if (do_grp_update) {
1290                 if (gr_close () == 0) {
1291                         fprintf (stderr,
1292                                  _("%s: failure while writing changes to %s\n"), Prog, gr_dbname ());
1293                         SYSLOG ((LOG_ERR, "failure while writing changes to %s", gr_dbname ()));
1294                         fail_exit (E_GRP_UPDATE);
1295                 }
1296 #ifdef  SHADOWGRP
1297                 if (is_shadow_grp && (sgr_close () == 0)) {
1298                         fprintf (stderr,
1299                                  _("%s: failure while writing changes to %s\n"),
1300                                  Prog, sgr_dbname ());
1301                         SYSLOG ((LOG_ERR, "failure while writing changes to %s", sgr_dbname ()));
1302                         fail_exit (E_GRP_UPDATE);
1303                 }
1304 #endif
1305         }
1306         if (is_shadow_pwd) {
1307                 if (spw_unlock () == 0) {
1308                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
1309                         SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
1310 #ifdef WITH_AUDIT
1311                         audit_logger (AUDIT_ADD_USER, Prog,
1312                                       "unlocking shadow file",
1313                                       user_name, AUDIT_NO_ID,
1314                                       SHADOW_AUDIT_FAILURE);
1315 #endif
1316                         /* continue */
1317                 }
1318                 spw_locked = false;
1319         }
1320         if (pw_unlock () == 0) {
1321                 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
1322                 SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
1323 #ifdef WITH_AUDIT
1324                 audit_logger (AUDIT_ADD_USER, Prog,
1325                               "unlocking passwd file",
1326                               user_name, AUDIT_NO_ID,
1327                               SHADOW_AUDIT_FAILURE);
1328 #endif
1329                 /* continue */
1330         }
1331         pw_locked = false;
1332         if (gr_unlock () == 0) {
1333                 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
1334                 SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
1335 #ifdef WITH_AUDIT
1336                 audit_logger (AUDIT_ADD_USER, Prog,
1337                               "unlocking group file",
1338                               user_name, AUDIT_NO_ID,
1339                               SHADOW_AUDIT_FAILURE);
1340 #endif
1341                 /* continue */
1342         }
1343         gr_locked = false;
1344 #ifdef  SHADOWGRP
1345         if (is_shadow_grp) {
1346                 if (sgr_unlock () == 0) {
1347                         fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
1348                         SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
1349 #ifdef WITH_AUDIT
1350                         audit_logger (AUDIT_ADD_USER, Prog,
1351                                       "unlocking gshadow file",
1352                                       user_name, AUDIT_NO_ID,
1353                                       SHADOW_AUDIT_FAILURE);
1354 #endif
1355                         /* continue */
1356                 }
1357                 sgr_locked = false;
1358         }
1359 #endif
1360 }
1361
1362 /*
1363  * open_files - lock and open the password files
1364  *
1365  *      open_files() opens the two password files.
1366  */
1367 static void open_files (void)
1368 {
1369         if (pw_lock () == 0) {
1370                 fprintf (stderr,
1371                          _("%s: cannot lock %s; try again later.\n"),
1372                          Prog, pw_dbname ());
1373                 exit (E_PW_UPDATE);
1374         }
1375         pw_locked = true;
1376         if (pw_open (O_RDWR) == 0) {
1377                 fprintf (stderr, _("%s: cannot open %s\n"), Prog, pw_dbname ());
1378                 fail_exit (E_PW_UPDATE);
1379         }
1380         if (is_shadow_pwd) {
1381                 if (spw_lock () == 0) {
1382                         fprintf (stderr,
1383                                  _("%s: cannot lock %s; try again later.\n"),
1384                                  Prog, spw_dbname ());
1385                         fail_exit (E_PW_UPDATE);
1386                 }
1387                 spw_locked = true;
1388                 if (spw_open (O_RDWR) == 0) {
1389                         fprintf (stderr,
1390                                  _("%s: cannot open %s\n"),
1391                                  Prog, spw_dbname ());
1392                         fail_exit (E_PW_UPDATE);
1393                 }
1394         }
1395
1396         /*
1397          * Lock and open the group file.
1398          */
1399         if (gr_lock () == 0) {
1400                 fprintf (stderr,
1401                          _("%s: cannot lock %s; try again later.\n"),
1402                          Prog, gr_dbname ());
1403                 fail_exit (E_GRP_UPDATE);
1404         }
1405         gr_locked = true;
1406         if (gr_open (O_RDWR) == 0) {
1407                 fprintf (stderr, _("%s: cannot open %s\n"), Prog, gr_dbname ());
1408                 fail_exit (E_GRP_UPDATE);
1409         }
1410 #ifdef  SHADOWGRP
1411         if (is_shadow_grp) {
1412                 if (sgr_lock () == 0) {
1413                         fprintf (stderr,
1414                                  _("%s: cannot lock %s; try again later.\n"),
1415                                  Prog, sgr_dbname ());
1416                         fail_exit (E_GRP_UPDATE);
1417                 }
1418                 sgr_locked = true;
1419                 if (sgr_open (O_RDWR) == 0) {
1420                         fprintf (stderr,
1421                                  _("%s: cannot open %s\n"),
1422                                  Prog, sgr_dbname ());
1423                         fail_exit (E_GRP_UPDATE);
1424                 }
1425         }
1426 #endif
1427 }
1428
1429 static char *empty_list = NULL;
1430
1431 /*
1432  * new_grent - initialize the values in a group file entry
1433  *
1434  *      new_grent() takes all of the values that have been entered and fills
1435  *      in a (struct group) with them.
1436  */
1437
1438 static void new_grent (struct group *grent)
1439 {
1440         memzero (grent, sizeof *grent);
1441         grent->gr_name = (char *) user_name;
1442         grent->gr_passwd = SHADOW_PASSWD_STRING;        /* XXX warning: const */
1443         grent->gr_gid = user_gid;
1444         grent->gr_mem = &empty_list;
1445 }
1446
1447 #ifdef  SHADOWGRP
1448 /*
1449  * new_sgent - initialize the values in a shadow group file entry
1450  *
1451  *      new_sgent() takes all of the values that have been entered and fills
1452  *      in a (struct sgrp) with them.
1453  */
1454
1455 static void new_sgent (struct sgrp *sgent)
1456 {
1457         memzero (sgent, sizeof *sgent);
1458         sgent->sg_name = (char *) user_name;
1459         sgent->sg_passwd = "!"; /* XXX warning: const */
1460         sgent->sg_adm = &empty_list;
1461         sgent->sg_mem = &empty_list;
1462 }
1463 #endif                          /* SHADOWGRP */
1464
1465
1466 /*
1467  * grp_add - add new group file entries
1468  *
1469  *      grp_add() writes the new records to the group files.
1470  */
1471
1472 static void grp_add (void)
1473 {
1474         struct group grp;
1475
1476 #ifdef  SHADOWGRP
1477         struct sgrp sgrp;
1478 #endif                          /* SHADOWGRP */
1479
1480         /*
1481          * Create the initial entries for this new group.
1482          */
1483         new_grent (&grp);
1484 #ifdef  SHADOWGRP
1485         new_sgent (&sgrp);
1486 #endif                          /* SHADOWGRP */
1487
1488         /*
1489          * Write out the new group file entry.
1490          */
1491         if (gr_update (&grp) == 0) {
1492                 fprintf (stderr,
1493                          _("%s: failed to prepare the new %s entry '%s'\n"),
1494                          Prog, gr_dbname (), grp.gr_name);
1495 #ifdef WITH_AUDIT
1496                 audit_logger (AUDIT_ADD_GROUP, Prog,
1497                               "adding group",
1498                               grp.gr_name, AUDIT_NO_ID,
1499                               SHADOW_AUDIT_FAILURE);
1500 #endif
1501                 fail_exit (E_GRP_UPDATE);
1502         }
1503 #ifdef  SHADOWGRP
1504         /*
1505          * Write out the new shadow group entries as well.
1506          */
1507         if (is_shadow_grp && (sgr_update (&sgrp) == 0)) {
1508                 fprintf (stderr,
1509                          _("%s: failed to prepare the new %s entry '%s'\n"),
1510                          Prog, sgr_dbname (), sgrp.sg_name);
1511 #ifdef WITH_AUDIT
1512                 audit_logger (AUDIT_ADD_GROUP, Prog,
1513                               "adding group",
1514                               grp.gr_name, AUDIT_NO_ID,
1515                               SHADOW_AUDIT_FAILURE);
1516 #endif
1517                 fail_exit (E_GRP_UPDATE);
1518         }
1519 #endif                          /* SHADOWGRP */
1520         SYSLOG ((LOG_INFO, "new group: name=%s, GID=%u", user_name, user_gid));
1521 #ifdef WITH_AUDIT
1522         audit_logger (AUDIT_ADD_GROUP, Prog,
1523                       "adding group",
1524                       grp.gr_name, AUDIT_NO_ID,
1525                       SHADOW_AUDIT_SUCCESS);
1526 #endif
1527         do_grp_update = true;
1528 }
1529
1530 static void faillog_reset (uid_t uid)
1531 {
1532         struct faillog fl;
1533         int fd;
1534         off_t offset_uid = (off_t) (sizeof fl) * uid;
1535
1536         if (access (FAILLOG_FILE, F_OK) != 0) {
1537                 return;
1538         }
1539
1540         memzero (&fl, sizeof (fl));
1541
1542         fd = open (FAILLOG_FILE, O_RDWR);
1543         if (   (-1 == fd)
1544             || (lseek (fd, offset_uid, SEEK_SET) != offset_uid)
1545             || (write (fd, &fl, sizeof (fl)) != (ssize_t) sizeof (fl))
1546             || (fsync (fd) != 0)
1547             || (close (fd) != 0)) {
1548                 fprintf (stderr,
1549                          _("%s: failed to reset the faillog entry of UID %lu: %s\n"),
1550                          Prog, (unsigned long) uid, strerror (errno));
1551                 SYSLOG ((LOG_WARN, "failed to reset the faillog entry of UID %lu", (unsigned long) uid));
1552                 /* continue */
1553         }
1554 }
1555
1556 static void lastlog_reset (uid_t uid)
1557 {
1558         struct lastlog ll;
1559         int fd;
1560         off_t offset_uid = (off_t) (sizeof ll) * uid;
1561
1562         if (access (LASTLOG_FILE, F_OK) != 0) {
1563                 return;
1564         }
1565
1566         memzero (&ll, sizeof (ll));
1567
1568         fd = open (LASTLOG_FILE, O_RDWR);
1569         if (   (-1 == fd)
1570             || (lseek (fd, offset_uid, SEEK_SET) != offset_uid)
1571             || (write (fd, &ll, sizeof (ll)) != (ssize_t) sizeof (ll))
1572             || (fsync (fd) != 0)
1573             || (close (fd) != 0)) {
1574                 fprintf (stderr,
1575                          _("%s: failed to reset the lastlog entry of UID %lu: %s\n"),
1576                          Prog, (unsigned long) uid, strerror (errno));
1577                 SYSLOG ((LOG_WARN, "failed to reset the lastlog entry of UID %lu", (unsigned long) uid));
1578                 /* continue */
1579         }
1580 }
1581
1582 /*
1583  * usr_update - create the user entries
1584  *
1585  *      usr_update() creates the password file entries for this user
1586  *      and will update the group entries if required.
1587  */
1588 static void usr_update (void)
1589 {
1590         struct passwd pwent;
1591         struct spwd spent;
1592
1593         /*
1594          * Fill in the password structure with any new fields, making
1595          * copies of strings.
1596          */
1597         new_pwent (&pwent);
1598         new_spent (&spent);
1599
1600         /*
1601          * Create a syslog entry. We need to do this now in case anything
1602          * happens so we know what we were trying to accomplish.
1603          */
1604         SYSLOG ((LOG_INFO,
1605                  "new user: name=%s, UID=%u, GID=%u, home=%s, shell=%s",
1606                  user_name, (unsigned int) user_id,
1607                  (unsigned int) user_gid, user_home, user_shell));
1608
1609         /*
1610          * Initialize faillog and lastlog entries for this UID in case
1611          * it belongs to a previously deleted user. We do it only if
1612          * no user with this UID exists yet (entries for shared UIDs
1613          * are left unchanged).  --marekm
1614          */
1615         /* local, no need for xgetpwuid */
1616         if ((!lflg) && (getpwuid (user_id) == NULL)) {
1617                 faillog_reset (user_id);
1618                 lastlog_reset (user_id);
1619         }
1620
1621         /*
1622          * Put the new (struct passwd) in the table.
1623          */
1624         if (pw_update (&pwent) == 0) {
1625                 fprintf (stderr,
1626                          _("%s: failed to prepare the new %s entry '%s'\n"),
1627                          Prog, pw_dbname (), pwent.pw_name);
1628                 fail_exit (E_PW_UPDATE);
1629         }
1630
1631         /*
1632          * Put the new (struct spwd) in the table.
1633          */
1634         if (is_shadow_pwd && (spw_update (&spent) == 0)) {
1635                 fprintf (stderr,
1636                          _("%s: failed to prepare the new %s entry '%s'\n"),
1637                          Prog, spw_dbname (), spent.sp_namp);
1638 #ifdef WITH_AUDIT
1639                 audit_logger (AUDIT_ADD_USER, Prog,
1640                               "adding shadow password",
1641                               user_name, (unsigned int) user_id,
1642                               SHADOW_AUDIT_FAILURE);
1643 #endif
1644                 fail_exit (E_PW_UPDATE);
1645         }
1646 #ifdef WITH_AUDIT
1647         audit_logger (AUDIT_ADD_USER, Prog,
1648                       "adding user",
1649                       user_name, (unsigned int) user_id,
1650                       SHADOW_AUDIT_SUCCESS);
1651 #endif
1652
1653         /*
1654          * Do any group file updates for this user.
1655          */
1656         if (do_grp_update) {
1657                 grp_update ();
1658         }
1659 }
1660
1661 /*
1662  * create_home - create the user's home directory
1663  *
1664  *      create_home() creates the user's home directory if it does not
1665  *      already exist. It will be created mode 755 owned by the user
1666  *      with the user's default group.
1667  */
1668 static void create_home (void)
1669 {
1670         if (access (user_home, F_OK) != 0) {
1671                 /* XXX - create missing parent directories.  --marekm */
1672                 if (mkdir (user_home, 0) != 0) {
1673                         fprintf (stderr,
1674                                  _("%s: cannot create directory %s\n"),
1675                                  Prog, user_home);
1676 #ifdef WITH_AUDIT
1677                         audit_logger (AUDIT_ADD_USER, Prog,
1678                                       "adding home directory",
1679                                       user_name, (unsigned int) user_id,
1680                                       SHADOW_AUDIT_FAILURE);
1681 #endif
1682                         fail_exit (E_HOMEDIR);
1683                 }
1684                 chown (user_home, user_id, user_gid);
1685                 chmod (user_home,
1686                        0777 & ~getdef_num ("UMASK", GETDEF_DEFAULT_UMASK));
1687                 home_added = true;
1688 #ifdef WITH_AUDIT
1689                 audit_logger (AUDIT_ADD_USER, Prog,
1690                               "adding home directory",
1691                               user_name, (unsigned int) user_id,
1692                               SHADOW_AUDIT_SUCCESS);
1693 #endif
1694         }
1695 }
1696
1697 /*
1698  * create_mail - create the user's mail spool
1699  *
1700  *      create_mail() creates the user's mail spool if it does not already
1701  *      exist. It will be created mode 660 owned by the user and group
1702  *      'mail'
1703  */
1704 static void create_mail (void)
1705 {
1706         char *spool, *file;
1707         int fd;
1708         struct group *gr;
1709         gid_t gid;
1710         mode_t mode;
1711
1712         if (strcasecmp (create_mail_spool, "yes") == 0) {
1713                 spool = getdef_str ("MAIL_DIR");
1714                 if (NULL == spool) {
1715                         spool = "/var/mail";
1716                 }
1717                 file = alloca (strlen (spool) + strlen (user_name) + 2);
1718                 sprintf (file, "%s/%s", spool, user_name);
1719                 fd = open (file, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0);
1720                 if (fd < 0) {
1721                         perror (_("Creating mailbox file"));
1722                         return;
1723                 }
1724
1725                 gr = getgrnam ("mail"); /* local, no need for xgetgrnam */
1726                 if (NULL == gr) {
1727                         fputs (_("Group 'mail' not found. Creating the user mailbox file with 0600 mode.\n"),
1728                                stderr);
1729                         gid = user_gid;
1730                         mode = 0600;
1731                 } else {
1732                         gid = gr->gr_gid;
1733                         mode = 0660;
1734                 }
1735
1736                 if (   (fchown (fd, user_id, gid) != 0)
1737                     || (fchmod (fd, mode) != 0)) {
1738                         perror (_("Setting mailbox file permissions"));
1739                 }
1740
1741                 fsync (fd);
1742                 close (fd);
1743         }
1744 }
1745
1746 /*
1747  * main - useradd command
1748  */
1749 int main (int argc, char **argv)
1750 {
1751 #ifdef ACCT_TOOLS_SETUID
1752 #ifdef USE_PAM
1753         pam_handle_t *pamh = NULL;
1754         int retval;
1755 #endif                          /* USE_PAM */
1756 #endif                          /* ACCT_TOOLS_SETUID */
1757
1758 #ifdef WITH_AUDIT
1759         audit_help_open ();
1760 #endif
1761
1762         /*
1763          * Get my name so that I can use it to report errors.
1764          */
1765         Prog = Basename (argv[0]);
1766
1767         (void) setlocale (LC_ALL, "");
1768         (void) bindtextdomain (PACKAGE, LOCALEDIR);
1769         (void) textdomain (PACKAGE);
1770
1771         OPENLOG ("useradd");
1772
1773         sys_ngroups = sysconf (_SC_NGROUPS_MAX);
1774         user_groups = malloc ((1 + sys_ngroups) * sizeof (char *));
1775         /*
1776          * Initialize the list to be empty
1777          */
1778         user_groups[0] = (char *) 0;
1779
1780
1781         is_shadow_pwd = spw_file_present ();
1782 #ifdef SHADOWGRP
1783         is_shadow_grp = sgr_file_present ();
1784 #endif
1785
1786         get_defaults ();
1787
1788         process_flags (argc, argv);
1789
1790 #ifdef ACCT_TOOLS_SETUID
1791 #ifdef USE_PAM
1792         {
1793                 struct passwd *pampw;
1794                 pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
1795                 if (pampw == NULL) {
1796                         fprintf (stderr,
1797                                  _("%s: Cannot determine your user name.\n"),
1798                                  Prog);
1799                         fail_exit (1);
1800                 }
1801
1802                 retval = pam_start ("useradd", pampw->pw_name, &conv, &pamh);
1803         }
1804
1805         if (PAM_SUCCESS == retval) {
1806                 retval = pam_authenticate (pamh, 0);
1807         }
1808
1809         if (PAM_SUCCESS == retval) {
1810                 retval = pam_acct_mgmt (pamh, 0);
1811         }
1812
1813         if (NULL != pamh) {
1814                 (void) pam_end (pamh, retval);
1815         }
1816         if (PAM_SUCCESS != retval) {
1817                 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
1818                 fail_exit (1);
1819         }
1820 #endif                          /* USE_PAM */
1821 #endif                          /* ACCT_TOOLS_SETUID */
1822
1823         /*
1824          * See if we are messing with the defaults file, or creating
1825          * a new user.
1826          */
1827         if (Dflg) {
1828                 if (gflg || bflg || fflg || eflg || sflg) {
1829                         exit ((set_defaults () != 0) ? 1 : 0);
1830                 }
1831
1832                 show_defaults ();
1833                 exit (E_SUCCESS);
1834         }
1835
1836         /*
1837          * Start with a quick check to see if the user exists.
1838          */
1839         if (getpwnam (user_name) != NULL) { /* local, no need for xgetpwnam */
1840                 fprintf (stderr, _("%s: user '%s' already exists\n"), Prog, user_name);
1841 #ifdef WITH_AUDIT
1842                 audit_logger (AUDIT_ADD_USER, Prog,
1843                               "adding user",
1844                               user_name, AUDIT_NO_ID,
1845                               SHADOW_AUDIT_FAILURE);
1846 #endif
1847                 fail_exit (E_NAME_IN_USE);
1848         }
1849
1850         /*
1851          * Don't blindly overwrite a group when a user is added...
1852          * If you already have a group username, and want to add the user
1853          * to that group, use useradd -g username username.
1854          * --bero
1855          */
1856         if (Uflg) {
1857                 /* local, no need for xgetgrnam */
1858                 if (getgrnam (user_name) != NULL) {
1859                         fprintf (stderr,
1860                                  _("%s: group %s exists - if you want to add this user to that group, use -g.\n"),
1861                                  Prog, user_name);
1862 #ifdef WITH_AUDIT
1863                         audit_logger (AUDIT_ADD_USER, Prog,
1864                                       "adding group",
1865                                       user_name, AUDIT_NO_ID,
1866                                       SHADOW_AUDIT_FAILURE);
1867 #endif
1868                         fail_exit (E_NAME_IN_USE);
1869                 }
1870         }
1871
1872         /*
1873          * Do the hard stuff:
1874          * - open the files,
1875          * - create the user entries,
1876          * - create the home directory,
1877          * - create user mail spool,
1878          * - flush nscd caches for passwd and group services,
1879          * - then close and update the files.
1880          */
1881         open_files ();
1882
1883         if (!oflg) {
1884                 /* first, seek for a valid uid to use for this user.
1885                  * We do this because later we can use the uid we found as
1886                  * gid too ... --gafton */
1887                 if (!uflg) {
1888                         if (find_new_uid (rflg, &user_id, NULL) < 0) {
1889                                 fprintf (stderr, _("%s: can't create user\n"), Prog);
1890                                 fail_exit (E_UID_IN_USE);
1891                         }
1892                 } else {
1893                         if (getpwuid (user_id) != NULL) {
1894                                 fprintf (stderr,
1895                                          _("%s: UID %lu is not unique\n"),
1896                                          Prog, (unsigned long) user_id);
1897 #ifdef WITH_AUDIT
1898                                 audit_logger (AUDIT_ADD_USER, Prog,
1899                                               "adding user",
1900                                               user_name, (unsigned int) user_id,
1901                                               SHADOW_AUDIT_FAILURE);
1902 #endif
1903                                 fail_exit (E_UID_IN_USE);
1904                         }
1905                 }
1906         }
1907
1908         /* do we have to add a group for that user? This is why we need to
1909          * open the group files in the open_files() function  --gafton */
1910         if (Uflg) {
1911                 if (find_new_gid (rflg, &user_gid, &user_id) < 0) {
1912                         fprintf (stderr,
1913                                  _("%s: can't create group\n"),
1914                                  Prog);
1915                         fail_exit (4);
1916                 }
1917                 grp_add ();
1918         }
1919
1920         usr_update ();
1921
1922         if (mflg) {
1923                 create_home ();
1924                 if (home_added) {
1925                         copy_tree (def_template, user_home, user_id, user_gid);
1926                 } else {
1927                         fprintf (stderr,
1928                                  _("%s: warning: the home directory already exists.\n"
1929                                    "Not copying any file from skel directory into it.\n"),
1930                                  Prog);
1931                 }
1932
1933         }
1934
1935         /* Do not create mail directory for system accounts */
1936         if( !rflg ) {
1937                 create_mail ();
1938         }
1939
1940         close_files ();
1941
1942         nscd_flush_cache ("passwd");
1943         nscd_flush_cache ("group");
1944
1945         return E_SUCCESS;
1946 }
1947