]> granicus.if.org Git - apache/blob - support/htpasswd.c
describe the recent changes to mod_headers (%%, envclause everywhere)
[apache] / support / htpasswd.c
1 /* Copyright 1999-2004 The Apache Software Foundation
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 /******************************************************************************
17  ******************************************************************************
18  * NOTE! This program is not safe as a setuid executable!  Do not make it
19  * setuid!
20  ******************************************************************************
21  *****************************************************************************/
22 /*
23  * htpasswd.c: simple program for manipulating password file for
24  * the Apache HTTP server
25  * 
26  * Originally by Rob McCool
27  *
28  * Exit values:
29  *  0: Success
30  *  1: Failure; file access/permission problem
31  *  2: Failure; command line syntax problem (usage message issued)
32  *  3: Failure; password verification failure
33  *  4: Failure; operation interrupted (such as with CTRL/C)
34  *  5: Failure; buffer would overflow (username, filename, or computed
35  *     record too long)
36  *  6: Failure; username contains illegal or reserved characters
37  *  7: Failure; file is not a valid htpasswd file
38  */
39
40 #include "apr.h"
41 #include "apr_lib.h"
42 #include "apr_strings.h"
43 #include "apr_errno.h"
44 #include "apr_file_io.h"
45 #include "apr_general.h"
46 #include "apr_signal.h"
47
48 #if APR_HAVE_STDIO_H
49 #include <stdio.h>
50 #endif
51
52 #include "apr_md5.h"
53 #include "apr_sha1.h"
54 #include <time.h>
55
56 #if APR_HAVE_CRYPT_H
57 #include <crypt.h>
58 #endif
59 #if APR_HAVE_STDLIB_H
60 #include <stdlib.h>
61 #endif
62 #if APR_HAVE_STRING_H
63 #include <string.h>
64 #endif
65 #if APR_HAVE_UNISTD_H
66 #include <unistd.h>
67 #endif
68
69 #ifdef WIN32
70 #include <conio.h>
71 #define unlink _unlink
72 #endif
73
74 #if !APR_CHARSET_EBCDIC
75 #define LF 10
76 #define CR 13
77 #else /*APR_CHARSET_EBCDIC*/
78 #define LF '\n'
79 #define CR '\r'
80 #endif /*APR_CHARSET_EBCDIC*/
81
82 #define MAX_STRING_LEN 256
83 #define ALG_PLAIN 0
84 #define ALG_CRYPT 1
85 #define ALG_APMD5 2
86 #define ALG_APSHA 3 
87
88 #define ERR_FILEPERM 1
89 #define ERR_SYNTAX 2
90 #define ERR_PWMISMATCH 3
91 #define ERR_INTERRUPTED 4
92 #define ERR_OVERFLOW 5
93 #define ERR_BADUSER 6
94 #define ERR_INVALID 7
95
96 #define APHTP_NEWFILE        1
97 #define APHTP_NOFILE         2
98 #define APHTP_NONINTERACTIVE 4
99 #define APHTP_DELUSER        8
100
101 apr_file_t *errfile;
102 apr_file_t *ftemp = NULL;
103
104 static void to64(char *s, unsigned long v, int n)
105 {
106     static unsigned char itoa64[] =         /* 0 ... 63 => ASCII - 64 */
107         "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
108
109     while (--n >= 0) {
110         *s++ = itoa64[v&0x3f];
111         v >>= 6;
112     }
113 }
114
115 static void putline(apr_file_t *f, const char *l)
116 {
117     apr_file_puts(l, f);
118 }
119
120 /*
121  * Make a password record from the given information.  A zero return
122  * indicates success; failure means that the output buffer contains an
123  * error message instead.
124  */
125 static int mkrecord(char *user, char *record, apr_size_t rlen, char *passwd,
126                     int alg)
127 {
128     char *pw;
129     char cpw[120];
130     char pwin[MAX_STRING_LEN];
131     char pwv[MAX_STRING_LEN];
132     char salt[9];
133     apr_size_t bufsize;
134
135     if (passwd != NULL) {
136         pw = passwd;
137     }
138     else {
139         bufsize = sizeof(pwin);
140         if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
141             apr_snprintf(record, (rlen - 1), "password too long (>%" 
142                          APR_SIZE_T_FMT ")", sizeof(pwin) - 1);
143             return ERR_OVERFLOW;
144         }
145         bufsize = sizeof(pwv);
146         apr_password_get("Re-type new password: ", pwv, &bufsize);
147         if (strcmp(pwin, pwv) != 0) {
148             apr_cpystrn(record, "password verification error", (rlen - 1));
149             return ERR_PWMISMATCH;
150         }
151         pw = pwin;
152         memset(pwv, '\0', sizeof(pwin));
153     }
154     switch (alg) {
155
156     case ALG_APSHA:
157         /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
158         apr_sha1_base64(pw,strlen(pw),cpw);
159         break;
160
161     case ALG_APMD5: 
162         (void) srand((int) time((time_t *) NULL));
163         to64(&salt[0], rand(), 8);
164         salt[8] = '\0';
165
166         apr_md5_encode((const char *)pw, (const char *)salt,
167                      cpw, sizeof(cpw));
168         break;
169
170     case ALG_PLAIN:
171         /* XXX this len limitation is not in sync with any HTTPd len. */
172         apr_cpystrn(cpw,pw,sizeof(cpw));
173         break;
174
175 #if !(defined(WIN32) || defined(NETWARE))
176     case ALG_CRYPT:
177     default:
178         (void) srand((int) time((time_t *) NULL));
179         to64(&salt[0], rand(), 8);
180         salt[8] = '\0';
181
182         apr_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
183         break;
184 #endif
185     }
186     memset(pw, '\0', strlen(pw));
187
188     /*
189      * Check to see if the buffer is large enough to hold the username,
190      * hash, and delimiters.
191      */
192     if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
193         apr_cpystrn(record, "resultant record too long", (rlen - 1));
194         return ERR_OVERFLOW;
195     }
196     strcpy(record, user);
197     strcat(record, ":");
198     strcat(record, cpw);
199     strcat(record, "\n");
200     return 0;
201 }
202
203 static void usage(void)
204 {
205     apr_file_printf(errfile, "Usage:\n");
206     apr_file_printf(errfile, "\thtpasswd [-cmdpsD] passwordfile username\n");
207     apr_file_printf(errfile, "\thtpasswd -b[cmdpsD] passwordfile username "
208                     "password\n\n");
209     apr_file_printf(errfile, "\thtpasswd -n[mdps] username\n");
210     apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password\n");
211     apr_file_printf(errfile, " -c  Create a new file.\n");
212     apr_file_printf(errfile, " -n  Don't update file; display results on "
213                     "stdout.\n");
214     apr_file_printf(errfile, " -m  Force MD5 encryption of the password"
215 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
216         " (default)"
217 #endif
218         ".\n");
219     apr_file_printf(errfile, " -d  Force CRYPT encryption of the password"
220 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
221             " (default)"
222 #endif
223             ".\n");
224     apr_file_printf(errfile, " -p  Do not encrypt the password (plaintext).\n");
225     apr_file_printf(errfile, " -s  Force SHA encryption of the password.\n");
226     apr_file_printf(errfile, " -b  Use the password from the command line "
227             "rather than prompting for it.\n");
228     apr_file_printf(errfile, " -D  Delete the specified user.\n");
229     apr_file_printf(errfile,
230             "On Windows, NetWare and TPF systems the '-m' flag is used by "
231             "default.\n");
232     apr_file_printf(errfile,
233             "On all other systems, the '-p' flag will probably not work.\n");
234     exit(ERR_SYNTAX);
235 }
236
237 /*
238  * Check to see if the specified file can be opened for the given
239  * access.
240  */
241 static int accessible(apr_pool_t *pool, char *fname, int mode)
242 {
243     apr_file_t *f = NULL;
244
245     if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
246         return 0;
247     }
248     apr_file_close(f);
249     return 1;
250 }
251
252 /*
253  * Return true if the named file exists, regardless of permissions.
254  */
255 static int exists(char *fname, apr_pool_t *pool)
256 {
257     apr_finfo_t sbuf;
258     apr_status_t check;
259
260     check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
261     return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
262 }
263
264 static void terminate(void)
265 {
266     apr_terminate();
267 #ifdef NETWARE
268     pressanykey();
269 #endif
270 }
271
272 static void check_args(apr_pool_t *pool, int argc, const char *const argv[], 
273                        int *alg, int *mask, char **user, char **pwfilename, 
274                        char **password)
275 {
276     const char *arg;
277     int args_left = 2;
278     int i;
279
280     /*
281      * Preliminary check to make sure they provided at least
282      * three arguments, we'll do better argument checking as 
283      * we parse the command line.
284      */
285     if (argc < 3) {
286         usage();
287     }
288
289     /*
290      * Go through the argument list and pick out any options.  They
291      * have to precede any other arguments.
292      */
293     for (i = 1; i < argc; i++) {
294         arg = argv[i];
295         if (*arg != '-') {
296             break;
297         }
298         while (*++arg != '\0') {
299             if (*arg == 'c') {
300                 *mask |= APHTP_NEWFILE;
301             }
302             else if (*arg == 'n') {
303                 *mask |= APHTP_NOFILE;
304                 args_left--;
305             }
306             else if (*arg == 'm') {
307                 *alg = ALG_APMD5;
308             }
309             else if (*arg == 's') {
310                 *alg = ALG_APSHA;
311             }
312             else if (*arg == 'p') {
313                 *alg = ALG_PLAIN;
314             }
315             else if (*arg == 'd') {
316                 *alg = ALG_CRYPT;
317             }
318             else if (*arg == 'b') {
319                 *mask |= APHTP_NONINTERACTIVE;
320                 args_left++;
321             }
322             else if (*arg == 'D') {
323                 *mask |= APHTP_DELUSER;
324             }
325             else {
326                 usage();
327             }
328         }
329     }
330
331     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
332         apr_file_printf(errfile, "%s: -c and -n options conflict\n", argv[0]);
333         exit(ERR_SYNTAX);
334     }
335     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_DELUSER)) {
336         apr_file_printf(errfile, "%s: -c and -D options conflict\n", argv[0]);
337         exit(ERR_SYNTAX);
338     }
339     if ((*mask & APHTP_NOFILE) && (*mask & APHTP_DELUSER)) {
340         apr_file_printf(errfile, "%s: -n and -D options conflict\n", argv[0]);
341         exit(ERR_SYNTAX);
342     }
343     /*
344      * Make sure we still have exactly the right number of arguments left
345      * (the filename, the username, and possibly the password if -b was
346      * specified).
347      */
348     if ((argc - i) != args_left) {
349         usage();
350     }
351
352     if (*mask & APHTP_NOFILE) {
353         i--;
354     }
355     else {
356         if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
357             apr_file_printf(errfile, "%s: filename too long\n", argv[0]);
358             exit(ERR_OVERFLOW);
359         }
360         *pwfilename = apr_pstrdup(pool, argv[i]);
361         if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
362             apr_file_printf(errfile, "%s: username too long (> %d)\n",
363                 argv[0], MAX_STRING_LEN - 1);
364             exit(ERR_OVERFLOW);
365         }
366     }
367     *user = apr_pstrdup(pool, argv[i + 1]);
368     if ((arg = strchr(*user, ':')) != NULL) {
369         apr_file_printf(errfile, "%s: username contains illegal "
370                         "character '%c'\n", argv[0], *arg);
371         exit(ERR_BADUSER);
372     }
373     if (*mask & APHTP_NONINTERACTIVE) {
374         if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
375             apr_file_printf(errfile, "%s: password too long (> %d)\n",
376                 argv[0], MAX_STRING_LEN);
377             exit(ERR_OVERFLOW);
378         }
379         *password = apr_pstrdup(pool, argv[i + 2]);
380     }
381 }
382
383 /*
384  * Let's do it.  We end up doing a lot of file opening and closing,
385  * but what do we care?  This application isn't run constantly.
386  */
387 int main(int argc, const char * const argv[])
388 {
389     apr_file_t *fpw = NULL;
390     char record[MAX_STRING_LEN];
391     char line[MAX_STRING_LEN];
392     char *password = NULL;
393     char *pwfilename = NULL;
394     char *user = NULL;
395     char tn[] = "htpasswd.tmp.XXXXXX";
396     char *dirname;
397     char scratch[MAX_STRING_LEN];
398     int found = 0;
399     int i;
400     int alg = ALG_CRYPT;
401     int mask = 0;
402     apr_pool_t *pool;
403     int existing_file = 0;
404 #if APR_CHARSET_EBCDIC
405     apr_status_t rv;
406     apr_xlate_t *to_ascii;
407 #endif
408
409     apr_app_initialize(&argc, &argv, NULL);
410     atexit(terminate);
411     apr_pool_create(&pool, NULL);
412     apr_file_open_stderr(&errfile, pool);
413
414 #if APR_CHARSET_EBCDIC
415     rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
416     if (rv) {
417         apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d\n", rv);
418         exit(1);
419     }
420     rv = apr_SHA1InitEBCDIC(to_ascii);
421     if (rv) {
422         apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d\n", rv);
423         exit(1);
424     }
425     rv = apr_MD5InitEBCDIC(to_ascii);
426     if (rv) {
427         apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d\n", rv);
428         exit(1);
429     }
430 #endif /*APR_CHARSET_EBCDIC*/
431
432     check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
433
434
435 #if defined(WIN32) || defined(NETWARE)
436     if (alg == ALG_CRYPT) {
437         alg = ALG_APMD5;
438         apr_file_printf(errfile, "Automatically using MD5 format.\n");
439     }
440 #endif
441
442 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
443     if (alg == ALG_PLAIN) {
444         apr_file_printf(errfile,"Warning: storing passwords as plain text "
445                         "might just not work on this platform.\n");
446     }
447 #endif
448
449     /*
450      * Only do the file checks if we're supposed to frob it.
451      */
452     if (!(mask & APHTP_NOFILE)) {
453         existing_file = exists(pwfilename, pool);
454         if (existing_file) {
455             /*
456              * Check that this existing file is readable and writable.
457              */
458             if (!accessible(pool, pwfilename, APR_READ | APR_APPEND)) {
459                 apr_file_printf(errfile, "%s: cannot open file %s for "
460                                 "read/write access\n", argv[0], pwfilename);
461                 exit(ERR_FILEPERM);
462             }
463         }
464         else {
465             /*
466              * Error out if -c was omitted for this non-existant file.
467              */
468             if (!(mask & APHTP_NEWFILE)) {
469                 apr_file_printf(errfile,
470                         "%s: cannot modify file %s; use '-c' to create it\n",
471                         argv[0], pwfilename);
472                 exit(ERR_FILEPERM);
473             }
474             /*
475              * As it doesn't exist yet, verify that we can create it.
476              */
477             if (!accessible(pool, pwfilename, APR_CREATE | APR_WRITE)) {
478                 apr_file_printf(errfile, "%s: cannot create file %s\n",
479                                 argv[0], pwfilename);
480                 exit(ERR_FILEPERM);
481             }
482         }
483     }
484
485     /*
486      * All the file access checks (if any) have been made.  Time to go to work;
487      * try to create the record for the username in question.  If that
488      * fails, there's no need to waste any time on file manipulations.
489      * Any error message text is returned in the record buffer, since
490      * the mkrecord() routine doesn't have access to argv[].
491      */
492     if (!(mask & APHTP_DELUSER)) {
493         i = mkrecord(user, record, sizeof(record) - 1,
494                      password, alg);
495         if (i != 0) {
496             apr_file_printf(errfile, "%s: %s\n", argv[0], record);
497             exit(i);
498         }
499         if (mask & APHTP_NOFILE) {
500             printf("%s\n", record);
501             exit(0);
502         }
503     }
504
505     /*
506      * We can access the files the right way, and we have a record
507      * to add or update.  Let's do it..
508      */
509     if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) {
510         apr_file_printf(errfile, "%s: could not determine temp dir\n",
511                         argv[0]);
512         exit(ERR_FILEPERM);
513     }
514     dirname = apr_psprintf(pool, "%s/%s", dirname, tn);
515
516     if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) {
517         apr_file_printf(errfile, "%s: unable to create temporary file %s\n", 
518                         argv[0], dirname);
519         exit(ERR_FILEPERM);
520     }
521
522     /*
523      * If we're not creating a new file, copy records from the existing
524      * one to the temporary file until we find the specified user.
525      */
526     if (existing_file && !(mask & APHTP_NEWFILE)) {
527         if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED,
528                           APR_OS_DEFAULT, pool) != APR_SUCCESS) {
529             apr_file_printf(errfile, "%s: unable to read file %s\n", 
530                             argv[0], pwfilename);
531             exit(ERR_FILEPERM);
532         }
533         while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) {
534             char *colon;
535
536             if ((line[0] == '#') || (line[0] == '\0')) {
537                 putline(ftemp, line);
538                 continue;
539             }
540             strcpy(scratch, line);
541             /*
542              * See if this is our user.
543              */
544             colon = strchr(scratch, ':');
545             if (colon != NULL) {
546                 *colon = '\0';
547             }
548             else {
549                 /*
550                  * If we've not got a colon on the line, this could well 
551                  * not be a valid htpasswd file.
552                  * We should bail at this point.
553                  */
554                 apr_file_printf(errfile, "\n%s: The file %s does not appear "
555                                          "to be a valid htpasswd file.\n",
556                                 argv[0], pwfilename);
557                 apr_file_close(fpw);
558                 exit(ERR_INVALID);
559             }
560             if (strcmp(user, scratch) != 0) {
561                 putline(ftemp, line);
562                 continue;
563             }
564             else {
565                 if (!(mask & APHTP_DELUSER)) {
566                     /* We found the user we were looking for.
567                      * Add him to the file.
568                     */
569                     apr_file_printf(errfile, "Updating ");
570                     putline(ftemp, record);
571                     found++;
572                 }
573                 else {
574                     /* We found the user we were looking for.
575                      * Delete them from the file.
576                      */
577                     apr_file_printf(errfile, "Deleting ");
578                     found++;
579                 }
580             }
581         }
582         apr_file_close(fpw);
583     }
584     if (!found && !(mask & APHTP_DELUSER)) {
585         apr_file_printf(errfile, "Adding ");
586         putline(ftemp, record);
587     }
588     else if (!found && (mask & APHTP_DELUSER)) {
589         apr_file_printf(errfile, "User %s not found\n", user);
590         exit(0);
591     }
592     apr_file_printf(errfile, "password for user %s\n", user);
593
594     /* The temporary file has all the data, just copy it to the new location.
595      */
596     if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) !=
597         APR_SUCCESS) {
598         apr_file_printf(errfile, "%s: unable to update file %s\n", 
599                         argv[0], pwfilename);
600         exit(ERR_FILEPERM);
601     }
602     apr_file_close(ftemp);
603     return 0;
604 }