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