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