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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * _ __ ___ ___ __| | ___ ___| | mod_ssl
19 * | '_ ` _ \ / _ \ / _` | / __/ __| | Apache Interface to OpenSSL
20 * | | | | | | (_) | (_| | \__ \__ \ |
21 * |_| |_| |_|\___/ \__,_|___|___/___/_|
23 * ssl_engine_pphrase.c
26 /* ``Treat your password like your
27 toothbrush. Don't let anybody
28 else use it, and get a new one
31 #include "ssl_private.h"
36 apr_array_header_t *aPassPhrase;
38 char *cpPassPhraseCur;
39 int nPassPhraseDialog;
40 int nPassPhraseDialogCur;
41 BOOL bPassPhraseDialogOnce;
43 const char *pkey_file;
47 * Return true if the named file exists and is readable
50 static apr_status_t exists_and_readable(const char *fname, apr_pool_t *pool,
57 if ((stat = apr_stat(&sbuf, fname, APR_FINFO_MIN, pool)) != APR_SUCCESS)
60 if (sbuf.filetype != APR_REG)
63 if ((stat = apr_file_open(&fd, fname, APR_READ, 0, pool)) != APR_SUCCESS)
75 * reuse vhost keys for asn1 tables where keys are allocated out
76 * of s->process->pool to prevent "leaking" each time we format
77 * a vhost key. since the key is stored in a table with lifetime
78 * of s->process->pool, the key needs to have the same lifetime.
80 * XXX: probably seems silly to use a hash table with keys and values
81 * being the same, but it is easier than doing a linear search
82 * and will make it easier to remove keys if needed in the future.
83 * also have the problem with apr_array_header_t that if we
84 * underestimate the number of vhost keys when we apr_array_make(),
85 * the array will get resized when we push past the initial number
86 * of elts. this resizing in the s->process->pool means "leaking"
87 * since apr_array_push() will apr_alloc arr->nalloc * 2 elts,
88 * leaving the original arr->elts to waste.
90 static const char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
91 const char *id, int i)
93 /* 'p' pool used here is cleared on restarts (or sooner) */
94 char *key = apr_psprintf(p, "%s:%d", id, i);
95 void *keyptr = apr_hash_get(mc->tVHostKeys, key,
99 /* make a copy out of s->process->pool */
100 keyptr = apr_pstrdup(mc->pPool, key);
101 apr_hash_set(mc->tVHostKeys, keyptr,
102 APR_HASH_KEY_STRING, keyptr);
105 return (char *)keyptr;
108 /* _________________________________________________________________
110 ** Pass Phrase and Private Key Handling
111 ** _________________________________________________________________
114 #define BUILTIN_DIALOG_BACKOFF 2
115 #define BUILTIN_DIALOG_RETRIES 5
117 static apr_file_t *writetty = NULL;
118 static apr_file_t *readtty = NULL;
120 int ssl_pphrase_Handle_CB(char *, int, int, void *);
122 static char *pphrase_array_get(apr_array_header_t *arr, int idx)
124 if ((idx < 0) || (idx >= arr->nelts)) {
128 return ((char **)arr->elts)[idx];
131 apr_status_t ssl_load_encrypted_pkey(server_rec *s, apr_pool_t *p, int idx,
132 const char *pkey_file,
133 apr_array_header_t **pphrases)
135 SSLModConfigRec *mc = myModConfig(s);
136 SSLSrvConfigRec *sc = mySrvConfig(s);
137 const char *key_id = asn1_table_vhost_key(mc, p, sc->vhost_id, idx);
138 EVP_PKEY *pPrivateKey = NULL;
143 int nPassPhrase = (*pphrases)->nelts;
144 int nPassPhraseRetry = 0;
145 apr_time_t pkey_mtime = 0;
147 pphrase_cb_arg_t ppcb_arg;
150 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02573)
151 "Init: No private key specified for %s", key_id);
154 else if ((rv = exists_and_readable(pkey_file, p, &pkey_mtime))
156 ap_log_error(APLOG_MARK, APLOG_EMERG, rv, s, APLOGNO(02574)
157 "Init: Can't open server private key file %s", pkey_file);
163 ppcb_arg.aPassPhrase = *pphrases;
164 ppcb_arg.nPassPhraseCur = 0;
165 ppcb_arg.cpPassPhraseCur = NULL;
166 ppcb_arg.nPassPhraseDialog = 0;
167 ppcb_arg.nPassPhraseDialogCur = 0;
168 ppcb_arg.bPassPhraseDialogOnce = TRUE;
169 ppcb_arg.key_id = key_id;
170 ppcb_arg.pkey_file = pkey_file;
173 * if the private key is encrypted and SSLPassPhraseDialog
174 * is configured to "builtin" it isn't possible to prompt for
175 * a password after httpd has detached from the tty.
176 * in this case if we already have a private key and the
177 * file name/mtime hasn't changed, then reuse the existing key.
178 * we also reuse existing private keys that were encrypted for
179 * exec: and pipe: dialogs to minimize chances to snoop the
180 * password. that and pipe: dialogs might prompt the user
181 * for password, which on win32 for example could happen 4
182 * times at startup. twice for each child and twice within
183 * each since apache "restarts itself" on startup.
184 * of course this will not work for the builtin dialog if
185 * the server was started without LoadModule ssl_module
186 * configured, then restarted with it configured.
187 * but we fall through with a chance of success if the key
188 * is not encrypted or can be handled via exec or pipe dialog.
189 * and in the case of fallthrough, pkey_mtime and isatty()
190 * are used to give a better idea as to what failed.
193 ssl_asn1_t *asn1 = ssl_asn1_table_get(mc->tPrivateKey, key_id);
194 if (asn1 && (asn1->source_mtime == pkey_mtime)) {
195 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02575)
196 "Reusing existing private key from %s on restart",
202 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s, APLOGNO(02576)
203 "Attempting to load encrypted (?) private key %s", key_id);
207 * Try to read the private key file with the help of
208 * the callback function which serves the pass
212 ppcb_arg.cpPassPhraseCur = NULL;
214 /* Ensure that the error stack is empty; some SSL
215 * functions will fail spuriously if the error stack
219 bReadable = ((pPrivateKey = SSL_read_PrivateKey(ppcb_arg.pkey_file,
220 NULL, ssl_pphrase_Handle_CB, &ppcb_arg)) != NULL ?
224 * when the private key file now was readable,
225 * it's fine and we go out of the loop
231 * when we have more remembered pass phrases
232 * try to reuse these first.
234 if (ppcb_arg.nPassPhraseCur < nPassPhrase) {
235 ppcb_arg.nPassPhraseCur++;
240 * else it's not readable and we have no more
241 * remembered pass phrases. Then this has to mean
242 * that the callback function popped up the dialog
243 * but a wrong pass phrase was entered. We give the
244 * user (but not the dialog program) a few more
248 if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
249 || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
251 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
253 && ppcb_arg.cpPassPhraseCur != NULL
254 && nPassPhraseRetry < BUILTIN_DIALOG_RETRIES ) {
255 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect "
256 "(%d more retr%s permitted).\n",
257 (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry),
258 (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry) == 1 ? "y" : "ies");
260 if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
261 apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
262 * 5 * APR_USEC_PER_SEC);
266 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN) {
267 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02577)
268 "Init: SSLPassPhraseDialog builtin is not "
269 "supported on Win32 (key file "
270 "%s)", ppcb_arg.pkey_file);
276 * Ok, anything else now means a fatal error.
278 if (ppcb_arg.cpPassPhraseCur == NULL) {
279 if (ppcb_arg.nPassPhraseDialogCur && pkey_mtime &&
280 !isatty(fileno(stdout))) /* XXX: apr_isatty() */
282 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
284 "Init: Unable to read pass phrase "
285 "[Hint: key introduced or changed "
287 ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
290 ap_log_error(APLOG_MARK, APLOG_ERR, 0,
291 s, APLOGNO(02579) "Init: Private key not found");
292 ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
295 apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
296 apr_file_printf(writetty, "**Stopped\n");
300 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02580)
301 "Init: Pass phrase incorrect for key %s",
303 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
306 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
307 apr_file_printf(writetty, "**Stopped\n");
313 if (pPrivateKey == NULL) {
314 ap_log_error(APLOG_MARK, APLOG_EMERG, 0, s, APLOGNO(02581)
315 "Init: Unable to read server private key from file %s",
317 ssl_log_ssl_error(SSLLOG_MARK, APLOG_EMERG, s);
322 * Log the type of reading
324 if (ppcb_arg.nPassPhraseDialogCur == 0) {
325 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, s, APLOGNO(02582)
326 "unencrypted %s private key - pass phrase not "
330 if (ppcb_arg.cpPassPhraseCur != NULL) {
331 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
333 "encrypted %s private key - pass phrase "
334 "requested", key_id);
337 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
339 "encrypted %s private key - pass phrase"
345 * Ok, when we have one more pass phrase store it
347 if (ppcb_arg.cpPassPhraseCur != NULL) {
348 *(const char **)apr_array_push(ppcb_arg.aPassPhrase) =
349 ppcb_arg.cpPassPhraseCur;
354 * Insert private key into the global module configuration
355 * (we convert it to a stand-alone DER byte sequence
356 * because the SSL library uses static variables inside a
357 * RSA structure which do not survive DSO reloads!)
359 length = i2d_PrivateKey(pPrivateKey, NULL);
360 ucp = ssl_asn1_table_set(mc->tPrivateKey, key_id, length);
361 (void)i2d_PrivateKey(pPrivateKey, &ucp); /* 2nd arg increments */
363 if (ppcb_arg.nPassPhraseDialogCur != 0) {
364 /* remember mtime of encrypted keys */
365 asn1 = ssl_asn1_table_get(mc->tPrivateKey, key_id);
366 asn1->source_mtime = pkey_mtime;
370 * Free the private key structure
372 EVP_PKEY_free(pPrivateKey);
375 * Let the user know when we're successful.
377 if ((ppcb_arg.nPassPhraseDialog > 0) &&
378 (ppcb_arg.cpPassPhraseCur != NULL)) {
380 apr_file_printf(writetty, "\n"
381 "OK: Pass Phrase Dialog successful.\n");
385 /* Close the pipes if they were opened
388 apr_file_close(readtty);
389 apr_file_close(writetty);
390 readtty = writetty = NULL;
396 static apr_status_t ssl_pipe_child_create(apr_pool_t *p, const char *progname)
398 /* Child process code for 'ErrorLog "|..."';
399 * may want a common framework for this, since I expect it will
400 * be common for other foo-loggers to want this sort of thing...
403 apr_procattr_t *procattr;
406 if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS) &&
407 ((rc = apr_procattr_io_set(procattr,
410 APR_NO_PIPE)) == APR_SUCCESS)) {
413 apr_tokenize_to_argv(progname, &args, p);
414 procnew = (apr_proc_t *)apr_pcalloc(p, sizeof(*procnew));
415 rc = apr_proc_create(procnew, args[0], (const char * const *)args,
417 if (rc == APR_SUCCESS) {
418 /* XXX: not sure if we aught to...
419 * apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
421 writetty = procnew->in;
422 readtty = procnew->out;
429 static int pipe_get_passwd_cb(char *buf, int length, char *prompt, int verify)
434 apr_file_puts(prompt, writetty);
437 rc = apr_file_gets(buf, length, readtty);
438 apr_file_puts(APR_EOL_STR, writetty);
440 if (rc != APR_SUCCESS || apr_file_eof(readtty)) {
441 memset(buf, 0, length);
442 return 1; /* failure */
444 if ((p = strchr(buf, '\n')) != NULL) {
448 /* XXX: apr_sometest */
449 if ((p = strchr(buf, '\r')) != NULL) {
456 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
458 pphrase_cb_arg_t *ppcb_arg = (pphrase_cb_arg_t *)srv;
459 SSLSrvConfigRec *sc = mySrvConfig(ppcb_arg->s);
463 ppcb_arg->nPassPhraseDialog++;
464 ppcb_arg->nPassPhraseDialogCur++;
467 * When remembered pass phrases are available use them...
469 if ((cpp = pphrase_array_get(ppcb_arg->aPassPhrase,
470 ppcb_arg->nPassPhraseCur)) != NULL) {
471 apr_cpystrn(buf, cpp, bufsize);
477 * Builtin or Pipe dialog
479 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
480 || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
484 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
486 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s,
488 "Init: Creating pass phrase dialog pipe child "
489 "'%s'", sc->server->pphrase_dialog_path);
490 if (ssl_pipe_child_create(ppcb_arg->p,
491 sc->server->pphrase_dialog_path)
493 ap_log_error(APLOG_MARK, APLOG_ERR, 0, ppcb_arg->s,
495 "Init: Failed to create pass phrase pipe '%s'",
496 sc->server->pphrase_dialog_path);
497 PEMerr(PEM_F_PEM_DEF_CALLBACK,
498 PEM_R_PROBLEMS_GETTING_PASSWORD);
499 memset(buf, 0, (unsigned int)bufsize);
503 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s, APLOGNO(01967)
504 "Init: Requesting pass phrase via piped dialog");
506 else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
508 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
509 memset(buf, 0, (unsigned int)bufsize);
513 * stderr has already been redirected to the error_log.
514 * rather than attempting to temporarily rehook it to the terminal,
515 * we print the prompt to stdout before EVP_read_pw_string turns
518 apr_file_open_stdout(&writetty, ppcb_arg->p);
520 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s, APLOGNO(01968)
521 "Init: Requesting pass phrase via builtin terminal "
527 * The first time display a header to inform the user about what
528 * program he actually speaks to, which module is responsible for
529 * this terminal dialog and why to the hell he has to enter
532 if (ppcb_arg->nPassPhraseDialog == 1) {
533 apr_file_printf(writetty, "%s mod_ssl (Pass Phrase Dialog)\n",
534 AP_SERVER_BASEVERSION);
535 apr_file_printf(writetty, "Some of your private key files are encrypted for security reasons.\n");
536 apr_file_printf(writetty, "In order to read them you have to provide the pass phrases.\n");
538 if (ppcb_arg->bPassPhraseDialogOnce) {
539 ppcb_arg->bPassPhraseDialogOnce = FALSE;
540 apr_file_printf(writetty, "\n");
541 apr_file_printf(writetty, "Private key %s (%s)\n",
542 ppcb_arg->key_id, ppcb_arg->pkey_file);
546 * Emulate the OpenSSL internal pass phrase dialog
547 * (see crypto/pem/pem_lib.c:def_callback() for details)
549 prompt = "Enter pass phrase:";
552 apr_file_puts(prompt, writetty);
553 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
554 i = pipe_get_passwd_cb(buf, bufsize, "", FALSE);
556 else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
557 i = EVP_read_pw_string(buf, bufsize, "", FALSE);
560 PEMerr(PEM_F_PEM_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
561 memset(buf, 0, (unsigned int)bufsize);
566 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase empty (needs to be at least 1 character).\n");
575 else if (sc->server->pphrase_dialog_type == SSL_PPTYPE_FILTER) {
576 const char *cmd = sc->server->pphrase_dialog_path;
577 const char **argv = apr_palloc(ppcb_arg->p, sizeof(char *) * 3);
580 ap_log_error(APLOG_MARK, APLOG_INFO, 0, ppcb_arg->s, APLOGNO(01969)
581 "Init: Requesting pass phrase from dialog filter "
582 "program (%s)", cmd);
585 argv[1] = ppcb_arg->key_id;
588 result = ssl_util_readfilter(ppcb_arg->s, ppcb_arg->p, cmd, argv);
589 apr_cpystrn(buf, result, bufsize);
594 * Ok, we now have the pass phrase, so give it back
596 ppcb_arg->cpPassPhraseCur = apr_pstrdup(ppcb_arg->p, buf);
599 * And return its length to OpenSSL...