]> granicus.if.org Git - shadow/blob - src/groupadd.c
Re-indent.
[shadow] / src / groupadd.c
1 /*
2  * Copyright 1991 - 1993, Julianne Frances Haugh
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of Julianne F. Haugh nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY JULIE HAUGH AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED. IN NO EVENT SHALL JULIE HAUGH OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 #include <config.h>
31
32 #ident "$Id$"
33
34 #include <assert.h>
35 #include <ctype.h>
36 #include <fcntl.h>
37 #include <getopt.h>
38 #include <grp.h>
39 #include <stdio.h>
40 #include <sys/types.h>
41 #ifdef USE_PAM
42 #include "pam_defs.h"
43 #include <pwd.h>
44 #endif                          /* USE_PAM */
45 #include "chkname.h"
46 #include "defines.h"
47 #include "getdef.h"
48 #include "groupio.h"
49 #include "nscd.h"
50 #include "prototypes.h"
51 #ifdef  SHADOWGRP
52 #include "sgroupio.h"
53 static int is_shadow_grp;
54 #endif
55
56 /*
57  * exit status values
58  */
59 #define E_SUCCESS       0       /* success */
60 #define E_USAGE         2       /* invalid command syntax */
61 #define E_BAD_ARG       3       /* invalid argument to option */
62 #define E_GID_IN_USE    4       /* gid not unique (when -o not used) */
63 #define E_NAME_IN_USE   9       /* group name not unique */
64 #define E_GRP_UPDATE    10      /* can't update group file */
65
66 /*
67  * Global variables
68  */
69 static char *group_name;
70 static gid_t group_id;
71 static char *empty_list = NULL;
72
73 static char *Prog;
74
75 static int oflg = 0;            /* permit non-unique group ID to be specified with -g */
76 static int gflg = 0;            /* ID value for the new group */
77 static int fflg = 0;            /* if group already exists, do nothing and exit(0) */
78
79 /* local function prototypes */
80 static void usage (void);
81 static void new_grent (struct group *grent);
82
83 #ifdef SHADOWGRP
84 static void new_sgent (struct sgrp *sgent);
85 #endif
86 static void grp_update (void);
87 static void find_new_gid (void);
88 static void check_new_name (void);
89 static void close_files (void);
90 static void open_files (void);
91 static void fail_exit (int code);
92 static gid_t get_gid (const char *gidstr);
93 static void process_flags (int argc, char **argv);
94
95 /*
96  * usage - display usage message and exit
97  */
98 static void usage (void)
99 {
100         fprintf (stderr, _("Usage: groupadd [options] GROUP\n"
101                            "\n"
102                            "Options:\n"
103                            "  -f, --force                   force exit with success status if the\n"
104                            "                                specified group already exists\n"
105                            "  -g, --gid GID                 use GID for the new group\n"
106                            "  -h, --help                    display this help message and exit\n"
107                            "  -K, --key KEY=VALUE           overrides /etc/login.defs defaults\n"
108                            "  -o, --non-unique              allow create group with duplicate\n"
109                            "                                (non-unique) GID\n"
110                            "\n"));
111         exit (E_USAGE);
112 }
113
114 /*
115  * new_grent - initialize the values in a group file entry
116  *
117  *      new_grent() takes all of the values that have been entered and fills
118  *      in a (struct group) with them.
119  */
120 static void new_grent (struct group *grent)
121 {
122         memzero (grent, sizeof *grent);
123         grent->gr_name = group_name;
124         grent->gr_passwd = SHADOW_PASSWD_STRING;        /* XXX warning: const */
125         grent->gr_gid = group_id;
126         grent->gr_mem = &empty_list;
127 }
128
129 #ifdef  SHADOWGRP
130 /*
131  * new_sgent - initialize the values in a shadow group file entry
132  *
133  *      new_sgent() takes all of the values that have been entered and fills
134  *      in a (struct sgrp) with them.
135  */
136 static void new_sgent (struct sgrp *sgent)
137 {
138         memzero (sgent, sizeof *sgent);
139         sgent->sg_name = group_name;
140         sgent->sg_passwd = "!"; /* XXX warning: const */
141         sgent->sg_adm = &empty_list;
142         sgent->sg_mem = &empty_list;
143 }
144 #endif                          /* SHADOWGRP */
145
146 /*
147  * grp_update - add new group file entries
148  *
149  *      grp_update() writes the new records to the group files.
150  */
151 static void grp_update (void)
152 {
153         struct group grp;
154
155 #ifdef  SHADOWGRP
156         struct sgrp sgrp;
157 #endif                          /* SHADOWGRP */
158
159         /*
160          * Create the initial entries for this new group.
161          */
162         new_grent (&grp);
163 #ifdef  SHADOWGRP
164         new_sgent (&sgrp);
165 #endif                          /* SHADOWGRP */
166
167         /*
168          * Write out the new group file entry.
169          */
170         if (!gr_update (&grp)) {
171                 fprintf (stderr, _("%s: error adding new group entry\n"), Prog);
172                 fail_exit (E_GRP_UPDATE);
173         }
174 #ifdef  SHADOWGRP
175         /*
176          * Write out the new shadow group entries as well.
177          */
178         if (is_shadow_grp && !sgr_update (&sgrp)) {
179                 fprintf (stderr, _("%s: error adding new group entry\n"), Prog);
180                 fail_exit (E_GRP_UPDATE);
181         }
182 #endif                          /* SHADOWGRP */
183 #ifdef WITH_AUDIT
184         audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "adding group", group_name,
185                       group_id, 1);
186 #endif
187         SYSLOG ((LOG_INFO, "new group: name=%s, GID=%u",
188                 group_name, (unsigned int) group_id));
189 }
190
191 /*
192  * find_new_gid - find the next available GID
193  *
194  *      find_new_gid() locates the next highest unused GID in the group
195  *      file.
196  */
197 static void find_new_gid (void)
198 {
199         const struct group *grp;
200         gid_t gid_min, gid_max;
201
202         /*
203          * It doesn't make sense to use find_new_uid(),
204          * if a GID is specified via "-g" option.
205          */
206         assert (!gflg);
207
208         gid_min = getdef_unum ("GID_MIN", 1000);
209         gid_max = getdef_unum ("GID_MAX", 60000);
210
211         /*
212          * Start with the lowest GID.
213          */
214         group_id = gid_min;
215
216         /*
217          * Search the entire group file, looking for the largest unused
218          * value.
219          */
220         setgrent ();
221         while ((grp = getgrent ())) {
222                 if ((grp->gr_gid >= group_id) && (grp->gr_gid <= gid_max)) {
223                         group_id = grp->gr_gid + 1;
224                 }
225         }
226         if (group_id == (gid_max + 1)) {
227                 for (group_id = gid_min; group_id < gid_max; group_id++) {
228                         /* local, no need for xgetgrgid */
229                         if (!getgrgid (group_id)) {
230                                 break;
231                         }
232                 }
233                 if (group_id == gid_max) {
234                         fprintf (stderr, _("%s: can't get unique GID\n"), Prog);
235                         fail_exit (E_GID_IN_USE);
236                 }
237         }
238 }
239
240 /*
241  * check_new_name - check the new name for validity
242  *
243  *      check_new_name() insures that the new name doesn't contain any
244  *      illegal characters.
245  */
246 static void check_new_name (void)
247 {
248         if (check_group_name (group_name)) {
249                 return;
250         }
251
252         /*
253          * All invalid group names land here.
254          */
255
256         fprintf (stderr, _("%s: %s is not a valid group name\n"),
257                  Prog, group_name);
258
259         exit (E_BAD_ARG);
260 }
261
262 /*
263  * close_files - close all of the files that were opened
264  *
265  *      close_files() closes all of the files that were opened for this new
266  *      group. This causes any modified entries to be written out.
267  */
268 static void close_files (void)
269 {
270         if (!gr_close ()) {
271                 fprintf (stderr, _("%s: cannot rewrite group file\n"), Prog);
272                 fail_exit (E_GRP_UPDATE);
273         }
274         gr_unlock ();
275 #ifdef  SHADOWGRP
276         if (is_shadow_grp && !sgr_close ()) {
277                 fprintf (stderr,
278                          _("%s: cannot rewrite shadow group file\n"), Prog);
279                 fail_exit (E_GRP_UPDATE);
280         }
281         if (is_shadow_grp) {
282                 sgr_unlock ();
283         }
284 #endif                          /* SHADOWGRP */
285 }
286
287 /*
288  * open_files - lock and open the group files
289  *
290  *      open_files() opens the two group files.
291  */
292 static void open_files (void)
293 {
294         if (!gr_lock ()) {
295                 fprintf (stderr, _("%s: unable to lock group file\n"), Prog);
296 #ifdef WITH_AUDIT
297                 audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "locking group file",
298                               group_name, -1, 0);
299 #endif
300                 exit (E_GRP_UPDATE);
301         }
302         if (!gr_open (O_RDWR)) {
303                 fprintf (stderr, _("%s: unable to open group file\n"), Prog);
304 #ifdef WITH_AUDIT
305                 audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "opening group file",
306                               group_name, -1, 0);
307 #endif
308                 fail_exit (E_GRP_UPDATE);
309         }
310 #ifdef  SHADOWGRP
311         if (is_shadow_grp && !sgr_lock ()) {
312                 fprintf (stderr,
313                          _("%s: unable to lock shadow group file\n"), Prog);
314                 fail_exit (E_GRP_UPDATE);
315         }
316         if (is_shadow_grp && !sgr_open (O_RDWR)) {
317                 fprintf (stderr,
318                          _("%s: unable to open shadow group file\n"), Prog);
319                 fail_exit (E_GRP_UPDATE);
320         }
321 #endif                          /* SHADOWGRP */
322 }
323
324 /*
325  * fail_exit - exit with an error code after unlocking files
326  */
327 static void fail_exit (int code)
328 {
329         (void) gr_unlock ();
330 #ifdef  SHADOWGRP
331         if (is_shadow_grp) {
332                 sgr_unlock ();
333         }
334 #endif
335
336 #ifdef WITH_AUDIT
337         if (code != E_SUCCESS) {
338                 audit_logger (AUDIT_USER_CHAUTHTOK, Prog, "adding group",
339                               group_name, -1, 0);
340         }
341 #endif
342         exit (code);
343 }
344
345 /*
346  * get_id - validate and get group ID
347  */
348 static gid_t get_gid (const char *gidstr)
349 {
350         long val;
351         char *errptr;
352
353         val = strtol (gidstr, &errptr, 10);
354         if (('\0' != *errptr) || (errno == ERANGE) || (val < 0)) {
355                 fprintf (stderr, _("%s: invalid numeric argument '%s'\n"),
356                          Prog, gidstr);
357                 exit (E_BAD_ARG);
358         }
359         return val;
360 }
361
362 /*
363  * process_flags - parse the command line options
364  *
365  *      It will not return if an error is encountered.
366  */
367 static void process_flags (int argc, char **argv)
368 {
369         /*
370          * Parse the command line options.
371          */
372         char *cp;
373         int option_index = 0;
374         int c;
375         static struct option long_options[] = {
376                 {"force", no_argument, NULL, 'f'},
377                 {"gid", required_argument, NULL, 'g'},
378                 {"help", no_argument, NULL, 'h'},
379                 {"key", required_argument, NULL, 'K'},
380                 {"non-unique", required_argument, NULL, 'o'},
381                 {NULL, 0, NULL, '\0'}
382         };
383
384         while ((c =
385                 getopt_long (argc, argv, "fg:hK:o", long_options,
386                              &option_index)) != -1) {
387                 switch (c) {
388                 case 'f':
389                         /*
390                          * "force" - do nothing, just exit(0), if the
391                          * specified group already exists. With -g, if
392                          * specified gid already exists, choose another
393                          * (unique) gid (turn off -g). Based on the RedHat's
394                          * patch from shadow-utils-970616-9.
395                          */
396                         fflg++;
397                         break;
398                 case 'g':
399                         gflg++;
400                         group_id = get_gid (optarg);
401                         break;
402                 case 'h':
403                         usage ();
404                         break;
405                 case 'K':
406                         /*
407                          * override login.defs defaults (-K name=value)
408                          * example: -K GID_MIN=100 -K GID_MAX=499
409                          * note: -K GID_MIN=10,GID_MAX=499 doesn't work yet
410                          */
411                         cp = strchr (optarg, '=');
412                         if (NULL == cp) {
413                                 fprintf (stderr,
414                                          _
415                                          ("%s: -K requires KEY=VALUE\n"),
416                                          Prog);
417                                 exit (E_BAD_ARG);
418                         }
419                         /* terminate name, point to value */
420                         *cp++ = '\0';
421                         if (putdef_str (optarg, cp) < 0) {
422                                 exit (E_BAD_ARG);
423                         }
424                         break;
425                 case 'o':
426                         oflg++;
427                         break;
428                 default:
429                         usage ();
430                 }
431         }
432
433         /*
434          * Check the flags consistency
435          */
436         if (oflg && !gflg) {
437                 usage ();
438         }
439
440         if (optind != argc - 1) {
441                 usage ();
442         }
443
444         group_name = argv[optind];
445
446         check_new_name ();
447
448         /*
449          * Check if the group already exist.
450          */
451         /* local, no need for xgetgrnam */
452         if (getgrnam (group_name) != NULL) {
453                 /* The group already exist */
454                 if (fflg) {
455                         /* OK, no need to do anything */
456                         fail_exit (E_SUCCESS);
457                 }
458                 fprintf (stderr, _("%s: group %s exists\n"), Prog, group_name);
459                 fail_exit (E_NAME_IN_USE);
460         }
461
462         if (gflg && (getgrgid (group_id) != NULL)) {
463                 /* A GID was specified, and a group already exist with that GID
464                  *  - either we will use this GID anyway (-o)
465                  *  - either we ignore the specified GID and
466                  *    we will use another one(-f)
467                  *  - either it is a failure
468                  */
469                 if (oflg) {
470                         /* Continue with this GID */
471                 } else if (fflg) {
472                         /* Turn off -g, we can use any GID */
473                         gflg = 0;
474                 } else {
475                         fprintf (stderr, _("%s: GID %u is not unique\n"),
476                                  Prog, (unsigned int) group_id);
477                         fail_exit (E_GID_IN_USE);
478                 }
479         }
480 }
481
482 /*
483  * main - groupadd command
484  */
485 int main (int argc, char **argv)
486 {
487 #ifdef USE_PAM
488         pam_handle_t *pamh = NULL;
489         int retval;
490 #endif
491
492 #ifdef WITH_AUDIT
493         audit_help_open ();
494 #endif
495         /*
496          * Get my name so that I can use it to report errors.
497          */
498         Prog = Basename (argv[0]);
499
500         setlocale (LC_ALL, "");
501         bindtextdomain (PACKAGE, LOCALEDIR);
502         textdomain (PACKAGE);
503
504         OPENLOG ("groupadd");
505
506         /*
507          * Parse the command line options.
508          */
509         process_flags (argc, argv);
510
511 #ifdef USE_PAM
512         retval = PAM_SUCCESS;
513
514         {
515                 struct passwd *pampw;
516                 pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
517                 if (pampw == NULL) {
518                         retval = PAM_USER_UNKNOWN;
519                 }
520
521                 if (retval == PAM_SUCCESS) {
522                         retval = pam_start ("groupadd", pampw->pw_name,
523                                             &conv, &pamh);
524                 }
525         }
526
527         if (retval == PAM_SUCCESS) {
528                 retval = pam_authenticate (pamh, 0);
529                 if (retval != PAM_SUCCESS) {
530                         pam_end (pamh, retval);
531                 }
532         }
533
534         if (retval == PAM_SUCCESS) {
535                 retval = pam_acct_mgmt (pamh, 0);
536                 if (retval != PAM_SUCCESS) {
537                         pam_end (pamh, retval);
538                 }
539         }
540
541         if (retval != PAM_SUCCESS) {
542                 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
543                 exit (1);
544         }
545 #endif                          /* USE_PAM */
546
547 #ifdef SHADOWGRP
548         is_shadow_grp = sgr_file_present ();
549 #endif
550
551         /*
552          * Do the hard stuff - open the files, create the group entries,
553          * then close and update the files.
554          */
555         open_files ();
556
557         if (!gflg) {
558                 find_new_gid ();
559         }
560
561         grp_update ();
562         close_files ();
563
564         nscd_flush_cache ("group");
565
566 #ifdef USE_PAM
567         if (retval == PAM_SUCCESS) {
568                 pam_end (pamh, PAM_SUCCESS);
569         }
570 #endif                          /* USE_PAM */
571         exit (E_SUCCESS);
572         /* NOT REACHED */
573 }
574