]> granicus.if.org Git - apache/blob - support/htpasswd.c
APR_FINFO_TYPE is all we really needed here.
[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_TYPE, pool);
359     return ((check || sbuf.filetype != APR_REG) ? 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     apr_pool_t *pool;
397 #if APR_CHARSET_EBCDIC
398     apr_status_t rv;
399     apr_xlate_t *to_ascii;
400 #endif
401
402     apr_initialize();
403     atexit(apr_terminate);
404     apr_pool_create(&pool, NULL);
405
406 #if APR_CHARSET_EBCDIC
407     rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
408     if (rv) {
409         fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", rv);
410         exit(1);
411     }
412     rv = apr_SHA1InitEBCDIC(to_ascii);
413     if (rv) {
414         fprintf(stderr, "apr_SHA1InitEBCDIC()->%d\n", rv);
415         exit(1);
416     }
417     rv = apr_MD5InitEBCDIC(to_ascii);
418     if (rv) {
419         fprintf(stderr, "apr_MD5InitEBCDIC()->%d\n", rv);
420         exit(1);
421     }
422 #endif /*APR_CHARSET_EBCDIC*/
423
424     tempfilename = NULL;
425     apr_signal(SIGINT, (void (*)(int)) interrupted);
426
427     /*
428      * Preliminary check to make sure they provided at least
429      * three arguments, we'll do better argument checking as 
430      * we parse the command line.
431      */
432     if (argc < 3) {
433         return usage();
434     }
435
436     /*
437      * Go through the argument list and pick out any options.  They
438      * have to precede any other arguments.
439      */
440     for (i = 1; i < argc; i++) {
441         arg = argv[i];
442         if (*arg != '-') {
443             break;
444         }
445         while (*++arg != '\0') {
446             if (*arg == 'c') {
447                 newfile++;
448             }
449             else if (*arg == 'n') {
450                 nofile++;
451                 args_left--;
452             }
453             else if (*arg == 'm') {
454                 alg = ALG_APMD5;
455             }
456             else if (*arg == 's') {
457                 alg = ALG_APSHA;
458             }
459             else if (*arg == 'p') {
460                 alg = ALG_PLAIN;
461             }
462             else if (*arg == 'd') {
463                 alg = ALG_CRYPT;
464             }
465             else if (*arg == 'b') {
466                 noninteractive++;
467                 args_left++;
468             }
469             else {
470                 return usage();
471             }
472         }
473     }
474
475     /*
476      * Make sure we still have exactly the right number of arguments left
477      * (the filename, the username, and possibly the password if -b was
478      * specified).
479      */
480     if ((argc - i) != args_left) {
481         return usage();
482     }
483     if (newfile && nofile) {
484         fprintf(stderr, "%s: -c and -n options conflict\n", argv[0]);
485         return ERR_SYNTAX;
486     }
487     if (nofile) {
488         i--;
489     }
490     else {
491         if (strlen(argv[i]) > (sizeof(pwfilename) - 1)) {
492             fprintf(stderr, "%s: filename too long\n", argv[0]);
493             return ERR_OVERFLOW;
494         }
495         strcpy(pwfilename, argv[i]);
496         if (strlen(argv[i + 1]) > (sizeof(user) - 1)) {
497             fprintf(stderr, "%s: username too long (>%" APR_SIZE_T_FMT ")\n",
498                 argv[0], sizeof(user) - 1);
499             return ERR_OVERFLOW;
500         }
501     }
502     strcpy(user, argv[i + 1]);
503     if ((arg = strchr(user, ':')) != NULL) {
504         fprintf(stderr, "%s: username contains illegal character '%c'\n",
505                 argv[0], *arg);
506         return ERR_BADUSER;
507     }
508     if (noninteractive) {
509         if (strlen(argv[i + 2]) > (sizeof(password) - 1)) {
510             fprintf(stderr, "%s: password too long (>%" APR_SIZE_T_FMT ")\n",
511                 argv[0], sizeof(password) - 1);
512             return ERR_OVERFLOW;
513         }
514         strcpy(password, argv[i + 2]);
515     }
516
517 #ifdef WIN32
518     if (alg == ALG_CRYPT) {
519         alg = ALG_APMD5;
520         fprintf(stderr, "Automatically using MD5 format on Windows.\n");
521     }
522 #endif
523
524 #if (!(defined(WIN32) || defined(TPF)))
525     if (alg == ALG_PLAIN) {
526         fprintf(stderr,"Warning: storing passwords as plain text might "
527                 "just not work on this platform.\n");
528     }
529 #endif
530     if (! nofile) {
531         /*
532          * Only do the file checks if we're supposed to frob it.
533          *
534          * Verify that the file exists if -c was omitted.  We give a special
535          * message if it doesn't.
536          */
537         if ((! newfile) && (! exists(pwfilename, pool))) {
538             fprintf(stderr,
539                     "%s: cannot modify file %s; use '-c' to create it\n",
540                     argv[0], pwfilename);
541             perror("fopen");
542             exit(ERR_FILEPERM);
543         }
544         /*
545          * Verify that we can read the existing file in the case of an update
546          * to it (rather than creation of a new one).
547          */
548         if ((! newfile) && (! readable(pwfilename))) {
549             fprintf(stderr, "%s: cannot open file %s for read access\n",
550                     argv[0], pwfilename);
551             perror("fopen");
552             exit(ERR_FILEPERM);
553         }
554         /*
555          * Now check to see if we can preserve an existing file in case
556          * of password verification errors on a -c operation.
557          */
558         if (newfile && exists(pwfilename, pool) && (! readable(pwfilename))) {
559             fprintf(stderr, "%s: cannot open file %s for read access\n"
560                     "%s: existing auth data would be lost on "
561                     "password mismatch",
562                     argv[0], pwfilename, argv[0]);
563             perror("fopen");
564             exit(ERR_FILEPERM);
565         }
566         /*
567          * Now verify that the file is writable!
568          */
569         if (! writable(pwfilename)) {
570             fprintf(stderr, "%s: cannot open file %s for write access\n",
571                     argv[0], pwfilename);
572             perror("fopen");
573             exit(ERR_FILEPERM);
574         }
575     }
576
577     /*
578      * All the file access checks (if any) have been made.  Time to go to work;
579      * try to create the record for the username in question.  If that
580      * fails, there's no need to waste any time on file manipulations.
581      * Any error message text is returned in the record buffer, since
582      * the mkrecord() routine doesn't have access to argv[].
583      */
584     i = mkrecord(user, record, sizeof(record) - 1,
585                  noninteractive ? password : NULL,
586                  alg);
587     if (i != 0) {
588         fprintf(stderr, "%s: %s\n", argv[0], record);
589         exit(i);
590     }
591     if (nofile) {
592         printf("%s\n", record);
593         exit(0);
594     }
595
596     /*
597      * We can access the files the right way, and we have a record
598      * to add or update.  Let's do it..
599      */
600     errno = 0;
601     tempfilename = tmpnam(tname_buf);
602     if ((tempfilename == NULL) || (*tempfilename == '\0')) {
603         fprintf(stderr, "%s: unable to generate temporary filename\n",
604                 argv[0]);
605         if (errno == 0) {
606             errno = ENOENT;
607         }
608         perror("tmpnam");
609         exit(ERR_FILEPERM);
610     }
611     ftemp = fopen(tempfilename, "w+");
612     if (ftemp == NULL) {
613         fprintf(stderr, "%s: unable to create temporary file '%s'\n", argv[0],
614                 tempfilename);
615         perror("fopen");
616         exit(ERR_FILEPERM);
617     }
618     /*
619      * If we're not creating a new file, copy records from the existing
620      * one to the temporary file until we find the specified user.
621      */
622     if (! newfile) {
623         char scratch[MAX_STRING_LEN];
624
625         fpw = fopen(pwfilename, "r");
626         while (! (getline(line, sizeof(line), fpw))) {
627             char *colon;
628
629             if ((line[0] == '#') || (line[0] == '\0')) {
630                 putline(ftemp, line);
631                 continue;
632             }
633             strcpy(scratch, line);
634             /*
635              * See if this is our user.
636              */
637             colon = strchr(scratch, ':');
638             if (colon != NULL) {
639                 *colon = '\0';
640             }
641             if (strcmp(user, scratch) != 0) {
642                 putline(ftemp, line);
643                 continue;
644             }
645             found++;
646             break;
647         }
648     }
649     if (found) {
650         fprintf(stderr, "Updating ");
651     }
652     else {
653         fprintf(stderr, "Adding ");
654     }
655     fprintf(stderr, "password for user %s\n", user);
656     /*
657      * Now add the user record we created.
658      */
659     putline(ftemp, record);
660     /*
661      * If we're updating an existing file, there may be additional
662      * records beyond the one we're updating, so copy them.
663      */
664     if (! newfile) {
665         copy_file(ftemp, fpw);
666         fclose(fpw);
667     }
668     /*
669      * The temporary file now contains the information that should be
670      * in the actual password file.  Close the open files, re-open them
671      * in the appropriate mode, and copy them file to the real one.
672      */
673     fclose(ftemp);
674     fpw = fopen(pwfilename, "w+");
675     ftemp = fopen(tempfilename, "r");
676     copy_file(fpw, ftemp);
677     fclose(fpw);
678     fclose(ftemp);
679     unlink(tempfilename);
680     return 0;
681 }