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