]> granicus.if.org Git - apache/blob - support/htpasswd.c
Start refactoring of htpasswd and htdbm
[apache] / support / htpasswd.c
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 /******************************************************************************
18  ******************************************************************************
19  * NOTE! This program is not safe as a setuid executable!  Do not make it
20  * setuid!
21  ******************************************************************************
22  *****************************************************************************/
23 /*
24  * htpasswd.c: simple program for manipulating password file for
25  * the Apache HTTP server
26  *
27  * Originally by Rob McCool
28  *
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
39  */
40
41 #include "passwd_common.h"
42 #include "apr_signal.h"
43 #include "apr_getopt.h"
44
45 #if APR_HAVE_STDIO_H
46 #include <stdio.h>
47 #endif
48
49 #include "apr_md5.h"
50 #include "apr_sha1.h"
51
52 #if APR_HAVE_STDLIB_H
53 #include <stdlib.h>
54 #endif
55 #if APR_HAVE_STRING_H
56 #include <string.h>
57 #endif
58 #if APR_HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif
61
62 #ifdef WIN32
63 #include <conio.h>
64 #define unlink _unlink
65 #endif
66
67 #define APHTP_NEWFILE        1
68 #define APHTP_NOFILE         2
69 #define APHTP_DELUSER        4
70
71 apr_file_t *ftemp = NULL;
72
73 static int mkrecord(struct passwd_ctx *ctx, char *user)
74 {
75     char hash_str[MAX_STRING_LEN];
76     int ret;
77     ctx->out = hash_str;
78     ctx->out_len = sizeof(hash_str);
79
80     ret = mkhash(ctx);
81     if (ret)
82         return ret;
83
84     ctx->out = apr_pstrcat(ctx->pool, user, ":", hash_str, NL, NULL);
85     if (strlen(ctx->out) >= MAX_STRING_LEN) {
86         ctx->errstr = "resultant record too long";
87         return ERR_OVERFLOW;
88     }
89     return 0;
90 }
91
92 static void usage(void)
93 {
94     apr_file_printf(errfile, "Usage:" NL
95         "\thtpasswd [-cmdpsD] passwordfile username" NL
96         "\thtpasswd -b[cmdpsD] passwordfile username password" NL
97         NL
98         "\thtpasswd -n[mdps] username" NL
99         "\thtpasswd -nb[mdps] username password" NL
100         " -c  Create a new file." NL
101         " -n  Don't update file; display results on stdout." NL
102         " -m  Force MD5 encryption of the password (default)." NL
103         " -d  Force CRYPT encryption of the password (8 chars max, "
104             "insecure)." NL
105         " -p  Do not encrypt the password (plaintext, insecure)." NL
106         " -s  Force SHA encryption of the password (insecure)." NL
107         " -b  Use the password from the command line rather than prompting "
108             "for it." NL
109         " -D  Delete the specified user." NL
110         "On other systems than Windows and NetWare the '-p' flag will "
111             "probably not work." NL
112         "The SHA algorithm does not use a salt and is less secure than the "
113             "MD5 algorithm." NL
114     );
115     exit(ERR_SYNTAX);
116 }
117
118 /*
119  * Check to see if the specified file can be opened for the given
120  * access.
121  */
122 static int accessible(apr_pool_t *pool, char *fname, int mode)
123 {
124     apr_file_t *f = NULL;
125
126     if (apr_file_open(&f, fname, mode, APR_OS_DEFAULT, pool) != APR_SUCCESS) {
127         return 0;
128     }
129     apr_file_close(f);
130     return 1;
131 }
132
133 /*
134  * Return true if the named file exists, regardless of permissions.
135  */
136 static int exists(char *fname, apr_pool_t *pool)
137 {
138     apr_finfo_t sbuf;
139     apr_status_t check;
140
141     check = apr_stat(&sbuf, fname, APR_FINFO_TYPE, pool);
142     return ((check || sbuf.filetype != APR_REG) ? 0 : 1);
143 }
144
145 static void terminate(void)
146 {
147     apr_terminate();
148 #ifdef NETWARE
149     pressanykey();
150 #endif
151 }
152
153 static void check_args(int argc, const char *const argv[],
154                        struct passwd_ctx *ctx, int *mask, char **user,
155                        char **pwfilename)
156 {
157     const char *arg;
158     int args_left = 2;
159     int i, ret;
160     apr_getopt_t *state;
161     apr_status_t rv;
162     char opt;
163     const char *opt_arg;
164     apr_pool_t *pool = ctx->pool;
165
166     rv = apr_getopt_init(&state, pool, argc, argv);
167     if (rv != APR_SUCCESS)
168         exit(ERR_SYNTAX);
169
170     while ((rv = apr_getopt(state, "cnmspdBbDiC:", &opt, &opt_arg)) == APR_SUCCESS) {
171         switch (opt) {
172         case 'c':
173             *mask |= APHTP_NEWFILE;
174             break;
175         case 'n':
176             args_left--;
177             *mask |= APHTP_NOFILE;
178             break;
179         case 'D':
180             *mask |= APHTP_DELUSER;
181             break;
182         default:
183             ret = parse_common_options(ctx, opt, opt_arg);
184             if (ret) {
185                 apr_file_printf(errfile, "%s: %s" NL, argv[0], ctx->errstr);
186                 exit(ret);
187             }
188         }
189     }
190     if (ctx->passwd_src == PW_ARG)
191         args_left++;
192     if (rv != APR_EOF)
193         usage();
194
195     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_NOFILE)) {
196         apr_file_printf(errfile, "%s: -c and -n options conflict" NL, argv[0]);
197         exit(ERR_SYNTAX);
198     }
199     if ((*mask & APHTP_NEWFILE) && (*mask & APHTP_DELUSER)) {
200         apr_file_printf(errfile, "%s: -c and -D options conflict" NL, argv[0]);
201         exit(ERR_SYNTAX);
202     }
203     if ((*mask & APHTP_NOFILE) && (*mask & APHTP_DELUSER)) {
204         apr_file_printf(errfile, "%s: -n and -D options conflict" NL, argv[0]);
205         exit(ERR_SYNTAX);
206     }
207     /*
208      * Make sure we still have exactly the right number of arguments left
209      * (the filename, the username, and possibly the password if -b was
210      * specified).
211      */
212     i = state->ind;
213     if ((argc - i) != args_left) {
214         usage();
215     }
216
217     if (!(*mask & APHTP_NOFILE)) {
218         if (strlen(argv[i]) > (APR_PATH_MAX - 1)) {
219             apr_file_printf(errfile, "%s: filename too long" NL, argv[0]);
220             exit(ERR_OVERFLOW);
221         }
222         *pwfilename = apr_pstrdup(pool, argv[i++]);
223     }
224     if (strlen(argv[i]) > (MAX_STRING_LEN - 1)) {
225         apr_file_printf(errfile, "%s: username too long (> %d)" NL,
226                         argv[0], MAX_STRING_LEN - 1);
227         exit(ERR_OVERFLOW);
228     }
229     *user = apr_pstrdup(pool, argv[i++]);
230     if ((arg = strchr(*user, ':')) != NULL) {
231         apr_file_printf(errfile, "%s: username contains illegal "
232                         "character '%c'" NL, argv[0], *arg);
233         exit(ERR_BADUSER);
234     }
235     if (ctx->passwd_src == PW_ARG) {
236         if (strlen(argv[i]) > (MAX_STRING_LEN - 1)) {
237             apr_file_printf(errfile, "%s: password too long (> %d)" NL,
238                 argv[0], MAX_STRING_LEN);
239             exit(ERR_OVERFLOW);
240         }
241         ctx->passwd = apr_pstrdup(pool, argv[i]);
242     }
243 }
244
245 /*
246  * Let's do it.  We end up doing a lot of file opening and closing,
247  * but what do we care?  This application isn't run constantly.
248  */
249 int main(int argc, const char * const argv[])
250 {
251     apr_file_t *fpw = NULL;
252     const char *errstr = NULL;
253     char line[MAX_STRING_LEN];
254     char *pwfilename = NULL;
255     char *user = NULL;
256     char tn[] = "htpasswd.tmp.XXXXXX";
257     char *dirname;
258     char *scratch, cp[MAX_STRING_LEN];
259     int found = 0;
260     int i;
261     int mask = 0;
262     apr_pool_t *pool;
263     int existing_file = 0;
264     struct passwd_ctx ctx = { 0 };
265 #if APR_CHARSET_EBCDIC
266     apr_status_t rv;
267     apr_xlate_t *to_ascii;
268 #endif
269
270     apr_app_initialize(&argc, &argv, NULL);
271     atexit(terminate);
272     apr_pool_create(&pool, NULL);
273     apr_file_open_stderr(&errfile, pool);
274     ctx.pool = pool;
275     ctx.alg = ALG_APMD5;
276
277 #if APR_CHARSET_EBCDIC
278     rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, pool);
279     if (rv) {
280         apr_file_printf(errfile, "apr_xlate_open(to ASCII)->%d" NL, rv);
281         exit(1);
282     }
283     rv = apr_SHA1InitEBCDIC(to_ascii);
284     if (rv) {
285         apr_file_printf(errfile, "apr_SHA1InitEBCDIC()->%d" NL, rv);
286         exit(1);
287     }
288     rv = apr_MD5InitEBCDIC(to_ascii);
289     if (rv) {
290         apr_file_printf(errfile, "apr_MD5InitEBCDIC()->%d" NL, rv);
291         exit(1);
292     }
293 #endif /*APR_CHARSET_EBCDIC*/
294
295     check_args(argc, argv, &ctx, &mask, &user, &pwfilename);
296
297     /*
298      * Only do the file checks if we're supposed to frob it.
299      */
300     if (!(mask & APHTP_NOFILE)) {
301         existing_file = exists(pwfilename, pool);
302         if (existing_file) {
303             /*
304              * Check that this existing file is readable and writable.
305              */
306             if (!accessible(pool, pwfilename, APR_FOPEN_READ|APR_FOPEN_WRITE)) {
307                 apr_file_printf(errfile, "%s: cannot open file %s for "
308                                 "read/write access" NL, argv[0], pwfilename);
309                 exit(ERR_FILEPERM);
310             }
311         }
312         else {
313             /*
314              * Error out if -c was omitted for this non-existant file.
315              */
316             if (!(mask & APHTP_NEWFILE)) {
317                 apr_file_printf(errfile,
318                         "%s: cannot modify file %s; use '-c' to create it" NL,
319                         argv[0], pwfilename);
320                 exit(ERR_FILEPERM);
321             }
322             /*
323              * As it doesn't exist yet, verify that we can create it.
324              */
325             if (!accessible(pool, pwfilename, APR_FOPEN_WRITE|APR_FOPEN_CREATE)) {
326                 apr_file_printf(errfile, "%s: cannot create file %s" NL,
327                                 argv[0], pwfilename);
328                 exit(ERR_FILEPERM);
329             }
330         }
331     }
332
333     /*
334      * All the file access checks (if any) have been made.  Time to go to work;
335      * try to create the record for the username in question.  If that
336      * fails, there's no need to waste any time on file manipulations.
337      * Any error message text is returned in the record buffer, since
338      * the mkrecord() routine doesn't have access to argv[].
339      */
340     if (!(mask & APHTP_DELUSER)) {
341         i = mkrecord(&ctx, user);
342         if (i != 0) {
343             apr_file_printf(errfile, "%s: %s" NL, argv[0], errstr);
344             exit(i);
345         }
346         if (mask & APHTP_NOFILE) {
347             printf("%s" NL, ctx.out);
348             exit(0);
349         }
350     }
351
352     /*
353      * We can access the files the right way, and we have a record
354      * to add or update.  Let's do it..
355      */
356     if (apr_temp_dir_get((const char**)&dirname, pool) != APR_SUCCESS) {
357         apr_file_printf(errfile, "%s: could not determine temp dir" NL,
358                         argv[0]);
359         exit(ERR_FILEPERM);
360     }
361     dirname = apr_psprintf(pool, "%s/%s", dirname, tn);
362
363     if (apr_file_mktemp(&ftemp, dirname, 0, pool) != APR_SUCCESS) {
364         apr_file_printf(errfile, "%s: unable to create temporary file %s" NL,
365                         argv[0], dirname);
366         exit(ERR_FILEPERM);
367     }
368
369     /*
370      * If we're not creating a new file, copy records from the existing
371      * one to the temporary file until we find the specified user.
372      */
373     if (existing_file && !(mask & APHTP_NEWFILE)) {
374         if (apr_file_open(&fpw, pwfilename, APR_READ | APR_BUFFERED,
375                           APR_OS_DEFAULT, pool) != APR_SUCCESS) {
376             apr_file_printf(errfile, "%s: unable to read file %s" NL,
377                             argv[0], pwfilename);
378             exit(ERR_FILEPERM);
379         }
380         while (apr_file_gets(line, sizeof(line), fpw) == APR_SUCCESS) {
381             char *colon;
382
383             strcpy(cp, line);
384             scratch = cp;
385             while (apr_isspace(*scratch)) {
386                 ++scratch;
387             }
388
389             if (!*scratch || (*scratch == '#')) {
390                 putline(ftemp, line);
391                 continue;
392             }
393             /*
394              * See if this is our user.
395              */
396             colon = strchr(scratch, ':');
397             if (colon != NULL) {
398                 *colon = '\0';
399             }
400             else {
401                 /*
402                  * If we've not got a colon on the line, this could well
403                  * not be a valid htpasswd file.
404                  * We should bail at this point.
405                  */
406                 apr_file_printf(errfile, "%s: The file %s does not appear "
407                                          "to be a valid htpasswd file." NL,
408                                 argv[0], pwfilename);
409                 apr_file_close(fpw);
410                 exit(ERR_INVALID);
411             }
412             if (strcmp(user, scratch) != 0) {
413                 putline(ftemp, line);
414                 continue;
415             }
416             else {
417                 if (!(mask & APHTP_DELUSER)) {
418                     /* We found the user we were looking for.
419                      * Add him to the file.
420                     */
421                     apr_file_printf(errfile, "Updating ");
422                     putline(ftemp, ctx.out);
423                     found++;
424                 }
425                 else {
426                     /* We found the user we were looking for.
427                      * Delete them from the file.
428                      */
429                     apr_file_printf(errfile, "Deleting ");
430                     found++;
431                 }
432             }
433         }
434         apr_file_close(fpw);
435     }
436     if (!found && !(mask & APHTP_DELUSER)) {
437         apr_file_printf(errfile, "Adding ");
438         putline(ftemp, ctx.out);
439     }
440     else if (!found && (mask & APHTP_DELUSER)) {
441         apr_file_printf(errfile, "User %s not found" NL, user);
442         exit(0);
443     }
444     apr_file_printf(errfile, "password for user %s" NL, user);
445
446     /* The temporary file has all the data, just copy it to the new location.
447      */
448     if (apr_file_copy(dirname, pwfilename, APR_FILE_SOURCE_PERMS, pool) !=
449         APR_SUCCESS) {
450         apr_file_printf(errfile, "%s: unable to update file %s" NL,
451                         argv[0], pwfilename);
452         exit(ERR_FILEPERM);
453     }
454     apr_file_close(ftemp);
455     return 0;
456 }