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