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 - 2008, Nicolas François
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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.
50 #include <sys/types.h>
58 #include "prototypes.h"
67 #define SKEL_DIR "/etc/skel"
69 #ifndef USER_DEFAULTS_FILE
70 #define USER_DEFAULTS_FILE "/etc/default/useradd"
71 #define NEW_USER_FILE "/etc/default/nuaddXXXXXX"
74 * Needed for MkLinux DR1/2/2.1 - J.
77 #define LASTLOG_FILE "/var/log/lastlog"
83 * These defaults are used if there is no defaults file.
85 static gid_t def_group = 100;
86 static const char *def_gname = "other";
87 static const char *def_home = "/home";
88 static const char *def_shell = "";
89 static const char *def_template = SKEL_DIR;
90 static const char *def_create_mail_spool = "no";
92 static long def_inactive = -1;
93 static const char *def_expire = "";
95 static char def_file[] = USER_DEFAULTS_FILE;
97 #define VALID(s) (strcspn (s, ":\n") == strlen (s))
99 static const char *user_name = "";
100 static const char *user_pass = "!";
101 static uid_t user_id;
102 static gid_t user_gid;
103 static const char *user_comment = "";
104 static const char *user_home = "";
105 static const char *user_shell = "";
106 static const char *create_mail_spool = "";
108 static long user_expire = -1;
109 static bool is_shadow_pwd;
112 static bool is_shadow_grp;
113 static bool sgr_locked = false;
115 static bool pw_locked = false;
116 static bool gr_locked = false;
117 static bool spw_locked = false;
118 static char **user_groups; /* NULL-terminated list */
119 static long sys_ngroups;
120 static bool do_grp_update = false; /* group files need to be updated */
125 bflg = false, /* new default root of home directory */
126 cflg = false, /* comment (GECOS) field for new account */
127 dflg = false, /* home directory for new account */
128 Dflg = false, /* set/show new user default values */
129 eflg = false, /* days since 1970-01-01 when account is locked */
130 fflg = false, /* days until account with expired password is locked */
131 gflg = false, /* primary group ID for new account */
132 Gflg = false, /* secondary group set for new account */
133 kflg = false, /* specify a directory to fill new user directory */
134 lflg = false, /* do not add user to lastlog database file */
135 mflg = false, /* create user's home directory if it doesn't exist */
136 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) */
137 oflg = false, /* permit non-unique user ID to be specified with -u */
138 rflg = false, /* create a system account */
139 sflg = false, /* shell program for new account */
140 uflg = false, /* specify user ID for new account */
141 Uflg = false; /* create a group having the same name as the user */
143 static bool home_added = false;
148 #define E_SUCCESS 0 /* success */
149 #define E_PW_UPDATE 1 /* can't update password file */
150 #define E_USAGE 2 /* invalid command syntax */
151 #define E_BAD_ARG 3 /* invalid argument to option */
152 #define E_UID_IN_USE 4 /* UID already in use (and no -o) */
153 #define E_NOTFOUND 6 /* specified group doesn't exist */
154 #define E_NAME_IN_USE 9 /* username already in use */
155 #define E_GRP_UPDATE 10 /* can't update group file */
156 #define E_HOMEDIR 12 /* can't create home directory */
157 #define E_MAIL_SPOOL 13 /* can't create mail spool */
159 #define DGROUP "GROUP="
161 #define SHELL "SHELL="
162 #define INACT "INACTIVE="
163 #define EXPIRE "EXPIRE="
165 #define CREATE_MAIL_SPOOL "CREATE_MAIL_SPOOL="
167 /* local function prototypes */
168 static void fail_exit (int);
169 static struct group *getgr_nam_gid (const char *);
170 static long get_number (const char *);
171 static uid_t get_uid (const char *);
172 static void get_defaults (void);
173 static void show_defaults (void);
174 static int set_defaults (void);
175 static int get_groups (char *);
176 static void usage (void);
177 static void new_pwent (struct passwd *);
179 static long scale_age (long);
180 static void new_spent (struct spwd *);
181 static void grp_update (void);
183 static void process_flags (int argc, char **argv);
184 static void close_files (void);
185 static void open_files (void);
186 static void faillog_reset (uid_t);
187 static void lastlog_reset (uid_t);
188 static void usr_update (void);
189 static void create_home (void);
190 static void create_mail (void);
193 * fail_exit - undo as much as possible
195 static void fail_exit (int code)
202 if (spw_unlock () == 0) {
203 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
204 SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
206 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
207 "unlocking shadow file",
208 user_name, AUDIT_NO_ID, 0);
214 if (pw_unlock () == 0) {
215 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
216 SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
218 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
219 "unlocking passwd file",
220 user_name, AUDIT_NO_ID, 0);
226 if (gr_unlock () == 0) {
227 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
228 SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
230 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
231 "unlocking group file",
232 user_name, AUDIT_NO_ID, 0);
239 if (sgr_unlock () == 0) {
240 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
241 SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
243 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
244 "unlocking gshadow file",
245 user_name, AUDIT_NO_ID, 0);
253 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
255 user_name, AUDIT_NO_ID, 0);
257 SYSLOG ((LOG_INFO, "failed adding user '%s', data deleted", user_name));
261 static struct group *getgr_nam_gid (const char *grname)
266 gid = strtol (grname, &errptr, 10);
267 if (*grname != '\0' && *errptr == '\0' && errno != ERANGE && gid >= 0) {
268 return xgetgrgid ((gid_t) gid);
270 return xgetgrnam (grname);
273 static long get_number (const char *numstr)
278 val = strtol (numstr, &errptr, 10);
279 if (('\0' != *errptr) || (ERANGE == errno)) {
280 fprintf (stderr, _("%s: invalid numeric argument '%s'\n"), Prog,
287 static uid_t get_uid (const char *uidstr)
292 val = strtol (uidstr, &errptr, 10);
293 if (('\0' != *errptr) || (ERANGE == errno) || (val < 0)) {
295 _("%s: invalid numeric argument '%s'\n"), Prog,
302 #define MATCH(x,y) (strncmp((x),(y),strlen(y)) == 0)
305 * get_defaults - read the defaults file
307 * get_defaults() reads the defaults file for this command. It sets the
308 * various values from the file, or uses built-in default values if the
309 * file does not exist.
311 static void get_defaults (void)
318 * Open the defaults file for reading.
321 fp = fopen (def_file, "r");
327 * Read the file a line at a time. Only the lines that have relevant
328 * values are used, everything else can be ignored.
330 while (fgets (buf, (int) sizeof buf, fp) == buf) {
331 cp = strrchr (buf, '\n');
336 cp = strchr (buf, '=');
344 * Primary GROUP identifier
346 if (MATCH (buf, DGROUP)) {
347 unsigned int val = (unsigned int) strtoul (cp, &ep, 10);
348 const struct group *grp;
350 if (*cp != '\0' && *ep == '\0') { /* valid number */
352 /* local, no need for xgetgrgid */
353 grp = getgrgid (def_group);
355 def_gname = xstrdup (grp->gr_name);
358 _("%s: GID '%s' does not exist\n"),
361 /* local, no need for xgetgrnam */
362 } else if ((grp = getgrnam (cp)) != NULL) {
363 def_group = grp->gr_gid;
364 def_gname = xstrdup (cp);
367 _("%s: group '%s' does not exist\n"), Prog, cp);
372 * Default HOME filesystem
374 else if (MATCH (buf, HOME)) {
375 def_home = xstrdup (cp);
379 * Default Login Shell command
381 else if (MATCH (buf, SHELL)) {
382 def_shell = xstrdup (cp);
386 * Default Password Inactive value
388 else if (MATCH (buf, INACT)) {
389 long val = strtol (cp, &ep, 10);
391 if (('\0' != *cp) || (ERANGE == errno)) {
399 * Default account expiration date
401 else if (MATCH (buf, EXPIRE)) {
402 def_expire = xstrdup (cp);
406 * Default Skeleton information
408 else if (MATCH (buf, SKEL)) {
410 cp = SKEL_DIR; /* XXX warning: const */
413 def_template = xstrdup (cp);
417 * Create by default user mail spool or not ?
419 else if (MATCH (buf, CREATE_MAIL_SPOOL)) {
421 cp = CREATE_MAIL_SPOOL; /* XXX warning: const */
424 def_create_mail_spool = xstrdup (cp);
430 * show_defaults - show the contents of the defaults file
432 * show_defaults() displays the values that are used from the default
433 * file and the built-in values.
435 static void show_defaults (void)
437 printf ("GROUP=%u\n", (unsigned int) def_group);
438 printf ("HOME=%s\n", def_home);
439 printf ("INACTIVE=%ld\n", def_inactive);
440 printf ("EXPIRE=%s\n", def_expire);
441 printf ("SHELL=%s\n", def_shell);
442 printf ("SKEL=%s\n", def_template);
443 printf ("CREATE_MAIL_SPOOL=%s\n", def_create_mail_spool);
447 * set_defaults - write new defaults file
449 * set_defaults() re-writes the defaults file using the values that
450 * are currently set. Duplicated lines are pruned, missing lines are
451 * added, and unrecognized lines are copied as is.
453 static int set_defaults (void)
458 static char new_file[] = NEW_USER_FILE;
461 bool out_group = false;
462 bool out_home = false;
463 bool out_inactive = false;
464 bool out_expire = false;
465 bool out_shell = false;
466 bool out_skel = false;
467 bool out_create_mail_spool = false;
470 * Create a temporary file to copy the new output to.
472 ofd = mkstemp (new_file);
475 _("%s: cannot create new defaults file\n"), Prog);
479 ofp = fdopen (ofd, "w");
481 fprintf (stderr, _("%s: cannot open new defaults file\n"),
487 * Open the existing defaults file and copy the lines to the
488 * temporary file, using any new values. Each line is checked
489 * to insure that it is not output more than once.
491 ifp = fopen (def_file, "r");
493 fprintf (ofp, "# useradd defaults file\n");
497 while (fgets (buf, (int) sizeof buf, ifp) == buf) {
498 cp = strrchr (buf, '\n');
503 if (!out_group && MATCH (buf, DGROUP)) {
504 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
506 } else if (!out_home && MATCH (buf, HOME)) {
507 fprintf (ofp, HOME "%s\n", def_home);
509 } else if (!out_inactive && MATCH (buf, INACT)) {
510 fprintf (ofp, INACT "%ld\n", def_inactive);
512 } else if (!out_expire && MATCH (buf, EXPIRE)) {
513 fprintf (ofp, EXPIRE "%s\n", def_expire);
515 } else if (!out_shell && MATCH (buf, SHELL)) {
516 fprintf (ofp, SHELL "%s\n", def_shell);
518 } else if (!out_skel && MATCH (buf, SKEL)) {
519 fprintf (ofp, SKEL "%s\n", def_template);
521 } else if (!out_create_mail_spool
522 && MATCH (buf, CREATE_MAIL_SPOOL)) {
523 fprintf (ofp, CREATE_MAIL_SPOOL "%s\n",
524 def_create_mail_spool);
525 out_create_mail_spool = true;
527 fprintf (ofp, "%s\n", buf);
533 * Check each line to insure that every line was output. This
534 * causes new values to be added to a file which did not previously
535 * have an entry for that value.
538 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
540 fprintf (ofp, HOME "%s\n", def_home);
542 fprintf (ofp, INACT "%ld\n", def_inactive);
544 fprintf (ofp, EXPIRE "%s\n", def_expire);
546 fprintf (ofp, SHELL "%s\n", def_shell);
548 fprintf (ofp, SKEL "%s\n", def_template);
550 if (!out_create_mail_spool)
551 fprintf (ofp, CREATE_MAIL_SPOOL "%s\n", def_create_mail_spool);
554 * Flush and close the file. Check for errors to make certain
555 * the new file is intact.
558 if ((ferror (ofp) != 0) || (fclose (ofp) != 0)) {
564 * Rename the current default file to its backup name.
566 snprintf (buf, sizeof buf, "%s-", def_file);
567 if ((rename (def_file, buf) != 0) && (ENOENT != errno)) {
568 snprintf (buf, sizeof buf, _("%s: rename: %s"), Prog, def_file);
575 * Rename the new default file to its correct name.
577 if (rename (new_file, def_file) != 0) {
578 snprintf (buf, sizeof buf, _("%s: rename: %s"), Prog, new_file);
583 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
584 "changing user defaults",
585 NULL, AUDIT_NO_ID, 1);
588 "useradd defaults: GROUP=%u, HOME=%s, SHELL=%s, INACTIVE=%ld, "
589 "EXPIRE=%s, SKEL=%s, CREATE_MAIL_SPOOL=%s",
590 (unsigned int) def_group, def_home, def_shell,
591 def_inactive, def_expire, def_template,
592 def_create_mail_spool));
597 * get_groups - convert a list of group names to an array of group IDs
599 * get_groups() takes a comma-separated list of group names and
600 * converts it to a NULL-terminated array. Any unknown group
601 * names are reported as errors.
603 static int get_groups (char *list)
606 const struct group *grp;
615 * So long as there is some data to be converted, strip off
616 * each name and look it up. A mix of numerical and string
617 * values for group identifiers is permitted.
621 * Strip off a single name from the list
623 cp = strchr (list, ',');
629 * Names starting with digits are treated as numerical
630 * GID values, otherwise the string is looked up as is.
632 grp = getgr_nam_gid (list);
635 * There must be a match, either by GID value or by
639 fprintf (stderr, _("%s: group '%s' does not exist\n"),
646 * If the group doesn't exist, don't dump core...
647 * Instead, try the next one. --marekm
655 * Don't add this group if they are an NIS group. Tell
656 * the user to go to the server for this group.
660 _("%s: group '%s' is a NIS group.\n"),
666 if (ngroups == sys_ngroups) {
669 ("%s: too many groups specified (max %d).\n"),
675 * Add the group name to the user's list of groups.
677 user_groups[ngroups++] = xstrdup (grp->gr_name);
678 } while (NULL != list);
680 user_groups[ngroups] = (char *) 0;
683 * Any errors in finding group names are fatal
693 * usage - display usage message and exit
695 static void usage (void)
697 fputs (_("Usage: useradd [options] LOGIN\n"
700 " -b, --base-dir BASE_DIR base directory for the new user account\n"
702 " -c, --comment COMMENT set the GECOS field for the new user account\n"
703 " -d, --home-dir HOME_DIR home directory for the new user account\n"
704 " -D, --defaults print or save modified default useradd\n"
706 " -e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE\n"
707 " -f, --inactive INACTIVE set password inactive after expiration\n"
709 " -g, --gid GROUP force use GROUP for the new user account\n"
710 " -G, --groups GROUPS list of supplementary groups for the new\n"
712 " -h, --help display this help message and exit\n"
713 " -k, --skel SKEL_DIR specify an alternative skel directory\n"
714 " -K, --key KEY=VALUE overrides /etc/login.defs defaults\n"
715 " -l, do not add the user to the lastlog and\n"
716 " faillog databases\n"
717 " -m, --create-home create home directory for the new user\n"
719 " -N, --no-user-group do not create a group with the same name as\n"
721 " -o, --non-unique allow create user with duplicate\n"
722 " (non-unique) UID\n"
723 " -p, --password PASSWORD use encrypted password for the new user\n"
725 " -r, --system create a system account\n"
726 " -s, --shell SHELL the login shell for the new user account\n"
727 " -u, --uid UID force use the UID for the new user account\n"
728 " -U, --user-group create a group with the same name as the user\n"
734 * new_pwent - initialize the values in a password file entry
736 * new_pwent() takes all of the values that have been entered and
737 * fills in a (struct passwd) with them.
739 static void new_pwent (struct passwd *pwent)
741 memzero (pwent, sizeof *pwent);
742 pwent->pw_name = (char *) user_name;
744 pwent->pw_passwd = (char *) SHADOW_PASSWD_STRING;
746 pwent->pw_passwd = (char *) user_pass;
749 pwent->pw_uid = user_id;
750 pwent->pw_gid = user_gid;
751 pwent->pw_gecos = (char *) user_comment;
752 pwent->pw_dir = (char *) user_home;
753 pwent->pw_shell = (char *) user_shell;
756 static long scale_age (long x)
762 return x * (DAY / SCALE);
766 * new_spent - initialize the values in a shadow password file entry
768 * new_spent() takes all of the values that have been entered and
769 * fills in a (struct spwd) with them.
771 static void new_spent (struct spwd *spent)
773 memzero (spent, sizeof *spent);
774 spent->sp_namp = (char *) user_name;
775 spent->sp_pwdp = (char *) user_pass;
776 spent->sp_lstchg = (long) time ((time_t *) 0) / SCALE;
778 spent->sp_min = scale_age (getdef_num ("PASS_MIN_DAYS", -1));
779 spent->sp_max = scale_age (getdef_num ("PASS_MAX_DAYS", -1));
780 spent->sp_warn = scale_age (getdef_num ("PASS_WARN_AGE", -1));
781 spent->sp_inact = scale_age (def_inactive);
782 spent->sp_expire = scale_age (user_expire);
784 spent->sp_min = scale_age (-1);
785 spent->sp_max = scale_age (-1);
786 spent->sp_warn = scale_age (-1);
787 spent->sp_inact = scale_age (-1);
788 spent->sp_expire = scale_age (-1);
790 spent->sp_flag = SHADOW_SP_FLAG_UNSET;
794 * grp_update - add user to secondary group set
796 * grp_update() takes the secondary group set given in user_groups
797 * and adds the user to each group given by that set.
799 * The group files are opened and locked in open_files().
801 * close_files() should be called afterwards to commit the changes
802 * and unlocking the group files.
804 static void grp_update (void)
806 const struct group *grp;
810 const struct sgrp *sgrp;
815 * Scan through the entire group file looking for the groups that
816 * the user is a member of.
818 for (gr_rewind (), grp = gr_next (); NULL != grp; grp = gr_next ()) {
821 * See if the user specified this group as one of their
824 if (!is_on_list (user_groups, grp->gr_name)) {
829 * Make a copy - gr_update() will free() everything
830 * from the old entry, and we need it later.
832 ngrp = __gr_dup (grp);
835 _("%s: Out of memory. Cannot update %s.\n"),
837 fail_exit (E_GRP_UPDATE); /* XXX */
841 * Add the username to the list of group members and
842 * update the group entry to reflect the change.
844 ngrp->gr_mem = add_list (ngrp->gr_mem, user_name);
845 if (gr_update (ngrp) == 0) {
847 _("%s: failed to prepare the new %s entry '%s'\n"),
848 Prog, gr_dbname (), ngrp->gr_name);
849 fail_exit (E_GRP_UPDATE);
852 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
853 "adding user to group",
854 user_name, AUDIT_NO_ID, 1);
856 SYSLOG ((LOG_INFO, "add '%s' to group '%s'",
857 user_name, ngrp->gr_name));
865 * Scan through the entire shadow group file looking for the groups
866 * that the user is a member of. The administrative list isn't
869 for (sgr_rewind (), sgrp = sgr_next (); NULL != sgrp; sgrp = sgr_next ()) {
872 * See if the user specified this group as one of their
875 if (gr_locate (sgrp->sg_name) == NULL) {
879 if (!is_on_list (user_groups, sgrp->sg_name)) {
884 * Make a copy - sgr_update() will free() everything
885 * from the old entry, and we need it later.
887 nsgrp = __sgr_dup (sgrp);
890 _("%s: Out of memory. Cannot update %s.\n"),
891 Prog, sgr_dbname ());
892 fail_exit (E_GRP_UPDATE); /* XXX */
896 * Add the username to the list of group members and
897 * update the group entry to reflect the change.
899 nsgrp->sg_mem = add_list (nsgrp->sg_mem, user_name);
900 if (sgr_update (nsgrp) == 0) {
902 _("%s: failed to prepare the new %s entry '%s'\n"),
903 Prog, sgr_dbname (), nsgrp->sg_name);
904 fail_exit (E_GRP_UPDATE);
907 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
908 "adding user to shadow group",
909 user_name, AUDIT_NO_ID, 1);
911 SYSLOG ((LOG_INFO, "add '%s' to shadow group '%s'",
912 user_name, nsgrp->sg_name));
914 #endif /* SHADOWGRP */
918 * process_flags - perform command line argument setting
920 * process_flags() interprets the command line arguments and sets
921 * the values that the user will be created with accordingly. The
922 * values are checked for sanity.
924 static void process_flags (int argc, char **argv)
926 const struct group *grp;
927 bool anyflag = false;
932 * Parse the command line options.
935 static struct option long_options[] = {
936 {"base-dir", required_argument, NULL, 'b'},
937 {"comment", required_argument, NULL, 'c'},
938 {"home-dir", required_argument, NULL, 'd'},
939 {"defaults", no_argument, NULL, 'D'},
940 {"expiredate", required_argument, NULL, 'e'},
941 {"inactive", required_argument, NULL, 'f'},
942 {"gid", required_argument, NULL, 'g'},
943 {"groups", required_argument, NULL, 'G'},
944 {"help", no_argument, NULL, 'h'},
945 {"skel", required_argument, NULL, 'k'},
946 {"key", required_argument, NULL, 'K'},
947 {"create-home", no_argument, NULL, 'm'},
948 {"no-user-group", no_argument, NULL, 'N'},
949 {"non-unique", no_argument, NULL, 'o'},
950 {"password", required_argument, NULL, 'p'},
951 {"system", no_argument, NULL, 'r'},
952 {"shell", required_argument, NULL, 's'},
953 {"uid", required_argument, NULL, 'u'},
954 {"user-group", no_argument, NULL, 'U'},
955 {NULL, 0, NULL, '\0'}
958 getopt_long (argc, argv, "b:c:d:De:f:g:G:k:K:lmMNop:rs:u:U",
959 long_options, NULL)) != -1) {
962 if ( ( !VALID (optarg) )
963 || ( optarg[0] != '/' )) {
965 _("%s: invalid base directory '%s'\n"),
973 if (!VALID (optarg)) {
975 _("%s: invalid comment '%s'\n"),
979 user_comment = optarg;
983 if ( ( !VALID (optarg) )
984 || ( optarg[0] != '/' )) {
986 _("%s: invalid home directory '%s'\n"),
1000 if ('\0' != *optarg) {
1001 user_expire = strtoday (optarg);
1002 if (user_expire == -1) {
1004 _("%s: invalid date '%s'\n"),
1013 * -e "" is allowed - it's a no-op without /etc/shadow
1015 if (('\0' != *optarg) && !is_shadow_pwd) {
1017 _("%s: shadow passwords required for -e\n"),
1022 def_expire = optarg;
1027 def_inactive = get_number (optarg);
1029 * -f -1 is allowed - it's a no-op without /etc/shadow
1031 if ((-1 != def_inactive) && !is_shadow_pwd) {
1034 ("%s: shadow passwords required for -f\n"),
1041 grp = getgr_nam_gid (optarg);
1044 _("%s: group '%s' does not exist\n"),
1049 def_group = grp->gr_gid;
1052 user_gid = grp->gr_gid;
1057 if (get_groups (optarg) != 0) {
1060 if (NULL != user_groups[0]) {
1061 do_grp_update = true;
1069 def_template = optarg;
1074 * override login.defs defaults (-K name=value)
1075 * example: -K UID_MIN=100 -K UID_MAX=499
1076 * note: -K UID_MIN=10,UID_MAX=499 doesn't work yet
1078 cp = strchr (optarg, '=');
1081 _("%s: -K requires KEY=VALUE\n"),
1085 /* terminate name, point to value */
1088 if (putdef_str (optarg, cp) < 0) {
1104 case 'p': /* set encrypted password */
1105 if (!VALID (optarg)) {
1107 _("%s: invalid field '%s'\n"),
1117 if ( ( !VALID (optarg) )
1118 || ( ('\0' != optarg[0])
1119 && ('/' != optarg[0])
1120 && ('*' != optarg[0]) )) {
1122 _("%s: invalid shell '%s'\n"),
1126 user_shell = optarg;
1131 user_id = get_uid (optarg);
1144 if (!gflg && !Nflg && !Uflg) {
1145 /* Get the settings from login.defs */
1146 Uflg = getdef_bool ("USERGROUPS_ENAB");
1150 * Certain options are only valid in combination with others.
1151 * Check it here so that they can be specified in any order.
1153 if (oflg && !uflg) {
1155 _("%s: %s flag is only allowed with the %s flag\n"),
1159 if (kflg && !mflg) {
1161 _("%s: %s flag is only allowed with the %s flag\n"),
1167 _("%s: options %s and %s conflict\n"),
1173 _("%s: options %s and %s conflict\n"),
1179 * Either -D or username is required. Defaults can be set with -D
1180 * for the -b, -e, -f, -g, -s options only.
1183 if (optind != argc) {
1187 if (uflg || oflg || Gflg || dflg || cflg || mflg) {
1191 if (optind != argc - 1) {
1195 user_name = argv[optind];
1196 if (!is_valid_user_name (user_name)) {
1198 _("%s: invalid user name '%s'\n"),
1201 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1203 user_name, AUDIT_NO_ID, 0);
1210 uh = xmalloc (strlen (def_home) +
1211 strlen (user_name) + 2);
1212 sprintf (uh, "%s/%s", def_home, user_name);
1218 user_expire = strtoday (def_expire);
1222 user_gid = def_group;
1226 user_shell = def_shell;
1229 /* TODO: add handle change default spool mail creation by
1230 -K CREATE_MAIL_SPOOL={yes,no}. It need rewrite internal API for handle
1231 shadow tools configuration */
1232 create_mail_spool = def_create_mail_spool;
1236 * close_files - close all of the files that were opened
1238 * close_files() closes all of the files that were opened for this
1239 * new user. This causes any modified entries to be written out.
1241 static void close_files (void)
1243 if (pw_close () == 0) {
1244 fprintf (stderr, _("%s: failure while writing changes to %s\n"), Prog, pw_dbname ());
1245 SYSLOG ((LOG_ERR, "failure while writing changes to %s", pw_dbname ()));
1246 fail_exit (E_PW_UPDATE);
1248 if (is_shadow_pwd && (spw_close () == 0)) {
1250 _("%s: failure while writing changes to %s\n"), Prog, spw_dbname ());
1251 SYSLOG ((LOG_ERR, "failure while writing changes to %s", spw_dbname ()));
1252 fail_exit (E_PW_UPDATE);
1254 if (do_grp_update) {
1255 if (gr_close () == 0) {
1257 _("%s: failure while writing changes to %s\n"), Prog, gr_dbname ());
1258 SYSLOG ((LOG_ERR, "failure while writing changes to %s", gr_dbname ()));
1259 fail_exit (E_GRP_UPDATE);
1262 if (is_shadow_grp && (sgr_close () == 0)) {
1264 _("%s: failure while writing changes to %s\n"),
1265 Prog, sgr_dbname ());
1266 SYSLOG ((LOG_ERR, "failure while writing changes to %s", sgr_dbname ()));
1267 fail_exit (E_GRP_UPDATE);
1271 if (is_shadow_pwd) {
1272 if (spw_unlock () == 0) {
1273 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
1274 SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
1276 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1277 "unlocking shadow file",
1278 user_name, AUDIT_NO_ID, 0);
1284 if (pw_unlock () == 0) {
1285 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
1286 SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
1288 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1289 "unlocking passwd file",
1290 user_name, AUDIT_NO_ID, 0);
1295 if (gr_unlock () == 0) {
1296 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
1297 SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
1299 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1300 "unlocking group file",
1301 user_name, AUDIT_NO_ID, 0);
1307 if (is_shadow_grp) {
1308 if (sgr_unlock () == 0) {
1309 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
1310 SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
1312 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1313 "unlocking gshadow file",
1314 user_name, AUDIT_NO_ID, 0);
1324 * open_files - lock and open the password files
1326 * open_files() opens the two password files.
1328 static void open_files (void)
1330 if (pw_lock () == 0) {
1332 _("%s: cannot lock %s; try again later.\n"),
1333 Prog, pw_dbname ());
1337 if (pw_open (O_RDWR) == 0) {
1338 fprintf (stderr, _("%s: cannot open %s\n"), Prog, pw_dbname ());
1339 fail_exit (E_PW_UPDATE);
1341 if (is_shadow_pwd) {
1342 if (spw_lock () == 0) {
1344 _("%s: cannot lock %s; try again later.\n"),
1345 Prog, spw_dbname ());
1346 fail_exit (E_PW_UPDATE);
1349 if (spw_open (O_RDWR) == 0) {
1351 _("%s: cannot open %s\n"),
1352 Prog, spw_dbname ());
1353 fail_exit (E_PW_UPDATE);
1358 * Lock and open the group file.
1360 if (gr_lock () == 0) {
1362 _("%s: cannot lock %s; try again later.\n"),
1363 Prog, gr_dbname ());
1364 fail_exit (E_GRP_UPDATE);
1367 if (gr_open (O_RDWR) == 0) {
1368 fprintf (stderr, _("%s: cannot open %s\n"), Prog, gr_dbname ());
1369 fail_exit (E_GRP_UPDATE);
1372 if (is_shadow_grp) {
1373 if (sgr_lock () == 0) {
1375 _("%s: cannot lock %s; try again later.\n"),
1376 Prog, sgr_dbname ());
1377 fail_exit (E_GRP_UPDATE);
1380 if (sgr_open (O_RDWR) == 0) {
1382 _("%s: cannot open %s\n"),
1383 Prog, sgr_dbname ());
1384 fail_exit (E_GRP_UPDATE);
1390 static char *empty_list = NULL;
1393 * new_grent - initialize the values in a group file entry
1395 * new_grent() takes all of the values that have been entered and fills
1396 * in a (struct group) with them.
1399 static void new_grent (struct group *grent)
1401 memzero (grent, sizeof *grent);
1402 grent->gr_name = (char *) user_name;
1403 grent->gr_passwd = SHADOW_PASSWD_STRING; /* XXX warning: const */
1404 grent->gr_gid = user_gid;
1405 grent->gr_mem = &empty_list;
1410 * new_sgent - initialize the values in a shadow group file entry
1412 * new_sgent() takes all of the values that have been entered and fills
1413 * in a (struct sgrp) with them.
1416 static void new_sgent (struct sgrp *sgent)
1418 memzero (sgent, sizeof *sgent);
1419 sgent->sg_name = (char *) user_name;
1420 sgent->sg_passwd = "!"; /* XXX warning: const */
1421 sgent->sg_adm = &empty_list;
1422 sgent->sg_mem = &empty_list;
1424 #endif /* SHADOWGRP */
1428 * grp_add - add new group file entries
1430 * grp_add() writes the new records to the group files.
1433 static void grp_add (void)
1439 #endif /* SHADOWGRP */
1442 * Create the initial entries for this new group.
1447 #endif /* SHADOWGRP */
1450 * Write out the new group file entry.
1452 if (gr_update (&grp) == 0) {
1454 _("%s: failed to prepare the new %s entry '%s'\n"),
1455 Prog, gr_dbname (), grp.gr_name);
1456 fail_exit (E_GRP_UPDATE);
1460 * Write out the new shadow group entries as well.
1462 if (is_shadow_grp && (sgr_update (&sgrp) == 0)) {
1464 _("%s: failed to prepare the new %s entry '%s'\n"),
1465 Prog, sgr_dbname (), sgrp.sg_name);
1466 fail_exit (E_GRP_UPDATE);
1468 #endif /* SHADOWGRP */
1469 SYSLOG ((LOG_INFO, "new group: name=%s, GID=%u", user_name, user_gid));
1470 do_grp_update = true;
1473 static void faillog_reset (uid_t uid)
1477 off_t offset_uid = (off_t) (sizeof fl) * uid;
1479 if (access (FAILLOG_FILE, F_OK) != 0) {
1483 memzero (&fl, sizeof (fl));
1485 fd = open (FAILLOG_FILE, O_RDWR);
1487 || (lseek (fd, offset_uid, SEEK_SET) != offset_uid)
1488 || (write (fd, &fl, sizeof (fl)) != (ssize_t) sizeof (fl))
1489 || (close (fd) != 0)) {
1491 _("%s: failed to reset the faillog entry of UID %lu: %s\n"),
1492 Prog, (unsigned long) uid, strerror (errno));
1493 SYSLOG ((LOG_WARN, "failed to reset the faillog entry of UID %lu", (unsigned long) uid));
1498 static void lastlog_reset (uid_t uid)
1502 off_t offset_uid = (off_t) (sizeof ll) * uid;
1504 if (access (LASTLOG_FILE, F_OK) != 0) {
1508 memzero (&ll, sizeof (ll));
1510 fd = open (LASTLOG_FILE, O_RDWR);
1512 || (lseek (fd, offset_uid, SEEK_SET) != offset_uid)
1513 || (write (fd, &ll, sizeof (ll)) != (ssize_t) sizeof (ll))
1514 || (close (fd) != 0)) {
1516 _("%s: failed to reset the lastlog entry of UID %lu: %s\n"),
1517 Prog, (unsigned long) uid, strerror (errno));
1518 SYSLOG ((LOG_WARN, "failed to reset the lastlog entry of UID %lu", (unsigned long) uid));
1524 * usr_update - create the user entries
1526 * usr_update() creates the password file entries for this user
1527 * and will update the group entries if required.
1529 static void usr_update (void)
1531 struct passwd pwent;
1535 * Fill in the password structure with any new fields, making
1536 * copies of strings.
1542 * Create a syslog entry. We need to do this now in case anything
1543 * happens so we know what we were trying to accomplish.
1546 "new user: name=%s, UID=%u, GID=%u, home=%s, shell=%s",
1547 user_name, (unsigned int) user_id,
1548 (unsigned int) user_gid, user_home, user_shell));
1551 * Initialize faillog and lastlog entries for this UID in case
1552 * it belongs to a previously deleted user. We do it only if
1553 * no user with this UID exists yet (entries for shared UIDs
1554 * are left unchanged). --marekm
1556 /* local, no need for xgetpwuid */
1557 if ((!lflg) && (getpwuid (user_id) == NULL)) {
1558 faillog_reset (user_id);
1559 lastlog_reset (user_id);
1563 * Put the new (struct passwd) in the table.
1565 if (pw_update (&pwent) == 0) {
1567 _("%s: failed to prepare the new %s entry '%s'\n"),
1568 Prog, pw_dbname (), pwent.pw_name);
1569 fail_exit (E_PW_UPDATE);
1573 * Put the new (struct spwd) in the table.
1575 if (is_shadow_pwd && (spw_update (&spent) == 0)) {
1577 _("%s: failed to prepare the new %s entry '%s'\n"),
1578 Prog, spw_dbname (), spent.sp_namp);
1580 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1581 "adding shadow password",
1582 user_name, (unsigned int) user_id, 0);
1584 fail_exit (E_PW_UPDATE);
1587 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1589 user_name, (unsigned int) user_id, 1);
1593 * Do any group file updates for this user.
1595 if (do_grp_update) {
1601 * create_home - create the user's home directory
1603 * create_home() creates the user's home directory if it does not
1604 * already exist. It will be created mode 755 owned by the user
1605 * with the user's default group.
1607 static void create_home (void)
1609 if (access (user_home, F_OK) != 0) {
1610 /* XXX - create missing parent directories. --marekm */
1611 if (mkdir (user_home, 0) != 0) {
1614 ("%s: cannot create directory %s\n"),
1617 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1618 "adding home directory",
1619 user_name, (unsigned int) user_id, 0);
1621 fail_exit (E_HOMEDIR);
1623 chown (user_home, user_id, user_gid);
1625 0777 & ~getdef_num ("UMASK", GETDEF_DEFAULT_UMASK));
1628 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1629 "adding home directory",
1630 user_name, (unsigned int) user_id, 1);
1636 * create_mail - create the user's mail spool
1638 * create_mail() creates the user's mail spool if it does not already
1639 * exist. It will be created mode 660 owned by the user and group
1642 static void create_mail (void)
1650 if (strcasecmp (create_mail_spool, "yes") == 0) {
1651 spool = getdef_str ("MAIL_DIR");
1652 if (NULL == spool) {
1653 spool = "/var/mail";
1655 file = alloca (strlen (spool) + strlen (user_name) + 2);
1656 sprintf (file, "%s/%s", spool, user_name);
1657 fd = open (file, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0);
1659 perror (_("Creating mailbox file"));
1663 gr = getgrnam ("mail"); /* local, no need for xgetgrnam */
1665 fputs (_("Group 'mail' not found. Creating the user mailbox file with 0600 mode.\n"),
1674 if ( (fchown (fd, user_id, gid) != 0)
1675 || (fchmod (fd, mode) != 0)) {
1676 perror (_("Setting mailbox file permissions"));
1684 * main - useradd command
1686 int main (int argc, char **argv)
1689 pam_handle_t *pamh = NULL;
1698 * Get my name so that I can use it to report errors.
1700 Prog = Basename (argv[0]);
1702 (void) setlocale (LC_ALL, "");
1703 (void) bindtextdomain (PACKAGE, LOCALEDIR);
1704 (void) textdomain (PACKAGE);
1706 OPENLOG ("useradd");
1708 sys_ngroups = sysconf (_SC_NGROUPS_MAX);
1709 user_groups = malloc ((1 + sys_ngroups) * sizeof (char *));
1711 * Initialize the list to be empty
1713 user_groups[0] = (char *) 0;
1716 is_shadow_pwd = spw_file_present ();
1718 is_shadow_grp = sgr_file_present ();
1723 process_flags (argc, argv);
1726 retval = PAM_SUCCESS;
1729 struct passwd *pampw;
1730 pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
1731 if (pampw == NULL) {
1732 retval = PAM_USER_UNKNOWN;
1735 if (PAM_SUCCESS == retval) {
1736 retval = pam_start ("useradd", pampw->pw_name,
1741 if (PAM_SUCCESS == retval) {
1742 retval = pam_authenticate (pamh, 0);
1745 if (PAM_SUCCESS == retval) {
1746 retval = pam_acct_mgmt (pamh, 0);
1749 if (PAM_SUCCESS != retval) {
1750 (void) pam_end (pamh, retval);
1751 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
1754 #endif /* USE_PAM */
1757 * See if we are messing with the defaults file, or creating
1761 if (gflg || bflg || fflg || eflg || sflg) {
1762 exit ((set_defaults () != 0) ? 1 : 0);
1770 * Start with a quick check to see if the user exists.
1772 if (getpwnam (user_name) != NULL) { /* local, no need for xgetpwnam */
1773 fprintf (stderr, _("%s: user '%s' already exists\n"), Prog, user_name);
1775 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1777 user_name, AUDIT_NO_ID, 0);
1779 fail_exit (E_NAME_IN_USE);
1783 * Don't blindly overwrite a group when a user is added...
1784 * If you already have a group username, and want to add the user
1785 * to that group, use useradd -g username username.
1789 /* local, no need for xgetgrnam */
1790 if (getgrnam (user_name) != NULL) {
1792 _("%s: group %s exists - if you want to add this user to that group, use -g.\n"),
1795 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1797 user_name, AUDIT_NO_ID, 0);
1799 fail_exit (E_NAME_IN_USE);
1804 * Do the hard stuff:
1806 * - create the user entries,
1807 * - create the home directory,
1808 * - create user mail spool,
1809 * - flush nscd caches for passwd and group services,
1810 * - then close and update the files.
1815 /* first, seek for a valid uid to use for this user.
1816 * We do this because later we can use the uid we found as
1817 * gid too ... --gafton */
1819 if (find_new_uid (rflg, &user_id, NULL) < 0) {
1820 fprintf (stderr, _("%s: can't create user\n"), Prog);
1821 fail_exit (E_UID_IN_USE);
1824 if (getpwuid (user_id) != NULL) {
1826 _("%s: UID %lu is not unique\n"),
1827 Prog, (unsigned long) user_id);
1829 audit_logger (AUDIT_USER_CHAUTHTOK, Prog,
1831 user_name, (unsigned int) user_id, 0);
1833 fail_exit (E_UID_IN_USE);
1838 /* do we have to add a group for that user? This is why we need to
1839 * open the group files in the open_files() function --gafton */
1841 if (find_new_gid (rflg, &user_gid, &user_id) < 0) {
1843 _("%s: can't create group\n"),
1855 copy_tree (def_template, user_home, user_id, user_gid);
1859 ("%s: warning: the home directory already exists.\n"
1860 "Not copying any file from skel directory into it.\n"),
1863 } else if (getdef_str ("CREATE_HOME") != NULL) {
1865 * RedHat added the CREATE_HOME option in login.defs in their
1866 * version of shadow-utils (which makes -m the default, with
1867 * new -M option to turn it off). Unfortunately, this
1868 * changes the way useradd works (it can be run by scripts
1869 * expecting some standard behaviour), compared to other
1870 * Unices and other Linux distributions, and also adds a lot
1872 * So we now recognize CREATE_HOME and give a warning here
1873 * (better than "configuration error ... notify administrator"
1874 * errors in every program that reads /etc/login.defs). -MM
1878 ("%s: warning: CREATE_HOME not supported, please use -m instead.\n"),
1886 nscd_flush_cache ("passwd");
1887 nscd_flush_cache ("group");
1890 (void) pam_end (pamh, PAM_SUCCESS);
1891 #endif /* USE_PAM */