Add one-line GPL boilerplate to numerous (but not all yet) source files.
[oweals/busybox.git] / loginutils / passwd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
4  */
5
6 #include <fcntl.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <signal.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include <utime.h>
14 #include <syslog.h>
15 #include <time.h>
16 #include <sys/resource.h>
17 #include <errno.h>
18
19 #include "busybox.h"
20
21 static char crypt_passwd[128];
22
23 static int create_backup(const char *backup, FILE * fp);
24 static int new_password(const struct passwd *pw, int amroot, int algo);
25 static void set_filesize_limit(int blocks);
26
27
28 static int get_algo(char *a)
29 {
30         int x = 1;                                      /* standard: MD5 */
31
32         if (strcasecmp(a, "des") == 0)
33                 x = 0;
34         return x;
35 }
36
37
38 static int update_passwd(const struct passwd *pw, const char *crypt_pw)
39 {
40         char filename[1024];
41         char buf[1025];
42         char buffer[80];
43         char username[32];
44         char *pw_rest;
45         int mask;
46         int continued;
47         FILE *fp;
48         FILE *out_fp;
49         struct stat sb;
50         struct flock lock;
51
52 #if ENABLE_FEATURE_SHADOWPASSWDS
53         if (access(bb_path_shadow_file, F_OK) == 0) {
54                 snprintf(filename, sizeof filename, "%s", bb_path_shadow_file);
55         } else
56 #endif
57         {
58                 snprintf(filename, sizeof filename, "%s", bb_path_passwd_file);
59         }
60
61         if (((fp = fopen(filename, "r+")) == 0) || (fstat(fileno(fp), &sb))) {
62                 /* return 0; */
63                 return 1;
64         }
65
66         /* Lock the password file before updating */
67         lock.l_type = F_WRLCK;
68         lock.l_whence = SEEK_SET;
69         lock.l_start = 0;
70         lock.l_len = 0;
71         if (fcntl(fileno(fp), F_SETLK, &lock) < 0) {
72                 fprintf(stderr, "%s: %s\n", filename, strerror(errno));
73                 return 1;
74         }
75         lock.l_type = F_UNLCK;
76
77         snprintf(buf, sizeof buf, "%s-", filename);
78         if (create_backup(buf, fp)) {
79                 fcntl(fileno(fp), F_SETLK, &lock);
80                 fclose(fp);
81                 return 1;
82         }
83         snprintf(buf, sizeof buf, "%s+", filename);
84         mask = umask(0777);
85         out_fp = fopen(buf, "w");
86         umask(mask);
87         if ((!out_fp) || (fchmod(fileno(out_fp), sb.st_mode & 0777))
88                 || (fchown(fileno(out_fp), sb.st_uid, sb.st_gid))) {
89                 fcntl(fileno(fp), F_SETLK, &lock);
90                 fclose(fp);
91                 fclose(out_fp);
92                 return 1;
93         }
94
95         continued = 0;
96         snprintf(username, sizeof username, "%s:", pw->pw_name);
97         rewind(fp);
98         while (!feof(fp)) {
99                 fgets(buffer, sizeof buffer, fp);
100                 if (!continued) { /* Check to see if we're updating this line.  */
101                         if (strncmp(username, buffer, strlen(username)) == 0) {
102                                 /* we have a match. */
103                                 pw_rest = strchr(buffer, ':');
104                                 *pw_rest++ = '\0';
105                                 pw_rest = strchr(pw_rest, ':');
106                                 fprintf(out_fp, "%s:%s%s", buffer, crypt_pw, pw_rest);
107                         } else {
108                                 fputs(buffer, out_fp);
109                         }
110                 } else {
111                         fputs(buffer, out_fp);
112                 }
113                 if (buffer[strlen(buffer) - 1] == '\n') {
114                         continued = 0;
115                 } else {
116                         continued = 1;
117                 }
118                 memset(buffer, 0, sizeof buffer);
119         }
120
121         if (fflush(out_fp) || fsync(fileno(out_fp)) || fclose(out_fp)) {
122                 unlink(buf);
123                 fcntl(fileno(fp), F_SETLK, &lock);
124                 fclose(fp);
125                 return 1;
126         }
127         if (rename(buf, filename) < 0) {
128                 fcntl(fileno(fp), F_SETLK, &lock);
129                 fclose(fp);
130                 return 1;
131         } else {
132                 fcntl(fileno(fp), F_SETLK, &lock);
133                 fclose(fp);
134                 return 0;
135         }
136 }
137
138
139 int passwd_main(int argc, char **argv)
140 {
141         int amroot;
142         char *cp;
143         char *np;
144         char *name;
145         char *myname;
146         int flag;
147         int algo = 1;                           /* -a - password algorithm */
148         int lflg = 0;                           /* -l - lock account */
149         int uflg = 0;                           /* -u - unlock account */
150         int dflg = 0;                           /* -d - delete password */
151         const struct passwd *pw;
152
153         amroot = (getuid() == 0);
154         openlog("passwd", LOG_PID | LOG_CONS | LOG_NOWAIT, LOG_AUTH);
155         while ((flag = getopt(argc, argv, "a:dlu")) != EOF) {
156                 switch (flag) {
157                 case 'a':
158                         algo = get_algo(optarg);
159                         break;
160                 case 'd':
161                         dflg++;
162                         break;
163                 case 'l':
164                         lflg++;
165                         break;
166                 case 'u':
167                         uflg++;
168                         break;
169                 default:
170                         bb_show_usage();
171                 }
172         }
173         myname = (char *) bb_xstrdup(bb_getpwuid(NULL, getuid(), -1));
174         /* exits on error */
175         if (optind < argc) {
176                 name = argv[optind];
177         } else {
178                 name = myname;
179         }
180         if ((lflg || uflg || dflg) && (optind >= argc || !amroot)) {
181                 bb_show_usage();
182         }
183         pw = getpwnam(name);
184         if (!pw) {
185                 bb_error_msg_and_die("Unknown user %s\n", name);
186         }
187         if (!amroot && pw->pw_uid != getuid()) {
188                 syslog(LOG_WARNING, "can't change pwd for `%s'", name);
189                 bb_error_msg_and_die("Permission denied.\n");
190         }
191         if (ENABLE_FEATURE_SHADOWPASSWDS) {
192                 struct spwd *sp = getspnam(name);
193                 if (!sp) bb_error_msg_and_die("Unknown user %s", name);
194                 cp = sp->sp_pwdp;
195         } else cp = pw->pw_passwd;
196
197         np = name;
198         safe_strncpy(crypt_passwd, cp, sizeof(crypt_passwd));
199         if (!(dflg || lflg || uflg)) {
200                 if (!amroot) {
201                         if (cp[0] == '!') {
202                                 syslog(LOG_WARNING, "password locked for `%s'", np);
203                                 bb_error_msg_and_die( "The password for `%s' cannot be changed.\n", np);
204                         }
205                 }
206                 printf("Changing password for %s\n", name);
207                 if (new_password(pw, amroot, algo)) {
208                         bb_error_msg_and_die( "The password for %s is unchanged.\n", name);
209                 }
210         } else if (lflg) {
211                 if (crypt_passwd[0] != '!') {
212                         memmove(&crypt_passwd[1], crypt_passwd,
213                                         sizeof crypt_passwd - 1);
214                         crypt_passwd[sizeof crypt_passwd - 1] = '\0';
215                         crypt_passwd[0] = '!';
216                 }
217         } else if (uflg) {
218                 if (crypt_passwd[0] == '!') {
219                         memmove(crypt_passwd, &crypt_passwd[1],
220                                         sizeof crypt_passwd - 1);
221                 }
222         } else if (dflg) {
223                 crypt_passwd[0] = '\0';
224         }
225         set_filesize_limit(30000);
226         signal(SIGHUP, SIG_IGN);
227         signal(SIGINT, SIG_IGN);
228         signal(SIGQUIT, SIG_IGN);
229         umask(077);
230         if (setuid(0)) {
231                 syslog(LOG_ERR, "can't setuid(0)");
232                 bb_error_msg_and_die( "Cannot change ID to root.\n");
233         }
234         if (!update_passwd(pw, crypt_passwd)) {
235                 syslog(LOG_INFO, "password for `%s' changed by user `%s'", name,
236                            myname);
237                 printf("Password changed.\n");
238         } else {
239                 syslog(LOG_WARNING, "an error occurred updating the password file");
240                 bb_error_msg_and_die("An error occurred updating the password file.\n");
241         }
242         if (ENABLE_FEATURE_CLEAN_UP) free(myname);
243         return (0);
244 }
245
246
247
248 static int create_backup(const char *backup, FILE * fp)
249 {
250         struct stat sb;
251         struct utimbuf ub;
252         FILE *bkfp;
253         int c, mask;
254
255         if (fstat(fileno(fp), &sb))
256                 /* return -1; */
257                 return 1;
258
259         mask = umask(077);
260         bkfp = fopen(backup, "w");
261         umask(mask);
262         if (!bkfp)
263                 /* return -1; */
264                 return 1;
265
266         /* TODO: faster copy, not one-char-at-a-time.  --marekm */
267         rewind(fp);
268         while ((c = getc(fp)) != EOF) {
269                 if (putc(c, bkfp) == EOF)
270                         break;
271         }
272         if (c != EOF || fflush(bkfp)) {
273                 fclose(bkfp);
274                 /* return -1; */
275                 return 1;
276         }
277         if (fclose(bkfp))
278                 /* return -1; */
279                 return 1;
280
281         ub.actime = sb.st_atime;
282         ub.modtime = sb.st_mtime;
283         utime(backup, &ub);
284         return 0;
285 }
286
287 static int i64c(int i)
288 {
289         if (i <= 0)
290                 return ('.');
291         if (i == 1)
292                 return ('/');
293         if (i >= 2 && i < 12)
294                 return ('0' - 2 + i);
295         if (i >= 12 && i < 38)
296                 return ('A' - 12 + i);
297         if (i >= 38 && i < 63)
298                 return ('a' - 38 + i);
299         return ('z');
300 }
301
302 static char *crypt_make_salt(void)
303 {
304         time_t now;
305         static unsigned long x;
306         static char result[3];
307
308         time(&now);
309         x += now + getpid() + clock();
310         result[0] = i64c(((x >> 18) ^ (x >> 6)) & 077);
311         result[1] = i64c(((x >> 12) ^ x) & 077);
312         result[2] = '\0';
313         return result;
314 }
315
316
317 static int new_password(const struct passwd *pw, int amroot, int algo)
318 {
319         char *clear;
320         char *cipher;
321         char *cp;
322         char salt[12]; /* "$N$XXXXXXXX" or "XX" */
323         char orig[200];
324         char pass[200];
325
326         if (!amroot && crypt_passwd[0]) {
327                 if (!(clear = bb_askpass(0, "Old password:"))) {
328                         /* return -1; */
329                         return 1;
330                 }
331                 cipher = pw_encrypt(clear, crypt_passwd);
332                 if (strcmp(cipher, crypt_passwd) != 0) {
333                         syslog(LOG_WARNING, "incorrect password for `%s'",
334                                    pw->pw_name);
335                         bb_do_delay(FAIL_DELAY);
336                         fprintf(stderr, "Incorrect password.\n");
337                         /* return -1; */
338                         return 1;
339                 }
340                 safe_strncpy(orig, clear, sizeof(orig));
341                 memset(clear, 0, strlen(clear));
342                 memset(cipher, 0, strlen(cipher));
343         } else {
344                 orig[0] = '\0';
345         }
346         if (! (cp=bb_askpass(0, "Enter the new password (minimum of 5, maximum of 8 characters)\n"
347                                           "Please use a combination of upper and lower case letters and numbers.\n"
348                                           "Enter new password: ")))
349         {
350                 memset(orig, 0, sizeof orig);
351                 /* return -1; */
352                 return 1;
353         }
354         safe_strncpy(pass, cp, sizeof(pass));
355         memset(cp, 0, strlen(cp));
356         /* if (!obscure(orig, pass, pw)) { */
357         if (obscure(orig, pass, pw)) {
358                 if (amroot) {
359                         printf("\nWarning: weak password (continuing).\n");
360                 } else {
361                         /* return -1; */
362                         return 1;
363                 }
364         }
365         if (!(cp = bb_askpass(0, "Re-enter new password: "))) {
366                 memset(orig, 0, sizeof orig);
367                 /* return -1; */
368                 return 1;
369         }
370         if (strcmp(cp, pass)) {
371                 fprintf(stderr, "Passwords do not match.\n");
372                 /* return -1; */
373                 return 1;
374         }
375         memset(cp, 0, strlen(cp));
376         memset(orig, 0, sizeof(orig));
377         memset(salt, 0, sizeof(salt));
378
379         if (algo == 1) {
380                 strcpy(salt, "$1$");
381                 strcat(salt, crypt_make_salt());
382                 strcat(salt, crypt_make_salt());
383                 strcat(salt, crypt_make_salt());
384         }
385
386         strcat(salt, crypt_make_salt());
387         cp = pw_encrypt(pass, salt);
388
389         memset(pass, 0, sizeof pass);
390         safe_strncpy(crypt_passwd, cp, sizeof(crypt_passwd));
391         return 0;
392 }
393
394 static void set_filesize_limit(int blocks)
395 {
396         struct rlimit rlimit_fsize;
397
398         rlimit_fsize.rlim_cur = rlimit_fsize.rlim_max = 512L * blocks;
399         setrlimit(RLIMIT_FSIZE, &rlimit_fsize);
400 }