usage.c: remove reference to busybox.h
[platform/upstream/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 "libbb.h"
7 #include <syslog.h>
8
9
10 static void nuke_str(char *str)
11 {
12         if (str) memset(str, 0, strlen(str));
13 }
14
15 static char* new_password(const struct passwd *pw, uid_t myuid, int algo)
16 {
17         char salt[sizeof("$N$XXXXXXXX")]; /* "$N$XXXXXXXX" or "XX" */
18         char *orig = (char*)"";
19         char *newp = NULL;
20         char *cipher = NULL;
21         char *cp = NULL;
22         char *ret = NULL; /* failure so far */
23
24         if (myuid && pw->pw_passwd[0]) {
25                 orig = bb_askpass(0, "Old password:"); /* returns ptr to static */
26                 if (!orig)
27                         goto err_ret;
28                 cipher = pw_encrypt(orig, pw->pw_passwd); /* returns ptr to static */
29                 if (strcmp(cipher, pw->pw_passwd) != 0) {
30                         syslog(LOG_WARNING, "incorrect password for '%s'",
31                                 pw->pw_name);
32                         bb_do_delay(FAIL_DELAY);
33                         puts("Incorrect password");
34                         goto err_ret;
35                 }
36         }
37         orig = xstrdup(orig); /* or else bb_askpass() will destroy it */
38         newp = bb_askpass(0, "New password:"); /* returns ptr to static */
39         if (!newp)
40                 goto err_ret;
41         newp = xstrdup(newp); /* we are going to bb_askpass() again, so save it */
42         if (ENABLE_FEATURE_PASSWD_WEAK_CHECK
43          && obscure(orig, newp, pw) && myuid)
44                 goto err_ret; /* non-root is not allowed to have weak passwd */
45
46         cp = bb_askpass(0, "Retype password:");
47         if (!cp)
48                 goto err_ret;
49         if (strcmp(cp, newp)) {
50                 puts("Passwords don't match");
51                 goto err_ret;
52         }
53
54         /*memset(salt, 0, sizeof(salt)); - why?*/
55         crypt_make_salt(salt, 1); /* des */
56         if (algo) { /* MD5 */
57                 strcpy(salt, "$1$");
58                 crypt_make_salt(salt + 3, 4);
59         }
60         ret = xstrdup(pw_encrypt(newp, salt)); /* returns ptr to static */
61         /* whee, success! */
62
63  err_ret:
64         nuke_str(orig);
65         if (ENABLE_FEATURE_CLEAN_UP) free(orig);
66         nuke_str(newp);
67         if (ENABLE_FEATURE_CLEAN_UP) free(newp);
68         nuke_str(cipher);
69         nuke_str(cp);
70         return ret;
71 }
72
73
74 static int update_passwd(const char *filename, const char *username,
75                         const char *new_pw)
76 {
77         struct stat sb;
78         struct flock lock;
79         FILE *old_fp;
80         FILE *new_fp;
81         char *new_name;
82         char *last_char;
83         unsigned user_len;
84         int old_fd;
85         int new_fd;
86         int i;
87         int ret = 1; /* failure */
88
89         logmode = LOGMODE_STDIO;
90         /* New passwd file, "/etc/passwd+" for now */
91         new_name = xasprintf("%s+", filename);
92         last_char = &new_name[strlen(new_name)-1];
93         username = xasprintf("%s:", username);
94         user_len = strlen(username);
95
96         old_fp = fopen(filename, "r+");
97         if (!old_fp)
98                 goto free_mem;
99         old_fd = fileno(old_fp);
100
101         /* Try to create "/etc/passwd+". Wait if it exists. */
102         i = 30;
103         do {
104                 // FIXME: on last iteration try w/o O_EXCL but with O_TRUNC?
105                 new_fd = open(new_name, O_WRONLY|O_CREAT|O_EXCL,0600);
106                 if (new_fd >= 0) goto created;
107                 if (errno != EEXIST) break;
108                 usleep(100000); /* 0.1 sec */
109         } while (--i);
110         bb_perror_msg("cannot create '%s'", new_name);
111         goto close_old_fp;
112  created:
113         if (!fstat(old_fd, &sb)) {
114                 fchmod(new_fd, sb.st_mode & 0777); /* ignore errors */
115                 fchown(new_fd, sb.st_uid, sb.st_gid);
116         }
117         new_fp = fdopen(new_fd, "w");
118         if (!new_fp) {
119                 close(new_fd);
120                 goto unlink_new;
121         }
122
123         /* Backup file is "/etc/passwd-" */
124         last_char[0] = '-';
125         /* Delete old one, create new as a hardlink to current */
126         i = (unlink(new_name) && errno != ENOENT);
127         if (i || link(filename, new_name))
128                 bb_perror_msg("warning: cannot create backup copy '%s'", new_name);
129         last_char[0] = '+';
130
131         /* Lock the password file before updating */
132         lock.l_type = F_WRLCK;
133         lock.l_whence = SEEK_SET;
134         lock.l_start = 0;
135         lock.l_len = 0;
136         if (fcntl(old_fd, F_SETLK, &lock) < 0)
137                 bb_perror_msg("warning: cannot lock '%s'", filename);
138         lock.l_type = F_UNLCK;
139
140         /* Read current password file, write updated one */
141         while (1) {
142                 char *line = xmalloc_fgets(old_fp);
143                 if (!line) break; /* EOF/error */
144                 if (strncmp(username, line, user_len) == 0) {
145                         /* we have a match with "username:"... */
146                         const char *cp = line + user_len;
147                         /* now cp -> old passwd, skip it: */
148                         cp = strchr(cp, ':');
149                         if (!cp) cp = "";
150                         /* now cp -> ':' after old passwd or -> "" */
151                         fprintf(new_fp, "%s%s%s", username, new_pw, cp);
152                         /* Erase password in memory */
153                 } else
154                         fputs(line, new_fp);
155                 free(line);
156         }
157         fcntl(old_fd, F_SETLK, &lock);
158
159         /* We do want all of them to execute, thus | instead of || */
160         if ((ferror(old_fp) | fflush(new_fp) | fsync(new_fd) | fclose(new_fp))
161          || rename(new_name, filename)
162         ) {
163                 /* At least one of those failed */
164                 goto unlink_new;
165         }
166         ret = 0; /* whee, success! */
167
168  unlink_new:
169         if (ret) unlink(new_name);
170
171  close_old_fp:
172         fclose(old_fp);
173
174  free_mem:
175         if (ENABLE_FEATURE_CLEAN_UP) free(new_name);
176         if (ENABLE_FEATURE_CLEAN_UP) free((char*)username);
177         logmode = LOGMODE_BOTH;
178         return ret;
179 }
180
181
182 int passwd_main(int argc, char **argv);
183 int passwd_main(int argc, char **argv)
184 {
185         enum {
186                 OPT_algo = 0x1, /* -a - password algorithm */
187                 OPT_lock = 0x2, /* -l - lock account */
188                 OPT_unlock = 0x4, /* -u - unlock account */
189                 OPT_delete = 0x8, /* -d - delete password */
190                 OPT_lud = 0xe,
191                 STATE_ALGO_md5 = 0x10,
192                 /*STATE_ALGO_des = 0x20, not needed yet */
193         };
194         unsigned opt;
195         const char *opt_a = "";
196         const char *filename;
197         char *myname;
198         char *name;
199         char *newp;
200         struct passwd *pw;
201         uid_t myuid;
202         struct rlimit rlimit_fsize;
203         char c;
204
205 #if ENABLE_FEATURE_SHADOWPASSWDS
206         /* Using _r function to avoid pulling in static buffers */
207         struct spwd spw;
208         struct spwd *result;
209         char buffer[256];
210 #endif
211
212         logmode = LOGMODE_BOTH;
213         openlog(applet_name, LOG_NOWAIT, LOG_AUTH);
214         opt = getopt32(argc, argv, "a:lud", &opt_a);
215         argc -= optind;
216         argv += optind;
217
218         if (strcasecmp(opt_a, "des") != 0) /* -a */
219                 opt |= STATE_ALGO_md5;
220         //else
221         //      opt |= STATE_ALGO_des;
222         myuid = getuid();
223         if ((opt & OPT_lud) && (!argc || myuid))
224                 bb_show_usage();
225
226         myname = xstrdup(bb_getpwuid(NULL, myuid, -1));
227         name = argc ? argv[0] : myname;
228
229         pw = getpwnam(name);
230         if (!pw) bb_error_msg_and_die("unknown user %s", name);
231         if (myuid && pw->pw_uid != myuid) {
232                 /* LOGMODE_BOTH */
233                 bb_error_msg_and_die("%s can't change password for %s", myname, name);
234         }
235
236         filename = bb_path_passwd_file;
237 #if ENABLE_FEATURE_SHADOWPASSWDS
238         if (getspnam_r(pw->pw_name, &spw, buffer, sizeof(buffer), &result)) {
239                 /* LOGMODE_BOTH */
240                 bb_error_msg("no record of %s in %s, using %s",
241                                 name, bb_path_shadow_file,
242                                 bb_path_passwd_file);
243         } else {
244                 filename = bb_path_shadow_file;
245                 pw->pw_passwd = spw.sp_pwdp;
246         }
247 #endif
248
249         /* Decide what the new password will be */
250         newp = NULL;
251         c = pw->pw_passwd[0] - '!';
252         if (!(opt & OPT_lud)) {
253                 if (myuid && !c) { /* passwd starts with '!' */
254                         /* LOGMODE_BOTH */
255                         bb_error_msg_and_die("cannot change "
256                                         "locked password for %s", name);
257                 }
258                 printf("Changing password for %s\n", name);
259                 newp = new_password(pw, myuid, opt & STATE_ALGO_md5);
260                 if (!newp) {
261                         logmode = LOGMODE_STDIO;
262                         bb_error_msg_and_die("password for %s is unchanged", name);
263                 }
264         } else if (opt & OPT_lock) {
265                 if (!c) goto skip; /* passwd starts with '!' */
266                 newp = xasprintf("!%s", pw->pw_passwd);
267         } else if (opt & OPT_unlock) {
268                 if (c) goto skip; /* not '!' */
269                 newp = xstrdup(&pw->pw_passwd[1]);
270         } else if (opt & OPT_delete) {
271                 newp = xstrdup("");
272         }
273
274         rlimit_fsize.rlim_cur = rlimit_fsize.rlim_max = 512L * 30000;
275         setrlimit(RLIMIT_FSIZE, &rlimit_fsize);
276         signal(SIGHUP, SIG_IGN);
277         signal(SIGINT, SIG_IGN);
278         signal(SIGQUIT, SIG_IGN);
279         umask(077);
280         xsetuid(0);
281         if (update_passwd(filename, name, newp) != 0) {
282                 /* LOGMODE_BOTH */
283                 bb_error_msg_and_die("cannot update password file %s",
284                                 filename);
285         }
286         /* LOGMODE_BOTH */
287         bb_info_msg("Password for %s changed by %s", name, myname);
288
289         if (ENABLE_FEATURE_CLEAN_UP) free(newp);
290 skip:
291         if (!newp) {
292                 bb_error_msg_and_die("password for %s is already %slocked",
293                         name, (opt & OPT_unlock) ? "un" : "");
294         }
295         if (ENABLE_FEATURE_CLEAN_UP) free(myname);
296         return 0;
297 }