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