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 */
52 #include <sys/types.h>
60 #include "prototypes.h"
69 #define SKEL_DIR "/etc/skel"
71 #ifndef USER_DEFAULTS_FILE
72 #define USER_DEFAULTS_FILE "/etc/default/useradd"
73 #define NEW_USER_FILE "/etc/default/nuaddXXXXXX"
76 * Needed for MkLinux DR1/2/2.1 - J.
79 #define LASTLOG_FILE "/var/log/lastlog"
87 * These defaults are used if there is no defaults file.
89 static gid_t def_group = 100;
90 static const char *def_gname = "other";
91 static const char *def_home = "/home";
92 static const char *def_shell = "";
93 static const char *def_template = SKEL_DIR;
94 static const char *def_create_mail_spool = "no";
96 static long def_inactive = -1;
97 static const char *def_expire = "";
99 static char def_file[] = USER_DEFAULTS_FILE;
101 #define VALID(s) (strcspn (s, ":\n") == strlen (s))
103 static const char *user_name = "";
104 static const char *user_pass = "!";
105 static uid_t user_id;
106 static gid_t user_gid;
107 static const char *user_comment = "";
108 static const char *user_home = "";
109 static const char *user_shell = "";
110 static const char *create_mail_spool = "";
112 static long user_expire = -1;
113 static bool is_shadow_pwd;
116 static bool is_shadow_grp;
117 static bool sgr_locked = false;
119 static bool pw_locked = false;
120 static bool gr_locked = false;
121 static bool spw_locked = false;
122 static char **user_groups; /* NULL-terminated list */
123 static long sys_ngroups;
124 static bool do_grp_update = false; /* group files need to be updated */
127 bflg = false, /* new default root of home directory */
128 cflg = false, /* comment (GECOS) field for new account */
129 dflg = false, /* home directory for new account */
130 Dflg = false, /* set/show new user default values */
131 eflg = false, /* days since 1970-01-01 when account is locked */
132 fflg = false, /* days until account with expired password is locked */
133 gflg = false, /* primary group ID for new account */
134 Gflg = false, /* secondary group set for new account */
135 kflg = false, /* specify a directory to fill new user directory */
136 lflg = false, /* do not add user to lastlog/faillog databases */
137 mflg = false, /* create user's home directory if it doesn't exist */
138 Mflg = false, /* do not create user's home directory even if CREATE_HOME is set */
139 Nflg = false, /* do not create a group having the same name as the user, but add the user to def_group (or the group specified with -g) */
140 oflg = false, /* permit non-unique user ID to be specified with -u */
141 rflg = false, /* create a system account */
142 sflg = false, /* shell program for new account */
143 uflg = false, /* specify user ID for new account */
144 Uflg = false; /* create a group having the same name as the user */
146 static bool home_added = false;
151 #define E_SUCCESS 0 /* success */
152 #define E_PW_UPDATE 1 /* can't update password file */
153 #define E_USAGE 2 /* invalid command syntax */
154 #define E_BAD_ARG 3 /* invalid argument to option */
155 #define E_UID_IN_USE 4 /* UID already in use (and no -o) */
156 #define E_NOTFOUND 6 /* specified group doesn't exist */
157 #define E_NAME_IN_USE 9 /* username already in use */
158 #define E_GRP_UPDATE 10 /* can't update group file */
159 #define E_HOMEDIR 12 /* can't create home directory */
160 #define E_MAIL_SPOOL 13 /* can't create mail spool */
162 #define DGROUP "GROUP="
164 #define SHELL "SHELL="
165 #define INACT "INACTIVE="
166 #define EXPIRE "EXPIRE="
168 #define CREATE_MAIL_SPOOL "CREATE_MAIL_SPOOL="
170 /* local function prototypes */
171 static void fail_exit (int);
172 static void get_defaults (void);
173 static void show_defaults (void);
174 static int set_defaults (void);
175 static int get_groups (char *);
176 static void usage (void);
177 static void new_pwent (struct passwd *);
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_ADD_USER, Prog,
207 "unlocking shadow file",
208 user_name, AUDIT_NO_ID,
209 SHADOW_AUDIT_FAILURE);
215 if (pw_unlock () == 0) {
216 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
217 SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
219 audit_logger (AUDIT_ADD_USER, Prog,
220 "unlocking passwd file",
221 user_name, AUDIT_NO_ID,
222 SHADOW_AUDIT_FAILURE);
228 if (gr_unlock () == 0) {
229 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
230 SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
232 audit_logger (AUDIT_ADD_USER, Prog,
233 "unlocking group file",
234 user_name, AUDIT_NO_ID,
235 SHADOW_AUDIT_FAILURE);
242 if (sgr_unlock () == 0) {
243 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
244 SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
246 audit_logger (AUDIT_ADD_USER, Prog,
247 "unlocking gshadow file",
248 user_name, AUDIT_NO_ID,
249 SHADOW_AUDIT_FAILURE);
257 audit_logger (AUDIT_ADD_USER, Prog,
259 user_name, AUDIT_NO_ID,
260 SHADOW_AUDIT_FAILURE);
262 SYSLOG ((LOG_INFO, "failed adding user '%s', data deleted", user_name));
266 #define MATCH(x,y) (strncmp((x),(y),strlen(y)) == 0)
269 * get_defaults - read the defaults file
271 * get_defaults() reads the defaults file for this command. It sets the
272 * various values from the file, or uses built-in default values if the
273 * file does not exist.
275 static void get_defaults (void)
282 * Open the defaults file for reading.
285 fp = fopen (def_file, "r");
291 * Read the file a line at a time. Only the lines that have relevant
292 * values are used, everything else can be ignored.
294 while (fgets (buf, (int) sizeof buf, fp) == buf) {
295 cp = strrchr (buf, '\n');
300 cp = strchr (buf, '=');
308 * Primary GROUP identifier
310 if (MATCH (buf, DGROUP)) {
311 const struct group *grp = getgr_nam_gid (cp);
314 _("%s: group '%s' does not exist\n"),
317 _("%s: the %s configuration in %s will be ignored\n"),
318 Prog, DGROUP, def_file);
320 def_group = grp->gr_gid;
321 def_gname = xstrdup (grp->gr_name);
326 * Default HOME filesystem
328 else if (MATCH (buf, HOME)) {
329 def_home = xstrdup (cp);
333 * Default Login Shell command
335 else if (MATCH (buf, SHELL)) {
336 def_shell = xstrdup (cp);
340 * Default Password Inactive value
342 else if (MATCH (buf, INACT)) {
343 if ( (getlong (cp, &def_inactive) == 0)
344 || (def_inactive < -1)) {
346 _("%s: invalid numeric argument '%s'\n"),
349 _("%s: the %s configuration in %s will be ignored\n"),
350 Prog, INACT, def_file);
356 * Default account expiration date
358 else if (MATCH (buf, EXPIRE)) {
359 def_expire = xstrdup (cp);
363 * Default Skeleton information
365 else if (MATCH (buf, SKEL)) {
367 cp = SKEL_DIR; /* XXX warning: const */
370 def_template = xstrdup (cp);
374 * Create by default user mail spool or not ?
376 else if (MATCH (buf, CREATE_MAIL_SPOOL)) {
378 cp = CREATE_MAIL_SPOOL; /* XXX warning: const */
381 def_create_mail_spool = xstrdup (cp);
387 * show_defaults - show the contents of the defaults file
389 * show_defaults() displays the values that are used from the default
390 * file and the built-in values.
392 static void show_defaults (void)
394 printf ("GROUP=%u\n", (unsigned int) def_group);
395 printf ("HOME=%s\n", def_home);
396 printf ("INACTIVE=%ld\n", def_inactive);
397 printf ("EXPIRE=%s\n", def_expire);
398 printf ("SHELL=%s\n", def_shell);
399 printf ("SKEL=%s\n", def_template);
400 printf ("CREATE_MAIL_SPOOL=%s\n", def_create_mail_spool);
404 * set_defaults - write new defaults file
406 * set_defaults() re-writes the defaults file using the values that
407 * are currently set. Duplicated lines are pruned, missing lines are
408 * added, and unrecognized lines are copied as is.
410 static int set_defaults (void)
415 static char new_file[] = NEW_USER_FILE;
418 bool out_group = false;
419 bool out_home = false;
420 bool out_inactive = false;
421 bool out_expire = false;
422 bool out_shell = false;
423 bool out_skel = false;
424 bool out_create_mail_spool = false;
427 * Create a temporary file to copy the new output to.
429 ofd = mkstemp (new_file);
432 _("%s: cannot create new defaults file\n"),
437 ofp = fdopen (ofd, "w");
440 _("%s: cannot open new defaults file\n"),
446 * Open the existing defaults file and copy the lines to the
447 * temporary file, using any new values. Each line is checked
448 * to insure that it is not output more than once.
450 ifp = fopen (def_file, "r");
452 fprintf (ofp, "# useradd defaults file\n");
456 while (fgets (buf, (int) sizeof buf, ifp) == buf) {
457 cp = strrchr (buf, '\n');
462 if (!out_group && MATCH (buf, DGROUP)) {
463 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
465 } else if (!out_home && MATCH (buf, HOME)) {
466 fprintf (ofp, HOME "%s\n", def_home);
468 } else if (!out_inactive && MATCH (buf, INACT)) {
469 fprintf (ofp, INACT "%ld\n", def_inactive);
471 } else if (!out_expire && MATCH (buf, EXPIRE)) {
472 fprintf (ofp, EXPIRE "%s\n", def_expire);
474 } else if (!out_shell && MATCH (buf, SHELL)) {
475 fprintf (ofp, SHELL "%s\n", def_shell);
477 } else if (!out_skel && MATCH (buf, SKEL)) {
478 fprintf (ofp, SKEL "%s\n", def_template);
480 } else if (!out_create_mail_spool
481 && MATCH (buf, CREATE_MAIL_SPOOL)) {
483 CREATE_MAIL_SPOOL "%s\n",
484 def_create_mail_spool);
485 out_create_mail_spool = true;
487 fprintf (ofp, "%s\n", buf);
493 * Check each line to insure that every line was output. This
494 * causes new values to be added to a file which did not previously
495 * have an entry for that value.
498 fprintf (ofp, DGROUP "%u\n", (unsigned int) def_group);
500 fprintf (ofp, HOME "%s\n", def_home);
502 fprintf (ofp, INACT "%ld\n", def_inactive);
504 fprintf (ofp, EXPIRE "%s\n", def_expire);
506 fprintf (ofp, SHELL "%s\n", def_shell);
508 fprintf (ofp, SKEL "%s\n", def_template);
510 if (!out_create_mail_spool)
511 fprintf (ofp, CREATE_MAIL_SPOOL "%s\n", def_create_mail_spool);
514 * Flush and close the file. Check for errors to make certain
515 * the new file is intact.
518 if ( (ferror (ofp) != 0)
519 || (fsync (fileno (ofp)) != 0)
520 || (fclose (ofp) != 0)) {
526 * Rename the current default file to its backup name.
528 snprintf (buf, sizeof buf, "%s-", def_file);
529 if ((rename (def_file, buf) != 0) && (ENOENT != errno)) {
530 snprintf (buf, sizeof buf, _("%s: rename: %s"), Prog, def_file);
537 * Rename the new default file to its correct name.
539 if (rename (new_file, def_file) != 0) {
540 snprintf (buf, sizeof buf, _("%s: rename: %s"), Prog, new_file);
545 audit_logger (AUDIT_USYS_CONFIG, Prog,
546 "changing useradd defaults",
548 SHADOW_AUDIT_SUCCESS);
551 "useradd defaults: GROUP=%u, HOME=%s, SHELL=%s, INACTIVE=%ld, "
552 "EXPIRE=%s, SKEL=%s, CREATE_MAIL_SPOOL=%s",
553 (unsigned int) def_group, def_home, def_shell,
554 def_inactive, def_expire, def_template,
555 def_create_mail_spool));
560 * get_groups - convert a list of group names to an array of group IDs
562 * get_groups() takes a comma-separated list of group names and
563 * converts it to a NULL-terminated array. Any unknown group
564 * names are reported as errors.
566 static int get_groups (char *list)
569 const struct group *grp;
578 * So long as there is some data to be converted, strip off
579 * each name and look it up. A mix of numerical and string
580 * values for group identifiers is permitted.
584 * Strip off a single name from the list
586 cp = strchr (list, ',');
592 * Names starting with digits are treated as numerical
593 * GID values, otherwise the string is looked up as is.
595 grp = getgr_nam_gid (list);
598 * There must be a match, either by GID value or by
603 _("%s: group '%s' does not exist\n"),
610 * If the group doesn't exist, don't dump core...
611 * Instead, try the next one. --marekm
619 * Don't add this group if they are an NIS group. Tell
620 * the user to go to the server for this group.
624 _("%s: group '%s' is a NIS group.\n"),
630 if (ngroups == sys_ngroups) {
632 _("%s: too many groups specified (max %d).\n"),
638 * Add the group name to the user's list of groups.
640 user_groups[ngroups++] = xstrdup (grp->gr_name);
641 } while (NULL != list);
643 user_groups[ngroups] = (char *) 0;
646 * Any errors in finding group names are fatal
656 * usage - display usage message and exit
658 static void usage (void)
660 fputs (_("Usage: useradd [options] LOGIN\n"
663 " -b, --base-dir BASE_DIR base directory for the new user account\n"
665 " -c, --comment COMMENT set the GECOS field for the new user account\n"
666 " -d, --home-dir HOME_DIR home directory for the new user account\n"
667 " -D, --defaults print or save modified default useradd\n"
669 " -e, --expiredate EXPIRE_DATE set account expiration date to EXPIRE_DATE\n"
670 " -f, --inactive INACTIVE set password inactive after expiration\n"
672 " -g, --gid GROUP force use GROUP for the new user account\n"
673 " -G, --groups GROUPS list of supplementary groups for the new\n"
675 " -h, --help display this help message and exit\n"
676 " -k, --skel SKEL_DIR specify an alternative skel directory\n"
677 " -K, --key KEY=VALUE overrides /etc/login.defs defaults\n"
678 " -l, --no-log-init do not add the user to the lastlog and\n"
679 " faillog databases\n"
680 " -m, --create-home create home directory for the new user\n"
682 " -M, --no-create-home do not create user's home directory\n"
683 " (overrides /etc/login.defs)\n"
684 " -N, --no-user-group do not create a group with the same name as\n"
686 " -o, --non-unique allow create user with duplicate\n"
687 " (non-unique) UID\n"
688 " -p, --password PASSWORD use encrypted password for the new user\n"
690 " -r, --system create a system account\n"
691 " -s, --shell SHELL the login shell for the new user account\n"
692 " -u, --uid UID force use the UID for the new user account\n"
693 " -U, --user-group create a group with the same name as the user\n"
699 * new_pwent - initialize the values in a password file entry
701 * new_pwent() takes all of the values that have been entered and
702 * fills in a (struct passwd) with them.
704 static void new_pwent (struct passwd *pwent)
706 memzero (pwent, sizeof *pwent);
707 pwent->pw_name = (char *) user_name;
709 pwent->pw_passwd = (char *) SHADOW_PASSWD_STRING;
711 pwent->pw_passwd = (char *) user_pass;
714 pwent->pw_uid = user_id;
715 pwent->pw_gid = user_gid;
716 pwent->pw_gecos = (char *) user_comment;
717 pwent->pw_dir = (char *) user_home;
718 pwent->pw_shell = (char *) user_shell;
721 static long scale_age (long x)
727 return x * (DAY / SCALE);
731 * new_spent - initialize the values in a shadow password file entry
733 * new_spent() takes all of the values that have been entered and
734 * fills in a (struct spwd) with them.
736 static void new_spent (struct spwd *spent)
738 memzero (spent, sizeof *spent);
739 spent->sp_namp = (char *) user_name;
740 spent->sp_pwdp = (char *) user_pass;
741 spent->sp_lstchg = (long) time ((time_t *) 0) / SCALE;
742 if (0 == spent->sp_lstchg) {
743 /* Better disable aging than requiring a password change */
744 spent->sp_lstchg = -1;
747 spent->sp_min = scale_age (getdef_num ("PASS_MIN_DAYS", -1));
748 spent->sp_max = scale_age (getdef_num ("PASS_MAX_DAYS", -1));
749 spent->sp_warn = scale_age (getdef_num ("PASS_WARN_AGE", -1));
750 spent->sp_inact = scale_age (def_inactive);
751 spent->sp_expire = scale_age (user_expire);
753 spent->sp_min = scale_age (-1);
754 spent->sp_max = scale_age (-1);
755 spent->sp_warn = scale_age (-1);
756 spent->sp_inact = scale_age (-1);
757 spent->sp_expire = scale_age (-1);
759 spent->sp_flag = SHADOW_SP_FLAG_UNSET;
763 * grp_update - add user to secondary group set
765 * grp_update() takes the secondary group set given in user_groups
766 * and adds the user to each group given by that set.
768 * The group files are opened and locked in open_files().
770 * close_files() should be called afterwards to commit the changes
771 * and unlocking the group files.
773 static void grp_update (void)
775 const struct group *grp;
779 const struct sgrp *sgrp;
784 * Scan through the entire group file looking for the groups that
785 * the user is a member of.
787 for (gr_rewind (), grp = gr_next (); NULL != grp; grp = gr_next ()) {
790 * See if the user specified this group as one of their
793 if (!is_on_list (user_groups, grp->gr_name)) {
798 * Make a copy - gr_update() will free() everything
799 * from the old entry, and we need it later.
801 ngrp = __gr_dup (grp);
804 _("%s: Out of memory. Cannot update %s.\n"),
806 SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", gr_dbname (), user_name));
808 audit_logger (AUDIT_ADD_USER, Prog,
809 "adding user to group",
810 user_name, AUDIT_NO_ID,
811 SHADOW_AUDIT_FAILURE);
813 fail_exit (E_GRP_UPDATE); /* XXX */
817 * Add the username to the list of group members and
818 * update the group entry to reflect the change.
820 ngrp->gr_mem = add_list (ngrp->gr_mem, user_name);
821 if (gr_update (ngrp) == 0) {
823 _("%s: failed to prepare the new %s entry '%s'\n"),
824 Prog, gr_dbname (), ngrp->gr_name);
825 SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", gr_dbname (), user_name));
827 audit_logger (AUDIT_ADD_USER, Prog,
828 "adding user to group",
829 user_name, AUDIT_NO_ID,
830 SHADOW_AUDIT_FAILURE);
832 fail_exit (E_GRP_UPDATE);
835 audit_logger (AUDIT_ADD_USER, Prog,
836 "adding user to group",
837 user_name, AUDIT_NO_ID,
838 SHADOW_AUDIT_SUCCESS);
841 "add '%s' to group '%s'",
842 user_name, ngrp->gr_name));
850 * Scan through the entire shadow group file looking for the groups
851 * that the user is a member of. The administrative list isn't
854 for (sgr_rewind (), sgrp = sgr_next (); NULL != sgrp; sgrp = sgr_next ()) {
857 * See if the user specified this group as one of their
860 if (gr_locate (sgrp->sg_name) == NULL) {
864 if (!is_on_list (user_groups, sgrp->sg_name)) {
869 * Make a copy - sgr_update() will free() everything
870 * from the old entry, and we need it later.
872 nsgrp = __sgr_dup (sgrp);
875 _("%s: Out of memory. Cannot update %s.\n"),
876 Prog, sgr_dbname ());
877 SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", sgr_dbname (), user_name));
879 audit_logger (AUDIT_ADD_USER, Prog,
880 "adding user to shadow group",
881 user_name, AUDIT_NO_ID,
882 SHADOW_AUDIT_FAILURE);
884 fail_exit (E_GRP_UPDATE); /* XXX */
888 * Add the username to the list of group members and
889 * update the group entry to reflect the change.
891 nsgrp->sg_mem = add_list (nsgrp->sg_mem, user_name);
892 if (sgr_update (nsgrp) == 0) {
894 _("%s: failed to prepare the new %s entry '%s'\n"),
895 Prog, sgr_dbname (), nsgrp->sg_name);
896 SYSLOG ((LOG_ERR, "failed to prepare the new %s entry '%s'", sgr_dbname (), user_name));
898 audit_logger (AUDIT_ADD_USER, Prog,
899 "adding user to shadow group",
900 user_name, AUDIT_NO_ID,
901 SHADOW_AUDIT_FAILURE);
903 fail_exit (E_GRP_UPDATE);
906 audit_logger (AUDIT_ADD_USER, Prog,
907 "adding user to shadow group",
908 user_name, AUDIT_NO_ID,
909 SHADOW_AUDIT_SUCCESS);
912 "add '%s' to shadow group '%s'",
913 user_name, nsgrp->sg_name));
915 #endif /* SHADOWGRP */
919 * process_flags - perform command line argument setting
921 * process_flags() interprets the command line arguments and sets
922 * the values that the user will be created with accordingly. The
923 * values are checked for sanity.
925 static void process_flags (int argc, char **argv)
927 const struct group *grp;
928 bool anyflag = false;
933 * Parse the command line options.
936 static struct option long_options[] = {
937 {"base-dir", required_argument, NULL, 'b'},
938 {"comment", required_argument, NULL, 'c'},
939 {"home-dir", required_argument, NULL, 'd'},
940 {"defaults", no_argument, NULL, 'D'},
941 {"expiredate", required_argument, NULL, 'e'},
942 {"inactive", required_argument, NULL, 'f'},
943 {"gid", required_argument, NULL, 'g'},
944 {"groups", required_argument, NULL, 'G'},
945 {"help", no_argument, NULL, 'h'},
946 {"skel", required_argument, NULL, 'k'},
947 {"key", required_argument, NULL, 'K'},
948 {"create-home", no_argument, NULL, 'm'},
949 {"no-create-home", no_argument, NULL, 'M'},
950 {"no-log-init", no_argument, NULL, 'l'},
951 {"no-user-group", no_argument, NULL, 'N'},
952 {"non-unique", no_argument, NULL, 'o'},
953 {"password", required_argument, NULL, 'p'},
954 {"system", no_argument, NULL, 'r'},
955 {"shell", required_argument, NULL, 's'},
956 {"uid", required_argument, NULL, 'u'},
957 {"user-group", no_argument, NULL, 'U'},
958 {NULL, 0, NULL, '\0'}
960 while ((c = getopt_long (argc, argv,
961 "b:c:d:De:f:g:G:k:K:lmMNop:rs:u:U",
962 long_options, NULL)) != -1) {
965 if ( ( !VALID (optarg) )
966 || ( optarg[0] != '/' )) {
968 _("%s: invalid base directory '%s'\n"),
976 if (!VALID (optarg)) {
978 _("%s: invalid comment '%s'\n"),
982 user_comment = optarg;
986 if ( ( !VALID (optarg) )
987 || ( optarg[0] != '/' )) {
989 _("%s: invalid home directory '%s'\n"),
1003 if ('\0' != *optarg) {
1004 user_expire = strtoday (optarg);
1005 if (user_expire == -1) {
1007 _("%s: invalid date '%s'\n"),
1016 * -e "" is allowed - it's a no-op without /etc/shadow
1018 if (('\0' != *optarg) && !is_shadow_pwd) {
1020 _("%s: shadow passwords required for -e\n"),
1025 def_expire = optarg;
1030 if ( (getlong (optarg, &def_inactive) == 0)
1031 || (def_inactive < -1)) {
1033 _("%s: invalid numeric argument '%s'\n"),
1039 * it's a no-op without /etc/shadow
1041 if ((-1 != def_inactive) && !is_shadow_pwd) {
1043 _("%s: shadow passwords required for -f\n"),
1050 grp = getgr_nam_gid (optarg);
1053 _("%s: group '%s' does not exist\n"),
1058 def_group = grp->gr_gid;
1061 user_gid = grp->gr_gid;
1066 if (get_groups (optarg) != 0) {
1069 if (NULL != user_groups[0]) {
1070 do_grp_update = true;
1078 def_template = optarg;
1083 * override login.defs defaults (-K name=value)
1084 * example: -K UID_MIN=100 -K UID_MAX=499
1085 * note: -K UID_MIN=10,UID_MAX=499 doesn't work yet
1087 cp = strchr (optarg, '=');
1090 _("%s: -K requires KEY=VALUE\n"),
1094 /* terminate name, point to value */
1097 if (putdef_str (optarg, cp) < 0) {
1116 case 'p': /* set encrypted password */
1117 if (!VALID (optarg)) {
1119 _("%s: invalid field '%s'\n"),
1129 if ( ( !VALID (optarg) )
1130 || ( ('\0' != optarg[0])
1131 && ('/' != optarg[0])
1132 && ('*' != optarg[0]) )) {
1134 _("%s: invalid shell '%s'\n"),
1138 user_shell = optarg;
1143 if ( (get_uid (optarg, &user_id) == 0)
1144 || (user_id == (gid_t)-1)) {
1146 _("%s: invalid user ID '%s'\n"),
1162 if (!gflg && !Nflg && !Uflg) {
1163 /* Get the settings from login.defs */
1164 Uflg = getdef_bool ("USERGROUPS_ENAB");
1168 * Certain options are only valid in combination with others.
1169 * Check it here so that they can be specified in any order.
1171 if (oflg && !uflg) {
1173 _("%s: %s flag is only allowed with the %s flag\n"),
1177 if (kflg && !mflg) {
1179 _("%s: %s flag is only allowed with the %s flag\n"),
1185 _("%s: options %s and %s conflict\n"),
1191 _("%s: options %s and %s conflict\n"),
1197 _("%s: options %s and %s conflict\n"),
1203 * Either -D or username is required. Defaults can be set with -D
1204 * for the -b, -e, -f, -g, -s options only.
1207 if (optind != argc) {
1211 if (uflg || oflg || Gflg || dflg || cflg || mflg) {
1215 if (optind != argc - 1) {
1219 user_name = argv[optind];
1220 if (!is_valid_user_name (user_name)) {
1222 _("%s: invalid user name '%s'\n"),
1225 audit_logger (AUDIT_ADD_USER, Prog,
1227 user_name, AUDIT_NO_ID,
1228 SHADOW_AUDIT_FAILURE);
1235 uh = xmalloc (strlen (def_home) +
1236 strlen (user_name) + 2);
1237 sprintf (uh, "%s/%s", def_home, user_name);
1243 user_expire = strtoday (def_expire);
1247 user_gid = def_group;
1251 user_shell = def_shell;
1254 create_mail_spool = def_create_mail_spool;
1257 /* for system accounts defaults are ignored and we
1258 * do not create a home dir */
1259 if (getdef_bool("CREATE_HOME")) {
1265 /* absolutely sure that we do not create home dirs */
1271 * close_files - close all of the files that were opened
1273 * close_files() closes all of the files that were opened for this
1274 * new user. This causes any modified entries to be written out.
1276 static void close_files (void)
1278 if (pw_close () == 0) {
1279 fprintf (stderr, _("%s: failure while writing changes to %s\n"), Prog, pw_dbname ());
1280 SYSLOG ((LOG_ERR, "failure while writing changes to %s", pw_dbname ()));
1281 fail_exit (E_PW_UPDATE);
1283 if (is_shadow_pwd && (spw_close () == 0)) {
1285 _("%s: failure while writing changes to %s\n"), Prog, spw_dbname ());
1286 SYSLOG ((LOG_ERR, "failure while writing changes to %s", spw_dbname ()));
1287 fail_exit (E_PW_UPDATE);
1289 if (do_grp_update) {
1290 if (gr_close () == 0) {
1292 _("%s: failure while writing changes to %s\n"), Prog, gr_dbname ());
1293 SYSLOG ((LOG_ERR, "failure while writing changes to %s", gr_dbname ()));
1294 fail_exit (E_GRP_UPDATE);
1297 if (is_shadow_grp && (sgr_close () == 0)) {
1299 _("%s: failure while writing changes to %s\n"),
1300 Prog, sgr_dbname ());
1301 SYSLOG ((LOG_ERR, "failure while writing changes to %s", sgr_dbname ()));
1302 fail_exit (E_GRP_UPDATE);
1306 if (is_shadow_pwd) {
1307 if (spw_unlock () == 0) {
1308 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, spw_dbname ());
1309 SYSLOG ((LOG_ERR, "failed to unlock %s", spw_dbname ()));
1311 audit_logger (AUDIT_ADD_USER, Prog,
1312 "unlocking shadow file",
1313 user_name, AUDIT_NO_ID,
1314 SHADOW_AUDIT_FAILURE);
1320 if (pw_unlock () == 0) {
1321 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, pw_dbname ());
1322 SYSLOG ((LOG_ERR, "failed to unlock %s", pw_dbname ()));
1324 audit_logger (AUDIT_ADD_USER, Prog,
1325 "unlocking passwd file",
1326 user_name, AUDIT_NO_ID,
1327 SHADOW_AUDIT_FAILURE);
1332 if (gr_unlock () == 0) {
1333 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, gr_dbname ());
1334 SYSLOG ((LOG_ERR, "failed to unlock %s", gr_dbname ()));
1336 audit_logger (AUDIT_ADD_USER, Prog,
1337 "unlocking group file",
1338 user_name, AUDIT_NO_ID,
1339 SHADOW_AUDIT_FAILURE);
1345 if (is_shadow_grp) {
1346 if (sgr_unlock () == 0) {
1347 fprintf (stderr, _("%s: failed to unlock %s\n"), Prog, sgr_dbname ());
1348 SYSLOG ((LOG_ERR, "failed to unlock %s", sgr_dbname ()));
1350 audit_logger (AUDIT_ADD_USER, Prog,
1351 "unlocking gshadow file",
1352 user_name, AUDIT_NO_ID,
1353 SHADOW_AUDIT_FAILURE);
1363 * open_files - lock and open the password files
1365 * open_files() opens the two password files.
1367 static void open_files (void)
1369 if (pw_lock () == 0) {
1371 _("%s: cannot lock %s; try again later.\n"),
1372 Prog, pw_dbname ());
1376 if (pw_open (O_RDWR) == 0) {
1377 fprintf (stderr, _("%s: cannot open %s\n"), Prog, pw_dbname ());
1378 fail_exit (E_PW_UPDATE);
1380 if (is_shadow_pwd) {
1381 if (spw_lock () == 0) {
1383 _("%s: cannot lock %s; try again later.\n"),
1384 Prog, spw_dbname ());
1385 fail_exit (E_PW_UPDATE);
1388 if (spw_open (O_RDWR) == 0) {
1390 _("%s: cannot open %s\n"),
1391 Prog, spw_dbname ());
1392 fail_exit (E_PW_UPDATE);
1397 * Lock and open the group file.
1399 if (gr_lock () == 0) {
1401 _("%s: cannot lock %s; try again later.\n"),
1402 Prog, gr_dbname ());
1403 fail_exit (E_GRP_UPDATE);
1406 if (gr_open (O_RDWR) == 0) {
1407 fprintf (stderr, _("%s: cannot open %s\n"), Prog, gr_dbname ());
1408 fail_exit (E_GRP_UPDATE);
1411 if (is_shadow_grp) {
1412 if (sgr_lock () == 0) {
1414 _("%s: cannot lock %s; try again later.\n"),
1415 Prog, sgr_dbname ());
1416 fail_exit (E_GRP_UPDATE);
1419 if (sgr_open (O_RDWR) == 0) {
1421 _("%s: cannot open %s\n"),
1422 Prog, sgr_dbname ());
1423 fail_exit (E_GRP_UPDATE);
1429 static char *empty_list = NULL;
1432 * new_grent - initialize the values in a group file entry
1434 * new_grent() takes all of the values that have been entered and fills
1435 * in a (struct group) with them.
1438 static void new_grent (struct group *grent)
1440 memzero (grent, sizeof *grent);
1441 grent->gr_name = (char *) user_name;
1442 grent->gr_passwd = SHADOW_PASSWD_STRING; /* XXX warning: const */
1443 grent->gr_gid = user_gid;
1444 grent->gr_mem = &empty_list;
1449 * new_sgent - initialize the values in a shadow group file entry
1451 * new_sgent() takes all of the values that have been entered and fills
1452 * in a (struct sgrp) with them.
1455 static void new_sgent (struct sgrp *sgent)
1457 memzero (sgent, sizeof *sgent);
1458 sgent->sg_name = (char *) user_name;
1459 sgent->sg_passwd = "!"; /* XXX warning: const */
1460 sgent->sg_adm = &empty_list;
1461 sgent->sg_mem = &empty_list;
1463 #endif /* SHADOWGRP */
1467 * grp_add - add new group file entries
1469 * grp_add() writes the new records to the group files.
1472 static void grp_add (void)
1478 #endif /* SHADOWGRP */
1481 * Create the initial entries for this new group.
1486 #endif /* SHADOWGRP */
1489 * Write out the new group file entry.
1491 if (gr_update (&grp) == 0) {
1493 _("%s: failed to prepare the new %s entry '%s'\n"),
1494 Prog, gr_dbname (), grp.gr_name);
1496 audit_logger (AUDIT_ADD_GROUP, Prog,
1498 grp.gr_name, AUDIT_NO_ID,
1499 SHADOW_AUDIT_FAILURE);
1501 fail_exit (E_GRP_UPDATE);
1505 * Write out the new shadow group entries as well.
1507 if (is_shadow_grp && (sgr_update (&sgrp) == 0)) {
1509 _("%s: failed to prepare the new %s entry '%s'\n"),
1510 Prog, sgr_dbname (), sgrp.sg_name);
1512 audit_logger (AUDIT_ADD_GROUP, Prog,
1514 grp.gr_name, AUDIT_NO_ID,
1515 SHADOW_AUDIT_FAILURE);
1517 fail_exit (E_GRP_UPDATE);
1519 #endif /* SHADOWGRP */
1520 SYSLOG ((LOG_INFO, "new group: name=%s, GID=%u", user_name, user_gid));
1522 audit_logger (AUDIT_ADD_GROUP, Prog,
1524 grp.gr_name, AUDIT_NO_ID,
1525 SHADOW_AUDIT_SUCCESS);
1527 do_grp_update = true;
1530 static void faillog_reset (uid_t uid)
1534 off_t offset_uid = (off_t) (sizeof fl) * uid;
1536 if (access (FAILLOG_FILE, F_OK) != 0) {
1540 memzero (&fl, sizeof (fl));
1542 fd = open (FAILLOG_FILE, O_RDWR);
1544 || (lseek (fd, offset_uid, SEEK_SET) != offset_uid)
1545 || (write (fd, &fl, sizeof (fl)) != (ssize_t) sizeof (fl))
1546 || (fsync (fd) != 0)
1547 || (close (fd) != 0)) {
1549 _("%s: failed to reset the faillog entry of UID %lu: %s\n"),
1550 Prog, (unsigned long) uid, strerror (errno));
1551 SYSLOG ((LOG_WARN, "failed to reset the faillog entry of UID %lu", (unsigned long) uid));
1556 static void lastlog_reset (uid_t uid)
1560 off_t offset_uid = (off_t) (sizeof ll) * uid;
1562 if (access (LASTLOG_FILE, F_OK) != 0) {
1566 memzero (&ll, sizeof (ll));
1568 fd = open (LASTLOG_FILE, O_RDWR);
1570 || (lseek (fd, offset_uid, SEEK_SET) != offset_uid)
1571 || (write (fd, &ll, sizeof (ll)) != (ssize_t) sizeof (ll))
1572 || (fsync (fd) != 0)
1573 || (close (fd) != 0)) {
1575 _("%s: failed to reset the lastlog entry of UID %lu: %s\n"),
1576 Prog, (unsigned long) uid, strerror (errno));
1577 SYSLOG ((LOG_WARN, "failed to reset the lastlog entry of UID %lu", (unsigned long) uid));
1583 * usr_update - create the user entries
1585 * usr_update() creates the password file entries for this user
1586 * and will update the group entries if required.
1588 static void usr_update (void)
1590 struct passwd pwent;
1594 * Fill in the password structure with any new fields, making
1595 * copies of strings.
1601 * Create a syslog entry. We need to do this now in case anything
1602 * happens so we know what we were trying to accomplish.
1605 "new user: name=%s, UID=%u, GID=%u, home=%s, shell=%s",
1606 user_name, (unsigned int) user_id,
1607 (unsigned int) user_gid, user_home, user_shell));
1610 * Initialize faillog and lastlog entries for this UID in case
1611 * it belongs to a previously deleted user. We do it only if
1612 * no user with this UID exists yet (entries for shared UIDs
1613 * are left unchanged). --marekm
1615 /* local, no need for xgetpwuid */
1616 if ((!lflg) && (getpwuid (user_id) == NULL)) {
1617 faillog_reset (user_id);
1618 lastlog_reset (user_id);
1622 * Put the new (struct passwd) in the table.
1624 if (pw_update (&pwent) == 0) {
1626 _("%s: failed to prepare the new %s entry '%s'\n"),
1627 Prog, pw_dbname (), pwent.pw_name);
1628 fail_exit (E_PW_UPDATE);
1632 * Put the new (struct spwd) in the table.
1634 if (is_shadow_pwd && (spw_update (&spent) == 0)) {
1636 _("%s: failed to prepare the new %s entry '%s'\n"),
1637 Prog, spw_dbname (), spent.sp_namp);
1639 audit_logger (AUDIT_ADD_USER, Prog,
1640 "adding shadow password",
1641 user_name, (unsigned int) user_id,
1642 SHADOW_AUDIT_FAILURE);
1644 fail_exit (E_PW_UPDATE);
1647 audit_logger (AUDIT_ADD_USER, Prog,
1649 user_name, (unsigned int) user_id,
1650 SHADOW_AUDIT_SUCCESS);
1654 * Do any group file updates for this user.
1656 if (do_grp_update) {
1662 * create_home - create the user's home directory
1664 * create_home() creates the user's home directory if it does not
1665 * already exist. It will be created mode 755 owned by the user
1666 * with the user's default group.
1668 static void create_home (void)
1670 if (access (user_home, F_OK) != 0) {
1671 /* XXX - create missing parent directories. --marekm */
1672 if (mkdir (user_home, 0) != 0) {
1674 _("%s: cannot create directory %s\n"),
1677 audit_logger (AUDIT_ADD_USER, Prog,
1678 "adding home directory",
1679 user_name, (unsigned int) user_id,
1680 SHADOW_AUDIT_FAILURE);
1682 fail_exit (E_HOMEDIR);
1684 chown (user_home, user_id, user_gid);
1686 0777 & ~getdef_num ("UMASK", GETDEF_DEFAULT_UMASK));
1689 audit_logger (AUDIT_ADD_USER, Prog,
1690 "adding home directory",
1691 user_name, (unsigned int) user_id,
1692 SHADOW_AUDIT_SUCCESS);
1698 * create_mail - create the user's mail spool
1700 * create_mail() creates the user's mail spool if it does not already
1701 * exist. It will be created mode 660 owned by the user and group
1704 static void create_mail (void)
1712 if (strcasecmp (create_mail_spool, "yes") == 0) {
1713 spool = getdef_str ("MAIL_DIR");
1714 if (NULL == spool) {
1715 spool = "/var/mail";
1717 file = alloca (strlen (spool) + strlen (user_name) + 2);
1718 sprintf (file, "%s/%s", spool, user_name);
1719 fd = open (file, O_CREAT | O_WRONLY | O_TRUNC | O_EXCL, 0);
1721 perror (_("Creating mailbox file"));
1725 gr = getgrnam ("mail"); /* local, no need for xgetgrnam */
1727 fputs (_("Group 'mail' not found. Creating the user mailbox file with 0600 mode.\n"),
1736 if ( (fchown (fd, user_id, gid) != 0)
1737 || (fchmod (fd, mode) != 0)) {
1738 perror (_("Setting mailbox file permissions"));
1747 * main - useradd command
1749 int main (int argc, char **argv)
1751 #ifdef ACCT_TOOLS_SETUID
1753 pam_handle_t *pamh = NULL;
1755 #endif /* USE_PAM */
1756 #endif /* ACCT_TOOLS_SETUID */
1763 * Get my name so that I can use it to report errors.
1765 Prog = Basename (argv[0]);
1767 (void) setlocale (LC_ALL, "");
1768 (void) bindtextdomain (PACKAGE, LOCALEDIR);
1769 (void) textdomain (PACKAGE);
1771 OPENLOG ("useradd");
1773 sys_ngroups = sysconf (_SC_NGROUPS_MAX);
1774 user_groups = malloc ((1 + sys_ngroups) * sizeof (char *));
1776 * Initialize the list to be empty
1778 user_groups[0] = (char *) 0;
1781 is_shadow_pwd = spw_file_present ();
1783 is_shadow_grp = sgr_file_present ();
1788 process_flags (argc, argv);
1790 #ifdef ACCT_TOOLS_SETUID
1793 struct passwd *pampw;
1794 pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
1795 if (pampw == NULL) {
1797 _("%s: Cannot determine your user name.\n"),
1802 retval = pam_start ("useradd", pampw->pw_name, &conv, &pamh);
1805 if (PAM_SUCCESS == retval) {
1806 retval = pam_authenticate (pamh, 0);
1809 if (PAM_SUCCESS == retval) {
1810 retval = pam_acct_mgmt (pamh, 0);
1814 (void) pam_end (pamh, retval);
1816 if (PAM_SUCCESS != retval) {
1817 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
1820 #endif /* USE_PAM */
1821 #endif /* ACCT_TOOLS_SETUID */
1824 * See if we are messing with the defaults file, or creating
1828 if (gflg || bflg || fflg || eflg || sflg) {
1829 exit ((set_defaults () != 0) ? 1 : 0);
1837 * Start with a quick check to see if the user exists.
1839 if (getpwnam (user_name) != NULL) { /* local, no need for xgetpwnam */
1840 fprintf (stderr, _("%s: user '%s' already exists\n"), Prog, user_name);
1842 audit_logger (AUDIT_ADD_USER, Prog,
1844 user_name, AUDIT_NO_ID,
1845 SHADOW_AUDIT_FAILURE);
1847 fail_exit (E_NAME_IN_USE);
1851 * Don't blindly overwrite a group when a user is added...
1852 * If you already have a group username, and want to add the user
1853 * to that group, use useradd -g username username.
1857 /* local, no need for xgetgrnam */
1858 if (getgrnam (user_name) != NULL) {
1860 _("%s: group %s exists - if you want to add this user to that group, use -g.\n"),
1863 audit_logger (AUDIT_ADD_USER, Prog,
1865 user_name, AUDIT_NO_ID,
1866 SHADOW_AUDIT_FAILURE);
1868 fail_exit (E_NAME_IN_USE);
1873 * Do the hard stuff:
1875 * - create the user entries,
1876 * - create the home directory,
1877 * - create user mail spool,
1878 * - flush nscd caches for passwd and group services,
1879 * - then close and update the files.
1884 /* first, seek for a valid uid to use for this user.
1885 * We do this because later we can use the uid we found as
1886 * gid too ... --gafton */
1888 if (find_new_uid (rflg, &user_id, NULL) < 0) {
1889 fprintf (stderr, _("%s: can't create user\n"), Prog);
1890 fail_exit (E_UID_IN_USE);
1893 if (getpwuid (user_id) != NULL) {
1895 _("%s: UID %lu is not unique\n"),
1896 Prog, (unsigned long) user_id);
1898 audit_logger (AUDIT_ADD_USER, Prog,
1900 user_name, (unsigned int) user_id,
1901 SHADOW_AUDIT_FAILURE);
1903 fail_exit (E_UID_IN_USE);
1908 /* do we have to add a group for that user? This is why we need to
1909 * open the group files in the open_files() function --gafton */
1911 if (find_new_gid (rflg, &user_gid, &user_id) < 0) {
1913 _("%s: can't create group\n"),
1925 copy_tree (def_template, user_home, user_id, user_gid);
1928 _("%s: warning: the home directory already exists.\n"
1929 "Not copying any file from skel directory into it.\n"),
1935 /* Do not create mail directory for system accounts */
1942 nscd_flush_cache ("passwd");
1943 nscd_flush_cache ("group");