]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_pphrase.c
* modules/ssl/ssl_engine_pphrase.c: Note that the ERR_clear_error()
[apache] / modules / ssl / ssl_engine_pphrase.c
1 /* Copyright 2001-2004 The Apache Software Foundation
2  *
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
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
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.
14  */
15
16 /*                      _             _
17  *  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
18  * | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
19  * | | | | | | (_) | (_| |   \__ \__ \ |
20  * |_| |_| |_|\___/ \__,_|___|___/___/_|
21  *                      |_____|
22  *  ssl_engine_pphrase.c
23  *  Pass Phrase Dialog
24  */
25                              /* ``Treat your password like your
26                                   toothbrush. Don't let anybody
27                                   else use it, and get a new one
28                                   every six months.''
29                                            -- Clifford Stoll     */
30 #include "mod_ssl.h"
31
32 /*
33  * Return true if the named file exists and is readable
34  */
35
36 static apr_status_t exists_and_readable(char *fname, apr_pool_t *pool, apr_time_t *mtime)
37 {
38     apr_status_t stat;
39     apr_finfo_t sbuf;
40     apr_file_t *fd;
41
42     if ((stat = apr_stat(&sbuf, fname, APR_FINFO_MIN, pool)) != APR_SUCCESS)
43         return stat;
44
45     if (sbuf.filetype != APR_REG)
46         return APR_EGENERAL;
47
48     if ((stat = apr_file_open(&fd, fname, APR_READ, 0, pool)) != APR_SUCCESS)
49         return stat;
50
51     if (mtime) {
52         *mtime = sbuf.mtime;
53     }
54
55     apr_file_close(fd);
56     return APR_SUCCESS;
57 }
58
59 /*
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.
64  *
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.
74  */
75 static char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
76                                   char *id, char *an)
77 {
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,
81                                 APR_HASH_KEY_STRING);
82
83     if (!keyptr) {
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);
88     }
89
90     return (char *)keyptr;
91 }
92
93 /*  _________________________________________________________________
94 **
95 **  Pass Phrase and Private Key Handling
96 **  _________________________________________________________________
97 */
98
99 #define BUILTIN_DIALOG_BACKOFF 2
100 #define BUILTIN_DIALOG_RETRIES 5
101
102 static apr_file_t *writetty = NULL;
103 static apr_file_t *readtty = NULL;
104
105 /*
106  * sslc has a nasty flaw where its
107  * PEM_read_bio_PrivateKey does not take a callback arg.
108  */
109 static server_rec *ssl_pphrase_server_rec = NULL;
110
111 #ifdef SSLC_VERSION_NUMBER
112 int ssl_pphrase_Handle_CB(char *, int, int);
113 #else
114 int ssl_pphrase_Handle_CB(char *, int, int, void *);
115 #endif
116
117 static char *pphrase_array_get(apr_array_header_t *arr, int idx)
118 {
119     if ((idx < 0) || (idx >= arr->nelts)) {
120         return NULL;
121     }
122
123     return ((char **)arr->elts)[idx];
124 }
125
126 static void pphrase_array_clear(apr_array_header_t *arr)
127 {
128     if (arr->nelts > 0) {
129         memset(arr->elts, 0, arr->elt_size * arr->nelts);
130     }
131     arr->nelts = 0;
132 }
133
134 void ssl_pphrase_Handle(server_rec *s, apr_pool_t *p)
135 {
136     SSLModConfigRec *mc = myModConfig(s);
137     SSLSrvConfigRec *sc;
138     server_rec *pServ;
139     char *cpVHostID;
140     char szPath[MAX_STRING_LEN];
141     EVP_PKEY *pPrivateKey;
142     ssl_asn1_t *asn1;
143     unsigned char *ucp;
144     long int length;
145     X509 *pX509Cert;
146     BOOL bReadable;
147     apr_array_header_t *aPassPhrase;
148     int nPassPhrase;
149     int nPassPhraseCur;
150     char *cpPassPhraseCur;
151     int nPassPhraseRetry;
152     int nPassPhraseDialog;
153     int nPassPhraseDialogCur;
154     BOOL bPassPhraseDialogOnce;
155     char **cpp;
156     int i, j;
157     ssl_algo_t algoCert, algoKey, at;
158     char *an;
159     char *cp;
160     apr_time_t pkey_mtime = 0;
161     int isterm = 1;
162     apr_status_t rv;
163     /*
164      * Start with a fresh pass phrase array
165      */
166     aPassPhrase       = apr_array_make(p, 2, sizeof(char *));
167     nPassPhrase       = 0;
168     nPassPhraseDialog = 0;
169
170     /*
171      * Walk through all configured servers
172      */
173     for (pServ = s; pServ != NULL; pServ = pServ->next) {
174         sc = mySrvConfig(pServ);
175
176         if (!sc->enabled)
177             continue;
178
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");
182
183         /*
184          * Read in server certificate(s): This is the easy part
185          * because this file isn't encrypted in any way.
186          */
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]");
191             ssl_die();
192         }
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++) {
196
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",
201                              szPath);
202                 ssl_die();
203             }
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);
208                 ssl_die();
209             }
210
211             /*
212              * check algorithm type of certificate and make
213              * sure only one certificate per type is used.
214              */
215             at = ssl_util_algotypeof(pX509Cert, NULL);
216             an = ssl_util_algotypestr(at);
217             if (algoCert & at) {
218                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
219                              "Init: Multiple %s server certificates not "
220                              "allowed", an);
221                 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
222                 ssl_die();
223             }
224             algoCert |= at;
225
226             /*
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).
232              */
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 */
237
238             /*
239              * Free the X509 structure
240              */
241             X509_free(pX509Cert);
242
243             /*
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
250              * dialogs.
251              *
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.
259              */
260             if (sc->server->pks->key_files[j] != NULL)
261                 apr_cpystrn(szPath, sc->server->pks->key_files[j++], sizeof(szPath));
262
263             /*
264              * Try to read the private key file with the help of
265              * the callback function which serves the pass
266              * phrases to OpenSSL
267              */
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);
278
279             nPassPhraseCur        = 0;
280             nPassPhraseRetry      = 0;
281             nPassPhraseDialogCur  = 0;
282             bPassPhraseDialogOnce = TRUE;
283
284             pPrivateKey = NULL;
285
286             for (;;) {
287                 /*
288                  * Try to read the private key file with the help of
289                  * the callback function which serves the pass
290                  * phrases to OpenSSL
291                  */
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 "
296                                   "%s",szPath);
297                      ssl_die();
298                 }
299
300                 /*
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.
319                  */
320                 if (pkey_mtime) {
321                     int i;
322
323                     for (i=0; i < SSL_AIDX_MAX; i++) {
324                         const char *key_id =
325                             ssl_asn1_table_keyfmt(p, cpVHostID, i);
326                         ssl_asn1_t *asn1 = 
327                             ssl_asn1_table_get(mc->tPrivateKey, key_id);
328                     
329                         if (asn1 && (asn1->source_mtime == pkey_mtime)) {
330                             ap_log_error(APLOG_MARK, APLOG_INFO,
331                                          0, pServ,
332                                          "%s reusing existing "
333                                          "%s private key on restart",
334                                          cpVHostID, ssl_asn1_keystr(i));
335                             return;
336                         }
337                     }
338                 }
339
340                 cpPassPhraseCur = NULL;
341                 ssl_pphrase_server_rec = s; /* to make up for sslc flaw */
342
343                 /* Ensure that the error stack is empty; some SSL
344                  * functions will fail spuriously if the error stack
345                  * is not empty. */
346                 ERR_clear_error();
347
348                 bReadable = ((pPrivateKey = SSL_read_PrivateKey(szPath, NULL,
349                             ssl_pphrase_Handle_CB, s)) != NULL ? TRUE : FALSE);
350
351                 /*
352                  * when the private key file now was readable,
353                  * it's fine and we go out of the loop
354                  */
355                 if (bReadable)
356                    break;
357
358                 /*
359                  * when we have more remembered pass phrases
360                  * try to reuse these first.
361                  */
362                 if (nPassPhraseCur < nPassPhrase) {
363                     nPassPhraseCur++;
364                     continue;
365                 }
366
367                 /*
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
373                  * chances...
374                  */
375 #ifndef WIN32
376                 if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
377                        || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
378 #else
379                 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
380 #endif
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");
387                     nPassPhraseRetry++;
388                     if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
389                         apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
390                                     * 5 * APR_USEC_PER_SEC);
391                     continue;
392                 }
393 #ifdef WIN32
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 "
398                                  "%s)", szPath);
399                     ssl_die();
400                 }
401 #endif /* WIN32 */
402
403                 /*
404                  * Ok, anything else now means a fatal error.
405                  */
406                 if (cpPassPhraseCur == NULL) {
407                     if (nPassPhraseDialogCur && pkey_mtime &&
408                         !(isterm = isatty(fileno(stdout)))) /* XXX: apr_isatty() */
409                     {
410                         ap_log_error(APLOG_MARK, APLOG_ERR, 0,
411                                      pServ,
412                                      "Init: Unable to read pass phrase "
413                                      "[Hint: key introduced or changed "
414                                      "before restart?]");
415                         ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, pServ);
416                     }
417                     else {
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);
421                     }
422                     if (writetty) {
423                         apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
424                         apr_file_printf(writetty, "**Stopped\n");
425                     }
426                 }
427                 else {
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);
431
432                     if (writetty) {
433                         apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
434                         apr_file_printf(writetty, "**Stopped\n");
435                     }
436                 }
437                 ssl_die();
438             }
439
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);
446                 ssl_die();
447             }
448
449             /*
450              * check algorithm type of private key and make
451              * sure only one private key per type is used.
452              */
453             at = ssl_util_algotypeof(NULL, pPrivateKey);
454             an = ssl_util_algotypestr(at);
455             if (algoKey & at) {
456                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
457                              "Init: Multiple %s server private keys not "
458                              "allowed", an);
459                 ssl_log_ssl_error(APLOG_MARK, APLOG_ERR, s);
460                 ssl_die();
461             }
462             algoKey |= at;
463
464             /*
465              * Log the type of reading
466              */
467             if (nPassPhraseDialogCur == 0) {
468                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, pServ, 
469                              "unencrypted %s private key - pass phrase not "
470                              "required", an);
471             }
472             else {
473                 if (cpPassPhraseCur != NULL) {
474                     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
475                                  pServ, 
476                                  "encrypted %s private key - pass phrase "
477                                  "requested", an);
478                 }
479                 else {
480                     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
481                                  pServ, 
482                                  "encrypted %s private key - pass phrase"
483                                  " reused", an);
484                 }
485             }
486
487             /*
488              * Ok, when we have one more pass phrase store it
489              */
490             if (cpPassPhraseCur != NULL) {
491                 cpp = (char **)apr_array_push(aPassPhrase);
492                 *cpp = cpPassPhraseCur;
493                 nPassPhrase++;
494             }
495
496             /*
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!)
501              */
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 */
506
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;
511             }
512
513             /*
514              * Free the private key structure
515              */
516             EVP_PKEY_free(pPrivateKey);
517         }
518     }
519
520     /*
521      * Let the user know when we're successful.
522      */
523     if (nPassPhraseDialog > 0) {
524         sc = mySrvConfig(s);
525         if (writetty) {
526             apr_file_printf(writetty, "\n");
527             apr_file_printf(writetty, "Ok: Pass Phrase Dialog successful.\n");
528         }
529     }
530
531     /*
532      * Wipe out the used memory from the
533      * pass phrase array and then deallocate it
534      */
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");
539     }
540
541     /* Close the pipes if they were opened
542      */
543     if (readtty) {
544         apr_file_close(readtty);
545         apr_file_close(writetty);
546         readtty = writetty = NULL;
547     }
548     return;
549 }
550
551 static apr_status_t ssl_pipe_child_create(apr_pool_t *p, const char *progname)
552 {
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...
556      */
557     apr_status_t rc;
558     apr_procattr_t *procattr;
559     apr_proc_t *procnew;
560
561     if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS) &&
562         ((rc = apr_procattr_io_set(procattr,
563                                    APR_FULL_BLOCK,
564                                    APR_FULL_BLOCK,
565                                    APR_NO_PIPE)) == APR_SUCCESS)) {
566         char **args;
567         const char *pname;
568         
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,
573                              NULL, procattr, p);
574         if (rc == APR_SUCCESS) {
575             /* XXX: not sure if we aught to...
576              * apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
577              */
578             writetty = procnew->in;
579             readtty = procnew->out;
580         }
581     }
582
583     return rc;
584 }
585
586 static int pipe_get_passwd_cb(char *buf, int length, char *prompt, int verify)
587 {
588     apr_status_t rc;
589     char *p;
590
591     apr_file_puts(prompt, writetty);
592
593     buf[0]='\0';
594     rc = apr_file_gets(buf, length, readtty);
595     apr_file_puts(APR_EOL_STR, writetty);
596     
597     if (rc != APR_SUCCESS || apr_file_eof(readtty)) {
598         memset(buf, 0, length);
599         return 1;  /* failure */
600     }
601     if ((p = strchr(buf, '\n')) != NULL) {
602         *p = '\0';
603     }
604 #ifdef WIN32
605     /* XXX: apr_sometest */
606     if ((p = strchr(buf, '\r')) != NULL) {
607         *p = '\0';
608     }
609 #endif
610     return 0;
611 }
612
613 #ifdef SSLC_VERSION_NUMBER
614 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify)
615 {
616     void *srv = ssl_pphrase_server_rec;
617 #else
618 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
619 {
620 #endif
621     SSLModConfigRec *mc;
622     server_rec *s;
623     apr_pool_t *p;
624     apr_array_header_t *aPassPhrase;
625     SSLSrvConfigRec *sc;
626     int *pnPassPhraseCur;
627     char **cppPassPhraseCur;
628     char *cpVHostID;
629     char *cpAlgoType;
630     int *pnPassPhraseDialog;
631     int *pnPassPhraseDialogCur;
632     BOOL *pbPassPhraseDialogOnce;
633     char *cpp;
634     int len = -1;
635
636     mc = myModConfig((server_rec *)srv);
637
638     /*
639      * Reconnect to the context of ssl_phrase_Handle()
640      */
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 *);
651     sc                     = mySrvConfig(s);
652
653     (*pnPassPhraseDialog)++;
654     (*pnPassPhraseDialogCur)++;
655
656     /*
657      * When remembered pass phrases are available use them...
658      */
659     if ((cpp = pphrase_array_get(aPassPhrase, *pnPassPhraseCur)) != NULL) {
660         apr_cpystrn(buf, cpp, bufsize);
661         len = strlen(buf);
662         return len;
663     }
664
665     /*
666      * Builtin or Pipe dialog
667      */
668     if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
669           || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
670         char *prompt;
671         int i;
672
673         if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
674             if (!readtty) {
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)
679                         != APR_SUCCESS) {
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);
685                     return (-1);
686                 }
687             }
688             ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
689                          "Init: Requesting pass phrase via piped dialog");
690         }
691         else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */ 
692 #ifdef WIN32
693             PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
694             memset(buf, 0, (unsigned int)bufsize);
695             return (-1);
696 #else
697             /*
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
701              * off tty echo
702              */
703             apr_file_open_stdout(&writetty, p);
704
705             ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
706                          "Init: Requesting pass phrase via builtin terminal "
707                          "dialog");
708 #endif
709         }
710
711         /*
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
715          * something...
716          */
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");
722         }
723         if (*pbPassPhraseDialogOnce) {
724             *pbPassPhraseDialogOnce = FALSE;
725             apr_file_printf(writetty, "\n");
726             apr_file_printf(writetty, "Server %s (%s)\n", cpVHostID, cpAlgoType);
727         }
728
729         /*
730          * Emulate the OpenSSL internal pass phrase dialog
731          * (see crypto/pem/pem_lib.c:def_callback() for details)
732          */
733         prompt = "Enter pass phrase:";
734
735         for (;;) {
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); 
739             }  
740             else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
741                 i = EVP_read_pw_string(buf, bufsize, "", FALSE); 
742             }  
743             if (i != 0) {
744                 PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
745                 memset(buf, 0, (unsigned int)bufsize);
746                 return (-1);
747             }
748             len = strlen(buf);
749             if (len < 1)
750                 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase empty (needs to be at least 1 character).\n");
751             else
752                 break;
753         }
754     }
755
756     /*
757      * Filter program
758      */
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);
762         char *result;
763
764         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
765                      "Init: Requesting pass phrase from dialog filter "
766                      "program (%s)", cmd);
767
768         argv[0] = cmd;
769         argv[1] = cpVHostID;
770         argv[2] = cpAlgoType;
771         argv[3] = NULL;
772
773         result = ssl_util_readfilter(s, p, cmd, argv);
774         apr_cpystrn(buf, result, bufsize);
775         len = strlen(buf);
776     }
777
778     /*
779      * Ok, we now have the pass phrase, so give it back
780      */
781     *cppPassPhraseCur = apr_pstrdup(p, buf);
782
783     /*
784      * And return it's length to OpenSSL...
785      */
786     return (len);
787 }
788