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
137 #define APHTP_NEWFILE 1
138 #define APHTP_NOFILE 2
139 #define APHTP_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);
239 strcat(record, "\n");
243 static void usage(void)
245 apr_file_printf(errfile, "Usage:\n");
246 apr_file_printf(errfile, "\thtpasswd [-cmdps] passwordfile username\n");
247 apr_file_printf(errfile, "\thtpasswd -b[cmdps] passwordfile username password\n\n");
248 apr_file_printf(errfile, "\thtpasswd -n[mdps] username\n");
249 apr_file_printf(errfile, "\thtpasswd -nb[mdps] username password\n");
250 apr_file_printf(errfile, " -c Create a new file.\n");
251 apr_file_printf(errfile, " -n Don't update file; display results on stdout.\n");
252 apr_file_printf(errfile, " -m Force MD5 encryption of the password"
253 #if defined(WIN32) || defined(TPF) || defined(NETWARE)
257 apr_file_printf(errfile, " -d Force CRYPT encryption of the password"
258 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
262 apr_file_printf(errfile, " -p Do not encrypt the password (plaintext).\n");
263 apr_file_printf(errfile, " -s Force SHA encryption of the password.\n");
264 apr_file_printf(errfile, " -b Use the password from the command line rather "
265 "than prompting for it.\n");
266 apr_file_printf(errfile,
267 "On Windows, NetWare and TPF systems the '-m' flag is used by default.\n");
268 apr_file_printf(errfile,
269 "On all other systems, the '-p' flag will probably not work.\n");
274 * Check to see if the specified file can be opened for the given
277 static int accessible(apr_pool_t *pool, char *fname, int mode)
279 apr_file_t *f = NULL;
281 if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
289 * Return true if a file is readable.
291 static int readable(apr_pool_t *pool, char *fname)
293 return accessible(pool, fname, APR_READ);
297 * Return true if the specified file can be opened for write access.
299 static int writable(apr_pool_t *pool, char *fname)
301 return accessible(pool, fname, APR_APPEND);
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(apr_pool_t *pool, int argc, const char *const argv[],
324 int *alg, int *mask, char **user, char **pwfilename,
332 * Preliminary check to make sure they provided at least
333 * three arguments, we'll do better argument checking as
334 * we parse the command line.
341 * Go through the argument list and pick out any options. They
342 * have to precede any other arguments.
344 for (i = 1; i < argc; i++) {
349 while (*++arg != '\0') {
351 *mask |= APHTP_NEWFILE;
353 else if (*arg == 'n') {
354 *mask |= APHTP_NOFILE;
357 else if (*arg == 'm') {
360 else if (*arg == 's') {
363 else if (*arg == 'p') {
366 else if (*arg == 'd') {
369 else if (*arg == 'b') {
370 *mask |= APHTP_NONINTERACTIVE;
379 if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
380 apr_file_printf(errfile, "%s: -c and -n options conflict\n", argv[0]);
384 * Make sure we still have exactly the right number of arguments left
385 * (the filename, the username, and possibly the password if -b was
388 if ((argc - i) != args_left) {
392 if (*mask & APHTP_NOFILE) {
396 if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
397 apr_file_printf(errfile, "%s: filename too long\n", argv[0]);
400 *pwfilename = apr_pstrdup(pool, argv[i]);
401 if (strlen(argv[i + 1]) > (MAX_STRING_LEN - 1)) {
402 apr_file_printf(errfile, "%s: username too long (> %d)\n",
403 argv[0], MAX_STRING_LEN - 1);
407 *user = apr_pstrdup(pool, argv[i + 1]);
408 if ((arg = strchr(*user, ':')) != NULL) {
409 apr_file_printf(errfile, "%s: username contains illegal character '%c'\n",
413 if (*mask & APHTP_NONINTERACTIVE) {
414 if (strlen(argv[i + 2]) > (MAX_STRING_LEN - 1)) {
415 apr_file_printf(errfile, "%s: password too long (> %d)\n",
416 argv[0], MAX_STRING_LEN);
419 *password = apr_pstrdup(pool, argv[i + 2]);
424 * Let's do it. We end up doing a lot of file opening and closing,
425 * but what do we care? This application isn't run constantly.
427 int main(int argc, const char * const argv[])
429 apr_file_t *fpw = NULL;
430 char record[MAX_STRING_LEN];
431 char line[MAX_STRING_LEN];
432 char *password = NULL;
433 char *pwfilename = NULL;
435 char tn[] = "htpasswd.tmp.XXXXXX";
436 char scratch[MAX_STRING_LEN];
443 #if APR_CHARSET_EBCDIC
445 apr_xlate_t *to_ascii;
448 apr_app_initialize(&argc, &argv, NULL);
449 atexit(apr_terminate);
453 apr_pool_create(&pool, NULL);
454 apr_file_open_stderr(&errfile, pool);
456 #if APR_CHARSET_EBCDIC
457 rv = apr_xlate_open(&to_ascii, "ISO8859-1", APR_DEFAULT_CHARSET, pool);
459 apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d\n", rv);
462 rv = apr_SHA1InitEBCDIC(to_ascii);
464 apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d\n", rv);
467 rv = apr_MD5InitEBCDIC(to_ascii);
469 apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d\n", rv);
472 #endif /*APR_CHARSET_EBCDIC*/
474 check_args(pool, argc, argv, &alg, &mask, &user, &pwfilename, &password);
477 #if defined(WIN32) || defined(NETWARE)
478 if (alg == ALG_CRYPT) {
480 apr_file_printf(errfile, "Automatically using MD5 format.\n");
484 #if (!(defined(WIN32) || defined(TPF) || defined(NETWARE)))
485 if (alg == ALG_PLAIN) {
486 apr_file_printf(errfile,"Warning: storing passwords as plain text might "
487 "just not work on this platform.\n");
490 if (! mask & APHTP_NOFILE) {
492 * Only do the file checks if we're supposed to frob it.
494 * Verify that the file exists if -c was omitted. We give a special
495 * message if it doesn't.
497 if ((! mask & APHTP_NEWFILE) && (! exists(pwfilename, pool))) {
498 apr_file_printf(errfile,
499 "%s: cannot modify file %s; use '-c' to create it\n",
500 argv[0], pwfilename);
501 perror("apr_file_open");
505 * Verify that we can read the existing file in the case of an update
506 * to it (rather than creation of a new one).
508 if ((! mask & APHTP_NEWFILE) && (! readable(pool, pwfilename))) {
509 apr_file_printf(errfile, "%s: cannot open file %s for read access\n",
510 argv[0], pwfilename);
511 perror("apr_file_open");
515 * Now check to see if we can preserve an existing file in case
516 * of password verification errors on a -c operation.
518 if ((mask & APHTP_NEWFILE) && exists(pwfilename, pool) &&
519 (! readable(pool, pwfilename))) {
520 apr_file_printf(errfile, "%s: cannot open file %s for read access\n"
521 "%s: existing auth data would be lost on "
523 argv[0], pwfilename, argv[0]);
524 perror("apr_file_open");
528 * Now verify that the file is writable!
530 if (! writable(pool, pwfilename)) {
531 apr_file_printf(errfile, "%s: cannot open file %s for write access\n",
532 argv[0], pwfilename);
533 perror("apr_file_open");
539 * All the file access checks (if any) have been made. Time to go to work;
540 * try to create the record for the username in question. If that
541 * fails, there's no need to waste any time on file manipulations.
542 * Any error message text is returned in the record buffer, since
543 * the mkrecord() routine doesn't have access to argv[].
545 i = mkrecord(user, record, sizeof(record) - 1,
548 apr_file_printf(errfile, "%s: %s\n", argv[0], record);
551 if (mask & APHTP_NOFILE) {
552 printf("%s\n", record);
557 * We can access the files the right way, and we have a record
558 * to add or update. Let's do it..
560 if (apr_file_mktemp(&ftemp, tn, 0, 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);
601 apr_file_printf(errfile, "Adding ");
602 putline(ftemp, record);
604 apr_file_printf(errfile, "password for user %s\n", user);
607 /* The temporary file has all the data, just copy it to the new location.
609 apr_file_copy(tn, pwfilename, APR_FILE_SOURCE_PERMS, pool);
610 apr_file_close(ftemp);