1 /* ====================================================================
2 * The Apache Software License, Version 1.1
4 * Copyright (c) 2000-2002 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
139 #define NONINTERACTIVE 4
142 apr_file_t *ftemp = NULL;
144 static void to64(char *s, unsigned long v, int n)
146 static unsigned char itoa64[] = /* 0 ... 63 => ASCII - 64 */
147 "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
150 *s++ = itoa64[v&0x3f];
155 static void putline(apr_file_t *f, const char *l)
161 * Make a password record from the given information. A zero return
162 * indicates success; failure means that the output buffer contains an
163 * error message instead.
165 static int mkrecord(char *user, char *record, size_t rlen, char *passwd,
170 char pwin[MAX_STRING_LEN];
171 char pwv[MAX_STRING_LEN];
175 if (passwd != NULL) {
179 bufsize = sizeof(pwin);
180 if (apr_password_get("New password: ", pwin, &bufsize) != 0) {
181 apr_snprintf(record, (rlen - 1), "password too long (>%" APR_SIZE_T_FMT
182 ")", sizeof(pwin) - 1);
185 bufsize = sizeof(pwv);
186 apr_password_get("Re-type new password: ", pwv, &bufsize);
187 if (strcmp(pwin, pwv) != 0) {
188 apr_cpystrn(record, "password verification error", (rlen - 1));
189 return ERR_PWMISMATCH;
192 memset(pwv, '\0', sizeof(pwin));
197 /* XXX cpw >= 28 + strlen(sha1) chars - fixed len SHA */
198 apr_sha1_base64(pw,strlen(pw),cpw);
202 (void) srand((int) time((time_t *) NULL));
203 to64(&salt[0], rand(), 8);
206 apr_md5_encode((const char *)pw, (const char *)salt,
211 /* XXX this len limitation is not in sync with any HTTPd len. */
212 apr_cpystrn(cpw,pw,sizeof(cpw));
215 #if !(defined(WIN32) || defined(NETWARE))
218 (void) srand((int) time((time_t *) NULL));
219 to64(&salt[0], rand(), 8);
222 apr_cpystrn(cpw, (char *)crypt(pw, salt), sizeof(cpw) - 1);
226 memset(pw, '\0', strlen(pw));
229 * Check to see if the buffer is large enough to hold the username,
230 * hash, and delimiters.
232 if ((strlen(user) + 1 + strlen(cpw)) > (rlen - 1)) {
233 apr_cpystrn(record, "resultant record too long", (rlen - 1));
236 strcpy(record, user);
242 static void usage(void)
244 apr_file_printf(errfile, "Usage:\n");
245 apr_file_printf(errfile, "\thtpasswd [-cmdps] passwordfile username\n");
246 apr_file_printf(errfile, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
247 apr_file_printf(errfile, "\thtpasswd -n[mdps] username\n");
248 apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password\n");
249 apr_file_printf(errfile, " -c Create a new file.\n");
250 apr_file_printf(errfile, " -n Don't update file; display results on stdout.\n");
251 apr_file_printf(errfile, " -m Force MD5 encryption of the password"
252 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
256 apr_file_printf(errfile, " -d Force CRYPT encryption of the password"
257 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
261 apr_file_printf(errfile, " -p Do not encrypt the password (plaintext).\n");
262 apr_file_printf(errfile, " -s Force SHA encryption of the password.\n");
263 apr_file_printf(errfile, " -b Use the password from the command line rather "
264 "than prompting for it.\n");
265 apr_file_printf(errfile,
266 "On Windows, NetWare and TPF systems the '-m' flag is used by default.\n");
267 apr_file_printf(errfile,
268 "On all other systems, the '-p' flag will probably not work.\n");
273 * Check to see if the specified file can be opened for the given
276 static int accessible(char *fname, char *mode)
280 s = fopen(fname, mode);
289 * Return true if a file is readable.
291 static int readable(char *fname)
293 return accessible(fname, "r");
297 * Return true if the specified file can be opened for write access.
299 static int writable(char *fname)
301 return accessible(fname, "a");
305 * Return true if the named file exists, regardless of permissions.
307 static int exists(char *fname, apr_pool_t *pool)
312 check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
313 return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
323 static void check_args(int argc, const char *const argv[], int *alg, int *mask,
331 * Preliminary check to make sure they provided at least
332 * three arguments, we'll do better argument checking as
333 * we parse the command line.
340 * Go through the argument list and pick out any options. They
341 * have to precede any other arguments.
343 for (i = 1; i < argc; i++) {
348 while (*++arg != '\0') {
352 else if (*arg == 'n') {
356 else if (*arg == 'm') {
359 else if (*arg == 's') {
362 else if (*arg == 'p') {
365 else if (*arg == 'd') {
368 else if (*arg == 'b') {
369 *mask |= NONINTERACTIVE;
378 if (*mask & (NEWFILE & NOFILE)) {
379 apr_file_printf(errfile, "%s: -c and -n options conflict\n", argv[0]);
383 * Make sure we still have exactly the right number of arguments left
384 * (the filename, the username, and possibly the password if -b was
387 if ((argc - i) != args_left) {
394 * Let's do it. We end up doing a lot of file opening and closing,
395 * but what do we care? This application isn't run constantly.
397 int main(int argc, const char * const argv[])
399 apr_file_t *fpw = NULL;
400 char user[MAX_STRING_LEN];
401 char record[MAX_STRING_LEN];
402 char line[MAX_STRING_LEN];
403 char *password = NULL;
404 char *pwfilename = NULL;
405 char tn[] = "htpasswd.tmp.XXXXXX";
406 char scratch[MAX_STRING_LEN];
413 #if APR_CHARSET_EBCDIC
415 apr_xlate_t *to_ascii;
418 apr_app_initialize(&argc, &argv, NULL);
419 atexit(apr_terminate);
423 apr_pool_create(&pool, NULL);
424 apr_file_open_stderr(&errfile, pool);
426 #if APR_CHARSET_EBCDIC
427 rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
429 apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d\n", rv);
432 rv = apr_SHA1InitEBCDIC(to_ascii);
434 apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d\n", rv);
437 rv = apr_MD5InitEBCDIC(to_ascii);
439 apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d\n", rv);
442 #endif /*APR_CHARSET_EBCDIC*/
444 check_args(argc, argv, &alg, &mask, &i);
450 if (strlen(argv[i]) > (PATH_MAX - 1)) {
451 apr_file_printf(errfile, "%s: filename too long\n", argv[0]);
454 pwfilename = apr_pstrdup(pool, argv[i]);
455 if (strlen(argv[i + 1]) > (sizeof(user) - 1)) {
456 apr_file_printf(errfile, "%s: username too long (>%" APR_SIZE_T_FMT ")\n",
457 argv[0], sizeof(user) - 1);
461 strcpy(user, argv[i + 1]);
462 if ((str = strchr(user, ':')) != NULL) {
463 apr_file_printf(errfile, "%s: username contains illegal character '%c'\n",
467 if (mask & NONINTERACTIVE) {
468 if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
469 apr_file_printf(errfile, "%s: password too long (>%" APR_SIZE_T_FMT ")\n",
470 argv[0], MAX_STRING_LEN);
473 password = apr_pstrdup(pool, argv[i + 2]);
476 #if defined(WIN32) || defined(NETWARE)
477 if (alg == ALG_CRYPT) {
479 apr_file_printf(errfile, "Automatically using MD5 format.\n");
483 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
484 if (alg == ALG_PLAIN) {
485 apr_file_printf(errfile,"Warning: storing passwords as plain text might "
486 "just not work on this platform.\n");
489 if (! mask & NOFILE) {
491 * Only do the file checks if we're supposed to frob it.
493 * Verify that the file exists if -c was omitted. We give a special
494 * message if it doesn't.
496 if ((! mask & NEWFILE) && (! exists(pwfilename, pool))) {
497 apr_file_printf(errfile,
498 "%s: cannot modify file %s; use '-c' to create it\n",
499 argv[0], pwfilename);
504 * Verify that we can read the existing file in the case of an update
505 * to it (rather than creation of a new one).
507 if ((! mask & NEWFILE) && (! readable(pwfilename))) {
508 apr_file_printf(errfile, "%s: cannot open file %s for read access\n",
509 argv[0], pwfilename);
514 * Now check to see if we can preserve an existing file in case
515 * of password verification errors on a -c operation.
517 if ((mask & NEWFILE) && exists(pwfilename, pool) && (! readable(pwfilename))) {
518 apr_file_printf(errfile, "%s: cannot open file %s for read access\n"
519 "%s: existing auth data would be lost on "
521 argv[0], pwfilename, argv[0]);
526 * Now verify that the file is writable!
528 if (! writable(pwfilename)) {
529 apr_file_printf(errfile, "%s: cannot open file %s for write access\n",
530 argv[0], pwfilename);
537 * All the file access checks (if any) have been made. Time to go to work;
538 * try to create the record for the username in question. If that
539 * fails, there's no need to waste any time on file manipulations.
540 * Any error message text is returned in the record buffer, since
541 * the mkrecord() routine doesn't have access to argv[].
543 i = mkrecord(user, record, sizeof(record) - 1,
546 apr_file_printf(errfile, "%s: %s\n", argv[0], record);
550 printf("%s\n", record);
555 * We can access the files the right way, and we have a record
556 * to add or update. Let's do it..
558 if (apr_file_mktemp(&ftemp, tn,
559 APR_CREATE | APR_READ | APR_WRITE | APR_EXCL,
560 pool) != APR_SUCCESS) {
561 apr_file_printf(errfile, "%s: unable to create temporary file '%s'\n",
567 * If we're not creating a new file, copy records from the existing
568 * one to the temporary file until we find the specified user.
570 if (apr_file_open(&fpw, pwfilename, APR_READ, APR_OS_DEFAULT,
571 pool) == APR_SUCCESS) {
572 while (! (apr_file_gets(line, sizeof(line), fpw))) {
575 if ((line[0] == '#') || (line[0] == '\0')) {
576 putline(ftemp, line);
579 strcpy(scratch, line);
581 * See if this is our user.
583 colon = strchr(scratch, ':');
587 if (strcmp(user, scratch) != 0) {
588 putline(ftemp, line);
592 /* We found the user we were looking for, add him to the file.
594 apr_file_printf(errfile, "Updating ");
595 putline(ftemp, record);
600 apr_file_printf(errfile, "Adding ");
601 putline(ftemp, record);
603 apr_file_printf(errfile, "password for user %s\n", user);
606 /* The temporary file has all the data, just copy it to the new location.
608 #if defined(OS2) || defined(WIN32)
609 str = apr_psprintf(pool, "copy \"%s\" \"%s\"", tn, pwfilename);
611 str = apr_psprintf(pool, "cp %s %s", tn, pwfilename);
614 apr_file_close(ftemp);