]> granicus.if.org Git - shadow/blob - src/chfn.c
Allow non-US-ASCII characters in the GECOS fields ("name", "room number",
[shadow] / src / chfn.c
1 /*
2  * Copyright 1989 - 1994, 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 <fcntl.h>
35 #include <pwd.h>
36 #include <signal.h>
37 #include <stdio.h>
38 #include <sys/types.h>
39 #ifdef WITH_SELINUX
40 #include <selinux/selinux.h>
41 #include <selinux/av_permissions.h>
42 #endif
43 #include "defines.h"
44 #include "exitcodes.h"
45 #include "getdef.h"
46 #include "nscd.h"
47 #ifdef USE_PAM
48 #include "pam_defs.h"
49 #endif
50 #include "prototypes.h"
51 #include "pwauth.h"
52 #include "pwio.h"
53 /*
54  * Global variables.
55  */
56 static char *Prog;
57 static char fullnm[BUFSIZ];
58 static char roomno[BUFSIZ];
59 static char workph[BUFSIZ];
60 static char homeph[BUFSIZ];
61 static char slop[BUFSIZ];
62 static int amroot;
63 /* Flags */
64 static int fflg = 0;            /* -f - set full name                */
65 static int rflg = 0;            /* -r - set room number              */
66 static int wflg = 0;            /* -w - set work phone number        */
67 static int hflg = 0;            /* -h - set home phone number        */
68 static int oflg = 0;            /* -o - set other information        */
69 #ifdef USE_PAM
70 static pam_handle_t *pamh = NULL;
71 #endif
72
73 /*
74  * External identifiers
75  */
76
77 /* local function prototypes */
78 static void usage (void);
79 static int may_change_field (int);
80 static void new_fields (void);
81 static char *copy_field (char *, char *, char *);
82 static void process_flags (int argc, char **argv);
83 static void check_perms (const struct passwd *pw);
84 static void update_gecos (const char *user, char *gecos);
85 static void get_old_fields (const char *gecos);
86
87 /*
88  * usage - print command line syntax and exit
89  */
90 static void usage (void)
91 {
92         if (amroot) {
93                 fprintf (stderr,
94                          _("Usage: %s [-f full_name] [-r room_no] "
95                            "[-w work_ph]\n"
96                            "\t[-h home_ph] [-o other] [user]\n"), Prog);
97         } else {
98                 fprintf (stderr,
99                          _("Usage: %s [-f full_name] [-r room_no] "
100                            "[-w work_ph] [-h home_ph]\n"), Prog);
101         }
102         exit (E_USAGE);
103 }
104
105 /*
106  * may_change_field - indicate if the user is allowed to change a given field
107  *                    of her gecos information
108  *
109  *      root can change any field.
110  *
111  *      field should be one of 'f', 'r', 'w', 'h'
112  *
113  *      Return 1 if the user can change the field and 0 otherwise.
114  */
115 static int may_change_field (int field)
116 {
117         const char *cp;
118
119         /*
120          * CHFN_RESTRICT can now specify exactly which fields may be changed
121          * by regular users, by using any combination of the following
122          * letters:
123          *  f - full name
124          *  r - room number
125          *  w - work phone
126          *  h - home phone
127          *
128          * This makes it possible to disallow changing the room number
129          * information, for example - this feature was suggested by Maciej
130          * 'Tycoon' Majchrowski.
131          *
132          * For backward compatibility, "yes" is equivalent to "rwh",
133          * "no" is equivalent to "frwh". Only root can change anything
134          * if the string is empty or not defined at all.
135          */
136         if (amroot) {
137                 return 1;
138         }
139
140         cp = getdef_str ("CHFN_RESTRICT");
141         if (NULL == cp) {
142                 cp = "";
143         } else if (strcmp (cp, "yes") == 0) {
144                 cp = "rwh";
145         } else if (strcmp (cp, "no") == 0) {
146                 cp = "frwh";
147         }
148
149         if (strchr (cp, field) != NULL) {
150                 return 1;
151         }
152
153         return 0;
154 }
155
156 /*
157  * new_fields - change the user's GECOS information interactively
158  *
159  * prompt the user for each of the four fields and fill in the fields from
160  * the user's response, or leave alone if nothing was entered.
161  */
162 static void new_fields (void)
163 {
164         puts (_("Enter the new value, or press ENTER for the default"));
165
166         if (may_change_field ('f')) {
167                 change_field (fullnm, sizeof fullnm, _("Full Name"));
168         } else {
169                 printf (_("\tFull Name: %s\n"), fullnm);
170         }
171
172         if (may_change_field ('r')) {
173                 change_field (roomno, sizeof roomno, _("Room Number"));
174         } else {
175                 printf (_("\tRoom Number: %s\n"), roomno);
176         }
177
178         if (may_change_field ('w')) {
179                 change_field (workph, sizeof workph, _("Work Phone"));
180         } else {
181                 printf (_("\tWork Phone: %s\n"), workph);
182         }
183
184         if (may_change_field ('h')) {
185                 change_field (homeph, sizeof homeph, _("Home Phone"));
186         } else {
187                 printf (_("\tHome Phone: %s\n"), homeph);
188         }
189
190         if (amroot) {
191                 change_field (slop, sizeof slop, _("Other"));
192         }
193 }
194
195 /*
196  * copy_field - get the next field from the gecos field
197  *
198  * copy_field copies the next field from the gecos field, returning a
199  * pointer to the field which follows, or NULL if there are no more fields.
200  *
201  *      in - the current GECOS field
202  *      out - where to copy the field to
203  *      extra - fields with '=' get copied here
204  */
205 static char *copy_field (char *in, char *out, char *extra)
206 {
207         char *cp = NULL;
208
209         while (NULL != in) {
210                 cp = strchr (in, ',');
211                 if (NULL != cp) {
212                         *cp++ = '\0';
213                 }
214
215                 if (strchr (in, '=') == NULL) {
216                         break;
217                 }
218
219                 if (NULL != extra) {
220                         if ('\0' != extra[0]) {
221                                 strcat (extra, ",");
222                         }
223
224                         strcat (extra, in);
225                 }
226                 in = cp;
227         }
228         if ((NULL != in) && (NULL != out)) {
229                 strcpy (out, in);
230         }
231
232         return cp;
233 }
234
235 /*
236  * process_flags - parse the command line options
237  *
238  *      It will not return if an error is encountered.
239  */
240 static void process_flags (int argc, char **argv)
241 {
242         int flag;               /* flag currently being processed    */
243
244         /* 
245          * The remaining arguments will be processed one by one and executed
246          * by this command. The name is the last argument if it does not
247          * begin with a "-", otherwise the name is determined from the
248          * environment and must agree with the real UID. Also, the UID will
249          * be checked for any commands which are restricted to root only.
250          */
251         while ((flag = getopt (argc, argv, "f:r:w:h:o:")) != EOF) {
252                 switch (flag) {
253                 case 'f':
254                         if (!may_change_field ('f')) {
255                                 fprintf (stderr,
256                                          _("%s: Permission denied.\n"), Prog);
257                                 exit (E_NOPERM);
258                         }
259                         fflg++;
260                         STRFCPY (fullnm, optarg);
261                         break;
262                 case 'h':
263                         if (!may_change_field ('h')) {
264                                 fprintf (stderr,
265                                          _("%s: Permission denied.\n"), Prog);
266                                 exit (E_NOPERM);
267                         }
268                         hflg++;
269                         STRFCPY (homeph, optarg);
270                         break;
271                 case 'r':
272                         if (!may_change_field ('r')) {
273                                 fprintf (stderr,
274                                          _("%s: Permission denied.\n"), Prog);
275                                 exit (E_NOPERM);
276                         }
277                         rflg++;
278                         STRFCPY (roomno, optarg);
279                         break;
280                 case 'o':
281                         if (!amroot) {
282                                 fprintf (stderr,
283                                          _("%s: Permission denied.\n"), Prog);
284                                 exit (E_NOPERM);
285                         }
286                         oflg++;
287                         STRFCPY (slop, optarg);
288                         break;
289                 case 'w':
290                         if (!may_change_field ('w')) {
291                                 fprintf (stderr,
292                                          _("%s: Permission denied.\n"), Prog);
293                                 exit (E_NOPERM);
294                         }
295                         wflg++;
296                         STRFCPY (workph, optarg);
297                         break;
298                 default:
299                         usage ();
300                 }
301         }
302 }
303
304 /*
305  * check_perms - check if the caller is allowed to add a group
306  *
307  *      Non-root users are only allowed to change their gecos field.
308  *      (see also may_change_field())
309  *
310  *      Non-root users must be authenticated.
311  *
312  *      It will not return if the user is not allowed.
313  */
314 static void check_perms (const struct passwd *pw)
315 {
316 #ifdef USE_PAM
317         int retval;
318         struct passwd *pampw;
319 #endif
320
321         /*
322          * Non-privileged users are only allowed to change the gecos field
323          * if the UID of the user matches the current real UID.
324          */
325         if (!amroot && pw->pw_uid != getuid ()) {
326                 fprintf (stderr, _("%s: Permission denied.\n"), Prog);
327                 closelog ();
328                 exit (E_NOPERM);
329         }
330 #ifdef WITH_SELINUX
331         /*
332          * If the UID of the user does not match the current real UID,
333          * check if the change is allowed by SELinux policy.
334          */
335         if ((pw->pw_uid != getuid ())
336             && (is_selinux_enabled () > 0)
337             && (selinux_check_passwd_access (PASSWD__CHFN) != 0)) {
338                 fprintf (stderr, _("%s: Permission denied.\n"), Prog);
339                 closelog ();
340                 exit (E_NOPERM);
341         }
342 #endif
343
344 #ifndef USE_PAM
345         /*
346          * Non-privileged users are optionally authenticated (must enter the
347          * password of the user whose information is being changed) before
348          * any changes can be made. Idea from util-linux chfn/chsh. 
349          * --marekm
350          */
351         if (!amroot && getdef_bool ("CHFN_AUTH")) {
352                 passwd_check (pw->pw_name, pw->pw_passwd, "chfn");
353         }
354
355 #else                           /* !USE_PAM */
356         retval = PAM_SUCCESS;
357
358         pampw = getpwuid (getuid ()); /* local, no need for xgetpwuid */
359         if (pampw == NULL) {
360                 retval = PAM_USER_UNKNOWN;
361         }
362
363         if (retval == PAM_SUCCESS) {
364                 retval = pam_start ("chfn", pampw->pw_name, &conv, &pamh);
365         }
366
367         if (retval == PAM_SUCCESS) {
368                 retval = pam_authenticate (pamh, 0);
369                 if (retval != PAM_SUCCESS) {
370                         pam_end (pamh, retval);
371                 }
372         }
373
374         if (retval == PAM_SUCCESS) {
375                 retval = pam_acct_mgmt (pamh, 0);
376                 if (retval != PAM_SUCCESS) {
377                         pam_end (pamh, retval);
378                 }
379         }
380
381         if (retval != PAM_SUCCESS) {
382                 fprintf (stderr, _("%s: PAM authentication failed\n"), Prog);
383                 exit (E_NOPERM);
384         }
385 #endif                          /* USE_PAM */
386 }
387
388 /*
389  * update_gecos - update the gecos fields in the password database
390  *
391  *      Commit the user's entry after changing her gecos field.
392  */
393 static void update_gecos (const char *user, char *gecos)
394 {
395         const struct passwd *pw;        /* The user's password file entry */
396         struct passwd pwent;            /* modified password file entry */
397
398         /*
399          * Before going any further, raise the ulimit to prevent colliding
400          * into a lowered ulimit, and set the real UID to root to protect
401          * against unexpected signals. Any keyboard signals are set to be
402          * ignored.
403          */
404         if (setuid (0) != 0) {
405                 fputs (_("Cannot change ID to root.\n"), stderr);
406                 SYSLOG ((LOG_ERR, "can't setuid(0)"));
407                 closelog ();
408                 exit (E_NOPERM);
409         }
410         pwd_init ();
411
412         /*
413          * The passwd entry is now ready to be committed back to the
414          * password file. Get a lock on the file and open it.
415          */
416         if (pw_lock () == 0) {
417                 fputs (_("Cannot lock the password file; try again later.\n"),
418                        stderr);
419                 SYSLOG ((LOG_WARN, "can't lock /etc/passwd"));
420                 closelog ();
421                 exit (E_NOPERM);
422         }
423         if (pw_open (O_RDWR) == 0) {
424                 fputs (_("Cannot open the password file.\n"), stderr);
425                 pw_unlock ();
426                 SYSLOG ((LOG_ERR, "can't open /etc/passwd"));
427                 closelog ();
428                 exit (E_NOPERM);
429         }
430
431         /*
432          * Get the entry to update using pw_locate() - we want the real one
433          * from /etc/passwd, not the one from getpwnam() which could contain
434          * the shadow password if (despite the warnings) someone enables
435          * AUTOSHADOW (or SHADOW_COMPAT in libc).  --marekm
436          */
437         pw = pw_locate (user);
438         if (NULL == pw) {
439                 pw_unlock ();
440                 fprintf (stderr,
441                          _("%s: %s not found in /etc/passwd\n"), Prog, user);
442                 exit (E_NOPERM);
443         }
444
445         /*
446          * Make a copy of the entry, then change the gecos field. The other
447          * fields remain unchanged.
448          */
449         pwent = *pw;
450         pwent.pw_gecos = gecos;
451
452         /*
453          * Update the passwd file entry. If there is a DBM file, update that
454          * entry as well.
455          */
456         if (pw_update (&pwent) == 0) {
457                 fputs (_("Error updating the password entry.\n"), stderr);
458                 pw_unlock ();
459                 SYSLOG ((LOG_ERR, "error updating passwd entry"));
460                 closelog ();
461                 exit (E_NOPERM);
462         }
463
464         /*
465          * Changes have all been made, so commit them and unlock the file.
466          */
467         if (pw_close () == 0) {
468                 fputs (_("Cannot commit password file changes.\n"), stderr);
469                 pw_unlock ();
470                 SYSLOG ((LOG_ERR, "can't rewrite /etc/passwd"));
471                 closelog ();
472                 exit (E_NOPERM);
473         }
474         if (pw_unlock () == 0) {
475                 fputs (_("Cannot unlock the password file.\n"), stderr);
476                 SYSLOG ((LOG_ERR, "can't unlock /etc/passwd"));
477                 closelog ();
478                 exit (E_NOPERM);
479         }
480 }
481
482 /*
483  * get_old_fields - parse the old gecos and use the old value for the fields
484  *                  which are not set on the command line
485  */
486 static void get_old_fields (const char *gecos)
487 {
488         char *cp;               /* temporary character pointer       */
489         char old_gecos[BUFSIZ]; /* buffer for old GECOS fields       */
490         STRFCPY (old_gecos, gecos);
491
492         /*
493          * Now get the full name. It is the first comma separated field in
494          * the GECOS field.
495          */
496         cp = copy_field (old_gecos, fflg ? (char *) 0 : fullnm, slop);
497
498         /*
499          * Now get the room number. It is the next comma separated field,
500          * if there is indeed one.
501          */
502         if (NULL != cp) {
503                 cp = copy_field (cp, rflg ? (char *) 0 : roomno, slop);
504         }
505
506         /*
507          * Now get the work phone number. It is the third field.
508          */
509         if (NULL != cp) {
510                 cp = copy_field (cp, wflg ? (char *) 0 : workph, slop);
511         }
512
513         /*
514          * Now get the home phone number. It is the fourth field.
515          */
516         if (NULL != cp) {
517                 cp = copy_field (cp, hflg ? (char *) 0 : homeph, slop);
518         }
519
520         /*
521          * Anything left over is "slop".
522          */
523         if ((NULL != cp) && !oflg) {
524                 if ('\0' != slop[0]) {
525                         strcat (slop, ",");
526                 }
527
528                 strcat (slop, cp);
529         }
530 }
531
532 /*
533  * check_fields - check all of the fields for valid information
534  *
535  *      It will not return if a field is not valid.
536  */
537 static void check_fields (void)
538 {
539         int err;
540         err = valid_field (fullnm, ":,=");
541         if (err > 0) {
542                 fprintf (stderr, _("%s: name with non-ASCII characters: '%s'\n"), Prog, fullnm);
543         } else if (err < 0) {
544                 fprintf (stderr, _("%s: invalid name: '%s'\n"), Prog, fullnm);
545                 closelog ();
546                 exit (E_NOPERM);
547         }
548         err = valid_field (roomno, ":,=");
549         if (err > 0) {
550                 fprintf (stderr, _("%s: room number with non-ASCII characters: '%s'\n"), Prog, roomno);
551         } else if (err < 0) {
552                 fprintf (stderr, _("%s: invalid room number: '%s'\n"),
553                          Prog, roomno);
554                 closelog ();
555                 exit (E_NOPERM);
556         }
557         if (valid_field (workph, ":,=")) {
558                 fprintf (stderr, _("%s: invalid work phone: '%s'\n"),
559                          Prog, workph);
560                 closelog ();
561                 exit (E_NOPERM);
562         }
563         if (valid_field (homeph, ":,=")) {
564                 fprintf (stderr, _("%s: invalid home phone: '%s'\n"),
565                          Prog, homeph);
566                 closelog ();
567                 exit (E_NOPERM);
568         }
569         err = valid_field (slop, ":");
570         if (err > 0) {
571                 fprintf (stderr, _("%s: '%s' contains non-ASCII characters\n"), Prog, slop);
572         } else if (err < 0) {
573                 fprintf (stderr,
574                          _("%s: '%s' contains illegal characters\n"),
575                          Prog, slop);
576                 closelog ();
577                 exit (E_NOPERM);
578         }
579 }
580
581 /*
582  * chfn - change a user's password file information
583  *
584  *      This command controls the GECOS field information in the password
585  *      file entry.
586  *
587  *      The valid options are
588  *
589  *      -f      full name
590  *      -r      room number
591  *      -w      work phone number
592  *      -h      home phone number
593  *      -o      other information (*)
594  *
595  *      (*) requires root permission to execute.
596  */
597 int main (int argc, char **argv)
598 {
599         const struct passwd *pw;        /* password file entry               */
600         char new_gecos[BUFSIZ]; /* buffer for new GECOS fields       */
601         char *user;
602
603         sanitize_env ();
604         setlocale (LC_ALL, "");
605         bindtextdomain (PACKAGE, LOCALEDIR);
606         textdomain (PACKAGE);
607
608         /*
609          * This command behaves different for root and non-root
610          * users.
611          */
612         amroot = (getuid () == 0);
613
614         /*
615          * Get the program name. The program name is used as a
616          * prefix to most error messages.
617          */
618         Prog = Basename (argv[0]);
619
620         OPENLOG ("chfn");
621
622         /* parse the command line options */
623         process_flags (argc, argv);
624
625         /*
626          * Get the name of the user to check. It is either the command line
627          * name, or the name getlogin() returns.
628          */
629         if (optind < argc) {
630                 user = argv[optind];
631                 pw = xgetpwnam (user);
632                 if (NULL == pw) {
633                         fprintf (stderr, _("%s: unknown user %s\n"), Prog,
634                                  user);
635                         exit (E_NOPERM);
636                 }
637         } else {
638                 pw = get_my_pwent ();
639                 if (NULL == pw) {
640                         fprintf (stderr,
641                                  _
642                                  ("%s: Cannot determine your user name.\n"),
643                                  Prog);
644                         exit (E_NOPERM);
645                 }
646                 user = xstrdup (pw->pw_name);
647         }
648
649 #ifdef  USE_NIS
650         /*
651          * Now we make sure this is a LOCAL password entry for this user ...
652          */
653         if (__ispwNIS ()) {
654                 char *nis_domain;
655                 char *nis_master;
656
657                 fprintf (stderr,
658                          _("%s: cannot change user '%s' on NIS client.\n"),
659                          Prog, user);
660
661                 if (!yp_get_default_domain (&nis_domain) &&
662                     !yp_master (nis_domain, "passwd.byname", &nis_master)) {
663                         fprintf (stderr,
664                                  _
665                                  ("%s: '%s' is the NIS master for this client.\n"),
666                                  Prog, nis_master);
667                 }
668                 exit (E_NOPERM);
669         }
670 #endif
671
672         /* Check that the caller is allowed to change the gecos of the
673          * specified user */
674         check_perms (pw);
675
676         /* If some fields were not set on the command line, load the value from
677          * the old gecos fields. */
678         get_old_fields (pw->pw_gecos);
679
680         /*
681          * If none of the fields were changed from the command line, let the
682          * user interactively change them.
683          */
684         if (!fflg && !rflg && !wflg && !hflg && !oflg) {
685                 printf (_("Changing the user information for %s\n"), user);
686                 new_fields ();
687         }
688
689         /*
690          * Check all of the fields for valid information
691          */
692         check_fields ();
693
694         /*
695          * Build the new GECOS field by plastering all the pieces together,
696          * if they will fit ...
697          */
698         if ((strlen (fullnm) + strlen (roomno) + strlen (workph) +
699              strlen (homeph) + strlen (slop)) > (unsigned int) 80) {
700                 fprintf (stderr, _("%s: fields too long\n"), Prog);
701                 closelog ();
702                 exit (E_NOPERM);
703         }
704         snprintf (new_gecos, sizeof new_gecos, "%s,%s,%s,%s%s%s",
705                   fullnm, roomno, workph, homeph, slop[0] ? "," : "", slop);
706
707         /* Rewrite the user's gecos in the passwd file */
708         update_gecos (user, new_gecos);
709
710         SYSLOG ((LOG_INFO, "changed user `%s' information", user));
711
712         nscd_flush_cache ("passwd");
713
714 #ifdef USE_PAM
715         pam_end (pamh, PAM_SUCCESS);
716 #endif                          /* USE_PAM */
717
718         closelog ();
719         exit (E_SUCCESS);
720 }
721