]> granicus.if.org Git - apache/blob - support/htpasswd.c
A pool is a REQUIRED ARGUMENT, never optional (NULL).
[apache] / support / htpasswd.c
1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2000-2001 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 /*
138  * This needs to be declared statically so the signal handler can
139  * access it.
140  */
141 static char *tempfilename;
142 /*
143  * If our platform knows about the tmpnam() external buffer size, create
144  * a buffer to pass in.  This is needed in a threaded environment, or
145  * one that thinks it is (like HP-UX).
146  */
147 #ifdef L_tmpnam
148 static char tname_buf[L_tmpnam];
149 #else
150 static char *tname_buf = NULL;
151 #endif
152
153 /*
154  * Get a line of input from the user, not including any terminating
155  * newline.
156  */
157 static int getline(char *s, int n, FILE *f)
158 {
159     register int i = 0;
160
161     while (1) {
162         s[i] = (char) fgetc(f);
163
164         if (s[i] == CR) {
165             s[i] = fgetc(f);
166         }
167
168         if ((s[i] == 0x4) || (s[i] == LF) || (i == (n - 1))) {
169             s[i] = '\0';
170             return (feof(f) ? 1 : 0);
171         }
172         ++i;
173     }
174 }
175
176 static void putline(FILE *f, char *l)
177 {
178     int x;
179
180     for (x = 0; l[x]; x++) {
181         fputc(l[x], f);
182     }
183     fputc('\n', f);
184 }
185
186 static void to64(char *s, unsigned long v, int n)
187 {
188     static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
189         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
190
191     while (--n >= 0) {
192         *s++ = itoa64[v&0x3f];
193         v >>= 6;
194     }
195 }
196
197 /*
198  * Make a password record from the given information.  A zero return
199  * indicates success; failure means that the output buffer contains an
200  * error message instead.
201  */
202 static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
203                     int alg)
204 {
205     char *pw;
206     char cpw[120];
207     char pwin[MAX_STRING_LEN];
208     char pwv[MAX_STRING_LEN];
209     char salt[9];
210     size_t bufsize;
211
212     if (passwd != NULL) {
213         pw = passwd;
214     }
215     else {
216         bufsize = sizeof(pwin);
217         if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
218             apr_snprintf(record, (rlen - 1), "password too long (>%" APR_SIZE_T_FMT
219                 ")", sizeof(pwin) - 1);
220             return ERR_OVERFLOW;
221         }
222         bufsize = sizeof(pwv);
223         apr_password_get("Re-type new password: ", pwv, &bufsize);
224         if (strcmp(pwin, pwv) != 0) {
225             apr_cpystrn(record, "password verification error", (rlen - 1));
226             return ERR_PWMISMATCH;
227         }
228         pw = pwin;
229         memset(pwv, '\0', sizeof(pwin));
230     }
231     switch (alg) {
232
233     case ALG_APSHA:
234         /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
235         apr_sha1_base64(pw,strlen(pw),cpw);
236         break;
237
238     case ALG_APMD5: 
239         (void) srand((int) time((time_t *) NULL));
240         to64(&salt[0], rand(), 8);
241         salt[8] = '\0';
242
243         apr_md5_encode((const char *)pw, (const char *)salt,
244                      cpw, sizeof(cpw));
245         break;
246
247     case ALG_PLAIN:
248         /* XXX this len limitation is not in sync with any HTTPd len. */
249         apr_cpystrn(cpw,pw,sizeof(cpw));
250         break;
251
252 #ifndef WIN32
253     case ALG_CRYPT:
254     default:
255         (void) srand((int) time((time_t *) NULL));
256         to64(&salt[0], rand(), 8);
257         salt[8] = '\0';
258
259         apr_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
260         break;
261 #endif
262     }
263     memset(pw, '\0', strlen(pw));
264
265     /*
266      * Check to see if the buffer is large enough to hold the username,
267      * hash, and delimiters.
268      */
269     if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
270         apr_cpystrn(record, "resultant record too long", (rlen - 1));
271         return ERR_OVERFLOW;
272     }
273     strcpy(record, user);
274     strcat(record, ":");
275     strcat(record, cpw);
276     return 0;
277 }
278
279 static int usage(void)
280 {
281     fprintf(stderr, "Usage:\n");
282     fprintf(stderr, "\thtpasswd [-cmdps] passwordfile username\n");
283     fprintf(stderr, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
284     fprintf(stderr, "\thtpasswd -n[mdps] username\n");
285     fprintf(stderr, "\thtpasswd -nb[mdps] username password\n");
286     fprintf(stderr, " -c  Create a new file.\n");
287     fprintf(stderr, " -n  Don't update file; display results on stdout.\n");
288     fprintf(stderr, " -m  Force MD5 encryption of the password"
289 #if defined(WIN32) || defined(TPF)
290         " (default)"
291 #endif
292         ".\n");
293     fprintf(stderr, " -d  Force CRYPT encryption of the password"
294 #if (!(defined(WIN32) || defined(TPF)))
295             " (default)"
296 #endif
297             ".\n");
298     fprintf(stderr, " -p  Do not encrypt the password (plaintext).\n");
299     fprintf(stderr, " -s  Force SHA encryption of the password.\n");
300     fprintf(stderr, " -b  Use the password from the command line rather "
301             "than prompting for it.\n");
302     fprintf(stderr,
303             "On Windows and TPF systems the '-m' flag is used by default.\n");
304     fprintf(stderr,
305             "On all other systems, the '-p' flag will probably not work.\n");
306     return ERR_SYNTAX;
307 }
308
309 static void interrupted(void)
310 {
311     fprintf(stderr, "Interrupted.\n");
312     if (tempfilename != NULL) {
313         unlink(tempfilename);
314     }
315     exit(ERR_INTERRUPTED);
316 }
317
318 /*
319  * Check to see if the specified file can be opened for the given
320  * access.
321  */
322 static int accessible(char *fname, char *mode)
323 {
324     FILE *s;
325
326     s = fopen(fname, mode);
327     if (s == NULL) {
328         return 0;
329     }
330     fclose(s);
331     return 1;
332 }
333
334 /*
335  * Return true if a file is readable.
336  */
337 static int readable(char *fname)
338 {
339     return accessible(fname, "r");
340 }
341
342 /*
343  * Return true if the specified file can be opened for write access.
344  */
345 static int writable(char *fname)
346 {
347     return accessible(fname, "a");
348 }
349
350 /*
351  * Return true if the named file exists, regardless of permissions.
352  */
353 static int exists(char *fname, apr_pool_t *pool)
354 {
355     apr_finfo_t sbuf;
356     apr_status_t check;
357
358     check = apr_stat(&sbuf, fname, APR_FINFO_NORM, pool);
359     return (check ? 0 : 1);
360 }
361
362 /*
363  * Copy from the current position of one file to the current position
364  * of another.
365  */
366 static void copy_file(FILE *target, FILE *source)
367 {
368     static char line[MAX_STRING_LEN];
369
370     while (fgets(line, sizeof(line), source) != NULL) {
371         fputs(line, target);
372     }
373 }
374
375 /*
376  * Let's do it.  We end up doing a lot of file opening and closing,
377  * but what do we care?  This application isn't run constantly.
378  */
379 int main(int argc, char *argv[])
380 {
381     FILE *ftemp = NULL;
382     FILE *fpw = NULL;
383     char user[MAX_STRING_LEN];
384     char password[MAX_STRING_LEN];
385     char record[MAX_STRING_LEN];
386     char line[MAX_STRING_LEN];
387     char pwfilename[MAX_STRING_LEN];
388     char *arg;
389     int found = 0;
390     int alg = ALG_CRYPT;
391     int newfile = 0;
392     int nofile = 0;
393     int noninteractive = 0;
394     int i;
395     int args_left = 2;
396 #if APR_CHARSET_EBCDIC
397     apr_pool_t *pool;
398     apr_status_t rv;
399     apr_xlate_t *to_ascii;
400
401     apr_initialize();
402     atexit(apr_terminate);
403     apr_pool_create(&pool, NULL);
404
405     rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
406     if (rv) {
407         fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", rv);
408         exit(1);
409     }
410     rv = apr_SHA1InitEBCDIC(to_ascii);
411     if (rv) {
412         fprintf(stderr, "apr_SHA1InitEBCDIC()->%d\n", rv);
413         exit(1);
414     }
415     rv = apr_MD5InitEBCDIC(to_ascii);
416     if (rv) {
417         fprintf(stderr, "apr_MD5InitEBCDIC()->%d\n", rv);
418         exit(1);
419     }
420 #endif /*APR_CHARSET_EBCDIC*/
421
422     tempfilename = NULL;
423     apr_signal(SIGINT, (void (*)(int)) interrupted);
424
425     /*
426      * Preliminary check to make sure they provided at least
427      * three arguments, we'll do better argument checking as 
428      * we parse the command line.
429      */
430     if (argc < 3) {
431         return usage();
432     }
433
434     /*
435      * Go through the argument list and pick out any options.  They
436      * have to precede any other arguments.
437      */
438     for (i = 1; i < argc; i++) {
439         arg = argv[i];
440         if (*arg != '-') {
441             break;
442         }
443         while (*++arg != '\0') {
444             if (*arg == 'c') {
445                 newfile++;
446             }
447             else if (*arg == 'n') {
448                 nofile++;
449                 args_left--;
450             }
451             else if (*arg == 'm') {
452                 alg = ALG_APMD5;
453             }
454             else if (*arg == 's') {
455                 alg = ALG_APSHA;
456             }
457             else if (*arg == 'p') {
458                 alg = ALG_PLAIN;
459             }
460             else if (*arg == 'd') {
461                 alg = ALG_CRYPT;
462             }
463             else if (*arg == 'b') {
464                 noninteractive++;
465                 args_left++;
466             }
467             else {
468                 return usage();
469             }
470         }
471     }
472
473     /*
474      * Make sure we still have exactly the right number of arguments left
475      * (the filename, the username, and possibly the password if -b was
476      * specified).
477      */
478     if ((argc - i) != args_left) {
479         return usage();
480     }
481     if (newfile && nofile) {
482         fprintf(stderr, "%s: -c and -n options conflict\n", argv[0]);
483         return ERR_SYNTAX;
484     }
485     if (nofile) {
486         i--;
487     }
488     else {
489         if (strlen(argv[i]) > (sizeof(pwfilename) - 1)) {
490             fprintf(stderr, "%s: filename too long\n", argv[0]);
491             return ERR_OVERFLOW;
492         }
493         strcpy(pwfilename, argv[i]);
494         if (strlen(argv[i + 1]) > (sizeof(user) - 1)) {
495             fprintf(stderr, "%s: username too long (>%" APR_SIZE_T_FMT ")\n",
496                 argv[0], sizeof(user) - 1);
497             return ERR_OVERFLOW;
498         }
499     }
500     strcpy(user, argv[i + 1]);
501     if ((arg = strchr(user, ':')) != NULL) {
502         fprintf(stderr, "%s: username contains illegal character '%c'\n",
503                 argv[0], *arg);
504         return ERR_BADUSER;
505     }
506     if (noninteractive) {
507         if (strlen(argv[i + 2]) > (sizeof(password) - 1)) {
508             fprintf(stderr, "%s: password too long (>%" APR_SIZE_T_FMT ")\n",
509                 argv[0], sizeof(password) - 1);
510             return ERR_OVERFLOW;
511         }
512         strcpy(password, argv[i + 2]);
513     }
514
515 #ifdef WIN32
516     if (alg == ALG_CRYPT) {
517         alg = ALG_APMD5;
518         fprintf(stderr, "Automatically using MD5 format on Windows.\n");
519     }
520 #endif
521
522 #if (!(defined(WIN32) || defined(TPF)))
523     if (alg == ALG_PLAIN) {
524         fprintf(stderr,"Warning: storing passwords as plain text might "
525                 "just not work on this platform.\n");
526     }
527 #endif
528     if (! nofile) {
529         /*
530          * Only do the file checks if we're supposed to frob it.
531          *
532          * Verify that the file exists if -c was omitted.  We give a special
533          * message if it doesn't.
534          */
535         if ((! newfile) && (! exists(pwfilename, pool))) {
536             fprintf(stderr,
537                     "%s: cannot modify file %s; use '-c' to create it\n",
538                     argv[0], pwfilename);
539             perror("fopen");
540             exit(ERR_FILEPERM);
541         }
542         /*
543          * Verify that we can read the existing file in the case of an update
544          * to it (rather than creation of a new one).
545          */
546         if ((! newfile) && (! readable(pwfilename))) {
547             fprintf(stderr, "%s: cannot open file %s for read access\n",
548                     argv[0], pwfilename);
549             perror("fopen");
550             exit(ERR_FILEPERM);
551         }
552         /*
553          * Now check to see if we can preserve an existing file in case
554          * of password verification errors on a -c operation.
555          */
556         if (newfile && exists(pwfilename) && (! readable(pwfilename))) {
557             fprintf(stderr, "%s: cannot open file %s for read access\n"
558                     "%s: existing auth data would be lost on "
559                     "password mismatch",
560                     argv[0], pwfilename, argv[0]);
561             perror("fopen");
562             exit(ERR_FILEPERM);
563         }
564         /*
565          * Now verify that the file is writable!
566          */
567         if (! writable(pwfilename)) {
568             fprintf(stderr, "%s: cannot open file %s for write access\n",
569                     argv[0], pwfilename);
570             perror("fopen");
571             exit(ERR_FILEPERM);
572         }
573     }
574
575     /*
576      * All the file access checks (if any) have been made.  Time to go to work;
577      * try to create the record for the username in question.  If that
578      * fails, there's no need to waste any time on file manipulations.
579      * Any error message text is returned in the record buffer, since
580      * the mkrecord() routine doesn't have access to argv[].
581      */
582     i = mkrecord(user, record, sizeof(record) - 1,
583                  noninteractive ? password : NULL,
584                  alg);
585     if (i != 0) {
586         fprintf(stderr, "%s: %s\n", argv[0], record);
587         exit(i);
588     }
589     if (nofile) {
590         printf("%s\n", record);
591         exit(0);
592     }
593
594     /*
595      * We can access the files the right way, and we have a record
596      * to add or update.  Let's do it..
597      */
598     errno = 0;
599     tempfilename = tmpnam(tname_buf);
600     if ((tempfilename == NULL) || (*tempfilename == '\0')) {
601         fprintf(stderr, "%s: unable to generate temporary filename\n",
602                 argv[0]);
603         if (errno == 0) {
604             errno = ENOENT;
605         }
606         perror("tmpnam");
607         exit(ERR_FILEPERM);
608     }
609     ftemp = fopen(tempfilename, "w+");
610     if (ftemp == NULL) {
611         fprintf(stderr, "%s: unable to create temporary file '%s'\n", argv[0],
612                 tempfilename);
613         perror("fopen");
614         exit(ERR_FILEPERM);
615     }
616     /*
617      * If we're not creating a new file, copy records from the existing
618      * one to the temporary file until we find the specified user.
619      */
620     if (! newfile) {
621         char scratch[MAX_STRING_LEN];
622
623         fpw = fopen(pwfilename, "r");
624         while (! (getline(line, sizeof(line), fpw))) {
625             char *colon;
626
627             if ((line[0] == '#') || (line[0] == '\0')) {
628                 putline(ftemp, line);
629                 continue;
630             }
631             strcpy(scratch, line);
632             /*
633              * See if this is our user.
634              */
635             colon = strchr(scratch, ':');
636             if (colon != NULL) {
637                 *colon = '\0';
638             }
639             if (strcmp(user, scratch) != 0) {
640                 putline(ftemp, line);
641                 continue;
642             }
643             found++;
644             break;
645         }
646     }
647     if (found) {
648         fprintf(stderr, "Updating ");
649     }
650     else {
651         fprintf(stderr, "Adding ");
652     }
653     fprintf(stderr, "password for user %s\n", user);
654     /*
655      * Now add the user record we created.
656      */
657     putline(ftemp, record);
658     /*
659      * If we're updating an existing file, there may be additional
660      * records beyond the one we're updating, so copy them.
661      */
662     if (! newfile) {
663         copy_file(ftemp, fpw);
664         fclose(fpw);
665     }
666     /*
667      * The temporary file now contains the information that should be
668      * in the actual password file.  Close the open files, re-open them
669      * in the appropriate mode, and copy them file to the real one.
670      */
671     fclose(ftemp);
672     fpw = fopen(pwfilename, "w+");
673     ftemp = fopen(tempfilename, "r");
674     copy_file(fpw, ftemp);
675     fclose(fpw);
676     fclose(ftemp);
677     unlink(tempfilename);
678     return 0;
679 }