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
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.
45 #ifdef ACCT_TOOLS_SETUID
49 #endif /* ACCT_TOOLS_SETUID */
53 #include <sys/types.h>
61 #include "prototypes.h"
70 #define SKEL_DIR "/etc/skel"
72 #ifndef USER_DEFAULTS_FILE
73 #define USER_DEFAULTS_FILE "/etc/default/useradd"
74 #define NEW_USER_FILE "/etc/default/nuaddXXXXXX"
77 * Needed for MkLinux DR1/2/2.1 - J.
80 #define LASTLOG_FILE "/var/log/lastlog"
88 * These defaults are used if there is no defaults file.
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";
97 static long def_inactive = -1;
98 static const char *def_expire = "";
100 static char def_file[] = USER_DEFAULTS_FILE;
102 #define VALID(s) (strcspn (s, ":\n") == strlen (s))
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 = "";
113 static const char *user_selinux = "";
116 static long user_expire = -1;
117 static bool is_shadow_pwd;
120 static bool is_shadow_grp;
121 static bool sgr_locked = false;
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 */
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 */
151 static bool home_added = false;
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 */
167 #define DGROUP "GROUP="
169 #define SHELL "SHELL="
170 #define INACT "INACTIVE="
171 #define EXPIRE "EXPIRE="
173 #define CREATE_MAIL_SPOOL "CREATE_MAIL_SPOOL="
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 *);
184 static void selinux_update_mapping (void);
187 static long scale_age (long);
188 static void new_spent (struct spwd *);
189 static void grp_update (void);
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);
201 * fail_exit - undo as much as possible
203 static void fail_exit (int code)
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 ()));
214 audit_logger (AUDIT_ADD_USER, Prog,
215 "unlocking shadow file",
216 user_name, AUDIT_NO_ID,
217 SHADOW_AUDIT_FAILURE);
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 ()));
227 audit_logger (AUDIT_ADD_USER, Prog,
228 "unlocking passwd file",
229 user_name, AUDIT_NO_ID,
230 SHADOW_AUDIT_FAILURE);
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 ()));
240 audit_logger (AUDIT_ADD_USER, Prog,
241 "unlocking group file",
242 user_name, AUDIT_NO_ID,
243 SHADOW_AUDIT_FAILURE);
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 ()));
254 audit_logger (AUDIT_ADD_USER, Prog,
255 "unlocking gshadow file",
256 user_name, AUDIT_NO_ID,
257 SHADOW_AUDIT_FAILURE);
265 audit_logger (AUDIT_ADD_USER, Prog,
267 user_name, AUDIT_NO_ID,
268 SHADOW_AUDIT_FAILURE);
270 SYSLOG ((LOG_INFO, "failed adding user '%s', data deleted", user_name));
274 #define MATCH(x,y) (strncmp((x),(y),strlen(y)) == 0)
277 * get_defaults - read the defaults file
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.
283 static void get_defaults (void)
290 * Open the defaults file for reading.
293 fp = fopen (def_file, "r");
299 * Read the file a line at a time. Only the lines that have relevant
300 * values are used, everything else can be ignored.
302 while (fgets (buf, (int) sizeof buf, fp) == buf) {
303 cp = strrchr (buf, '\n');
308 cp = strchr (buf, '=');
316 * Primary GROUP identifier
318 if (MATCH (buf, DGROUP)) {
319 const struct group *grp = getgr_nam_gid (cp);
322 _("%s: group '%s' does not exist\n"),
325 _("%s: the %s configuration in %s will be ignored\n"),
326 Prog, DGROUP, def_file);
328 def_group = grp->gr_gid;
329 def_gname = xstrdup (grp->gr_name);
334 * Default HOME filesystem
336 else if (MATCH (buf, HOME)) {
337 def_home = xstrdup (cp);
341 * Default Login Shell command
343 else if (MATCH (buf, SHELL)) {
344 def_shell = xstrdup (cp);
348 * Default Password Inactive value
350 else if (MATCH (buf, INACT)) {
351 if ( (getlong (cp, &def_inactive) == 0)
352 || (def_inactive < -1)) {
354 _("%s: invalid numeric argument '%s'\n"),
357 _("%s: the %s configuration in %s will be ignored\n"),
358 Prog, INACT, def_file);
364 * Default account expiration date
366 else if (MATCH (buf, EXPIRE)) {
367 def_expire = xstrdup (cp);
371 * Default Skeleton information
373 else if (MATCH (buf, SKEL)) {
375 cp = SKEL_DIR; /* XXX warning: const */
378 def_template = xstrdup (cp);
382 * Create by default user mail spool or not ?
384 else if (MATCH (buf, CREATE_MAIL_SPOOL)) {
386 cp = CREATE_MAIL_SPOOL; /* XXX warning: const */
389 def_create_mail_spool = xstrdup (cp);
396 * show_defaults - show the contents of the defaults file
398 * show_defaults() displays the values that are used from the default
399 * file and the built-in values.
401 static void show_defaults (void)
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);
413 * set_defaults - write new defaults file
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.
419 static int set_defaults (void)
424 static char new_file[] = NEW_USER_FILE;
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;
437 * Create a temporary file to copy the new output to.
439 ofd = mkstemp (new_file);
442 _("%s: cannot create new defaults file\n"),
447 ofp = fdopen (ofd, "w");
450 _("%s: cannot open new defaults file\n"),
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.
460 ifp = fopen (def_file, "r");
462 fprintf (ofp, "# useradd defaults file\n");
466 while (fgets (buf, (int) sizeof buf, ifp) == buf) {
467 cp = strrchr (buf, '\n');
472 if (!out_group && MATCH (buf, DGROUP)) {
473 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
475 } else if (!out_home && MATCH (buf, HOME)) {
476 fprintf (ofp, HOME "%s\n", def_home);
478 } else if (!out_inactive && MATCH (buf, INACT)) {
479 fprintf (ofp, INACT "%ld\n", def_inactive);
481 } else if (!out_expire && MATCH (buf, EXPIRE)) {
482 fprintf (ofp, EXPIRE "%s\n", def_expire);
484 } else if (!out_shell && MATCH (buf, SHELL)) {
485 fprintf (ofp, SHELL "%s\n", def_shell);
487 } else if (!out_skel && MATCH (buf, SKEL)) {
488 fprintf (ofp, SKEL "%s\n", def_template);
490 } else if (!out_create_mail_spool
491 && MATCH (buf, CREATE_MAIL_SPOOL)) {
493 CREATE_MAIL_SPOOL "%s\n",
494 def_create_mail_spool);
495 out_create_mail_spool = true;
497 fprintf (ofp, "%s\n", buf);
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.
508 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
510 fprintf (ofp, HOME "%s\n", def_home);
512 fprintf (ofp, INACT "%ld\n", def_inactive);
514 fprintf (ofp, EXPIRE "%s\n", def_expire);
516 fprintf (ofp, SHELL "%s\n", def_shell);
518 fprintf (ofp, SKEL "%s\n", def_template);
520 if (!out_create_mail_spool)
521 fprintf (ofp, CREATE_MAIL_SPOOL "%s\n", def_create_mail_spool);
524 * Flush and close the file. Check for errors to make certain
525 * the new file is intact.
528 if ( (ferror (ofp) != 0)
529 || (fsync (fileno (ofp)) != 0)
530 || (fclose (ofp) != 0)) {
536 * Rename the current default file to its backup name.
538 wlen = snprintf (buf, sizeof buf, "%s-", def_file);
539 assert (wlen < sizeof buf);
540 if ((rename (def_file, buf) != 0) && (ENOENT != errno)) {
543 _("%s: rename: %s: %s"),
544 Prog, def_file, strerror (err));
550 * Rename the new default file to its correct name.
552 if (rename (new_file, def_file) != 0) {
555 _("%s: rename: %s: %s"),
556 Prog, new_file, strerror (err));
560 audit_logger (AUDIT_USYS_CONFIG, Prog,
561 "changing useradd defaults",
563 SHADOW_AUDIT_SUCCESS);
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));
575 * get_groups - convert a list of group names to an array of group IDs
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.
581 static int get_groups (char *list)
584 const struct group *grp;
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.
599 * Strip off a single name from the list
601 cp = strchr (list, ',');
607 * Names starting with digits are treated as numerical
608 * GID values, otherwise the string is looked up as is.
610 grp = getgr_nam_gid (list);
613 * There must be a match, either by GID value or by
618 _("%s: group '%s' does not exist\n"),
625 * If the group doesn't exist, don't dump core...
626 * Instead, try the next one. --marekm
634 * Don't add this group if they are an NIS group. Tell
635 * the user to go to the server for this group.
639 _("%s: group '%s' is a NIS group.\n"),
645 if (ngroups == sys_ngroups) {
647 _("%s: too many groups specified (max %d).\n"),
653 * Add the group name to the user's list of groups.
655 user_groups[ngroups++] = xstrdup (grp->gr_name);
656 } while (NULL != list);
658 user_groups[ngroups] = (char *) 0;
661 * Any errors in finding group names are fatal
671 * usage - display usage message and exit
673 static void usage (void)
676 _("Usage: useradd [options] LOGIN\n"
679 " -b, --base-dir BASE_DIR base directory for the new user account\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"
685 " -e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE\n"
686 " -f, --inactive INACTIVE set password inactive after expiration\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"
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"
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"
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"
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"
713 _(" -Z, --selinux-user SEUSER use a specific SEUSER for the SELinux user mapping\n")
722 * new_pwent - initialize the values in a password file entry
724 * new_pwent() takes all of the values that have been entered and
725 * fills in a (struct passwd) with them.
727 static void new_pwent (struct passwd *pwent)
729 memzero (pwent, sizeof *pwent);
730 pwent->pw_name = (char *) user_name;
732 pwent->pw_passwd = (char *) SHADOW_PASSWD_STRING;
734 pwent->pw_passwd = (char *) user_pass;
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;
744 static long scale_age (long x)
750 return x * (DAY / SCALE);
754 * new_spent - initialize the values in a shadow password file entry
756 * new_spent() takes all of the values that have been entered and
757 * fills in a (struct spwd) with them.
759 static void new_spent (struct spwd *spent)
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;
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);
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);
782 spent->sp_flag = SHADOW_SP_FLAG_UNSET;
786 * grp_update - add user to secondary group set
788 * grp_update() takes the secondary group set given in user_groups
789 * and adds the user to each group given by that set.
791 * The group files are opened and locked in open_files().
793 * close_files() should be called afterwards to commit the changes
794 * and unlocking the group files.
796 static void grp_update (void)
798 const struct group *grp;
802 const struct sgrp *sgrp;
807 * Scan through the entire group file looking for the groups that
808 * the user is a member of.
810 for (gr_rewind (), grp = gr_next (); NULL != grp; grp = gr_next ()) {
813 * See if the user specified this group as one of their
816 if (!is_on_list (user_groups, grp->gr_name)) {
821 * Make a copy - gr_update() will free() everything
822 * from the old entry, and we need it later.
824 ngrp = __gr_dup (grp);
827 _("%s: Out of memory. Cannot update %s.\n"),
829 SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", gr_dbname (), user_name));
831 audit_logger (AUDIT_ADD_USER, Prog,
832 "adding user to group",
833 user_name, AUDIT_NO_ID,
834 SHADOW_AUDIT_FAILURE);
836 fail_exit (E_GRP_UPDATE); /* XXX */
840 * Add the username to the list of group members and
841 * update the group entry to reflect the change.
843 ngrp->gr_mem = add_list (ngrp->gr_mem, user_name);
844 if (gr_update (ngrp) == 0) {
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));
850 audit_logger (AUDIT_ADD_USER, Prog,
851 "adding user to group",
852 user_name, AUDIT_NO_ID,
853 SHADOW_AUDIT_FAILURE);
855 fail_exit (E_GRP_UPDATE);
858 audit_logger (AUDIT_ADD_USER, Prog,
859 "adding user to group",
860 user_name, AUDIT_NO_ID,
861 SHADOW_AUDIT_SUCCESS);
864 "add '%s' to group '%s'",
865 user_name, ngrp->gr_name));
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
877 for (sgr_rewind (), sgrp = sgr_next (); NULL != sgrp; sgrp = sgr_next ()) {
880 * See if the user specified this group as one of their
883 if (gr_locate (sgrp->sg_name) == NULL) {
887 if (!is_on_list (user_groups, sgrp->sg_name)) {
892 * Make a copy - sgr_update() will free() everything
893 * from the old entry, and we need it later.
895 nsgrp = __sgr_dup (sgrp);
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));
902 audit_logger (AUDIT_ADD_USER, Prog,
903 "adding user to shadow group",
904 user_name, AUDIT_NO_ID,
905 SHADOW_AUDIT_FAILURE);
907 fail_exit (E_GRP_UPDATE); /* XXX */
911 * Add the username to the list of group members and
912 * update the group entry to reflect the change.
914 nsgrp->sg_mem = add_list (nsgrp->sg_mem, user_name);
915 if (sgr_update (nsgrp) == 0) {
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));
921 audit_logger (AUDIT_ADD_USER, Prog,
922 "adding user to shadow group",
923 user_name, AUDIT_NO_ID,
924 SHADOW_AUDIT_FAILURE);
926 fail_exit (E_GRP_UPDATE);
929 audit_logger (AUDIT_ADD_USER, Prog,
930 "adding user to shadow group",
931 user_name, AUDIT_NO_ID,
932 SHADOW_AUDIT_SUCCESS);
935 "add '%s' to shadow group '%s'",
936 user_name, nsgrp->sg_name));
938 #endif /* SHADOWGRP */
942 * process_flags - perform command line argument setting
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.
948 static void process_flags (int argc, char **argv)
950 const struct group *grp;
951 bool anyflag = false;
956 * Parse the command line options.
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'},
980 {"selinux-user", required_argument, NULL, 'Z'},
982 {"uid", required_argument, NULL, 'u'},
983 {"user-group", no_argument, NULL, 'U'},
984 {NULL, 0, NULL, '\0'}
986 while ((c = getopt_long (argc, argv,
988 "b:c:d:De:f:g:G:k:K:lmMNop:rs:u:UZ:",
990 "b:c:d:De:f:g:G:k:K:lmMNop:rs:u:U",
992 long_options, NULL)) != -1) {
995 if ( ( !VALID (optarg) )
996 || ( optarg[0] != '/' )) {
998 _("%s: invalid base directory '%s'\n"),
1006 if (!VALID (optarg)) {
1008 _("%s: invalid comment '%s'\n"),
1012 user_comment = optarg;
1016 if ( ( !VALID (optarg) )
1017 || ( optarg[0] != '/' )) {
1019 _("%s: invalid home directory '%s'\n"),
1033 if ('\0' != *optarg) {
1034 user_expire = strtoday (optarg);
1035 if (user_expire == -1) {
1037 _("%s: invalid date '%s'\n"),
1046 * -e "" is allowed - it's a no-op without /etc/shadow
1048 if (('\0' != *optarg) && !is_shadow_pwd) {
1050 _("%s: shadow passwords required for -e\n"),
1055 def_expire = optarg;
1060 if ( (getlong (optarg, &def_inactive) == 0)
1061 || (def_inactive < -1)) {
1063 _("%s: invalid numeric argument '%s'\n"),
1069 * it's a no-op without /etc/shadow
1071 if ((-1 != def_inactive) && !is_shadow_pwd) {
1073 _("%s: shadow passwords required for -f\n"),
1080 grp = getgr_nam_gid (optarg);
1083 _("%s: group '%s' does not exist\n"),
1088 def_group = grp->gr_gid;
1091 user_gid = grp->gr_gid;
1096 if (get_groups (optarg) != 0) {
1099 if (NULL != user_groups[0]) {
1100 do_grp_update = true;
1108 def_template = optarg;
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
1117 cp = strchr (optarg, '=');
1120 _("%s: -K requires KEY=VALUE\n"),
1124 /* terminate name, point to value */
1127 if (putdef_str (optarg, cp) < 0) {
1146 case 'p': /* set encrypted password */
1147 if (!VALID (optarg)) {
1149 _("%s: invalid field '%s'\n"),
1159 if ( ( !VALID (optarg) )
1160 || ( ('\0' != optarg[0])
1161 && ('/' != optarg[0])
1162 && ('*' != optarg[0]) )) {
1164 _("%s: invalid shell '%s'\n"),
1168 user_shell = optarg;
1173 if ( (get_uid (optarg, &user_id) == 0)
1174 || (user_id == (gid_t)-1)) {
1176 _("%s: invalid user ID '%s'\n"),
1187 if (is_selinux_enabled () > 0) {
1188 user_selinux = optarg;
1192 _("%s: -Z requires SELinux enabled kernel\n"),
1206 if (!gflg && !Nflg && !Uflg) {
1207 /* Get the settings from login.defs */
1208 Uflg = getdef_bool ("USERGROUPS_ENAB");
1212 * Certain options are only valid in combination with others.
1213 * Check it here so that they can be specified in any order.
1215 if (oflg && !uflg) {
1217 _("%s: %s flag is only allowed with the %s flag\n"),
1221 if (kflg && !mflg) {
1223 _("%s: %s flag is only allowed with the %s flag\n"),
1229 _("%s: options %s and %s conflict\n"),
1235 _("%s: options %s and %s conflict\n"),
1241 _("%s: options %s and %s conflict\n"),
1247 * Either -D or username is required. Defaults can be set with -D
1248 * for the -b, -e, -f, -g, -s options only.
1251 if (optind != argc) {
1255 if (uflg || oflg || Gflg || dflg || cflg || mflg) {
1259 if (optind != argc - 1) {
1263 user_name = argv[optind];
1264 if (!is_valid_user_name (user_name)) {
1266 _("%s: invalid user name '%s'\n"),
1269 audit_logger (AUDIT_ADD_USER, Prog,
1271 user_name, AUDIT_NO_ID,
1272 SHADOW_AUDIT_FAILURE);
1278 size_t len = strlen (def_home) + strlen (user_name) + 2;
1282 wlen = snprintf (uh, len, "%s/%s", def_home, user_name);
1283 assert (wlen == (int) len -1);
1290 user_expire = strtoday (def_expire);
1294 user_gid = def_group;
1298 user_shell = def_shell;
1301 create_mail_spool = def_create_mail_spool;
1304 /* for system accounts defaults are ignored and we
1305 * do not create a home dir */
1306 if (getdef_bool("CREATE_HOME")) {
1312 /* absolutely sure that we do not create home dirs */
1318 * close_files - close all of the files that were opened
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.
1323 static void close_files (void)
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);
1330 if (is_shadow_pwd && (spw_close () == 0)) {
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);
1336 if (do_grp_update) {
1337 if (gr_close () == 0) {
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);
1344 if (is_shadow_grp && (sgr_close () == 0)) {
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);
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 ()));
1358 audit_logger (AUDIT_ADD_USER, Prog,
1359 "unlocking shadow file",
1360 user_name, AUDIT_NO_ID,
1361 SHADOW_AUDIT_FAILURE);
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 ()));
1371 audit_logger (AUDIT_ADD_USER, Prog,
1372 "unlocking passwd file",
1373 user_name, AUDIT_NO_ID,
1374 SHADOW_AUDIT_FAILURE);
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 ()));
1383 audit_logger (AUDIT_ADD_USER, Prog,
1384 "unlocking group file",
1385 user_name, AUDIT_NO_ID,
1386 SHADOW_AUDIT_FAILURE);
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 ()));
1397 audit_logger (AUDIT_ADD_USER, Prog,
1398 "unlocking gshadow file",
1399 user_name, AUDIT_NO_ID,
1400 SHADOW_AUDIT_FAILURE);
1410 * open_files - lock and open the password files
1412 * open_files() opens the two password files.
1414 static void open_files (void)
1416 if (pw_lock () == 0) {
1418 _("%s: cannot lock %s; try again later.\n"),
1419 Prog, pw_dbname ());
1423 if (pw_open (O_RDWR) == 0) {
1424 fprintf (stderr, _("%s: cannot open %s\n"), Prog, pw_dbname ());
1425 fail_exit (E_PW_UPDATE);
1427 if (is_shadow_pwd) {
1428 if (spw_lock () == 0) {
1430 _("%s: cannot lock %s; try again later.\n"),
1431 Prog, spw_dbname ());
1432 fail_exit (E_PW_UPDATE);
1435 if (spw_open (O_RDWR) == 0) {
1437 _("%s: cannot open %s\n"),
1438 Prog, spw_dbname ());
1439 fail_exit (E_PW_UPDATE);
1444 * Lock and open the group file.
1446 if (gr_lock () == 0) {
1448 _("%s: cannot lock %s; try again later.\n"),
1449 Prog, gr_dbname ());
1450 fail_exit (E_GRP_UPDATE);
1453 if (gr_open (O_RDWR) == 0) {
1454 fprintf (stderr, _("%s: cannot open %s\n"), Prog, gr_dbname ());
1455 fail_exit (E_GRP_UPDATE);
1458 if (is_shadow_grp) {
1459 if (sgr_lock () == 0) {
1461 _("%s: cannot lock %s; try again later.\n"),
1462 Prog, sgr_dbname ());
1463 fail_exit (E_GRP_UPDATE);
1466 if (sgr_open (O_RDWR) == 0) {
1468 _("%s: cannot open %s\n"),
1469 Prog, sgr_dbname ());
1470 fail_exit (E_GRP_UPDATE);
1476 static char *empty_list = NULL;
1479 * new_grent - initialize the values in a group file entry
1481 * new_grent() takes all of the values that have been entered and fills
1482 * in a (struct group) with them.
1485 static void new_grent (struct group *grent)
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;
1496 * new_sgent - initialize the values in a shadow group file entry
1498 * new_sgent() takes all of the values that have been entered and fills
1499 * in a (struct sgrp) with them.
1502 static void new_sgent (struct sgrp *sgent)
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;
1510 #endif /* SHADOWGRP */
1514 * grp_add - add new group file entries
1516 * grp_add() writes the new records to the group files.
1519 static void grp_add (void)
1525 #endif /* SHADOWGRP */
1528 * Create the initial entries for this new group.
1533 #endif /* SHADOWGRP */
1536 * Write out the new group file entry.
1538 if (gr_update (&grp) == 0) {
1540 _("%s: failed to prepare the new %s entry '%s'\n"),
1541 Prog, gr_dbname (), grp.gr_name);
1543 audit_logger (AUDIT_ADD_GROUP, Prog,
1545 grp.gr_name, AUDIT_NO_ID,
1546 SHADOW_AUDIT_FAILURE);
1548 fail_exit (E_GRP_UPDATE);
1552 * Write out the new shadow group entries as well.
1554 if (is_shadow_grp && (sgr_update (&sgrp) == 0)) {
1556 _("%s: failed to prepare the new %s entry '%s'\n"),
1557 Prog, sgr_dbname (), sgrp.sg_name);
1559 audit_logger (AUDIT_ADD_GROUP, Prog,
1561 grp.gr_name, AUDIT_NO_ID,
1562 SHADOW_AUDIT_FAILURE);
1564 fail_exit (E_GRP_UPDATE);
1566 #endif /* SHADOWGRP */
1567 SYSLOG ((LOG_INFO, "new group: name=%s, GID=%u", user_name, user_gid));
1569 audit_logger (AUDIT_ADD_GROUP, Prog,
1571 grp.gr_name, AUDIT_NO_ID,
1572 SHADOW_AUDIT_SUCCESS);
1574 do_grp_update = true;
1577 static void faillog_reset (uid_t uid)
1581 off_t offset_uid = (off_t) (sizeof fl) * uid;
1583 if (access (FAILLOG_FILE, F_OK) != 0) {
1587 memzero (&fl, sizeof (fl));
1589 fd = open (FAILLOG_FILE, O_RDWR);
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)) {
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));
1603 static void lastlog_reset (uid_t uid)
1607 off_t offset_uid = (off_t) (sizeof ll) * uid;
1609 if (access (LASTLOG_FILE, F_OK) != 0) {
1613 memzero (&ll, sizeof (ll));
1615 fd = open (LASTLOG_FILE, O_RDWR);
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)) {
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));
1630 * usr_update - create the user entries
1632 * usr_update() creates the password file entries for this user
1633 * and will update the group entries if required.
1635 static void usr_update (void)
1637 struct passwd pwent;
1641 * Fill in the password structure with any new fields, making
1642 * copies of strings.
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.
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));
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
1662 /* local, no need for xgetpwuid */
1663 if ((!lflg) && (getpwuid (user_id) == NULL)) {
1664 faillog_reset (user_id);
1665 lastlog_reset (user_id);
1669 * Put the new (struct passwd) in the table.
1671 if (pw_update (&pwent) == 0) {
1673 _("%s: failed to prepare the new %s entry '%s'\n"),
1674 Prog, pw_dbname (), pwent.pw_name);
1675 fail_exit (E_PW_UPDATE);
1679 * Put the new (struct spwd) in the table.
1681 if (is_shadow_pwd && (spw_update (&spent) == 0)) {
1683 _("%s: failed to prepare the new %s entry '%s'\n"),
1684 Prog, spw_dbname (), spent.sp_namp);
1686 audit_logger (AUDIT_ADD_USER, Prog,
1687 "adding shadow password",
1688 user_name, (unsigned int) user_id,
1689 SHADOW_AUDIT_FAILURE);
1691 fail_exit (E_PW_UPDATE);
1694 audit_logger (AUDIT_ADD_USER, Prog,
1696 user_name, (unsigned int) user_id,
1697 SHADOW_AUDIT_SUCCESS);
1701 * Do any group file updates for this user.
1703 if (do_grp_update) {
1709 static void selinux_update_mapping (void) {
1710 if (is_selinux_enabled () <= 0) return;
1712 if (*user_selinux) { /* must be done after passwd write() */
1713 const char *argv[7];
1714 argv[0] = "/usr/sbin/semanage";
1718 argv[4] = user_selinux;
1719 argv[5] = user_name;
1721 if (safe_system (argv[0], argv, NULL, 0)) {
1723 _("%s: warning: the user name %s to %s SELinux user mapping failed.\n"),
1724 Prog, user_name, user_selinux);
1726 audit_logger (AUDIT_ADD_USER, Prog,
1727 "adding SELinux user mapping",
1728 user_name, (unsigned int) user_id, 0);
1735 * create_home - create the user's home directory
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.
1741 static void create_home (void)
1743 if (access (user_home, F_OK) != 0) {
1745 selinux_file_context (user_home);
1747 /* XXX - create missing parent directories. --marekm */
1748 if (mkdir (user_home, 0) != 0) {
1750 _("%s: cannot create directory %s\n"),
1753 audit_logger (AUDIT_ADD_USER, Prog,
1754 "adding home directory",
1755 user_name, (unsigned int) user_id,
1756 SHADOW_AUDIT_FAILURE);
1758 fail_exit (E_HOMEDIR);
1760 chown (user_home, user_id, user_gid);
1762 0777 & ~getdef_num ("UMASK", GETDEF_DEFAULT_UMASK));
1765 audit_logger (AUDIT_ADD_USER, Prog,
1766 "adding home directory",
1767 user_name, (unsigned int) user_id,
1768 SHADOW_AUDIT_SUCCESS);
1771 /* Reset SELinux to create files with default contexts */
1772 setfscreatecon (NULL);
1778 * create_mail - create the user's mail spool
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
1784 static void create_mail (void)
1792 if (strcasecmp (create_mail_spool, "yes") == 0) {
1793 spool = getdef_str ("MAIL_DIR");
1794 if (NULL == spool) {
1795 spool = "/var/mail";
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);
1801 perror (_("Creating mailbox file"));
1805 gr = getgrnam ("mail"); /* local, no need for xgetgrnam */
1807 fputs (_("Group 'mail' not found. Creating the user mailbox file with 0600 mode.\n"),
1816 if ( (fchown (fd, user_id, gid) != 0)
1817 || (fchmod (fd, mode) != 0)) {
1818 perror (_("Setting mailbox file permissions"));
1827 * main - useradd command
1829 int main (int argc, char **argv)
1831 #ifdef ACCT_TOOLS_SETUID
1833 pam_handle_t *pamh = NULL;
1835 #endif /* USE_PAM */
1836 #endif /* ACCT_TOOLS_SETUID */
1843 * Get my name so that I can use it to report errors.
1845 Prog = Basename (argv[0]);
1847 (void) setlocale (LC_ALL, "");
1848 (void) bindtextdomain (PACKAGE, LOCALEDIR);
1849 (void) textdomain (PACKAGE);
1851 OPENLOG ("useradd");
1853 sys_ngroups = sysconf (_SC_NGROUPS_MAX);
1854 user_groups = xmalloc ((1 + sys_ngroups) * sizeof (char *));
1856 * Initialize the list to be empty
1858 user_groups[0] = (char *) 0;
1861 is_shadow_pwd = spw_file_present ();
1863 is_shadow_grp = sgr_file_present ();
1868 process_flags (argc, argv);
1870 #ifdef ACCT_TOOLS_SETUID
1873 struct passwd *pampw;
1874 pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
1875 if (pampw == NULL) {
1877 _("%s: Cannot determine your user name.\n"),
1882 retval = pam_start ("useradd", pampw->pw_name, &conv, &pamh);
1885 if (PAM_SUCCESS == retval) {
1886 retval = pam_authenticate (pamh, 0);
1889 if (PAM_SUCCESS == retval) {
1890 retval = pam_acct_mgmt (pamh, 0);
1894 (void) pam_end (pamh, retval);
1896 if (PAM_SUCCESS != retval) {
1897 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
1900 #endif /* USE_PAM */
1901 #endif /* ACCT_TOOLS_SETUID */
1904 * See if we are messing with the defaults file, or creating
1908 if (gflg || bflg || fflg || eflg || sflg) {
1909 exit ((set_defaults () != 0) ? 1 : 0);
1917 * Start with a quick check to see if the user exists.
1919 if (getpwnam (user_name) != NULL) { /* local, no need for xgetpwnam */
1920 fprintf (stderr, _("%s: user '%s' already exists\n"), Prog, user_name);
1922 audit_logger (AUDIT_ADD_USER, Prog,
1924 user_name, AUDIT_NO_ID,
1925 SHADOW_AUDIT_FAILURE);
1927 fail_exit (E_NAME_IN_USE);
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.
1937 /* local, no need for xgetgrnam */
1938 if (getgrnam (user_name) != NULL) {
1940 _("%s: group %s exists - if you want to add this user to that group, use -g.\n"),
1943 audit_logger (AUDIT_ADD_USER, Prog,
1945 user_name, AUDIT_NO_ID,
1946 SHADOW_AUDIT_FAILURE);
1948 fail_exit (E_NAME_IN_USE);
1953 * Do the hard stuff:
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.
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 */
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);
1973 if (getpwuid (user_id) != NULL) {
1975 _("%s: UID %lu is not unique\n"),
1976 Prog, (unsigned long) user_id);
1978 audit_logger (AUDIT_ADD_USER, Prog,
1980 user_name, (unsigned int) user_id,
1981 SHADOW_AUDIT_FAILURE);
1983 fail_exit (E_UID_IN_USE);
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 */
1991 if (find_new_gid (rflg, &user_gid, &user_id) < 0) {
1993 _("%s: can't create group\n"),
2005 copy_tree (def_template, user_home, user_id, user_gid);
2008 _("%s: warning: the home directory already exists.\n"
2009 "Not copying any file from skel directory into it.\n"),
2015 /* Do not create mail directory for system accounts */
2023 selinux_update_mapping ();
2026 nscd_flush_cache ("passwd");
2027 nscd_flush_cache ("group");