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_TYPE, pool);
359 return ((check || sbuf.filetype != APR_REG) ? 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;
397 #if APR_CHARSET_EBCDIC
399 apr_xlate_t *to_ascii;
403 atexit(apr_terminate);
404 apr_pool_create(&pool, NULL);
406 #if APR_CHARSET_EBCDIC
407 rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
409 fprintf(stderr, "apr_xlate_open(to ASCII)->%d\n", rv);
412 rv = apr_SHA1InitEBCDIC(to_ascii);
414 fprintf(stderr, "apr_SHA1InitEBCDIC()->%d\n", rv);
417 rv = apr_MD5InitEBCDIC(to_ascii);
419 fprintf(stderr, "apr_MD5InitEBCDIC()->%d\n", rv);
422 #endif /*APR_CHARSET_EBCDIC*/
425 apr_signal(SIGINT, (void (*)(int)) interrupted);
428 * Preliminary check to make sure they provided at least
429 * three arguments, we'll do better argument checking as
430 * we parse the command line.
437 * Go through the argument list and pick out any options. They
438 * have to precede any other arguments.
440 for (i = 1; i < argc; i++) {
445 while (*++arg != '\0') {
449 else if (*arg == 'n') {
453 else if (*arg == 'm') {
456 else if (*arg == 's') {
459 else if (*arg == 'p') {
462 else if (*arg == 'd') {
465 else if (*arg == 'b') {
476 * Make sure we still have exactly the right number of arguments left
477 * (the filename, the username, and possibly the password if -b was
480 if ((argc - i) != args_left) {
483 if (newfile && nofile) {
484 fprintf(stderr, "%s: -c and -n options conflict\n", argv[0]);
491 if (strlen(argv[i]) > (sizeof(pwfilename) - 1)) {
492 fprintf(stderr, "%s: filename too long\n", argv[0]);
495 strcpy(pwfilename, argv[i]);
496 if (strlen(argv[i + 1]) > (sizeof(user) - 1)) {
497 fprintf(stderr, "%s: username too long (>%" APR_SIZE_T_FMT ")\n",
498 argv[0], sizeof(user) - 1);
502 strcpy(user, argv[i + 1]);
503 if ((arg = strchr(user, ':')) != NULL) {
504 fprintf(stderr, "%s: username contains illegal character '%c'\n",
508 if (noninteractive) {
509 if (strlen(argv[i + 2]) > (sizeof(password) - 1)) {
510 fprintf(stderr, "%s: password too long (>%" APR_SIZE_T_FMT ")\n",
511 argv[0], sizeof(password) - 1);
514 strcpy(password, argv[i + 2]);
518 if (alg == ALG_CRYPT) {
520 fprintf(stderr, "Automatically using MD5 format on Windows.\n");
524 #if (!(defined(WIN32) || defined(TPF)))
525 if (alg == ALG_PLAIN) {
526 fprintf(stderr,"Warning: storing passwords as plain text might "
527 "just not work on this platform.\n");
532 * Only do the file checks if we're supposed to frob it.
534 * Verify that the file exists if -c was omitted. We give a special
535 * message if it doesn't.
537 if ((! newfile) && (! exists(pwfilename, pool))) {
539 "%s: cannot modify file %s; use '-c' to create it\n",
540 argv[0], pwfilename);
545 * Verify that we can read the existing file in the case of an update
546 * to it (rather than creation of a new one).
548 if ((! newfile) && (! readable(pwfilename))) {
549 fprintf(stderr, "%s: cannot open file %s for read access\n",
550 argv[0], pwfilename);
555 * Now check to see if we can preserve an existing file in case
556 * of password verification errors on a -c operation.
558 if (newfile && exists(pwfilename, pool) && (! readable(pwfilename))) {
559 fprintf(stderr, "%s: cannot open file %s for read access\n"
560 "%s: existing auth data would be lost on "
562 argv[0], pwfilename, argv[0]);
567 * Now verify that the file is writable!
569 if (! writable(pwfilename)) {
570 fprintf(stderr, "%s: cannot open file %s for write access\n",
571 argv[0], pwfilename);
578 * All the file access checks (if any) have been made. Time to go to work;
579 * try to create the record for the username in question. If that
580 * fails, there's no need to waste any time on file manipulations.
581 * Any error message text is returned in the record buffer, since
582 * the mkrecord() routine doesn't have access to argv[].
584 i = mkrecord(user, record, sizeof(record) - 1,
585 noninteractive ? password : NULL,
588 fprintf(stderr, "%s: %s\n", argv[0], record);
592 printf("%s\n", record);
597 * We can access the files the right way, and we have a record
598 * to add or update. Let's do it..
601 tempfilename = tmpnam(tname_buf);
602 if ((tempfilename == NULL) || (*tempfilename == '\0')) {
603 fprintf(stderr, "%s: unable to generate temporary filename\n",
611 ftemp = fopen(tempfilename, "w+");
613 fprintf(stderr, "%s: unable to create temporary file '%s'\n", argv[0],
619 * If we're not creating a new file, copy records from the existing
620 * one to the temporary file until we find the specified user.
623 char scratch[MAX_STRING_LEN];
625 fpw = fopen(pwfilename, "r");
626 while (! (getline(line, sizeof(line), fpw))) {
629 if ((line[0] == '#') || (line[0] == '\0')) {
630 putline(ftemp, line);
633 strcpy(scratch, line);
635 * See if this is our user.
637 colon = strchr(scratch, ':');
641 if (strcmp(user, scratch) != 0) {
642 putline(ftemp, line);
650 fprintf(stderr, "Updating ");
653 fprintf(stderr, "Adding ");
655 fprintf(stderr, "password for user %s\n", user);
657 * Now add the user record we created.
659 putline(ftemp, record);
661 * If we're updating an existing file, there may be additional
662 * records beyond the one we're updating, so copy them.
665 copy_file(ftemp, fpw);
669 * The temporary file now contains the information that should be
670 * in the actual password file. Close the open files, re-open them
671 * in the appropriate mode, and copy them file to the real one.
674 fpw = fopen(pwfilename, "w+");
675 ftemp = fopen(tempfilename, "r");
676 copy_file(fpw, ftemp);
679 unlink(tempfilename);