1 /* Copyright 2001-2004 The Apache Software Foundation
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
17 * _ __ ___ ___ __| | ___ ___| | mod_ssl
18 * | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
19 * | | | | | | (_) | (_| | \__ \__ \ |
20 * |_| |_| |_|\___/ \__,_|___|___/___/_|
22 * ssl_engine_pphrase.c
25 /* ``Treat your password like your
26 toothbrush. Don't let anybody
27 else use it, and get a new one
33 * Return true if the named file exists and is readable
36 static apr_status_t exists_and_readable(char *fname, apr_pool_t *pool, apr_time_t *mtime)
42 if ((stat = apr_stat(&sbuf, fname, APR_FINFO_MIN, pool)) != APR_SUCCESS)
45 if (sbuf.filetype != APR_REG)
48 if ((stat = apr_file_open(&fd, fname, APR_READ, 0, pool)) != APR_SUCCESS)
60 * reuse vhost keys for asn1 tables where keys are allocated out
61 * of s->process->pool to prevent "leaking" each time we format
62 * a vhost key. since the key is stored in a table with lifetime
63 * of s->process->pool, the key needs to have the same lifetime.
65 * XXX: probably seems silly to use a hash table with keys and values
66 * being the same, but it is easier than doing a linear search
67 * and will make it easier to remove keys if needed in the future.
68 * also have the problem with apr_array_header_t that if we
69 * underestimate the number of vhost keys when we apr_array_make(),
70 * the array will get resized when we push past the initial number
71 * of elts. this resizing in the s->process->pool means "leaking"
72 * since apr_array_push() will apr_alloc arr->nalloc * 2 elts,
73 * leaving the original arr->elts to waste.
75 static char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
78 /* 'p' pool used here is cleared on restarts (or sooner) */
79 char *key = apr_psprintf(p, "%s:%s", id, an);
80 void *keyptr = apr_hash_get(mc->tVHostKeys, key,
84 /* make a copy out of s->process->pool */
85 keyptr = apr_pstrdup(mc->pPool, key);
86 apr_hash_set(mc->tVHostKeys, keyptr,
87 APR_HASH_KEY_STRING, keyptr);
90 return (char *)keyptr;
93 /* _________________________________________________________________
95 ** Pass Phrase and Private Key Handling
96 ** _________________________________________________________________
99 #define BUILTIN_DIALOG_BACKOFF 2
100 #define BUILTIN_DIALOG_RETRIES 5
102 static apr_file_t *writetty = NULL;
103 static apr_file_t *readtty = NULL;
106 * sslc has a nasty flaw where its
107 * PEM_read_bio_PrivateKey does not take a callback arg.
109 static server_rec *ssl_pphrase_server_rec = NULL;
111 #ifdef SSLC_VERSION_NUMBER
112 int ssl_pphrase_Handle_CB(char *, int, int);
114 int ssl_pphrase_Handle_CB(char *, int, int, void *);
117 static char *pphrase_array_get(apr_array_header_t *arr, int idx)
119 if ((idx < 0) || (idx >= arr->nelts)) {
123 return ((char **)arr->elts)[idx];
126 static void pphrase_array_clear(apr_array_header_t *arr)
128 if (arr->nelts > 0) {
129 memset(arr->elts, 0, arr->elt_size * arr->nelts);
134 void ssl_pphrase_Handle(server_rec *s, apr_pool_t *p)
136 SSLModConfigRec *mc = myModConfig(s);
140 char szPath[MAX_STRING_LEN];
141 EVP_PKEY *pPrivateKey;
147 apr_array_header_t *aPassPhrase;
150 char *cpPassPhraseCur;
151 int nPassPhraseRetry;
152 int nPassPhraseDialog;
153 int nPassPhraseDialogCur;
154 BOOL bPassPhraseDialogOnce;
157 ssl_algo_t algoCert, algoKey, at;
160 apr_time_t pkey_mtime = 0;
164 * Start with a fresh pass phrase array
166 aPassPhrase = apr_array_make(p, 2, sizeof(char *));
168 nPassPhraseDialog = 0;
171 * Walk through all configured servers
173 for (pServ = s; pServ != NULL; pServ = pServ->next) {
174 sc = mySrvConfig(pServ);
179 cpVHostID = ssl_util_vhostid(p, pServ);
180 ap_log_error(APLOG_MARK, APLOG_INFO, 0, pServ,
181 "Loading certificate & private key of SSL-aware server");
184 * Read in server certificate(s): This is the easy part
185 * because this file isn't encrypted in any way.
187 if (sc->server->pks->cert_files[0] == NULL) {
188 ap_log_error(APLOG_MARK, APLOG_ERR, 0, pServ,
189 "Server should be SSL-aware but has no certificate "
190 "configured [Hint: SSLCertificateFile]");
193 algoCert = SSL_ALGO_UNKNOWN;
194 algoKey = SSL_ALGO_UNKNOWN;
195 for (i = 0, j = 0; i < SSL_AIDX_MAX && sc->server->pks->cert_files[i] != NULL; i++) {
197 apr_cpystrn(szPath, sc->server->pks->cert_files[i], sizeof(szPath));
198 if ((rv = exists_and_readable(szPath, p, NULL)) != APR_SUCCESS) {
199 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
200 "Init: Can't open server certificate file %s",
204 if ((pX509Cert = SSL_read_X509(szPath, NULL, NULL)) == NULL) {
205 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
206 "Init: Unable to read server certificate from file %s", szPath);
207 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
212 * check algorithm type of certificate and make
213 * sure only one certificate per type is used.
215 at = ssl_util_algotypeof(pX509Cert, NULL);
216 an = ssl_util_algotypestr(at);
218 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
219 "Init: Multiple %s server certificates not "
221 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
227 * Insert the certificate into global module configuration to let it
228 * survive the processing between the 1st Apache API init round (where
229 * we operate here) and the 2nd Apache init round (where the
230 * certificate is actually used to configure mod_ssl's per-server
231 * configuration structures).
233 cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
234 length = i2d_X509(pX509Cert, NULL);
235 ucp = ssl_asn1_table_set(mc->tPublicCert, cp, length);
236 (void)i2d_X509(pX509Cert, &ucp); /* 2nd arg increments */
239 * Free the X509 structure
241 X509_free(pX509Cert);
244 * Read in the private key: This is the non-trivial part, because the
245 * key is typically encrypted, so a pass phrase dialog has to be used
246 * to request it from the user (or it has to be alternatively gathered
247 * from a dialog program). The important point here is that ISPs
248 * usually have hundrets of virtual servers configured and a lot of
249 * them use SSL, so really we have to minimize the pass phrase
252 * The idea is this: When N virtual hosts are configured and all of
253 * them use encrypted private keys with different pass phrases, we
254 * have no chance and have to pop up N pass phrase dialogs. But
255 * usually the admin is clever enough and uses the same pass phrase
256 * for more private key files (typically he even uses one single pass
257 * phrase for all). When this is the case we can minimize the dialogs
258 * by trying to re-use already known/entered pass phrases.
260 if (sc->server->pks->key_files[j] != NULL)
261 apr_cpystrn(szPath, sc->server->pks->key_files[j++], sizeof(szPath));
264 * Try to read the private key file with the help of
265 * the callback function which serves the pass
268 myCtxVarSet(mc, 1, pServ);
269 myCtxVarSet(mc, 2, p);
270 myCtxVarSet(mc, 3, aPassPhrase);
271 myCtxVarSet(mc, 4, &nPassPhraseCur);
272 myCtxVarSet(mc, 5, &cpPassPhraseCur);
273 myCtxVarSet(mc, 6, cpVHostID);
274 myCtxVarSet(mc, 7, an);
275 myCtxVarSet(mc, 8, &nPassPhraseDialog);
276 myCtxVarSet(mc, 9, &nPassPhraseDialogCur);
277 myCtxVarSet(mc, 10, &bPassPhraseDialogOnce);
280 nPassPhraseRetry = 0;
281 nPassPhraseDialogCur = 0;
282 bPassPhraseDialogOnce = TRUE;
288 * Try to read the private key file with the help of
289 * the callback function which serves the pass
292 if ((rv = exists_and_readable(szPath, p,
293 &pkey_mtime)) != APR_SUCCESS ) {
294 ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
295 "Init: Can't open server private key file "
301 * if the private key is encrypted and SSLPassPhraseDialog
302 * is configured to "builtin" it isn't possible to prompt for
303 * a password after httpd has detached from the tty.
304 * in this case if we already have a private key and the
305 * file name/mtime hasn't changed, then reuse the existing key.
306 * we also reuse existing private keys that were encrypted for
307 * exec: and pipe: dialogs to minimize chances to snoop the
308 * password. that and pipe: dialogs might prompt the user
309 * for password, which on win32 for example could happen 4
310 * times at startup. twice for each child and twice within
311 * each since apache "restarts itself" on startup.
312 * of course this will not work for the builtin dialog if
313 * the server was started without LoadModule ssl_module
314 * configured, then restarted with it configured.
315 * but we fall through with a chance of success if the key
316 * is not encrypted or can be handled via exec or pipe dialog.
317 * and in the case of fallthrough, pkey_mtime and isatty()
318 * are used to give a better idea as to what failed.
323 for (i=0; i < SSL_AIDX_MAX; i++) {
325 ssl_asn1_table_keyfmt(p, cpVHostID, i);
327 ssl_asn1_table_get(mc->tPrivateKey, key_id);
329 if (asn1 && (asn1->source_mtime == pkey_mtime)) {
330 ap_log_error(APLOG_MARK, APLOG_INFO,
332 "%s reusing existing "
333 "%s private key on restart",
334 cpVHostID, ssl_asn1_keystr(i));
340 cpPassPhraseCur = NULL;
341 ssl_pphrase_server_rec = s; /* to make up for sslc flaw */
343 /* Ensure that the error stack is empty; some SSL
344 * functions will fail spuriously if the error stack
348 bReadable = ((pPrivateKey = SSL_read_PrivateKey(szPath, NULL,
349 ssl_pphrase_Handle_CB, s)) != NULL ? TRUE : FALSE);
352 * when the private key file now was readable,
353 * it's fine and we go out of the loop
359 * when we have more remembered pass phrases
360 * try to reuse these first.
362 if (nPassPhraseCur < nPassPhrase) {
368 * else it's not readable and we have no more
369 * remembered pass phrases. Then this has to mean
370 * that the callback function popped up the dialog
371 * but a wrong pass phrase was entered. We give the
372 * user (but not the dialog program) a few more
376 if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
377 || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
379 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
381 && cpPassPhraseCur != NULL
382 && nPassPhraseRetry < BUILTIN_DIALOG_RETRIES ) {
383 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect "
384 "(%d more retr%s permitted).\n",
385 (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry),
386 (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry) == 1 ? "y" : "ies");
388 if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
389 apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
390 * 5 * APR_USEC_PER_SEC);
394 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN) {
395 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
396 "Init: SSLPassPhraseDialog builtin is not "
397 "supported on Win32 (key file "
404 * Ok, anything else now means a fatal error.
406 if (cpPassPhraseCur == NULL) {
407 if (nPassPhraseDialogCur && pkey_mtime &&
408 !(isterm = isatty(fileno(stdout)))) /* XXX: apr_isatty() */
410 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
412 "Init: Unable to read pass phrase "
413 "[Hint: key introduced or changed "
415 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
418 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
419 pServ, "Init: Private key not found");
420 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
423 apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
424 apr_file_printf(writetty, "**Stopped\n");
428 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
429 pServ, "Init: Pass phrase incorrect");
430 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
433 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
434 apr_file_printf(writetty, "**Stopped\n");
440 if (pPrivateKey == NULL) {
441 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
442 "Init: Unable to read server private key from "
443 "file %s [Hint: Perhaps it is in a separate file? "
444 " See SSLCertificateKeyFile]", szPath);
445 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
450 * check algorithm type of private key and make
451 * sure only one private key per type is used.
453 at = ssl_util_algotypeof(NULL, pPrivateKey);
454 an = ssl_util_algotypestr(at);
456 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
457 "Init: Multiple %s server private keys not "
459 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
465 * Log the type of reading
467 if (nPassPhraseDialogCur == 0) {
468 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, pServ,
469 "unencrypted %s private key - pass phrase not "
473 if (cpPassPhraseCur != NULL) {
474 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
476 "encrypted %s private key - pass phrase "
480 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
482 "encrypted %s private key - pass phrase"
488 * Ok, when we have one more pass phrase store it
490 if (cpPassPhraseCur != NULL) {
491 cpp = (char **)apr_array_push(aPassPhrase);
492 *cpp = cpPassPhraseCur;
497 * Insert private key into the global module configuration
498 * (we convert it to a stand-alone DER byte sequence
499 * because the SSL library uses static variables inside a
500 * RSA structure which do not survive DSO reloads!)
502 cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
503 length = i2d_PrivateKey(pPrivateKey, NULL);
504 ucp = ssl_asn1_table_set(mc->tPrivateKey, cp, length);
505 (void)i2d_PrivateKey(pPrivateKey, &ucp); /* 2nd arg increments */
507 if (nPassPhraseDialogCur != 0) {
508 /* remember mtime of encrypted keys */
509 asn1 = ssl_asn1_table_get(mc->tPrivateKey, cp);
510 asn1->source_mtime = pkey_mtime;
514 * Free the private key structure
516 EVP_PKEY_free(pPrivateKey);
521 * Let the user know when we're successful.
523 if (nPassPhraseDialog > 0) {
526 apr_file_printf(writetty, "\n");
527 apr_file_printf(writetty, "Ok: Pass Phrase Dialog successful.\n");
532 * Wipe out the used memory from the
533 * pass phrase array and then deallocate it
535 if (aPassPhrase->nelts) {
536 pphrase_array_clear(aPassPhrase);
537 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
538 "Init: Wiped out the queried pass phrases from memory");
541 /* Close the pipes if they were opened
544 apr_file_close(readtty);
545 apr_file_close(writetty);
546 readtty = writetty = NULL;
551 static apr_status_t ssl_pipe_child_create(apr_pool_t *p, const char *progname)
553 /* Child process code for 'ErrorLog "|..."';
554 * may want a common framework for this, since I expect it will
555 * be common for other foo-loggers to want this sort of thing...
558 apr_procattr_t *procattr;
561 if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS) &&
562 ((rc = apr_procattr_io_set(procattr,
565 APR_NO_PIPE)) == APR_SUCCESS)) {
569 apr_tokenize_to_argv(progname, &args, p);
570 pname = apr_pstrdup(p, args[0]);
571 procnew = (apr_proc_t *)apr_pcalloc(p, sizeof(*procnew));
572 rc = apr_proc_create(procnew, pname, (const char * const *)args,
574 if (rc == APR_SUCCESS) {
575 /* XXX: not sure if we aught to...
576 * apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
578 writetty = procnew->in;
579 readtty = procnew->out;
586 static int pipe_get_passwd_cb(char *buf, int length, char *prompt, int verify)
591 apr_file_puts(prompt, writetty);
594 rc = apr_file_gets(buf, length, readtty);
595 apr_file_puts(APR_EOL_STR, writetty);
597 if (rc != APR_SUCCESS || apr_file_eof(readtty)) {
598 memset(buf, 0, length);
599 return 1; /* failure */
601 if ((p = strchr(buf, '\n')) != NULL) {
605 /* XXX: apr_sometest */
606 if ((p = strchr(buf, '\r')) != NULL) {
613 #ifdef SSLC_VERSION_NUMBER
614 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify)
616 void *srv = ssl_pphrase_server_rec;
618 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
624 apr_array_header_t *aPassPhrase;
626 int *pnPassPhraseCur;
627 char **cppPassPhraseCur;
630 int *pnPassPhraseDialog;
631 int *pnPassPhraseDialogCur;
632 BOOL *pbPassPhraseDialogOnce;
636 mc = myModConfig((server_rec *)srv);
639 * Reconnect to the context of ssl_phrase_Handle()
641 s = myCtxVarGet(mc, 1, server_rec *);
642 p = myCtxVarGet(mc, 2, apr_pool_t *);
643 aPassPhrase = myCtxVarGet(mc, 3, apr_array_header_t *);
644 pnPassPhraseCur = myCtxVarGet(mc, 4, int *);
645 cppPassPhraseCur = myCtxVarGet(mc, 5, char **);
646 cpVHostID = myCtxVarGet(mc, 6, char *);
647 cpAlgoType = myCtxVarGet(mc, 7, char *);
648 pnPassPhraseDialog = myCtxVarGet(mc, 8, int *);
649 pnPassPhraseDialogCur = myCtxVarGet(mc, 9, int *);
650 pbPassPhraseDialogOnce = myCtxVarGet(mc, 10, BOOL *);
653 (*pnPassPhraseDialog)++;
654 (*pnPassPhraseDialogCur)++;
657 * When remembered pass phrases are available use them...
659 if ((cpp = pphrase_array_get(aPassPhrase, *pnPassPhraseCur)) != NULL) {
660 apr_cpystrn(buf, cpp, bufsize);
666 * Builtin or Pipe dialog
668 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
669 || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
673 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
675 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
676 "Init: Creating pass phrase dialog pipe child "
677 "'%s'", sc->server->pphrase_dialog_path);
678 if (ssl_pipe_child_create(p, sc->server->pphrase_dialog_path)
680 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
681 "Init: Failed to create pass phrase pipe '%s'",
682 sc->server->pphrase_dialog_path);
683 PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
684 memset(buf, 0, (unsigned int)bufsize);
688 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
689 "Init: Requesting pass phrase via piped dialog");
691 else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
693 PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
694 memset(buf, 0, (unsigned int)bufsize);
698 * stderr has already been redirected to the error_log.
699 * rather than attempting to temporarily rehook it to the terminal,
700 * we print the prompt to stdout before EVP_read_pw_string turns
703 apr_file_open_stdout(&writetty, p);
705 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
706 "Init: Requesting pass phrase via builtin terminal "
712 * The first time display a header to inform the user about what
713 * program he actually speaks to, which module is responsible for
714 * this terminal dialog and why to the hell he has to enter
717 if (*pnPassPhraseDialog == 1) {
718 apr_file_printf(writetty, "%s mod_ssl/%s (Pass Phrase Dialog)\n",
719 AP_SERVER_BASEVERSION, MOD_SSL_VERSION);
720 apr_file_printf(writetty, "Some of your private key files are encrypted for security reasons.\n");
721 apr_file_printf(writetty, "In order to read them you have to provide us with the pass phrases.\n");
723 if (*pbPassPhraseDialogOnce) {
724 *pbPassPhraseDialogOnce = FALSE;
725 apr_file_printf(writetty, "\n");
726 apr_file_printf(writetty, "Server %s (%s)\n", cpVHostID, cpAlgoType);
730 * Emulate the OpenSSL internal pass phrase dialog
731 * (see crypto/pem/pem_lib.c:def_callback() for details)
733 prompt = "Enter pass phrase:";
736 apr_file_puts(prompt, writetty);
737 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
738 i = pipe_get_passwd_cb(buf, bufsize, "", FALSE);
740 else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
741 i = EVP_read_pw_string(buf, bufsize, "", FALSE);
744 PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
745 memset(buf, 0, (unsigned int)bufsize);
750 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase empty (needs to be at least 1 character).\n");
759 else if (sc->server->pphrase_dialog_type == SSL_PPTYPE_FILTER) {
760 const char *cmd = sc->server->pphrase_dialog_path;
761 const char **argv = apr_palloc(p, sizeof(char *) * 4);
764 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
765 "Init: Requesting pass phrase from dialog filter "
766 "program (%s)", cmd);
770 argv[2] = cpAlgoType;
773 result = ssl_util_readfilter(s, p, cmd, argv);
774 apr_cpystrn(buf, result, bufsize);
779 * Ok, we now have the pass phrase, so give it back
781 *cppPassPhraseCur = apr_pstrdup(p, buf);
784 * And return it's length to OpenSSL...