1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2001 The Apache Software Foundation. All rights
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
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
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.
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.
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.
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
47 * ====================================================================
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/>.
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.
59 /******************************************************************************
60 ******************************************************************************
61 * NOTE! This program is not safe as a setuid executable! Do not make it
63 ******************************************************************************
64 *****************************************************************************/
66 * htpasswd.c: simple program for manipulating password file for
67 * the Apache HTTP server
69 * Originally by Rob McCool
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
79 * 6: Failure; username contains illegal or reserved characters
84 #include "apr_strings.h"
85 #include "apr_errno.h"
86 #include "apr_file_io.h"
87 #include "apr_general.h"
88 #include "apr_signal.h"
101 #if APR_HAVE_STDLIB_H
104 #if APR_HAVE_STRING_H
107 #if APR_HAVE_UNISTD_H
113 #define unlink _unlink
116 #if !APR_CHARSET_EBCDIC
119 #else /*APR_CHARSET_EBCDIC*/
122 #endif /*APR_CHARSET_EBCDIC*/
124 #define MAX_STRING_LEN 256
130 #define ERR_FILEPERM 1
132 #define ERR_PWMISMATCH 3
133 #define ERR_INTERRUPTED 4
134 #define ERR_OVERFLOW 5
135 #define ERR_BADUSER 6
138 * This needs to be declared statically so the signal handler can
141 static char *tempfilename;
143 * If our platform knows about the tmpnam() external buffer size, create
144 * a buffer to pass in. This is needed in a threaded environment, or
145 * one that thinks it is (like HP-UX).
148 static char tname_buf[L_tmpnam];
150 static char *tname_buf = NULL;
154 * Get a line of input from the user, not including any terminating
157 static int getline(char *s, int n, FILE *f)
162 s[i] = (char) fgetc(f);
168 if ((s[i] == 0x4) || (s[i] == LF) || (i == (n - 1))) {
170 return (feof(f) ? 1 : 0);
176 static void putline(FILE *f, char *l)
180 for (x = 0; l[x]; x++) {
186 static void to64(char *s, unsigned long v, int n)
188 static unsigned char itoa64[] = /* 0 ... 63 => ASCII - 64 */
189 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
192 *s++ = itoa64[v&0x3f];
198 * Make a password record from the given information. A zero return
199 * indicates success; failure means that the output buffer contains an
200 * error message instead.
202 static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
207 char pwin[MAX_STRING_LEN];
208 char pwv[MAX_STRING_LEN];
212 if (passwd != NULL) {
216 bufsize = sizeof(pwin);
217 if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
218 apr_snprintf(record, (rlen - 1), "password too long (>%" APR_SIZE_T_FMT
219 ")", sizeof(pwin) - 1);
222 bufsize = sizeof(pwv);
223 apr_password_get("Re-type new password: ", pwv, &bufsize);
224 if (strcmp(pwin, pwv) != 0) {
225 apr_cpystrn(record, "password verification error", (rlen - 1));
226 return ERR_PWMISMATCH;
229 memset(pwv, '\0', sizeof(pwin));
234 /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
235 apr_sha1_base64(pw,strlen(pw),cpw);
239 (void) srand((int) time((time_t *) NULL));
240 to64(&salt[0], rand(), 8);
243 apr_md5_encode((const char *)pw, (const char *)salt,
248 /* XXX this len limitation is not in sync with any HTTPd len. */
249 apr_cpystrn(cpw,pw,sizeof(cpw));
255 (void) srand((int) time((time_t *) NULL));
256 to64(&salt[0], rand(), 8);
259 apr_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
263 memset(pw, '\0', strlen(pw));
266 * Check to see if the buffer is large enough to hold the username,
267 * hash, and delimiters.
269 if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
270 apr_cpystrn(record, "resultant record too long", (rlen - 1));
273 strcpy(record, user);
279 static int usage(void)
281 fprintf(stderr, "Usage:\n");
282 fprintf(stderr, "\thtpasswd [-cmdps] passwordfile username\n");
283 fprintf(stderr, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
284 fprintf(stderr, "\thtpasswd -n[mdps] username\n");
285 fprintf(stderr, "\thtpasswd -nb[mdps] username password\n");
286 fprintf(stderr, " -c Create a new file.\n");
287 fprintf(stderr, " -n Don't update file; display results on stdout.\n");
288 fprintf(stderr, " -m Force MD5 encryption of the password"
289 #if defined(WIN32) || defined(TPF)
293 fprintf(stderr, " -d Force CRYPT encryption of the password"
294 #if (!(defined(WIN32) || defined(TPF)))
298 fprintf(stderr, " -p Do not encrypt the password (plaintext).\n");
299 fprintf(stderr, " -s Force SHA encryption of the password.\n");
300 fprintf(stderr, " -b Use the password from the command line rather "
301 "than prompting for it.\n");
303 "On Windows and TPF systems the '-m' flag is used by default.\n");
305 "On all other systems, the '-p' flag will probably not work.\n");
309 static void interrupted(void)
311 fprintf(stderr, "Interrupted.\n");
312 if (tempfilename != NULL) {
313 unlink(tempfilename);
315 exit(ERR_INTERRUPTED);
319 * Check to see if the specified file can be opened for the given
322 static int accessible(char *fname, char *mode)
326 s = fopen(fname, mode);
335 * Return true if a file is readable.
337 static int readable(char *fname)
339 return accessible(fname, "r");
343 * Return true if the specified file can be opened for write access.
345 static int writable(char *fname)
347 return accessible(fname, "a");
351 * Return true if the named file exists, regardless of permissions.
353 static int exists(char *fname, apr_pool_t *pool)
358 check = apr_stat(&sbuf, fname, APR_FINFO_NORM, pool);
359 return (check ? 0 : 1);
363 * Copy from the current position of one file to the current position
366 static void copy_file(FILE *target, FILE *source)
368 static char line[MAX_STRING_LEN];
370 while (fgets(line, sizeof(line), source) != NULL) {
376 * Let's do it. We end up doing a lot of file opening and closing,
377 * but what do we care? This application isn't run constantly.
379 int main(int argc, char *argv[])
383 char user[MAX_STRING_LEN];
384 char password[MAX_STRING_LEN];
385 char record[MAX_STRING_LEN];
386 char line[MAX_STRING_LEN];
387 char pwfilename[MAX_STRING_LEN];
393 int noninteractive = 0;
396 #if APR_CHARSET_EBCDIC
399 apr_xlate_t *to_ascii;
402 atexit(apr_terminate);
403 apr_pool_create(&pool, NULL);
405 rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
407 fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", rv);
410 rv = apr_SHA1InitEBCDIC(to_ascii);
412 fprintf(stderr, "apr_SHA1InitEBCDIC()->%d\n", rv);
415 rv = apr_MD5InitEBCDIC(to_ascii);
417 fprintf(stderr, "apr_MD5InitEBCDIC()->%d\n", rv);
420 #endif /*APR_CHARSET_EBCDIC*/
423 apr_signal(SIGINT, (void (*)(int)) interrupted);
426 * Preliminary check to make sure they provided at least
427 * three arguments, we'll do better argument checking as
428 * we parse the command line.
435 * Go through the argument list and pick out any options. They
436 * have to precede any other arguments.
438 for (i = 1; i < argc; i++) {
443 while (*++arg != '\0') {
447 else if (*arg == 'n') {
451 else if (*arg == 'm') {
454 else if (*arg == 's') {
457 else if (*arg == 'p') {
460 else if (*arg == 'd') {
463 else if (*arg == 'b') {
474 * Make sure we still have exactly the right number of arguments left
475 * (the filename, the username, and possibly the password if -b was
478 if ((argc - i) != args_left) {
481 if (newfile && nofile) {
482 fprintf(stderr, "%s: -c and -n options conflict\n", argv[0]);
489 if (strlen(argv[i]) > (sizeof(pwfilename) - 1)) {
490 fprintf(stderr, "%s: filename too long\n", argv[0]);
493 strcpy(pwfilename, argv[i]);
494 if (strlen(argv[i + 1]) > (sizeof(user) - 1)) {
495 fprintf(stderr, "%s: username too long (>%" APR_SIZE_T_FMT ")\n",
496 argv[0], sizeof(user) - 1);
500 strcpy(user, argv[i + 1]);
501 if ((arg = strchr(user, ':')) != NULL) {
502 fprintf(stderr, "%s: username contains illegal character '%c'\n",
506 if (noninteractive) {
507 if (strlen(argv[i + 2]) > (sizeof(password) - 1)) {
508 fprintf(stderr, "%s: password too long (>%" APR_SIZE_T_FMT ")\n",
509 argv[0], sizeof(password) - 1);
512 strcpy(password, argv[i + 2]);
516 if (alg == ALG_CRYPT) {
518 fprintf(stderr, "Automatically using MD5 format on Windows.\n");
522 #if (!(defined(WIN32) || defined(TPF)))
523 if (alg == ALG_PLAIN) {
524 fprintf(stderr,"Warning: storing passwords as plain text might "
525 "just not work on this platform.\n");
530 * Only do the file checks if we're supposed to frob it.
532 * Verify that the file exists if -c was omitted. We give a special
533 * message if it doesn't.
535 if ((! newfile) && (! exists(pwfilename, pool))) {
537 "%s: cannot modify file %s; use '-c' to create it\n",
538 argv[0], pwfilename);
543 * Verify that we can read the existing file in the case of an update
544 * to it (rather than creation of a new one).
546 if ((! newfile) && (! readable(pwfilename))) {
547 fprintf(stderr, "%s: cannot open file %s for read access\n",
548 argv[0], pwfilename);
553 * Now check to see if we can preserve an existing file in case
554 * of password verification errors on a -c operation.
556 if (newfile && exists(pwfilename) && (! readable(pwfilename))) {
557 fprintf(stderr, "%s: cannot open file %s for read access\n"
558 "%s: existing auth data would be lost on "
560 argv[0], pwfilename, argv[0]);
565 * Now verify that the file is writable!
567 if (! writable(pwfilename)) {
568 fprintf(stderr, "%s: cannot open file %s for write access\n",
569 argv[0], pwfilename);
576 * All the file access checks (if any) have been made. Time to go to work;
577 * try to create the record for the username in question. If that
578 * fails, there's no need to waste any time on file manipulations.
579 * Any error message text is returned in the record buffer, since
580 * the mkrecord() routine doesn't have access to argv[].
582 i = mkrecord(user, record, sizeof(record) - 1,
583 noninteractive ? password : NULL,
586 fprintf(stderr, "%s: %s\n", argv[0], record);
590 printf("%s\n", record);
595 * We can access the files the right way, and we have a record
596 * to add or update. Let's do it..
599 tempfilename = tmpnam(tname_buf);
600 if ((tempfilename == NULL) || (*tempfilename == '\0')) {
601 fprintf(stderr, "%s: unable to generate temporary filename\n",
609 ftemp = fopen(tempfilename, "w+");
611 fprintf(stderr, "%s: unable to create temporary file '%s'\n", argv[0],
617 * If we're not creating a new file, copy records from the existing
618 * one to the temporary file until we find the specified user.
621 char scratch[MAX_STRING_LEN];
623 fpw = fopen(pwfilename, "r");
624 while (! (getline(line, sizeof(line), fpw))) {
627 if ((line[0] == '#') || (line[0] == '\0')) {
628 putline(ftemp, line);
631 strcpy(scratch, line);
633 * See if this is our user.
635 colon = strchr(scratch, ':');
639 if (strcmp(user, scratch) != 0) {
640 putline(ftemp, line);
648 fprintf(stderr, "Updating ");
651 fprintf(stderr, "Adding ");
653 fprintf(stderr, "password for user %s\n", user);
655 * Now add the user record we created.
657 putline(ftemp, record);
659 * If we're updating an existing file, there may be additional
660 * records beyond the one we're updating, so copy them.
663 copy_file(ftemp, fpw);
667 * The temporary file now contains the information that should be
668 * in the actual password file. Close the open files, re-open them
669 * in the appropriate mode, and copy them file to the real one.
672 fpw = fopen(pwfilename, "w+");
673 ftemp = fopen(tempfilename, "r");
674 copy_file(fpw, ftemp);
677 unlink(tempfilename);