]> granicus.if.org Git - apache/blob - support/htpasswd.c
Finish the htpasswd port to APR. This brings the file checking code to
[apache] / support / htpasswd.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2002 The Apache Software Foundation.  All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in
16  *    the documentation and/or other materials provided with the
17  *    distribution.
18  *
19  * 3. The end-user documentation included with the redistribution,
20  *    if any, must include the following acknowledgment:
21  *       "This product includes software developed by the
22  *        Apache Software Foundation (http://www.apache.org/)."
23  *    Alternately, this acknowledgment may appear in the software itself,
24  *    if and wherever such third-party acknowledgments normally appear.
25  *
26  * 4. The names "Apache" and "Apache Software Foundation" must
27  *    not be used to endorse or promote products derived from this
28  *    software without prior written permission. For written
29  *    permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache",
32  *    nor may "Apache" appear in their name, without prior written
33  *    permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation.  For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  *
54  * Portions of this software are based upon public domain software
55  * originally written at the National Center for Supercomputing Applications,
56  * University of Illinois, Urbana-Champaign.
57  */
58
59 /******************************************************************************
60  ******************************************************************************
61  * NOTE! This program is not safe as a setuid executable!  Do not make it
62  * setuid!
63  ******************************************************************************
64  *****************************************************************************/
65 /*
66  * htpasswd.c: simple program for manipulating password file for
67  * the Apache HTTP server
68  * 
69  * Originally by Rob McCool
70  *
71  * Exit values:
72  *  0: Success
73  *  1: Failure; file access/permission problem
74  *  2: Failure; command line syntax problem (usage message issued)
75  *  3: Failure; password verification failure
76  *  4: Failure; operation interrupted (such as with CTRL/C)
77  *  5: Failure; buffer would overflow (username, filename, or computed
78  *     record too long)
79  *  6: Failure; username contains illegal or reserved characters
80  */
81
82 #include "apr.h"
83 #include "apr_lib.h"
84 #include "apr_strings.h"
85 #include "apr_errno.h"
86 #include "apr_file_io.h"
87 #include "apr_general.h"
88 #include "apr_signal.h"
89
90 #if APR_HAVE_STDIO_H
91 #include <stdio.h>
92 #endif
93
94 #include "apr_md5.h"
95 #include "apr_sha1.h"
96 #include <time.h>
97
98 #if APR_HAVE_CRYPT_H
99 #include <crypt.h>
100 #endif
101 #if APR_HAVE_STDLIB_H
102 #include <stdlib.h>
103 #endif
104 #if APR_HAVE_STRING_H
105 #include <string.h>
106 #endif
107 #if APR_HAVE_UNISTD_H
108 #include <unistd.h>
109 #endif
110
111 #ifdef WIN32
112 #include <conio.h>
113 #define unlink _unlink
114 #endif
115
116 #if !APR_CHARSET_EBCDIC
117 #define LF 10
118 #define CR 13
119 #else /*APR_CHARSET_EBCDIC*/
120 #define LF '\n'
121 #define CR '\r'
122 #endif /*APR_CHARSET_EBCDIC*/
123
124 #define MAX_STRING_LEN 256
125 #define ALG_PLAIN 0
126 #define ALG_CRYPT 1
127 #define ALG_APMD5 2
128 #define ALG_APSHA 3 
129
130 #define ERR_FILEPERM 1
131 #define ERR_SYNTAX 2
132 #define ERR_PWMISMATCH 3
133 #define ERR_INTERRUPTED 4
134 #define ERR_OVERFLOW 5
135 #define ERR_BADUSER 6
136
137 #define NEWFILE        1
138 #define NOFILE         2
139 #define NONINTERACTIVE 4
140
141 apr_file_t *errfile;
142 apr_file_t *ftemp = NULL;
143
144 static void to64(char *s, unsigned long v, int n)
145 {
146     static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
147         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
148
149     while (--n >= 0) {
150         *s++ = itoa64[v&0x3f];
151         v >>= 6;
152     }
153 }
154
155 static void putline(apr_file_t *f, const char *l)
156 {
157     apr_file_puts(l, f);
158 }
159
160 /*
161  * Make a password record from the given information.  A zero return
162  * indicates success; failure means that the output buffer contains an
163  * error message instead.
164  */
165 static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
166                     int alg)
167 {
168     char *pw;
169     char cpw[120];
170     char pwin[MAX_STRING_LEN];
171     char pwv[MAX_STRING_LEN];
172     char salt[9];
173     size_t bufsize;
174
175     if (passwd != NULL) {
176         pw = passwd;
177     }
178     else {
179         bufsize = sizeof(pwin);
180         if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
181             apr_snprintf(record, (rlen - 1), "password too long (>%" APR_SIZE_T_FMT
182                 ")", sizeof(pwin) - 1);
183             return ERR_OVERFLOW;
184         }
185         bufsize = sizeof(pwv);
186         apr_password_get("Re-type new password: ", pwv, &bufsize);
187         if (strcmp(pwin, pwv) != 0) {
188             apr_cpystrn(record, "password verification error", (rlen - 1));
189             return ERR_PWMISMATCH;
190         }
191         pw = pwin;
192         memset(pwv, '\0', sizeof(pwin));
193     }
194     switch (alg) {
195
196     case ALG_APSHA:
197         /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
198         apr_sha1_base64(pw,strlen(pw),cpw);
199         break;
200
201     case ALG_APMD5: 
202         (void) srand((int) time((time_t *) NULL));
203         to64(&salt[0], rand(), 8);
204         salt[8] = '\0';
205
206         apr_md5_encode((const char *)pw, (const char *)salt,
207                      cpw, sizeof(cpw));
208         break;
209
210     case ALG_PLAIN:
211         /* XXX this len limitation is not in sync with any HTTPd len. */
212         apr_cpystrn(cpw,pw,sizeof(cpw));
213         break;
214
215 #if !(defined(WIN32) || defined(NETWARE))
216     case ALG_CRYPT:
217     default:
218         (void) srand((int) time((time_t *) NULL));
219         to64(&salt[0], rand(), 8);
220         salt[8] = '\0';
221
222         apr_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
223         break;
224 #endif
225     }
226     memset(pw, '\0', strlen(pw));
227
228     /*
229      * Check to see if the buffer is large enough to hold the username,
230      * hash, and delimiters.
231      */
232     if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
233         apr_cpystrn(record, "resultant record too long", (rlen - 1));
234         return ERR_OVERFLOW;
235     }
236     strcpy(record, user);
237     strcat(record, ":");
238     strcat(record, cpw);
239     return 0;
240 }
241
242 static void usage(void)
243 {
244     apr_file_printf(errfile, "Usage:\n");
245     apr_file_printf(errfile, "\thtpasswd [-cmdps] passwordfile username\n");
246     apr_file_printf(errfile, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
247     apr_file_printf(errfile, "\thtpasswd -n[mdps] username\n");
248     apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password\n");
249     apr_file_printf(errfile, " -c  Create a new file.\n");
250     apr_file_printf(errfile, " -n  Don't update file; display results on stdout.\n");
251     apr_file_printf(errfile, " -m  Force MD5 encryption of the password"
252 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
253         " (default)"
254 #endif
255         ".\n");
256     apr_file_printf(errfile, " -d  Force CRYPT encryption of the password"
257 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
258             " (default)"
259 #endif
260             ".\n");
261     apr_file_printf(errfile, " -p  Do not encrypt the password (plaintext).\n");
262     apr_file_printf(errfile, " -s  Force SHA encryption of the password.\n");
263     apr_file_printf(errfile, " -b  Use the password from the command line rather "
264             "than prompting for it.\n");
265     apr_file_printf(errfile,
266             "On Windows, NetWare and TPF systems the '-m' flag is used by default.\n");
267     apr_file_printf(errfile,
268             "On all other systems, the '-p' flag will probably not work.\n");
269     exit(ERR_SYNTAX);
270 }
271
272 /*
273  * Check to see if the specified file can be opened for the given
274  * access.
275  */
276 static int accessible(apr_pool_t *pool, char *fname, int mode)
277 {
278     apr_file_t *f = NULL;
279
280     if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
281         return 0;
282     }
283     apr_file_close(f);
284     return 1;
285 }
286
287 /*
288  * Return true if a file is readable.
289  */
290 static int readable(apr_pool_t *pool, char *fname)
291 {
292     return accessible(pool, fname, APR_READ);
293 }
294
295 /*
296  * Return true if the specified file can be opened for write access.
297  */
298 static int writable(apr_pool_t *pool, char *fname)
299 {
300     return accessible(pool, fname, APR_APPEND);
301 }
302
303 /*
304  * Return true if the named file exists, regardless of permissions.
305  */
306 static int exists(char *fname, apr_pool_t *pool)
307 {
308     apr_finfo_t sbuf;
309     apr_status_t check;
310
311     check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
312     return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
313 }
314
315 #ifdef NETWARE
316 void nwTerminate()
317 {
318     pressanykey();
319 }
320 #endif
321
322 static void check_args(apr_pool_t *pool, int argc, const char *const argv[], 
323                        int *alg, int *mask, char **user, char **pwfilename, 
324                        char **password)
325 {
326     const char *arg;
327     int args_left = 2;
328     int i;
329
330     /*
331      * Preliminary check to make sure they provided at least
332      * three arguments, we'll do better argument checking as 
333      * we parse the command line.
334      */
335     if (argc < 3) {
336         usage();
337     }
338
339     /*
340      * Go through the argument list and pick out any options.  They
341      * have to precede any other arguments.
342      */
343     for (i = 1; i < argc; i++) {
344         arg = argv[i];
345         if (*arg != '-') {
346             break;
347         }
348         while (*++arg != '\0') {
349             if (*arg == 'c') {
350                 *mask |= NEWFILE;
351             }
352             else if (*arg == 'n') {
353                 *mask |= NOFILE;
354                 args_left--;
355             }
356             else if (*arg == 'm') {
357                 *alg = ALG_APMD5;
358             }
359             else if (*arg == 's') {
360                 *alg = ALG_APSHA;
361             }
362             else if (*arg == 'p') {
363                 *alg = ALG_PLAIN;
364             }
365             else if (*arg == 'd') {
366                 *alg = ALG_CRYPT;
367             }
368             else if (*arg == 'b') {
369                 *mask |= NONINTERACTIVE;
370                 args_left++;
371             }
372             else {
373                 usage();
374             }
375         }
376     }
377
378     if (*mask & (NEWFILE & NOFILE)) {
379         apr_file_printf(errfile, "%s: -c and -n options conflict\n", argv[0]);
380         exit(ERR_SYNTAX);
381     }
382     /*
383      * Make sure we still have exactly the right number of arguments left
384      * (the filename, the username, and possibly the password if -b was
385      * specified).
386      */
387     if ((argc - i) != args_left) {
388         usage();
389     }
390
391     if (*mask & NOFILE) {
392         i--;
393     }
394     else {
395         if (strlen(argv[i]) > (PATH_MAX - 1)) {
396             apr_file_printf(errfile, "%s: filename too long\n", argv[0]);
397             exit(ERR_OVERFLOW);
398         }
399         *pwfilename = apr_pstrdup(pool, argv[i]);
400         if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
401             apr_file_printf(errfile, "%s: username too long (>%" APR_SIZE_T_FMT ")\n",
402                 argv[0], MAX_STRING_LEN - 1);
403             exit(ERR_OVERFLOW);
404         }
405     }
406     *user = apr_pstrdup(pool, argv[i + 1]);
407     if ((arg = strchr(*user, ':')) != NULL) {
408         apr_file_printf(errfile, "%s: username contains illegal character '%c'\n",
409                 argv[0], *arg);
410         exit(ERR_BADUSER);
411     }
412     if (*mask & NONINTERACTIVE) {
413         if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
414             apr_file_printf(errfile, "%s: password too long (>%" APR_SIZE_T_FMT ")\n",
415                 argv[0], MAX_STRING_LEN);
416             exit(ERR_OVERFLOW);
417         }
418         *password = apr_pstrdup(pool, argv[i + 2]);
419     }
420 }
421
422 /*
423  * Let's do it.  We end up doing a lot of file opening and closing,
424  * but what do we care?  This application isn't run constantly.
425  */
426 int main(int argc, const char * const argv[])
427 {
428     apr_file_t *fpw = NULL;
429     char record[MAX_STRING_LEN];
430     char line[MAX_STRING_LEN];
431     char *password = NULL;
432     char *pwfilename = NULL;
433     char *user = NULL;
434     char tn[] = "htpasswd.tmp.XXXXXX";
435     char scratch[MAX_STRING_LEN];
436     char *str = NULL;
437     int found = 0;
438     int i;
439     int alg = ALG_CRYPT;
440     int mask = 0;
441     apr_pool_t *pool;
442 #if APR_CHARSET_EBCDIC
443     apr_status_t rv;
444     apr_xlate_t *to_ascii;
445 #endif
446
447     apr_app_initialize(&argc, &argv, NULL);
448     atexit(apr_terminate);
449 #ifdef NETWARE
450     atexit(nwTerminate);
451 #endif
452     apr_pool_create(&pool, NULL);
453     apr_file_open_stderr(&errfile, pool);
454
455 #if APR_CHARSET_EBCDIC
456     rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
457     if (rv) {
458         apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d\n", rv);
459         exit(1);
460     }
461     rv = apr_SHA1InitEBCDIC(to_ascii);
462     if (rv) {
463         apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d\n", rv);
464         exit(1);
465     }
466     rv = apr_MD5InitEBCDIC(to_ascii);
467     if (rv) {
468         apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d\n", rv);
469         exit(1);
470     }
471 #endif /*APR_CHARSET_EBCDIC*/
472
473     check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
474
475
476 #if defined(WIN32) || defined(NETWARE)
477     if (alg == ALG_CRYPT) {
478         alg = ALG_APMD5;
479         apr_file_printf(errfile, "Automatically using MD5 format.\n");
480     }
481 #endif
482
483 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
484     if (alg == ALG_PLAIN) {
485         apr_file_printf(errfile,"Warning: storing passwords as plain text might "
486                 "just not work on this platform.\n");
487     }
488 #endif
489     if (! mask & NOFILE) {
490         /*
491          * Only do the file checks if we're supposed to frob it.
492          *
493          * Verify that the file exists if -c was omitted.  We give a special
494          * message if it doesn't.
495          */
496         if ((! mask & NEWFILE) && (! exists(pwfilename, pool))) {
497             apr_file_printf(errfile,
498                     "%s: cannot modify file %s; use '-c' to create it\n",
499                     argv[0], pwfilename);
500             perror("apr_file_open");
501             exit(ERR_FILEPERM);
502         }
503         /*
504          * Verify that we can read the existing file in the case of an update
505          * to it (rather than creation of a new one).
506          */
507         if ((! mask & NEWFILE) && (! readable(pool, pwfilename))) {
508             apr_file_printf(errfile, "%s: cannot open file %s for read access\n",
509                     argv[0], pwfilename);
510             perror("apr_file_open");
511             exit(ERR_FILEPERM);
512         }
513         /*
514          * Now check to see if we can preserve an existing file in case
515          * of password verification errors on a -c operation.
516          */
517         if ((mask & NEWFILE) && exists(pwfilename, pool) && 
518             (! readable(pool, pwfilename))) {
519             apr_file_printf(errfile, "%s: cannot open file %s for read access\n"
520                     "%s: existing auth data would be lost on "
521                     "password mismatch",
522                     argv[0], pwfilename, argv[0]);
523             perror("apr_file_open");
524             exit(ERR_FILEPERM);
525         }
526         /*
527          * Now verify that the file is writable!
528          */
529         if (! writable(pool, pwfilename)) {
530             apr_file_printf(errfile, "%s: cannot open file %s for write access\n",
531                     argv[0], pwfilename);
532             perror("apr_file_open");
533             exit(ERR_FILEPERM);
534         }
535     }
536
537     /*
538      * All the file access checks (if any) have been made.  Time to go to work;
539      * try to create the record for the username in question.  If that
540      * fails, there's no need to waste any time on file manipulations.
541      * Any error message text is returned in the record buffer, since
542      * the mkrecord() routine doesn't have access to argv[].
543      */
544     i = mkrecord(user, record, sizeof(record) - 1,
545                  password, alg);
546     if (i != 0) {
547         apr_file_printf(errfile, "%s: %s\n", argv[0], record);
548         exit(i);
549     }
550     if (mask & NOFILE) {
551         printf("%s\n", record);
552         exit(0);
553     }
554
555     /*
556      * We can access the files the right way, and we have a record
557      * to add or update.  Let's do it..
558      */
559     if (apr_file_mktemp(&ftemp, tn, 0, pool) != APR_SUCCESS) {
560         apr_file_printf(errfile, "%s: unable to create temporary file '%s'\n", 
561                         argv[0], tn);
562         exit(ERR_FILEPERM);
563     }
564
565     /*
566      * If we're not creating a new file, copy records from the existing
567      * one to the temporary file until we find the specified user.
568      */
569     if (apr_file_open(&fpw, pwfilename, APR_READ, APR_OS_DEFAULT, 
570                       pool) == APR_SUCCESS) {
571         while (! (apr_file_gets(line, sizeof(line), fpw))) {
572             char *colon;
573
574             if ((line[0] == '#') || (line[0] == '\0')) {
575                 putline(ftemp, line);
576                 continue;
577             }
578             strcpy(scratch, line);
579             /*
580              * See if this is our user.
581              */
582             colon = strchr(scratch, ':');
583             if (colon != NULL) {
584                 *colon = '\0';
585             }
586             if (strcmp(user, scratch) != 0) {
587                 putline(ftemp, line);
588                 continue;
589             }
590             else {
591                 /* We found the user we were looking for, add him to the file.
592                  */
593                 apr_file_printf(errfile, "Updating ");
594                 putline(ftemp, record);
595             }
596         }
597     }
598     if (!found) {
599         apr_file_printf(errfile, "Adding ");
600         putline(ftemp, record);
601     }
602     apr_file_printf(errfile, "password for user %s\n", user);
603     apr_file_close(fpw);
604
605     /* The temporary file has all the data, just copy it to the new location.
606      */
607 #if defined(OS2) || defined(WIN32)
608     str = apr_psprintf(pool, "copy \"%s\" \"%s\"", tn, pwfilename);
609 #else
610     str = apr_psprintf(pool, "cp %s %s", tn, pwfilename);
611 #endif
612     system(str);
613     apr_file_close(ftemp);
614     return 0;
615 }