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