]> granicus.if.org Git - apache/blob - support/htpasswd.c
ae7d76a05ea9921c49522d502f734d6a8625adbc
[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 APHTP_NEWFILE        1
138 #define APHTP_NOFILE         2
139 #define APHTP_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     strcat(record, "\n");
240     return 0;
241 }
242
243 static void usage(void)
244 {
245     apr_file_printf(errfile, "Usage:\n");
246     apr_file_printf(errfile, "\thtpasswd [-cmdps] passwordfile username\n");
247     apr_file_printf(errfile, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
248     apr_file_printf(errfile, "\thtpasswd -n[mdps] username\n");
249     apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password\n");
250     apr_file_printf(errfile, " -c  Create a new file.\n");
251     apr_file_printf(errfile, " -n  Don't update file; display results on stdout.\n");
252     apr_file_printf(errfile, " -m  Force MD5 encryption of the password"
253 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
254         " (default)"
255 #endif
256         ".\n");
257     apr_file_printf(errfile, " -d  Force CRYPT encryption of the password"
258 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
259             " (default)"
260 #endif
261             ".\n");
262     apr_file_printf(errfile, " -p  Do not encrypt the password (plaintext).\n");
263     apr_file_printf(errfile, " -s  Force SHA encryption of the password.\n");
264     apr_file_printf(errfile, " -b  Use the password from the command line rather "
265             "than prompting for it.\n");
266     apr_file_printf(errfile,
267             "On Windows, NetWare and TPF systems the '-m' flag is used by default.\n");
268     apr_file_printf(errfile,
269             "On all other systems, the '-p' flag will probably not work.\n");
270     exit(ERR_SYNTAX);
271 }
272
273 /*
274  * Check to see if the specified file can be opened for the given
275  * access.
276  */
277 static int accessible(apr_pool_t *pool, char *fname, int mode)
278 {
279     apr_file_t *f = NULL;
280
281     if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
282         return 0;
283     }
284     apr_file_close(f);
285     return 1;
286 }
287
288 /*
289  * Return true if a file is readable.
290  */
291 static int readable(apr_pool_t *pool, char *fname)
292 {
293     return accessible(pool, fname, APR_READ);
294 }
295
296 /*
297  * Return true if the specified file can be opened for write access.
298  */
299 static int writable(apr_pool_t *pool, char *fname)
300 {
301     return accessible(pool, fname, APR_APPEND);
302 }
303
304 /*
305  * Return true if the named file exists, regardless of permissions.
306  */
307 static int exists(char *fname, apr_pool_t *pool)
308 {
309     apr_finfo_t sbuf;
310     apr_status_t check;
311
312     check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
313     return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
314 }
315
316 #ifdef NETWARE
317 void nwTerminate()
318 {
319     pressanykey();
320 }
321 #endif
322
323 static void check_args(apr_pool_t *pool, int argc, const char *const argv[], 
324                        int *alg, int *mask, char **user, char **pwfilename, 
325                        char **password)
326 {
327     const char *arg;
328     int args_left = 2;
329     int i;
330
331     /*
332      * Preliminary check to make sure they provided at least
333      * three arguments, we'll do better argument checking as 
334      * we parse the command line.
335      */
336     if (argc < 3) {
337         usage();
338     }
339
340     /*
341      * Go through the argument list and pick out any options.  They
342      * have to precede any other arguments.
343      */
344     for (i = 1; i < argc; i++) {
345         arg = argv[i];
346         if (*arg != '-') {
347             break;
348         }
349         while (*++arg != '\0') {
350             if (*arg == 'c') {
351                 *mask |= APHTP_NEWFILE;
352             }
353             else if (*arg == 'n') {
354                 *mask |= APHTP_NOFILE;
355                 args_left--;
356             }
357             else if (*arg == 'm') {
358                 *alg = ALG_APMD5;
359             }
360             else if (*arg == 's') {
361                 *alg = ALG_APSHA;
362             }
363             else if (*arg == 'p') {
364                 *alg = ALG_PLAIN;
365             }
366             else if (*arg == 'd') {
367                 *alg = ALG_CRYPT;
368             }
369             else if (*arg == 'b') {
370                 *mask |= APHTP_NONINTERACTIVE;
371                 args_left++;
372             }
373             else {
374                 usage();
375             }
376         }
377     }
378
379     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
380         apr_file_printf(errfile, "%s: -c and -n options conflict\n", argv[0]);
381         exit(ERR_SYNTAX);
382     }
383     /*
384      * Make sure we still have exactly the right number of arguments left
385      * (the filename, the username, and possibly the password if -b was
386      * specified).
387      */
388     if ((argc - i) != args_left) {
389         usage();
390     }
391
392     if (*mask & APHTP_NOFILE) {
393         i--;
394     }
395     else {
396         if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
397             apr_file_printf(errfile, "%s: filename too long\n", argv[0]);
398             exit(ERR_OVERFLOW);
399         }
400         *pwfilename = apr_pstrdup(pool, argv[i]);
401         if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
402             apr_file_printf(errfile, "%s: username too long (> %d)\n",
403                 argv[0], MAX_STRING_LEN - 1);
404             exit(ERR_OVERFLOW);
405         }
406     }
407     *user = apr_pstrdup(pool, argv[i + 1]);
408     if ((arg = strchr(*user, ':')) != NULL) {
409         apr_file_printf(errfile, "%s: username contains illegal character '%c'\n",
410                 argv[0], *arg);
411         exit(ERR_BADUSER);
412     }
413     if (*mask & APHTP_NONINTERACTIVE) {
414         if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
415             apr_file_printf(errfile, "%s: password too long (> %d)\n",
416                 argv[0], MAX_STRING_LEN);
417             exit(ERR_OVERFLOW);
418         }
419         *password = apr_pstrdup(pool, argv[i + 2]);
420     }
421 }
422
423 /*
424  * Let's do it.  We end up doing a lot of file opening and closing,
425  * but what do we care?  This application isn't run constantly.
426  */
427 int main(int argc, const char * const argv[])
428 {
429     apr_file_t *fpw = NULL;
430     char record[MAX_STRING_LEN];
431     char line[MAX_STRING_LEN];
432     char *password = NULL;
433     char *pwfilename = NULL;
434     char *user = NULL;
435     char tn[] = "htpasswd.tmp.XXXXXX";
436     char scratch[MAX_STRING_LEN];
437     char *str = NULL;
438     int found = 0;
439     int i;
440     int alg = ALG_CRYPT;
441     int mask = 0;
442     apr_pool_t *pool;
443 #if APR_CHARSET_EBCDIC
444     apr_status_t rv;
445     apr_xlate_t *to_ascii;
446 #endif
447
448     apr_app_initialize(&argc, &argv, NULL);
449     atexit(apr_terminate);
450 #ifdef NETWARE
451     atexit(nwTerminate);
452 #endif
453     apr_pool_create(&pool, NULL);
454     apr_file_open_stderr(&errfile, pool);
455
456 #if APR_CHARSET_EBCDIC
457     rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
458     if (rv) {
459         apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d\n", rv);
460         exit(1);
461     }
462     rv = apr_SHA1InitEBCDIC(to_ascii);
463     if (rv) {
464         apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d\n", rv);
465         exit(1);
466     }
467     rv = apr_MD5InitEBCDIC(to_ascii);
468     if (rv) {
469         apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d\n", rv);
470         exit(1);
471     }
472 #endif /*APR_CHARSET_EBCDIC*/
473
474     check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
475
476
477 #if defined(WIN32) || defined(NETWARE)
478     if (alg == ALG_CRYPT) {
479         alg = ALG_APMD5;
480         apr_file_printf(errfile, "Automatically using MD5 format.\n");
481     }
482 #endif
483
484 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
485     if (alg == ALG_PLAIN) {
486         apr_file_printf(errfile,"Warning: storing passwords as plain text might "
487                 "just not work on this platform.\n");
488     }
489 #endif
490     if (! mask & APHTP_NOFILE) {
491         /*
492          * Only do the file checks if we're supposed to frob it.
493          *
494          * Verify that the file exists if -c was omitted.  We give a special
495          * message if it doesn't.
496          */
497         if ((! mask & APHTP_NEWFILE) && (! exists(pwfilename, pool))) {
498             apr_file_printf(errfile,
499                     "%s: cannot modify file %s; use '-c' to create it\n",
500                     argv[0], pwfilename);
501             perror("apr_file_open");
502             exit(ERR_FILEPERM);
503         }
504         /*
505          * Verify that we can read the existing file in the case of an update
506          * to it (rather than creation of a new one).
507          */
508         if ((! mask & APHTP_NEWFILE) && (! readable(pool, pwfilename))) {
509             apr_file_printf(errfile, "%s: cannot open file %s for read access\n",
510                     argv[0], pwfilename);
511             perror("apr_file_open");
512             exit(ERR_FILEPERM);
513         }
514         /*
515          * Now check to see if we can preserve an existing file in case
516          * of password verification errors on a -c operation.
517          */
518         if ((mask & APHTP_NEWFILE) && exists(pwfilename, pool) && 
519             (! readable(pool, pwfilename))) {
520             apr_file_printf(errfile, "%s: cannot open file %s for read access\n"
521                     "%s: existing auth data would be lost on "
522                     "password mismatch",
523                     argv[0], pwfilename, argv[0]);
524             perror("apr_file_open");
525             exit(ERR_FILEPERM);
526         }
527         /*
528          * Now verify that the file is writable!
529          */
530         if (! writable(pool, pwfilename)) {
531             apr_file_printf(errfile, "%s: cannot open file %s for write access\n",
532                     argv[0], pwfilename);
533             perror("apr_file_open");
534             exit(ERR_FILEPERM);
535         }
536     }
537
538     /*
539      * All the file access checks (if any) have been made.  Time to go to work;
540      * try to create the record for the username in question.  If that
541      * fails, there's no need to waste any time on file manipulations.
542      * Any error message text is returned in the record buffer, since
543      * the mkrecord() routine doesn't have access to argv[].
544      */
545     i = mkrecord(user, record, sizeof(record) - 1,
546                  password, alg);
547     if (i != 0) {
548         apr_file_printf(errfile, "%s: %s\n", argv[0], record);
549         exit(i);
550     }
551     if (mask & APHTP_NOFILE) {
552         printf("%s\n", record);
553         exit(0);
554     }
555
556     /*
557      * We can access the files the right way, and we have a record
558      * to add or update.  Let's do it..
559      */
560     if (apr_file_mktemp(&ftemp, tn, 0, pool) != APR_SUCCESS) {
561         apr_file_printf(errfile, "%s: unable to create temporary file '%s'\n", 
562                         argv[0], tn);
563         exit(ERR_FILEPERM);
564     }
565
566     /*
567      * If we're not creating a new file, copy records from the existing
568      * one to the temporary file until we find the specified user.
569      */
570     if (apr_file_open(&fpw, pwfilename, APR_READ, APR_OS_DEFAULT, 
571                       pool) == APR_SUCCESS) {
572         while (! (apr_file_gets(line, sizeof(line), fpw))) {
573             char *colon;
574
575             if ((line[0] == '#') || (line[0] == '\0')) {
576                 putline(ftemp, line);
577                 continue;
578             }
579             strcpy(scratch, line);
580             /*
581              * See if this is our user.
582              */
583             colon = strchr(scratch, ':');
584             if (colon != NULL) {
585                 *colon = '\0';
586             }
587             if (strcmp(user, scratch) != 0) {
588                 putline(ftemp, line);
589                 continue;
590             }
591             else {
592                 /* We found the user we were looking for, add him to the file.
593                  */
594                 apr_file_printf(errfile, "Updating ");
595                 putline(ftemp, record);
596             }
597         }
598     }
599     if (!found) {
600         apr_file_printf(errfile, "Adding ");
601         putline(ftemp, record);
602     }
603     apr_file_printf(errfile, "password for user %s\n", user);
604     apr_file_close(fpw);
605
606     /* The temporary file has all the data, just copy it to the new location.
607      */
608 #if defined(OS2) || defined(WIN32)
609     str = apr_psprintf(pool, "copy \"%s\" \"%s\"", tn, pwfilename);
610 #else
611     str = apr_psprintf(pool, "cp %s %s", tn, pwfilename);
612 #endif
613     system(str);
614     apr_file_close(ftemp);
615     return 0;
616 }