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