Moved apache code into a folder to help prepare for packaging where we dont want...
[httpd-crcsyncproxy.git] / apache / support / htpasswd.c
blobc94f2a757342bf1d0f097d8a4d8a98ebdce8d9f3
1 /* Licensed to the Apache Software Foundation (ASF) under one or more
2 * contributor license agreements. See the NOTICE file distributed with
3 * this work for additional information regarding copyright ownership.
4 * The ASF licenses this file to You under the Apache License, Version 2.0
5 * (the "License"); you may not use this file except in compliance with
6 * the License. You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 /******************************************************************************
18 ******************************************************************************
19 * NOTE! This program is not safe as a setuid executable! Do not make it
20 * setuid!
21 ******************************************************************************
22 *****************************************************************************/
24 * htpasswd.c: simple program for manipulating password file for
25 * the Apache HTTP server
27 * Originally by Rob McCool
29 * Exit values:
30 * 0: Success
31 * 1: Failure; file access/permission problem
32 * 2: Failure; command line syntax problem (usage message issued)
33 * 3: Failure; password verification failure
34 * 4: Failure; operation interrupted (such as with CTRL/C)
35 * 5: Failure; buffer would overflow (username, filename, or computed
36 * record too long)
37 * 6: Failure; username contains illegal or reserved characters
38 * 7: Failure; file is not a valid htpasswd file
41 #include "apr.h"
42 #include "apr_lib.h"
43 #include "apr_strings.h"
44 #include "apr_errno.h"
45 #include "apr_file_io.h"
46 #include "apr_general.h"
47 #include "apr_signal.h"
49 #if APR_HAVE_STDIO_H
50 #include <stdio.h>
51 #endif
53 #include "apr_md5.h"
54 #include "apr_sha1.h"
55 #include <time.h>
57 #if APR_HAVE_CRYPT_H
58 #include <crypt.h>
59 #endif
60 #if APR_HAVE_STDLIB_H
61 #include <stdlib.h>
62 #endif
63 #if APR_HAVE_STRING_H
64 #include <string.h>
65 #endif
66 #if APR_HAVE_UNISTD_H
67 #include <unistd.h>
68 #endif
70 #ifdef WIN32
71 #include <conio.h>
72 #define unlink _unlink
73 #endif
75 #if !APR_CHARSET_EBCDIC
76 #define LF 10
77 #define CR 13
78 #else /*APR_CHARSET_EBCDIC*/
79 #define LF '\n'
80 #define CR '\r'
81 #endif /*APR_CHARSET_EBCDIC*/
83 #define MAX_STRING_LEN 256
84 #define ALG_PLAIN 0
85 #define ALG_CRYPT 1
86 #define ALG_APMD5 2
87 #define ALG_APSHA 3
89 #define ERR_FILEPERM 1
90 #define ERR_SYNTAX 2
91 #define ERR_PWMISMATCH 3
92 #define ERR_INTERRUPTED 4
93 #define ERR_OVERFLOW 5
94 #define ERR_BADUSER 6
95 #define ERR_INVALID 7
97 #define APHTP_NEWFILE 1
98 #define APHTP_NOFILE 2
99 #define APHTP_NONINTERACTIVE 4
100 #define APHTP_DELUSER 8
102 apr_file_t *errfile;
103 apr_file_t *ftemp = NULL;
105 #define NL APR_EOL_STR
107 static void to64(char *s, unsigned long v, int n)
109 static unsigned char itoa64[] = /* 0 ... 63 => ASCII - 64 */
110 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
112 while (--n >= 0) {
113 *s++ = itoa64[v&0x3f];
114 v >>= 6;
118 static void generate_salt(char *s, size_t size)
120 static unsigned char tbl[] =
121 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
122 size_t i;
123 for (i = 0; i < size; ++i) {
124 int idx = (int) (64.0 * rand() / (RAND_MAX + 1.0));
125 s[i] = tbl[idx];
129 static apr_status_t seed_rand(void)
131 int seed = 0;
132 apr_status_t rv;
133 rv = apr_generate_random_bytes((unsigned char*) &seed, sizeof(seed));
134 if (rv) {
135 apr_file_printf(errfile, "Unable to generate random bytes: %pm" NL, &rv);
136 return rv;
138 srand(seed);
139 return rv;
142 static void putline(apr_file_t *f, const char *l)
144 apr_file_puts(l, f);
148 * Make a password record from the given information. A zero return
149 * indicates success; failure means that the output buffer contains an
150 * error message instead.
152 static int mkrecord(char *user, char *record, apr_size_t rlen, char *passwd,
153 int alg)
155 char *pw;
156 char cpw[120];
157 char pwin[MAX_STRING_LEN];
158 char pwv[MAX_STRING_LEN];
159 char salt[9];
160 apr_size_t bufsize;
162 if (passwd != NULL) {
163 pw = passwd;
165 else {
166 bufsize = sizeof(pwin);
167 if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
168 apr_snprintf(record, (rlen - 1), "password too long (>%"
169 APR_SIZE_T_FMT ")", sizeof(pwin) - 1);
170 return ERR_OVERFLOW;
172 bufsize = sizeof(pwv);
173 apr_password_get("Re-type new password: ", pwv, &bufsize);
174 if (strcmp(pwin, pwv) != 0) {
175 apr_cpystrn(record, "password verification error", (rlen - 1));
176 return ERR_PWMISMATCH;
178 pw = pwin;
179 memset(pwv, '\0', sizeof(pwin));
181 switch (alg) {
183 case ALG_APSHA:
184 /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
185 apr_sha1_base64(pw,strlen(pw),cpw);
186 break;
188 case ALG_APMD5:
189 if (seed_rand()) {
190 break;
192 generate_salt(&salt[0], 8);
193 salt[8] = '\0';
195 apr_md5_encode((const char *)pw, (const char *)salt,
196 cpw, sizeof(cpw));
197 break;
199 case ALG_PLAIN:
200 /* XXX this len limitation is not in sync with any HTTPd len. */
201 apr_cpystrn(cpw,pw,sizeof(cpw));
202 break;
204 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
205 case ALG_CRYPT:
206 default:
207 if (seed_rand()) {
208 break;
210 to64(&salt[0], rand(), 8);
211 salt[8] = '\0';
213 apr_cpystrn(cpw, crypt(pw, salt), sizeof(cpw) - 1);
214 break;
215 #endif
217 memset(pw, '\0', strlen(pw));
220 * Check to see if the buffer is large enough to hold the username,
221 * hash, and delimiters.
223 if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
224 apr_cpystrn(record, "resultant record too long", (rlen - 1));
225 return ERR_OVERFLOW;
227 strcpy(record, user);
228 strcat(record, ":");
229 strcat(record, cpw);
230 strcat(record, "\n");
231 return 0;
234 static void usage(void)
236 apr_file_printf(errfile, "Usage:" NL);
237 apr_file_printf(errfile, "\thtpasswd [-cmdpsD] passwordfile username" NL);
238 apr_file_printf(errfile, "\thtpasswd -b[cmdpsD] passwordfile username "
239 "password" NL NL);
240 apr_file_printf(errfile, "\thtpasswd -n[mdps] username" NL);
241 apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password" NL);
242 apr_file_printf(errfile, " -c Create a new file." NL);
243 apr_file_printf(errfile, " -n Don't update file; display results on "
244 "stdout." NL);
245 apr_file_printf(errfile, " -m Force MD5 encryption of the password"
246 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
247 " (default)"
248 #endif
249 "." NL);
250 apr_file_printf(errfile, " -d Force CRYPT encryption of the password"
251 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
252 " (default)"
253 #endif
254 "." NL);
255 apr_file_printf(errfile, " -p Do not encrypt the password (plaintext)." NL);
256 apr_file_printf(errfile, " -s Force SHA encryption of the password." NL);
257 apr_file_printf(errfile, " -b Use the password from the command line "
258 "rather than prompting for it." NL);
259 apr_file_printf(errfile, " -D Delete the specified user." NL);
260 apr_file_printf(errfile,
261 "On Windows, NetWare and TPF systems the '-m' flag is used by "
262 "default." NL);
263 apr_file_printf(errfile,
264 "On all other systems, the '-p' flag will probably not work." NL);
265 exit(ERR_SYNTAX);
269 * Check to see if the specified file can be opened for the given
270 * access.
272 static int accessible(apr_pool_t *pool, char *fname, int mode)
274 apr_file_t *f = NULL;
276 if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
277 return 0;
279 apr_file_close(f);
280 return 1;
284 * Return true if the named file exists, regardless of permissions.
286 static int exists(char *fname, apr_pool_t *pool)
288 apr_finfo_t sbuf;
289 apr_status_t check;
291 check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
292 return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
295 static void terminate(void)
297 apr_terminate();
298 #ifdef NETWARE
299 pressanykey();
300 #endif
303 static void check_args(apr_pool_t *pool, int argc, const char *const argv[],
304 int *alg, int *mask, char **user, char **pwfilename,
305 char **password)
307 const char *arg;
308 int args_left = 2;
309 int i;
312 * Preliminary check to make sure they provided at least
313 * three arguments, we'll do better argument checking as
314 * we parse the command line.
316 if (argc < 3) {
317 usage();
321 * Go through the argument list and pick out any options. They
322 * have to precede any other arguments.
324 for (i = 1; i < argc; i++) {
325 arg = argv[i];
326 if (*arg != '-') {
327 break;
329 while (*++arg != '\0') {
330 if (*arg == 'c') {
331 *mask |= APHTP_NEWFILE;
333 else if (*arg == 'n') {
334 *mask |= APHTP_NOFILE;
335 args_left--;
337 else if (*arg == 'm') {
338 *alg = ALG_APMD5;
340 else if (*arg == 's') {
341 *alg = ALG_APSHA;
343 else if (*arg == 'p') {
344 *alg = ALG_PLAIN;
346 else if (*arg == 'd') {
347 *alg = ALG_CRYPT;
349 else if (*arg == 'b') {
350 *mask |= APHTP_NONINTERACTIVE;
351 args_left++;
353 else if (*arg == 'D') {
354 *mask |= APHTP_DELUSER;
356 else {
357 usage();
362 if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
363 apr_file_printf(errfile, "%s: -c and -n options conflict" NL, argv[0]);
364 exit(ERR_SYNTAX);
366 if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_DELUSER)) {
367 apr_file_printf(errfile, "%s: -c and -D options conflict" NL, argv[0]);
368 exit(ERR_SYNTAX);
370 if ((*mask & APHTP_NOFILE) && (*mask & APHTP_DELUSER)) {
371 apr_file_printf(errfile, "%s: -n and -D options conflict" NL, argv[0]);
372 exit(ERR_SYNTAX);
375 * Make sure we still have exactly the right number of arguments left
376 * (the filename, the username, and possibly the password if -b was
377 * specified).
379 if ((argc - i) != args_left) {
380 usage();
383 if (*mask & APHTP_NOFILE) {
384 i--;
386 else {
387 if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
388 apr_file_printf(errfile, "%s: filename too long" NL, argv[0]);
389 exit(ERR_OVERFLOW);
391 *pwfilename = apr_pstrdup(pool, argv[i]);
392 if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
393 apr_file_printf(errfile, "%s: username too long (> %d)" NL,
394 argv[0], MAX_STRING_LEN - 1);
395 exit(ERR_OVERFLOW);
398 *user = apr_pstrdup(pool, argv[i + 1]);
399 if ((arg = strchr(*user, ':')) != NULL) {
400 apr_file_printf(errfile, "%s: username contains illegal "
401 "character '%c'" NL, argv[0], *arg);
402 exit(ERR_BADUSER);
404 if (*mask & APHTP_NONINTERACTIVE) {
405 if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
406 apr_file_printf(errfile, "%s: password too long (> %d)" NL,
407 argv[0], MAX_STRING_LEN);
408 exit(ERR_OVERFLOW);
410 *password = apr_pstrdup(pool, argv[i + 2]);
415 * Let's do it. We end up doing a lot of file opening and closing,
416 * but what do we care? This application isn't run constantly.
418 int main(int argc, const char * const argv[])
420 apr_file_t *fpw = NULL;
421 char record[MAX_STRING_LEN];
422 char line[MAX_STRING_LEN];
423 char *password = NULL;
424 char *pwfilename = NULL;
425 char *user = NULL;
426 char tn[] = "htpasswd.tmp.XXXXXX";
427 char *dirname;
428 char *scratch, cp[MAX_STRING_LEN];
429 int found = 0;
430 int i;
431 int alg = ALG_CRYPT;
432 int mask = 0;
433 apr_pool_t *pool;
434 int existing_file = 0;
435 #if APR_CHARSET_EBCDIC
436 apr_status_t rv;
437 apr_xlate_t *to_ascii;
438 #endif
440 apr_app_initialize(&argc, &argv, NULL);
441 atexit(terminate);
442 apr_pool_create(&pool, NULL);
443 apr_file_open_stderr(&errfile, pool);
445 #if APR_CHARSET_EBCDIC
446 rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, pool);
447 if (rv) {
448 apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d" NL, rv);
449 exit(1);
451 rv = apr_SHA1InitEBCDIC(to_ascii);
452 if (rv) {
453 apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d" NL, rv);
454 exit(1);
456 rv = apr_MD5InitEBCDIC(to_ascii);
457 if (rv) {
458 apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d" NL, rv);
459 exit(1);
461 #endif /*APR_CHARSET_EBCDIC*/
463 check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
466 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
467 if (alg == ALG_CRYPT) {
468 alg = ALG_APMD5;
469 apr_file_printf(errfile, "Automatically using MD5 format." NL);
471 #endif
473 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
474 if (alg == ALG_PLAIN) {
475 apr_file_printf(errfile,"Warning: storing passwords as plain text "
476 "might just not work on this platform." NL);
478 #endif
481 * Only do the file checks if we're supposed to frob it.
483 if (!(mask & APHTP_NOFILE)) {
484 existing_file = exists(pwfilename, pool);
485 if (existing_file) {
487 * Check that this existing file is readable and writable.
489 if (!accessible(pool, pwfilename, APR_READ | APR_APPEND)) {
490 apr_file_printf(errfile, "%s: cannot open file %s for "
491 "read/write access" NL, argv[0], pwfilename);
492 exit(ERR_FILEPERM);
495 else {
497 * Error out if -c was omitted for this non-existant file.
499 if (!(mask & APHTP_NEWFILE)) {
500 apr_file_printf(errfile,
501 "%s: cannot modify file %s; use '-c' to create it" NL,
502 argv[0], pwfilename);
503 exit(ERR_FILEPERM);
506 * As it doesn't exist yet, verify that we can create it.
508 if (!accessible(pool, pwfilename, APR_CREATE | APR_WRITE)) {
509 apr_file_printf(errfile, "%s: cannot create file %s" NL,
510 argv[0], pwfilename);
511 exit(ERR_FILEPERM);
517 * All the file access checks (if any) have been made. Time to go to work;
518 * try to create the record for the username in question. If that
519 * fails, there's no need to waste any time on file manipulations.
520 * Any error message text is returned in the record buffer, since
521 * the mkrecord() routine doesn't have access to argv[].
523 if (!(mask & APHTP_DELUSER)) {
524 i = mkrecord(user, record, sizeof(record) - 1,
525 password, alg);
526 if (i != 0) {
527 apr_file_printf(errfile, "%s: %s" NL, argv[0], record);
528 exit(i);
530 if (mask & APHTP_NOFILE) {
531 printf("%s" NL, record);
532 exit(0);
537 * We can access the files the right way, and we have a record
538 * to add or update. Let's do it..
540 if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) {
541 apr_file_printf(errfile, "%s: could not determine temp dir" NL,
542 argv[0]);
543 exit(ERR_FILEPERM);
545 dirname = apr_psprintf(pool, "%s/%s", dirname, tn);
547 if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) {
548 apr_file_printf(errfile, "%s: unable to create temporary file %s" NL,
549 argv[0], dirname);
550 exit(ERR_FILEPERM);
554 * If we're not creating a new file, copy records from the existing
555 * one to the temporary file until we find the specified user.
557 if (existing_file && !(mask & APHTP_NEWFILE)) {
558 if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED,
559 APR_OS_DEFAULT, pool) != APR_SUCCESS) {
560 apr_file_printf(errfile, "%s: unable to read file %s" NL,
561 argv[0], pwfilename);
562 exit(ERR_FILEPERM);
564 while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) {
565 char *colon;
567 strcpy(cp, line);
568 scratch = cp;
569 while (apr_isspace(*scratch)) {
570 ++scratch;
573 if (!*scratch || (*scratch == '#')) {
574 putline(ftemp, line);
575 continue;
578 * See if this is our user.
580 colon = strchr(scratch, ':');
581 if (colon != NULL) {
582 *colon = '\0';
584 else {
586 * If we've not got a colon on the line, this could well
587 * not be a valid htpasswd file.
588 * We should bail at this point.
590 apr_file_printf(errfile, "%s: The file %s does not appear "
591 "to be a valid htpasswd file." NL,
592 argv[0], pwfilename);
593 apr_file_close(fpw);
594 exit(ERR_INVALID);
596 if (strcmp(user, scratch) != 0) {
597 putline(ftemp, line);
598 continue;
600 else {
601 if (!(mask & APHTP_DELUSER)) {
602 /* We found the user we were looking for.
603 * Add him to the file.
605 apr_file_printf(errfile, "Updating ");
606 putline(ftemp, record);
607 found++;
609 else {
610 /* We found the user we were looking for.
611 * Delete them from the file.
613 apr_file_printf(errfile, "Deleting ");
614 found++;
618 apr_file_close(fpw);
620 if (!found && !(mask & APHTP_DELUSER)) {
621 apr_file_printf(errfile, "Adding ");
622 putline(ftemp, record);
624 else if (!found && (mask & APHTP_DELUSER)) {
625 apr_file_printf(errfile, "User %s not found" NL, user);
626 exit(0);
628 apr_file_printf(errfile, "password for user %s" NL, user);
630 /* The temporary file has all the data, just copy it to the new location.
632 if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) !=
633 APR_SUCCESS) {
634 apr_file_printf(errfile, "%s: unable to update file %s" NL,
635 argv[0], pwfilename);
636 exit(ERR_FILEPERM);
638 apr_file_close(ftemp);
639 return 0;