]> granicus.if.org Git - apache/blob - modules/ssl/ssl_engine_pphrase.c
Introduce SSLLOG_MARK for use with ssl_log_ssl_error(). This will allow to
[apache] / modules / ssl / ssl_engine_pphrase.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  *  _ __ ___   ___   __| |    ___ ___| |  mod_ssl
19  * | '_ ` _ \ / _ \ / _` |   / __/ __| |  Apache Interface to OpenSSL
20  * | | | | | | (_) | (_| |   \__ \__ \ |
21  * |_| |_| |_|\___/ \__,_|___|___/___/_|
22  *                      |_____|
23  *  ssl_engine_pphrase.c
24  *  Pass Phrase Dialog
25  */
26                              /* ``Treat your password like your
27                                   toothbrush. Don't let anybody
28                                   else use it, and get a new one
29                                   every six months.''
30                                            -- Clifford Stoll     */
31 #include "ssl_private.h"
32
33 /*
34  * Return true if the named file exists and is readable
35  */
36
37 static apr_status_t exists_and_readable(char *fname, apr_pool_t *pool, apr_time_t *mtime)
38 {
39     apr_status_t stat;
40     apr_finfo_t sbuf;
41     apr_file_t *fd;
42
43     if ((stat = apr_stat(&sbuf, fname, APR_FINFO_MIN, pool)) != APR_SUCCESS)
44         return stat;
45
46     if (sbuf.filetype != APR_REG)
47         return APR_EGENERAL;
48
49     if ((stat = apr_file_open(&fd, fname, APR_READ, 0, pool)) != APR_SUCCESS)
50         return stat;
51
52     if (mtime) {
53         *mtime = sbuf.mtime;
54     }
55
56     apr_file_close(fd);
57     return APR_SUCCESS;
58 }
59
60 /*
61  * reuse vhost keys for asn1 tables where keys are allocated out
62  * of s->process->pool to prevent "leaking" each time we format
63  * a vhost key.  since the key is stored in a table with lifetime
64  * of s->process->pool, the key needs to have the same lifetime.
65  *
66  * XXX: probably seems silly to use a hash table with keys and values
67  * being the same, but it is easier than doing a linear search
68  * and will make it easier to remove keys if needed in the future.
69  * also have the problem with apr_array_header_t that if we
70  * underestimate the number of vhost keys when we apr_array_make(),
71  * the array will get resized when we push past the initial number
72  * of elts.  this resizing in the s->process->pool means "leaking"
73  * since apr_array_push() will apr_alloc arr->nalloc * 2 elts,
74  * leaving the original arr->elts to waste.
75  */
76 static char *asn1_table_vhost_key(SSLModConfigRec *mc, apr_pool_t *p,
77                                   char *id, char *an)
78 {
79     /* 'p' pool used here is cleared on restarts (or sooner) */
80     char *key = apr_psprintf(p, "%s:%s", id, an);
81     void *keyptr = apr_hash_get(mc->tVHostKeys, key,
82                                 APR_HASH_KEY_STRING);
83
84     if (!keyptr) {
85         /* make a copy out of s->process->pool */
86         keyptr = apr_pstrdup(mc->pPool, key);
87         apr_hash_set(mc->tVHostKeys, keyptr,
88                      APR_HASH_KEY_STRING, keyptr);
89     }
90
91     return (char *)keyptr;
92 }
93
94 /*  _________________________________________________________________
95 **
96 **  Pass Phrase and Private Key Handling
97 **  _________________________________________________________________
98 */
99
100 #define BUILTIN_DIALOG_BACKOFF 2
101 #define BUILTIN_DIALOG_RETRIES 5
102
103 static apr_file_t *writetty = NULL;
104 static apr_file_t *readtty = NULL;
105
106 /*
107  * sslc has a nasty flaw where its
108  * PEM_read_bio_PrivateKey does not take a callback arg.
109  */
110 static server_rec *ssl_pphrase_server_rec = NULL;
111
112 #ifdef SSLC_VERSION_NUMBER
113 int ssl_pphrase_Handle_CB(char *, int, int);
114 #else
115 int ssl_pphrase_Handle_CB(char *, int, int, void *);
116 #endif
117
118 static char *pphrase_array_get(apr_array_header_t *arr, int idx)
119 {
120     if ((idx < 0) || (idx >= arr->nelts)) {
121         return NULL;
122     }
123
124     return ((char **)arr->elts)[idx];
125 }
126
127 static void pphrase_array_clear(apr_array_header_t *arr)
128 {
129     if (arr->nelts > 0) {
130         memset(arr->elts, 0, arr->elt_size * arr->nelts);
131     }
132     arr->nelts = 0;
133 }
134
135 void ssl_pphrase_Handle(server_rec *s, apr_pool_t *p)
136 {
137     SSLModConfigRec *mc = myModConfig(s);
138     SSLSrvConfigRec *sc;
139     server_rec *pServ;
140     char *cpVHostID;
141     char szPath[MAX_STRING_LEN];
142     EVP_PKEY *pPrivateKey;
143     ssl_asn1_t *asn1;
144     unsigned char *ucp;
145     long int length;
146     X509 *pX509Cert;
147     BOOL bReadable;
148     apr_array_header_t *aPassPhrase;
149     int nPassPhrase;
150     int nPassPhraseCur;
151     char *cpPassPhraseCur;
152     int nPassPhraseRetry;
153     int nPassPhraseDialog;
154     int nPassPhraseDialogCur;
155     BOOL bPassPhraseDialogOnce;
156     char **cpp;
157     int i, j;
158     ssl_algo_t algoCert, algoKey, at;
159     char *an;
160     char *cp;
161     apr_time_t pkey_mtime = 0;
162     int isterm = 1;
163     apr_status_t rv;
164     /*
165      * Start with a fresh pass phrase array
166      */
167     aPassPhrase       = apr_array_make(p, 2, sizeof(char *));
168     nPassPhrase       = 0;
169     nPassPhraseDialog = 0;
170
171     /*
172      * Walk through all configured servers
173      */
174     for (pServ = s; pServ != NULL; pServ = pServ->next) {
175         sc = mySrvConfig(pServ);
176
177         if (!sc->enabled)
178             continue;
179
180         cpVHostID = ssl_util_vhostid(p, pServ);
181         ap_log_error(APLOG_MARK, APLOG_INFO, 0, pServ,
182                      "Loading certificate & private key of SSL-aware server");
183
184         /*
185          * Read in server certificate(s): This is the easy part
186          * because this file isn't encrypted in any way.
187          */
188         if (sc->server->pks->cert_files[0] == NULL
189             && sc->server->pkcs7 == NULL) {
190             ap_log_error(APLOG_MARK, APLOG_ERR, 0, pServ,
191                          "Server should be SSL-aware but has no certificate "
192                          "configured [Hint: SSLCertificateFile] (%s:%d)",
193                          pServ->defn_name, pServ->defn_line_number);
194             ssl_die();
195         }
196
197         algoCert = SSL_ALGO_UNKNOWN;
198         algoKey  = SSL_ALGO_UNKNOWN;
199         for (i = 0, j = 0; i < SSL_AIDX_MAX
200                  && (sc->server->pks->cert_files[i] != NULL
201                      || sc->server->pkcs7); i++) {
202             if (sc->server->pkcs7) {
203                 STACK_OF(X509) *certs = ssl_read_pkcs7(pServ,
204                                                        sc->server->pkcs7);
205                 pX509Cert = sk_X509_value(certs, 0);
206                 i = SSL_AIDX_MAX;
207             } else {
208                 apr_cpystrn(szPath, sc->server->pks->cert_files[i],
209                             sizeof(szPath));
210                 if ((rv = exists_and_readable(szPath, p, NULL))
211                     != APR_SUCCESS) {
212                     ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
213                                  "Init: Can't open server certificate file %s",
214                                  szPath);
215                     ssl_die();
216                 }
217                 if ((pX509Cert = SSL_read_X509(szPath, NULL, NULL)) == NULL) {
218                     ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
219                                  "Init: Unable to read server certificate from"
220                                  " file %s", szPath);
221                     ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
222                     ssl_die();
223                 }
224             }
225             /*
226              * check algorithm type of certificate and make
227              * sure only one certificate per type is used.
228              */
229             at = ssl_util_algotypeof(pX509Cert, NULL);
230             an = ssl_util_algotypestr(at);
231             if (algoCert & at) {
232                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
233                              "Init: Multiple %s server certificates not "
234                              "allowed", an);
235                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
236                 ssl_die();
237             }
238             algoCert |= at;
239
240             /*
241              * Insert the certificate into global module configuration to let it
242              * survive the processing between the 1st Apache API init round (where
243              * we operate here) and the 2nd Apache init round (where the
244              * certificate is actually used to configure mod_ssl's per-server
245              * configuration structures).
246              */
247             cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
248             length = i2d_X509(pX509Cert, NULL);
249             ucp = ssl_asn1_table_set(mc->tPublicCert, cp, length);
250             (void)i2d_X509(pX509Cert, &ucp); /* 2nd arg increments */
251
252             /*
253              * Free the X509 structure
254              */
255             X509_free(pX509Cert);
256
257             /*
258              * Read in the private key: This is the non-trivial part, because the
259              * key is typically encrypted, so a pass phrase dialog has to be used
260              * to request it from the user (or it has to be alternatively gathered
261              * from a dialog program). The important point here is that ISPs
262              * usually have hundrets of virtual servers configured and a lot of
263              * them use SSL, so really we have to minimize the pass phrase
264              * dialogs.
265              *
266              * The idea is this: When N virtual hosts are configured and all of
267              * them use encrypted private keys with different pass phrases, we
268              * have no chance and have to pop up N pass phrase dialogs. But
269              * usually the admin is clever enough and uses the same pass phrase
270              * for more private key files (typically he even uses one single pass
271              * phrase for all). When this is the case we can minimize the dialogs
272              * by trying to re-use already known/entered pass phrases.
273              */
274             if (sc->server->pks->key_files[j] != NULL)
275                 apr_cpystrn(szPath, sc->server->pks->key_files[j++], sizeof(szPath));
276
277             /*
278              * Try to read the private key file with the help of
279              * the callback function which serves the pass
280              * phrases to OpenSSL
281              */
282             myCtxVarSet(mc,  1, pServ);
283             myCtxVarSet(mc,  2, p);
284             myCtxVarSet(mc,  3, aPassPhrase);
285             myCtxVarSet(mc,  4, &nPassPhraseCur);
286             myCtxVarSet(mc,  5, &cpPassPhraseCur);
287             myCtxVarSet(mc,  6, cpVHostID);
288             myCtxVarSet(mc,  7, an);
289             myCtxVarSet(mc,  8, &nPassPhraseDialog);
290             myCtxVarSet(mc,  9, &nPassPhraseDialogCur);
291             myCtxVarSet(mc, 10, &bPassPhraseDialogOnce);
292
293             nPassPhraseCur        = 0;
294             nPassPhraseRetry      = 0;
295             nPassPhraseDialogCur  = 0;
296             bPassPhraseDialogOnce = TRUE;
297
298             pPrivateKey = NULL;
299
300             for (;;) {
301                 /*
302                  * Try to read the private key file with the help of
303                  * the callback function which serves the pass
304                  * phrases to OpenSSL
305                  */
306                 if ((rv = exists_and_readable(szPath, p,
307                                               &pkey_mtime)) != APR_SUCCESS ) {
308                      ap_log_error(APLOG_MARK, APLOG_ERR, rv, s,
309                                   "Init: Can't open server private key file "
310                                   "%s",szPath);
311                      ssl_die();
312                 }
313
314                 /*
315                  * if the private key is encrypted and SSLPassPhraseDialog
316                  * is configured to "builtin" it isn't possible to prompt for
317                  * a password after httpd has detached from the tty.
318                  * in this case if we already have a private key and the
319                  * file name/mtime hasn't changed, then reuse the existing key.
320                  * we also reuse existing private keys that were encrypted for
321                  * exec: and pipe: dialogs to minimize chances to snoop the
322                  * password.  that and pipe: dialogs might prompt the user
323                  * for password, which on win32 for example could happen 4
324                  * times at startup.  twice for each child and twice within
325                  * each since apache "restarts itself" on startup.
326                  * of course this will not work for the builtin dialog if
327                  * the server was started without LoadModule ssl_module
328                  * configured, then restarted with it configured.
329                  * but we fall through with a chance of success if the key
330                  * is not encrypted or can be handled via exec or pipe dialog.
331                  * and in the case of fallthrough, pkey_mtime and isatty()
332                  * are used to give a better idea as to what failed.
333                  */
334                 if (pkey_mtime) {
335                     int i;
336
337                     for (i=0; i < SSL_AIDX_MAX; i++) {
338                         const char *key_id =
339                             ssl_asn1_table_keyfmt(p, cpVHostID, i);
340                         ssl_asn1_t *asn1 =
341                             ssl_asn1_table_get(mc->tPrivateKey, key_id);
342
343                         if (asn1 && (asn1->source_mtime == pkey_mtime)) {
344                             ap_log_error(APLOG_MARK, APLOG_INFO,
345                                          0, pServ,
346                                          "%s reusing existing "
347                                          "%s private key on restart",
348                                          cpVHostID, ssl_asn1_keystr(i));
349                             return;
350                         }
351                     }
352                 }
353
354                 cpPassPhraseCur = NULL;
355                 ssl_pphrase_server_rec = s; /* to make up for sslc flaw */
356
357                 /* Ensure that the error stack is empty; some SSL
358                  * functions will fail spuriously if the error stack
359                  * is not empty. */
360                 ERR_clear_error();
361
362                 bReadable = ((pPrivateKey = SSL_read_PrivateKey(szPath, NULL,
363                             ssl_pphrase_Handle_CB, s)) != NULL ? TRUE : FALSE);
364
365                 /*
366                  * when the private key file now was readable,
367                  * it's fine and we go out of the loop
368                  */
369                 if (bReadable)
370                    break;
371
372                 /*
373                  * when we have more remembered pass phrases
374                  * try to reuse these first.
375                  */
376                 if (nPassPhraseCur < nPassPhrase) {
377                     nPassPhraseCur++;
378                     continue;
379                 }
380
381                 /*
382                  * else it's not readable and we have no more
383                  * remembered pass phrases. Then this has to mean
384                  * that the callback function popped up the dialog
385                  * but a wrong pass phrase was entered.  We give the
386                  * user (but not the dialog program) a few more
387                  * chances...
388                  */
389 #ifndef WIN32
390                 if ((sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
391                        || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE)
392 #else
393                 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE
394 #endif
395                     && cpPassPhraseCur != NULL
396                     && nPassPhraseRetry < BUILTIN_DIALOG_RETRIES ) {
397                     apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect "
398                             "(%d more retr%s permitted).\n",
399                             (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry),
400                             (BUILTIN_DIALOG_RETRIES-nPassPhraseRetry) == 1 ? "y" : "ies");
401                     nPassPhraseRetry++;
402                     if (nPassPhraseRetry > BUILTIN_DIALOG_BACKOFF)
403                         apr_sleep((nPassPhraseRetry-BUILTIN_DIALOG_BACKOFF)
404                                     * 5 * APR_USEC_PER_SEC);
405                     continue;
406                 }
407 #ifdef WIN32
408                 if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN) {
409                     ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
410                                  "Init: SSLPassPhraseDialog builtin is not "
411                                  "supported on Win32 (key file "
412                                  "%s)", szPath);
413                     ssl_die();
414                 }
415 #endif /* WIN32 */
416
417                 /*
418                  * Ok, anything else now means a fatal error.
419                  */
420                 if (cpPassPhraseCur == NULL) {
421                     if (nPassPhraseDialogCur && pkey_mtime &&
422                         !(isterm = isatty(fileno(stdout)))) /* XXX: apr_isatty() */
423                     {
424                         ap_log_error(APLOG_MARK, APLOG_ERR, 0,
425                                      pServ,
426                                      "Init: Unable to read pass phrase "
427                                      "[Hint: key introduced or changed "
428                                      "before restart?]");
429                         ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, pServ);
430                     }
431                     else {
432                         ap_log_error(APLOG_MARK, APLOG_ERR, 0,
433                                      pServ, "Init: Private key not found");
434                         ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, pServ);
435                     }
436                     if (writetty) {
437                         apr_file_printf(writetty, "Apache:mod_ssl:Error: Private key not found.\n");
438                         apr_file_printf(writetty, "**Stopped\n");
439                     }
440                 }
441                 else {
442                     ap_log_error(APLOG_MARK, APLOG_ERR, 0,
443                                  pServ, "Init: Pass phrase incorrect");
444                     ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, pServ);
445
446                     if (writetty) {
447                         apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase incorrect.\n");
448                         apr_file_printf(writetty, "**Stopped\n");
449                     }
450                 }
451                 ssl_die();
452             }
453
454             if (pPrivateKey == NULL) {
455                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
456                             "Init: Unable to read server private key from "
457                             "file %s [Hint: Perhaps it is in a separate file? "
458                             "  See SSLCertificateKeyFile]", szPath);
459                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
460                 ssl_die();
461             }
462
463             /*
464              * check algorithm type of private key and make
465              * sure only one private key per type is used.
466              */
467             at = ssl_util_algotypeof(NULL, pPrivateKey);
468             an = ssl_util_algotypestr(at);
469             if (algoKey & at) {
470                 ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
471                              "Init: Multiple %s server private keys not "
472                              "allowed", an);
473                 ssl_log_ssl_error(SSLLOG_MARK, APLOG_ERR, s);
474                 ssl_die();
475             }
476             algoKey |= at;
477
478             /*
479              * Log the type of reading
480              */
481             if (nPassPhraseDialogCur == 0) {
482                 ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, pServ,
483                              "unencrypted %s private key - pass phrase not "
484                              "required", an);
485             }
486             else {
487                 if (cpPassPhraseCur != NULL) {
488                     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
489                                  pServ,
490                                  "encrypted %s private key - pass phrase "
491                                  "requested", an);
492                 }
493                 else {
494                     ap_log_error(APLOG_MARK, APLOG_DEBUG, 0,
495                                  pServ,
496                                  "encrypted %s private key - pass phrase"
497                                  " reused", an);
498                 }
499             }
500
501             /*
502              * Ok, when we have one more pass phrase store it
503              */
504             if (cpPassPhraseCur != NULL) {
505                 cpp = (char **)apr_array_push(aPassPhrase);
506                 *cpp = cpPassPhraseCur;
507                 nPassPhrase++;
508             }
509
510             /*
511              * Insert private key into the global module configuration
512              * (we convert it to a stand-alone DER byte sequence
513              * because the SSL library uses static variables inside a
514              * RSA structure which do not survive DSO reloads!)
515              */
516             cp = asn1_table_vhost_key(mc, p, cpVHostID, an);
517             length = i2d_PrivateKey(pPrivateKey, NULL);
518             ucp = ssl_asn1_table_set(mc->tPrivateKey, cp, length);
519             (void)i2d_PrivateKey(pPrivateKey, &ucp); /* 2nd arg increments */
520
521             if (nPassPhraseDialogCur != 0) {
522                 /* remember mtime of encrypted keys */
523                 asn1 = ssl_asn1_table_get(mc->tPrivateKey, cp);
524                 asn1->source_mtime = pkey_mtime;
525             }
526
527             /*
528              * Free the private key structure
529              */
530             EVP_PKEY_free(pPrivateKey);
531         }
532     }
533
534     /*
535      * Let the user know when we're successful.
536      */
537     if (nPassPhraseDialog > 0) {
538         sc = mySrvConfig(s);
539         if (writetty) {
540             apr_file_printf(writetty, "\n"
541                             "OK: Pass Phrase Dialog successful.\n");
542         }
543     }
544
545     /*
546      * Wipe out the used memory from the
547      * pass phrase array and then deallocate it
548      */
549     if (aPassPhrase->nelts) {
550         pphrase_array_clear(aPassPhrase);
551         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
552                      "Init: Wiped out the queried pass phrases from memory");
553     }
554
555     /* Close the pipes if they were opened
556      */
557     if (readtty) {
558         apr_file_close(readtty);
559         apr_file_close(writetty);
560         readtty = writetty = NULL;
561     }
562     return;
563 }
564
565 static apr_status_t ssl_pipe_child_create(apr_pool_t *p, const char *progname)
566 {
567     /* Child process code for 'ErrorLog "|..."';
568      * may want a common framework for this, since I expect it will
569      * be common for other foo-loggers to want this sort of thing...
570      */
571     apr_status_t rc;
572     apr_procattr_t *procattr;
573     apr_proc_t *procnew;
574
575     if (((rc = apr_procattr_create(&procattr, p)) == APR_SUCCESS) &&
576         ((rc = apr_procattr_io_set(procattr,
577                                    APR_FULL_BLOCK,
578                                    APR_FULL_BLOCK,
579                                    APR_NO_PIPE)) == APR_SUCCESS)) {
580         char **args;
581         const char *pname;
582
583         apr_tokenize_to_argv(progname, &args, p);
584         pname = apr_pstrdup(p, args[0]);
585         procnew = (apr_proc_t *)apr_pcalloc(p, sizeof(*procnew));
586         rc = apr_proc_create(procnew, pname, (const char * const *)args,
587                              NULL, procattr, p);
588         if (rc == APR_SUCCESS) {
589             /* XXX: not sure if we aught to...
590              * apr_pool_note_subprocess(p, procnew, APR_KILL_AFTER_TIMEOUT);
591              */
592             writetty = procnew->in;
593             readtty = procnew->out;
594         }
595     }
596
597     return rc;
598 }
599
600 static int pipe_get_passwd_cb(char *buf, int length, char *prompt, int verify)
601 {
602     apr_status_t rc;
603     char *p;
604
605     apr_file_puts(prompt, writetty);
606
607     buf[0]='\0';
608     rc = apr_file_gets(buf, length, readtty);
609     apr_file_puts(APR_EOL_STR, writetty);
610
611     if (rc != APR_SUCCESS || apr_file_eof(readtty)) {
612         memset(buf, 0, length);
613         return 1;  /* failure */
614     }
615     if ((p = strchr(buf, '\n')) != NULL) {
616         *p = '\0';
617     }
618 #ifdef WIN32
619     /* XXX: apr_sometest */
620     if ((p = strchr(buf, '\r')) != NULL) {
621         *p = '\0';
622     }
623 #endif
624     return 0;
625 }
626
627 #ifdef SSLC_VERSION_NUMBER
628 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify)
629 {
630     void *srv = ssl_pphrase_server_rec;
631 #else
632 int ssl_pphrase_Handle_CB(char *buf, int bufsize, int verify, void *srv)
633 {
634 #endif
635     SSLModConfigRec *mc;
636     server_rec *s;
637     apr_pool_t *p;
638     apr_array_header_t *aPassPhrase;
639     SSLSrvConfigRec *sc;
640     int *pnPassPhraseCur;
641     char **cppPassPhraseCur;
642     char *cpVHostID;
643     char *cpAlgoType;
644     int *pnPassPhraseDialog;
645     int *pnPassPhraseDialogCur;
646     BOOL *pbPassPhraseDialogOnce;
647     char *cpp;
648     int len = -1;
649
650     mc = myModConfig((server_rec *)srv);
651
652     /*
653      * Reconnect to the context of ssl_phrase_Handle()
654      */
655     s                      = myCtxVarGet(mc,  1, server_rec *);
656     p                      = myCtxVarGet(mc,  2, apr_pool_t *);
657     aPassPhrase            = myCtxVarGet(mc,  3, apr_array_header_t *);
658     pnPassPhraseCur        = myCtxVarGet(mc,  4, int *);
659     cppPassPhraseCur       = myCtxVarGet(mc,  5, char **);
660     cpVHostID              = myCtxVarGet(mc,  6, char *);
661     cpAlgoType             = myCtxVarGet(mc,  7, char *);
662     pnPassPhraseDialog     = myCtxVarGet(mc,  8, int *);
663     pnPassPhraseDialogCur  = myCtxVarGet(mc,  9, int *);
664     pbPassPhraseDialogOnce = myCtxVarGet(mc, 10, BOOL *);
665     sc                     = mySrvConfig(s);
666
667     (*pnPassPhraseDialog)++;
668     (*pnPassPhraseDialogCur)++;
669
670     /*
671      * When remembered pass phrases are available use them...
672      */
673     if ((cpp = pphrase_array_get(aPassPhrase, *pnPassPhraseCur)) != NULL) {
674         apr_cpystrn(buf, cpp, bufsize);
675         len = strlen(buf);
676         return len;
677     }
678
679     /*
680      * Builtin or Pipe dialog
681      */
682     if (sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN
683           || sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
684         char *prompt;
685         int i;
686
687         if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
688             if (!readtty) {
689                 ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
690                              "Init: Creating pass phrase dialog pipe child "
691                              "'%s'", sc->server->pphrase_dialog_path);
692                 if (ssl_pipe_child_create(p, sc->server->pphrase_dialog_path)
693                         != APR_SUCCESS) {
694                     ap_log_error(APLOG_MARK, APLOG_ERR, 0, s,
695                                  "Init: Failed to create pass phrase pipe '%s'",
696                                  sc->server->pphrase_dialog_path);
697                     PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
698                     memset(buf, 0, (unsigned int)bufsize);
699                     return (-1);
700                 }
701             }
702             ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
703                          "Init: Requesting pass phrase via piped dialog");
704         }
705         else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
706 #ifdef WIN32
707             PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
708             memset(buf, 0, (unsigned int)bufsize);
709             return (-1);
710 #else
711             /*
712              * stderr has already been redirected to the error_log.
713              * rather than attempting to temporarily rehook it to the terminal,
714              * we print the prompt to stdout before EVP_read_pw_string turns
715              * off tty echo
716              */
717             apr_file_open_stdout(&writetty, p);
718
719             ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
720                          "Init: Requesting pass phrase via builtin terminal "
721                          "dialog");
722 #endif
723         }
724
725         /*
726          * The first time display a header to inform the user about what
727          * program he actually speaks to, which module is responsible for
728          * this terminal dialog and why to the hell he has to enter
729          * something...
730          */
731         if (*pnPassPhraseDialog == 1) {
732             apr_file_printf(writetty, "%s mod_ssl/%s (Pass Phrase Dialog)\n",
733                             AP_SERVER_BASEVERSION, MOD_SSL_VERSION);
734             apr_file_printf(writetty, "Some of your private key files are encrypted for security reasons.\n");
735             apr_file_printf(writetty, "In order to read them you have to provide the pass phrases.\n");
736         }
737         if (*pbPassPhraseDialogOnce) {
738             *pbPassPhraseDialogOnce = FALSE;
739             apr_file_printf(writetty, "\n");
740             apr_file_printf(writetty, "Server %s (%s)\n", cpVHostID, cpAlgoType);
741         }
742
743         /*
744          * Emulate the OpenSSL internal pass phrase dialog
745          * (see crypto/pem/pem_lib.c:def_callback() for details)
746          */
747         prompt = "Enter pass phrase:";
748
749         for (;;) {
750             apr_file_puts(prompt, writetty);
751             if (sc->server->pphrase_dialog_type == SSL_PPTYPE_PIPE) {
752                 i = pipe_get_passwd_cb(buf, bufsize, "", FALSE);
753             }
754             else { /* sc->server->pphrase_dialog_type == SSL_PPTYPE_BUILTIN */
755                 i = EVP_read_pw_string(buf, bufsize, "", FALSE);
756             }
757             if (i != 0) {
758                 PEMerr(PEM_F_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
759                 memset(buf, 0, (unsigned int)bufsize);
760                 return (-1);
761             }
762             len = strlen(buf);
763             if (len < 1)
764                 apr_file_printf(writetty, "Apache:mod_ssl:Error: Pass phrase empty (needs to be at least 1 character).\n");
765             else
766                 break;
767         }
768     }
769
770     /*
771      * Filter program
772      */
773     else if (sc->server->pphrase_dialog_type == SSL_PPTYPE_FILTER) {
774         const char *cmd = sc->server->pphrase_dialog_path;
775         const char **argv = apr_palloc(p, sizeof(char *) * 4);
776         char *result;
777
778         ap_log_error(APLOG_MARK, APLOG_INFO, 0, s,
779                      "Init: Requesting pass phrase from dialog filter "
780                      "program (%s)", cmd);
781
782         argv[0] = cmd;
783         argv[1] = cpVHostID;
784         argv[2] = cpAlgoType;
785         argv[3] = NULL;
786
787         result = ssl_util_readfilter(s, p, cmd, argv);
788         apr_cpystrn(buf, result, bufsize);
789         len = strlen(buf);
790     }
791
792     /*
793      * Ok, we now have the pass phrase, so give it back
794      */
795     *cppPassPhraseCur = apr_pstrdup(p, buf);
796
797     /*
798      * And return it's length to OpenSSL...
799      */
800     return (len);
801 }
802