]> granicus.if.org Git - apache/blob - support/htpasswd.c
Use APR_WANT_STRFUNC and apr_want.h instead
[apache] / support / htpasswd.c
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2  * contributor license agreements.  See the NOTICE file distributed with
3  * this work for additional information regarding copyright ownership.
4  * The ASF licenses this file to You under the Apache License, Version 2.0
5  * (the "License"); you may not use this file except in compliance with
6  * the License.  You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /******************************************************************************
18  ******************************************************************************
19  * NOTE! This program is not safe as a setuid executable!  Do not make it
20  * setuid!
21  ******************************************************************************
22  *****************************************************************************/
23 /*
24  * htpasswd.c: simple program for manipulating password file for
25  * the Apache HTTP server
26  *
27  * Originally by Rob McCool
28  *
29  * Exit values:
30  *  0: Success
31  *  1: Failure; file access/permission problem
32  *  2: Failure; command line syntax problem (usage message issued)
33  *  3: Failure; password verification failure
34  *  4: Failure; operation interrupted (such as with CTRL/C)
35  *  5: Failure; buffer would overflow (username, filename, or computed
36  *     record too long)
37  *  6: Failure; username contains illegal or reserved characters
38  *  7: Failure; file is not a valid htpasswd file
39  */
40
41 #include "apr.h"
42 #include "apr_lib.h"
43 #include "apr_strings.h"
44 #include "apr_errno.h"
45 #include "apr_file_io.h"
46 #include "apr_general.h"
47 #include "apr_signal.h"
48
49 #if APR_HAVE_STDIO_H
50 #include <stdio.h>
51 #endif
52
53 #include "apr_md5.h"
54 #include "apr_sha1.h"
55 #include <time.h>
56
57 #if APR_HAVE_CRYPT_H
58 #include <crypt.h>
59 #endif
60 #if APR_HAVE_STDLIB_H
61 #include <stdlib.h>
62 #endif
63 #if APR_HAVE_STRING_H
64 #include <string.h>
65 #endif
66 #if APR_HAVE_UNISTD_H
67 #include <unistd.h>
68 #endif
69
70 #ifdef WIN32
71 #include <conio.h>
72 #define unlink _unlink
73 #endif
74
75 #if !APR_CHARSET_EBCDIC
76 #define LF 10
77 #define CR 13
78 #else /*APR_CHARSET_EBCDIC*/
79 #define LF '\n'
80 #define CR '\r'
81 #endif /*APR_CHARSET_EBCDIC*/
82
83 #define MAX_STRING_LEN 256
84 #define ALG_PLAIN 0
85 #define ALG_CRYPT 1
86 #define ALG_APMD5 2
87 #define ALG_APSHA 3
88
89 #define ERR_FILEPERM 1
90 #define ERR_SYNTAX 2
91 #define ERR_PWMISMATCH 3
92 #define ERR_INTERRUPTED 4
93 #define ERR_OVERFLOW 5
94 #define ERR_BADUSER 6
95 #define ERR_INVALID 7
96
97 #define APHTP_NEWFILE        1
98 #define APHTP_NOFILE         2
99 #define APHTP_NONINTERACTIVE 4
100 #define APHTP_DELUSER        8
101
102 apr_file_t *errfile;
103 apr_file_t *ftemp = NULL;
104
105 #define NL APR_EOL_STR
106
107 static void to64(char *s, unsigned long v, int n)
108 {
109     static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
110         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
111
112     while (--n >= 0) {
113         *s++ = itoa64[v&0x3f];
114         v >>= 6;
115     }
116 }
117
118 static void generate_salt(char *s, size_t size)
119 {
120     static unsigned char tbl[] = 
121         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
122     size_t i;
123     for (i = 0; i < size; ++i) {
124         int idx = (int) (64.0 * rand() / (RAND_MAX + 1.0));
125         s[i] = tbl[idx];
126     }
127 }
128
129 static apr_status_t seed_rand(void)
130 {
131     int seed = 0;
132     apr_status_t rv;
133     rv = apr_generate_random_bytes((unsigned char*) &seed, sizeof(seed));
134     if (rv) {
135         apr_file_printf(errfile, "Unable to generate random bytes: %pm" NL, &rv);
136         return rv;
137     }
138     srand(seed);
139     return rv;
140 }
141
142 static void putline(apr_file_t *f, const char *l)
143 {
144     apr_file_puts(l, f);
145 }
146
147 /*
148  * Make a password record from the given information.  A zero return
149  * indicates success; failure means that the output buffer contains an
150  * error message instead.
151  */
152 static int mkrecord(char *user, char *record, apr_size_t rlen, char *passwd,
153                     int alg)
154 {
155     char *pw;
156     char cpw[120];
157     char pwin[MAX_STRING_LEN];
158     char pwv[MAX_STRING_LEN];
159     char salt[9];
160     apr_size_t bufsize;
161
162     if (passwd != NULL) {
163         pw = passwd;
164     }
165     else {
166         bufsize = sizeof(pwin);
167         if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
168             apr_snprintf(record, (rlen - 1), "password too long (>%"
169                          APR_SIZE_T_FMT ")", sizeof(pwin) - 1);
170             return ERR_OVERFLOW;
171         }
172         bufsize = sizeof(pwv);
173         apr_password_get("Re-type new password: ", pwv, &bufsize);
174         if (strcmp(pwin, pwv) != 0) {
175             apr_cpystrn(record, "password verification error", (rlen - 1));
176             return ERR_PWMISMATCH;
177         }
178         pw = pwin;
179         memset(pwv, '\0', sizeof(pwin));
180     }
181     switch (alg) {
182
183     case ALG_APSHA:
184         /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
185         apr_sha1_base64(pw,strlen(pw),cpw);
186         break;
187
188     case ALG_APMD5:
189         if (seed_rand()) {
190             break;
191         }
192         generate_salt(&salt[0], 8);
193         salt[8] = '\0';
194
195         apr_md5_encode((const char *)pw, (const char *)salt,
196                      cpw, sizeof(cpw));
197         break;
198
199     case ALG_PLAIN:
200         /* XXX this len limitation is not in sync with any HTTPd len. */
201         apr_cpystrn(cpw,pw,sizeof(cpw));
202         break;
203
204 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
205     case ALG_CRYPT:
206     default:
207         if (seed_rand()) {
208             break;
209         }
210         to64(&salt[0], rand(), 8);
211         salt[8] = '\0';
212
213         apr_cpystrn(cpw, crypt(pw, salt), sizeof(cpw) - 1);
214         break;
215 #endif
216     }
217     memset(pw, '\0', strlen(pw));
218
219     /*
220      * Check to see if the buffer is large enough to hold the username,
221      * hash, and delimiters.
222      */
223     if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
224         apr_cpystrn(record, "resultant record too long", (rlen - 1));
225         return ERR_OVERFLOW;
226     }
227     strcpy(record, user);
228     strcat(record, ":");
229     strcat(record, cpw);
230     strcat(record, "\n");
231     return 0;
232 }
233
234 static void usage(void)
235 {
236     apr_file_printf(errfile, "Usage:" NL);
237     apr_file_printf(errfile, "\thtpasswd [-cmdpsD] passwordfile username" NL);
238     apr_file_printf(errfile, "\thtpasswd -b[cmdpsD] passwordfile username "
239                     "password" NL NL);
240     apr_file_printf(errfile, "\thtpasswd -n[mdps] username" NL);
241     apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password" NL);
242     apr_file_printf(errfile, " -c  Create a new file." NL);
243     apr_file_printf(errfile, " -n  Don't update file; display results on "
244                     "stdout." NL);
245     apr_file_printf(errfile, " -m  Force MD5 encryption of the password"
246 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
247         " (default)"
248 #endif
249         "." NL);
250     apr_file_printf(errfile, " -d  Force CRYPT encryption of the password"
251 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
252             " (default)"
253 #endif
254             "." NL);
255     apr_file_printf(errfile, " -p  Do not encrypt the password (plaintext)." NL);
256     apr_file_printf(errfile, " -s  Force SHA encryption of the password." NL);
257     apr_file_printf(errfile, " -b  Use the password from the command line "
258             "rather than prompting for it." NL);
259     apr_file_printf(errfile, " -D  Delete the specified user." NL);
260     apr_file_printf(errfile,
261             "On Windows, NetWare and TPF systems the '-m' flag is used by "
262             "default." NL);
263     apr_file_printf(errfile,
264             "On all other systems, the '-p' flag will probably not work." NL);
265     exit(ERR_SYNTAX);
266 }
267
268 /*
269  * Check to see if the specified file can be opened for the given
270  * access.
271  */
272 static int accessible(apr_pool_t *pool, char *fname, int mode)
273 {
274     apr_file_t *f = NULL;
275
276     if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
277         return 0;
278     }
279     apr_file_close(f);
280     return 1;
281 }
282
283 /*
284  * Return true if the named file exists, regardless of permissions.
285  */
286 static int exists(char *fname, apr_pool_t *pool)
287 {
288     apr_finfo_t sbuf;
289     apr_status_t check;
290
291     check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
292     return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
293 }
294
295 static void terminate(void)
296 {
297     apr_terminate();
298 #ifdef NETWARE
299     pressanykey();
300 #endif
301 }
302
303 static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
304                        int *alg, int *mask, char **user, char **pwfilename,
305                        char **password)
306 {
307     const char *arg;
308     int args_left = 2;
309     int i;
310
311     /*
312      * Preliminary check to make sure they provided at least
313      * three arguments, we'll do better argument checking as
314      * we parse the command line.
315      */
316     if (argc < 3) {
317         usage();
318     }
319
320     /*
321      * Go through the argument list and pick out any options.  They
322      * have to precede any other arguments.
323      */
324     for (i = 1; i < argc; i++) {
325         arg = argv[i];
326         if (*arg != '-') {
327             break;
328         }
329         while (*++arg != '\0') {
330             if (*arg == 'c') {
331                 *mask |= APHTP_NEWFILE;
332             }
333             else if (*arg == 'n') {
334                 *mask |= APHTP_NOFILE;
335                 args_left--;
336             }
337             else if (*arg == 'm') {
338                 *alg = ALG_APMD5;
339             }
340             else if (*arg == 's') {
341                 *alg = ALG_APSHA;
342             }
343             else if (*arg == 'p') {
344                 *alg = ALG_PLAIN;
345             }
346             else if (*arg == 'd') {
347                 *alg = ALG_CRYPT;
348             }
349             else if (*arg == 'b') {
350                 *mask |= APHTP_NONINTERACTIVE;
351                 args_left++;
352             }
353             else if (*arg == 'D') {
354                 *mask |= APHTP_DELUSER;
355             }
356             else {
357                 usage();
358             }
359         }
360     }
361
362     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
363         apr_file_printf(errfile, "%s: -c and -n options conflict" NL, argv[0]);
364         exit(ERR_SYNTAX);
365     }
366     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_DELUSER)) {
367         apr_file_printf(errfile, "%s: -c and -D options conflict" NL, argv[0]);
368         exit(ERR_SYNTAX);
369     }
370     if ((*mask & APHTP_NOFILE) && (*mask & APHTP_DELUSER)) {
371         apr_file_printf(errfile, "%s: -n and -D options conflict" NL, argv[0]);
372         exit(ERR_SYNTAX);
373     }
374     /*
375      * Make sure we still have exactly the right number of arguments left
376      * (the filename, the username, and possibly the password if -b was
377      * specified).
378      */
379     if ((argc - i) != args_left) {
380         usage();
381     }
382
383     if (*mask & APHTP_NOFILE) {
384         i--;
385     }
386     else {
387         if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
388             apr_file_printf(errfile, "%s: filename too long" NL, argv[0]);
389             exit(ERR_OVERFLOW);
390         }
391         *pwfilename = apr_pstrdup(pool, argv[i]);
392         if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
393             apr_file_printf(errfile, "%s: username too long (> %d)" NL,
394                 argv[0], MAX_STRING_LEN - 1);
395             exit(ERR_OVERFLOW);
396         }
397     }
398     *user = apr_pstrdup(pool, argv[i + 1]);
399     if ((arg = strchr(*user, ':')) != NULL) {
400         apr_file_printf(errfile, "%s: username contains illegal "
401                         "character '%c'" NL, argv[0], *arg);
402         exit(ERR_BADUSER);
403     }
404     if (*mask & APHTP_NONINTERACTIVE) {
405         if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
406             apr_file_printf(errfile, "%s: password too long (> %d)" NL,
407                 argv[0], MAX_STRING_LEN);
408             exit(ERR_OVERFLOW);
409         }
410         *password = apr_pstrdup(pool, argv[i + 2]);
411     }
412 }
413
414 /*
415  * Let's do it.  We end up doing a lot of file opening and closing,
416  * but what do we care?  This application isn't run constantly.
417  */
418 int main(int argc, const char * const argv[])
419 {
420     apr_file_t *fpw = NULL;
421     char record[MAX_STRING_LEN];
422     char line[MAX_STRING_LEN];
423     char *password = NULL;
424     char *pwfilename = NULL;
425     char *user = NULL;
426     char tn[] = "htpasswd.tmp.XXXXXX";
427     char *dirname;
428     char *scratch, cp[MAX_STRING_LEN];
429     int found = 0;
430     int i;
431     int alg = ALG_CRYPT;
432     int mask = 0;
433     apr_pool_t *pool;
434     int existing_file = 0;
435 #if APR_CHARSET_EBCDIC
436     apr_status_t rv;
437     apr_xlate_t *to_ascii;
438 #endif
439
440     apr_app_initialize(&argc, &argv, NULL);
441     atexit(terminate);
442     apr_pool_create(&pool, NULL);
443     apr_file_open_stderr(&errfile, pool);
444
445 #if APR_CHARSET_EBCDIC
446     rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, pool);
447     if (rv) {
448         apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d" NL, rv);
449         exit(1);
450     }
451     rv = apr_SHA1InitEBCDIC(to_ascii);
452     if (rv) {
453         apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d" NL, rv);
454         exit(1);
455     }
456     rv = apr_MD5InitEBCDIC(to_ascii);
457     if (rv) {
458         apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d" NL, rv);
459         exit(1);
460     }
461 #endif /*APR_CHARSET_EBCDIC*/
462
463     check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
464
465
466 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
467     if (alg == ALG_CRYPT) {
468         alg = ALG_APMD5;
469         apr_file_printf(errfile, "Automatically using MD5 format." NL);
470     }
471 #endif
472
473 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
474     if (alg == ALG_PLAIN) {
475         apr_file_printf(errfile,"Warning: storing passwords as plain text "
476                         "might just not work on this platform." NL);
477     }
478 #endif
479
480     /*
481      * Only do the file checks if we're supposed to frob it.
482      */
483     if (!(mask & APHTP_NOFILE)) {
484         existing_file = exists(pwfilename, pool);
485         if (existing_file) {
486             /*
487              * Check that this existing file is readable and writable.
488              */
489             if (!accessible(pool, pwfilename, APR_READ | APR_APPEND)) {
490                 apr_file_printf(errfile, "%s: cannot open file %s for "
491                                 "read/write access" NL, argv[0], pwfilename);
492                 exit(ERR_FILEPERM);
493             }
494         }
495         else {
496             /*
497              * Error out if -c was omitted for this non-existant file.
498              */
499             if (!(mask & APHTP_NEWFILE)) {
500                 apr_file_printf(errfile,
501                         "%s: cannot modify file %s; use '-c' to create it" NL,
502                         argv[0], pwfilename);
503                 exit(ERR_FILEPERM);
504             }
505             /*
506              * As it doesn't exist yet, verify that we can create it.
507              */
508             if (!accessible(pool, pwfilename, APR_CREATE | APR_WRITE)) {
509                 apr_file_printf(errfile, "%s: cannot create file %s" NL,
510                                 argv[0], pwfilename);
511                 exit(ERR_FILEPERM);
512             }
513         }
514     }
515
516     /*
517      * All the file access checks (if any) have been made.  Time to go to work;
518      * try to create the record for the username in question.  If that
519      * fails, there's no need to waste any time on file manipulations.
520      * Any error message text is returned in the record buffer, since
521      * the mkrecord() routine doesn't have access to argv[].
522      */
523     if (!(mask & APHTP_DELUSER)) {
524         i = mkrecord(user, record, sizeof(record) - 1,
525                      password, alg);
526         if (i != 0) {
527             apr_file_printf(errfile, "%s: %s" NL, argv[0], record);
528             exit(i);
529         }
530         if (mask & APHTP_NOFILE) {
531             printf("%s" NL, record);
532             exit(0);
533         }
534     }
535
536     /*
537      * We can access the files the right way, and we have a record
538      * to add or update.  Let's do it..
539      */
540     if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) {
541         apr_file_printf(errfile, "%s: could not determine temp dir" NL,
542                         argv[0]);
543         exit(ERR_FILEPERM);
544     }
545     dirname = apr_psprintf(pool, "%s/%s", dirname, tn);
546
547     if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) {
548         apr_file_printf(errfile, "%s: unable to create temporary file %s" NL,
549                         argv[0], dirname);
550         exit(ERR_FILEPERM);
551     }
552
553     /*
554      * If we're not creating a new file, copy records from the existing
555      * one to the temporary file until we find the specified user.
556      */
557     if (existing_file && !(mask & APHTP_NEWFILE)) {
558         if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED,
559                           APR_OS_DEFAULT, pool) != APR_SUCCESS) {
560             apr_file_printf(errfile, "%s: unable to read file %s" NL,
561                             argv[0], pwfilename);
562             exit(ERR_FILEPERM);
563         }
564         while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) {
565             char *colon;
566
567             strcpy(cp, line);
568             scratch = cp;
569             while (apr_isspace(*scratch)) {
570                 ++scratch;
571             }
572
573             if (!*scratch || (*scratch == '#')) {
574                 putline(ftemp, line);
575                 continue;
576             }
577             /*
578              * See if this is our user.
579              */
580             colon = strchr(scratch, ':');
581             if (colon != NULL) {
582                 *colon = '\0';
583             }
584             else {
585                 /*
586                  * If we've not got a colon on the line, this could well
587                  * not be a valid htpasswd file.
588                  * We should bail at this point.
589                  */
590                 apr_file_printf(errfile, "%s: The file %s does not appear "
591                                          "to be a valid htpasswd file." NL,
592                                 argv[0], pwfilename);
593                 apr_file_close(fpw);
594                 exit(ERR_INVALID);
595             }
596             if (strcmp(user, scratch) != 0) {
597                 putline(ftemp, line);
598                 continue;
599             }
600             else {
601                 if (!(mask & APHTP_DELUSER)) {
602                     /* We found the user we were looking for.
603                      * Add him to the file.
604                     */
605                     apr_file_printf(errfile, "Updating ");
606                     putline(ftemp, record);
607                     found++;
608                 }
609                 else {
610                     /* We found the user we were looking for.
611                      * Delete them from the file.
612                      */
613                     apr_file_printf(errfile, "Deleting ");
614                     found++;
615                 }
616             }
617         }
618         apr_file_close(fpw);
619     }
620     if (!found && !(mask & APHTP_DELUSER)) {
621         apr_file_printf(errfile, "Adding ");
622         putline(ftemp, record);
623     }
624     else if (!found && (mask & APHTP_DELUSER)) {
625         apr_file_printf(errfile, "User %s not found" NL, user);
626         exit(0);
627     }
628     apr_file_printf(errfile, "password for user %s" NL, user);
629
630     /* The temporary file has all the data, just copy it to the new location.
631      */
632     if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) !=
633         APR_SUCCESS) {
634         apr_file_printf(errfile, "%s: unable to update file %s" NL,
635                         argv[0], pwfilename);
636         exit(ERR_FILEPERM);
637     }
638     apr_file_close(ftemp);
639     return 0;
640 }