This adds support to 'tunala' for supplying DH parameters (without which it
[openssl.git] / demos / tunala / tunala.c
1 #if defined(NO_BUFFER) || defined(NO_IP) || defined(NO_OPENSSL)
2 #error "Badness, NO_BUFFER, NO_IP or NO_OPENSSL is defined, turn them *off*"
3 #endif
4
5 /* Include our bits'n'pieces */
6 #include "tunala.h"
7
8
9 /********************************************/
10 /* Our local types that specify our "world" */
11 /********************************************/
12
13 /* These represent running "tunnels". Eg. if you wanted to do SSL in a
14  * "message-passing" scanario, the "int" file-descriptors might be replaced by
15  * thread or process IDs, and the "select" code might be replaced by message
16  * handling code. Whatever. */
17 typedef struct _tunala_item_t {
18         /* The underlying SSL state machine. This is a data-only processing unit
19          * and we communicate with it by talking to its four "buffers". */
20         state_machine_t sm;
21         /* The file-descriptors for the "dirty" (encrypted) side of the SSL
22          * setup. In actuality, this is typically a socket and both values are
23          * identical. */
24         int dirty_read, dirty_send;
25         /* The file-descriptors for the "clean" (unencrypted) side of the SSL
26          * setup. These could be stdin/stdout, a socket (both values the same),
27          * or whatever you like. */
28         int clean_read, clean_send;
29 } tunala_item_t;
30
31 /* This structure is used as the data for running the main loop. Namely, in a
32  * network format such as this, it is stuff for select() - but as pointed out,
33  * when moving the real-world to somewhere else, this might be replaced by
34  * something entirely different. It's basically the stuff that controls when
35  * it's time to do some "work". */
36 typedef struct _select_sets_t {
37         int max; /* As required as the first argument to select() */
38         fd_set reads, sends, excepts; /* As passed to select() */
39 } select_sets_t;
40 typedef struct _tunala_selector_t {
41         select_sets_t last_selected; /* Results of the last select() */
42         select_sets_t next_select; /* What we'll next select on */
43 } tunala_selector_t;
44
45 /* This structure is *everything*. We do it to avoid the use of globals so that,
46  * for example, it would be easier to shift things around between async-IO,
47  * thread-based, or multi-fork()ed (or combinations thereof). */
48 typedef struct _tunala_world_t {
49         /* The file-descriptor we "listen" on for new connections */
50         int listen_fd;
51         /* The array of tunnels */
52         tunala_item_t *tunnels;
53         /* the number of tunnels in use and allocated, respectively */
54         unsigned int tunnels_used, tunnels_size;
55         /* Our outside "loop" context stuff */
56         tunala_selector_t selector;
57         /* Our SSL_CTX, which is configured as the SSL client or server and has
58          * the various cert-settings and callbacks configured. */
59         SSL_CTX *ssl_ctx;
60         /* Simple flag with complex logic :-) Indicates whether we're an SSL
61          * server or an SSL client. */
62         int server_mode;
63 } tunala_world_t;
64
65 /*****************************/
66 /* Internal static functions */
67 /*****************************/
68
69 static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
70                 const char *CAfile, const char *cert, const char *key,
71                 const char *dcert, const char *dkey, const char *cipher_list,
72                 const char *dh_file, const char *dh_special, int out_state,
73                 int out_verify, int verify_mode, unsigned int verify_depth);
74 static void selector_init(tunala_selector_t *selector);
75 static void selector_add_listener(tunala_selector_t *selector, int fd);
76 static void selector_add_tunala(tunala_selector_t *selector, tunala_item_t *t);
77 static int selector_select(tunala_selector_t *selector);
78 /* This returns -1 for error, 0 for no new connections, or 1 for success, in
79  * which case *newfd is populated. */
80 static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd);
81 static int tunala_world_new_item(tunala_world_t *world, int fd,
82                 const unsigned char *ip, unsigned short port);
83 static void tunala_world_del_item(tunala_world_t *world, unsigned int idx);
84 static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item);
85
86 /*********************************************/
87 /* MAIN FUNCTION (and its utility functions) */
88 /*********************************************/
89
90 static const char *def_proxyhost = "127.0.0.1:443";
91 static const char *def_listenhost = "127.0.0.1:8080";
92 static int def_max_tunnels = 50;
93 static const char *def_cacert = NULL;
94 static const char *def_cert = NULL;
95 static const char *def_key = NULL;
96 static const char *def_dcert = NULL;
97 static const char *def_dkey = NULL;
98 static const char *def_engine_id = NULL;
99 static int def_server_mode = 0;
100 static const char *def_cipher_list = NULL;
101 static const char *def_dh_file = NULL;
102 static const char *def_dh_special = NULL;
103 static int def_out_state = 0;
104 static unsigned int def_out_verify = 0;
105 static int def_out_totals = 0;
106 static int def_verify_mode = 0;
107 static unsigned int def_verify_depth = 10;
108
109 static const char *helpstring =
110 "\n'Tunala' (A tunneler with a New Zealand accent)\n"
111 "Usage: tunala [options], where options are from;\n"
112 " -listen [host:]<port>  (default = 127.0.0.1:8080)\n"
113 " -proxy <host>:<port>   (default = 127.0.0.1:443)\n"
114 " -maxtunnels <num>      (default = 50)\n"
115 " -cacert <path|NULL>    (default = NULL)\n"
116 " -cert <path|NULL>      (default = NULL)\n"
117 " -key <path|NULL>       (default = whatever '-cert' is)\n"
118 " -dcert <path|NULL>     (usually for DSA, default = NULL)\n"
119 " -dkey <path|NULL>      (usually for DSA, default = whatever '-dcert' is)\n"
120 " -engine <id|NULL>      (default = NULL)\n"
121 " -server <0|1>          (default = 0, ie. an SSL client)\n"
122 " -cipher <list>         (specifies cipher list to use)\n"
123 " -dh_file <path>        (a PEM file containing DH parameters to use)\n"
124 " -dh_special <NULL|generate|standard> (see below: def=NULL)\n"
125 " -out_state             (prints SSL handshake states)\n"
126 " -out_verify <0|1|2|3>  (prints certificate verification states: def=1)\n"
127 " -out_totals            (prints out byte-totals when a tunnel closes)\n"
128 " -v_peer                (verify the peer certificate)\n"
129 " -v_strict              (do not continue if peer doesn't authenticate)\n"
130 " -v_once                (no verification in renegotiates)\n"
131 " -v_depth <num>         (limit certificate chain depth, default = 10)\n"
132 " -<h|help|?>            (displays this help screen)\n"
133 "Notes:\n"
134 "(1) It is recommended to specify a cert+key when operating as an SSL server.\n"
135 "    If you only specify '-cert', the same file must contain a matching\n"
136 "    private key.\n"
137 "(2) Either dh_file or dh_special can be used to specify where DH parameters\n"
138 "    will be obtained from (or '-dh_special NULL' for the default choice) but\n"
139 "    you cannot specify both. For dh_special, 'generate' will create new DH\n"
140 "    parameters on startup, and 'standard' will use embedded parameters\n"
141 "    instead.\n";
142
143 /* Default DH parameters for use with "-dh_special standard" ... stolen striaght
144  * from s_server. */
145 static unsigned char dh512_p[]={
146         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
147         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
148         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
149         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
150         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
151         0x47,0x74,0xE8,0x33,
152         };
153 static unsigned char dh512_g[]={
154         0x02,
155         };
156
157 /* And the function that parses the above "standard" parameters, again, straight
158  * out of s_server. */
159 static DH *get_dh512(void)
160         {
161         DH *dh=NULL;
162
163         if ((dh=DH_new()) == NULL) return(NULL);
164         dh->p=BN_bin2bn(dh512_p,sizeof(dh512_p),NULL);
165         dh->g=BN_bin2bn(dh512_g,sizeof(dh512_g),NULL);
166         if ((dh->p == NULL) || (dh->g == NULL))
167                 return(NULL);
168         return(dh);
169         }
170
171 /* Various help/error messages used by main() */
172 static int usage(const char *errstr, int isunknownarg)
173 {
174         if(isunknownarg)
175                 fprintf(stderr, "Error: unknown argument '%s'\n", errstr);
176         else
177                 fprintf(stderr, "Error: %s\n", errstr);
178         fprintf(stderr, "%s\n", helpstring);
179         return 1;
180 }
181
182 static int err_str0(const char *str0)
183 {
184         fprintf(stderr, str0);
185         fprintf(stderr, "\n");
186         return 1;
187 }
188
189 static int err_str1(const char *str0, const char *str1)
190 {
191         fprintf(stderr, str0, str1);
192         fprintf(stderr, "\n");
193         return 1;
194 }
195
196 static int parse_max_tunnels(const char *s, unsigned int *maxtunnels)
197 {
198         unsigned long l;
199         char *temp;
200         l = strtoul(s, &temp, 10);
201         if((temp == s) || (*temp != '\0') || (l < 1) || (l > 1024)) {
202                 fprintf(stderr, "Error, '%s' is an invalid value for "
203                                 "maxtunnels\n", s);
204                 return 0;
205         }
206         *maxtunnels = (unsigned int)l;
207         return 1;
208 }
209
210 static int parse_server_mode(const char *s, int *servermode)
211 {
212         unsigned long l;
213         char *temp;
214         l = strtoul(s, &temp, 10);
215         if((temp == s) || (*temp != '\0') || (l > 1)) {
216                 fprintf(stderr, "Error, '%s' is an invalid value for the "
217                                 "server mode\n", s);
218                 return 0;
219         }
220         *servermode = (int)l;
221         return 1;
222 }
223
224 static int parse_dh_special(const char *s, const char **dh_special)
225 {
226         if((strcmp(s, "NULL") == 0) || (strcmp(s, "generate") == 0) ||
227                         (strcmp(s, "standard") == 0)) {
228                 *dh_special = s;
229                 return 1;
230         }
231         fprintf(stderr, "Error, '%s' is an invalid value for 'dh_special'\n", s);
232         return 0;
233 }
234
235 static int parse_verify_level(const char *s, unsigned int *verify_level)
236 {
237         unsigned long l;
238         char *temp;
239         l = strtoul(s, &temp, 10);
240         if((temp == s) || (*temp != '\0') || (l > 3)) {
241                 fprintf(stderr, "Error, '%s' is an invalid value for "
242                                 "out_verify\n", s);
243                 return 0;
244         }
245         *verify_level = (unsigned int)l;
246         return 1;
247 }
248
249 static int parse_verify_depth(const char *s, unsigned int *verify_depth)
250 {
251         unsigned long l;
252         char *temp;
253         l = strtoul(s, &temp, 10);
254         if((temp == s) || (*temp != '\0') || (l < 1) || (l > 50)) {
255                 fprintf(stderr, "Error, '%s' is an invalid value for "
256                                 "verify_depth\n", s);
257                 return 0;
258         }
259         *verify_depth = (unsigned int)l;
260         return 1;
261 }
262
263 /* Some fprintf format strings used when tunnels close */
264 static const char *io_stats_client_dirty =
265 "    SSL (network) traffic to/from server; %8lu bytes in, %8lu bytes out\n";
266 static const char *io_stats_client_clean =
267 "    tunnelled data to/from server;        %8lu bytes in, %8lu bytes out\n";
268 static const char *io_stats_server_dirty =
269 "    SSL (network) traffic to/from client; %8lu bytes in, %8lu bytes out\n";
270 static const char *io_stats_server_clean =
271 "    tunnelled data to/from client;        %8lu bytes in, %8lu bytes out\n";
272
273 int main(int argc, char *argv[])
274 {
275         unsigned int loop;
276         int newfd;
277         tunala_world_t world;
278         tunala_item_t *t_item;
279         unsigned char *proxy_ip;
280         unsigned short proxy_port;
281         /* Overridables */
282         const char *proxyhost = def_proxyhost;
283         const char *listenhost = def_listenhost;
284         unsigned int max_tunnels = def_max_tunnels;
285         const char *cacert = def_cacert;
286         const char *cert = def_cert;
287         const char *key = def_key;
288         const char *dcert = def_dcert;
289         const char *dkey = def_dkey;
290         const char *engine_id = def_engine_id;
291         int server_mode = def_server_mode;
292         const char *cipher_list = def_cipher_list;
293         const char *dh_file = def_dh_file;
294         const char *dh_special = def_dh_special;
295         int out_state = def_out_state;
296         unsigned int out_verify = def_out_verify;
297         int out_totals = def_out_totals;
298         int verify_mode = def_verify_mode;
299         unsigned int verify_depth = def_verify_depth;
300
301 /* Parse command-line arguments */
302 next_arg:
303         argc--; argv++;
304         if(argc > 0) {
305                 if(strcmp(*argv, "-listen") == 0) {
306                         if(argc < 2)
307                                 return usage("-listen requires an argument", 0);
308                         argc--; argv++;
309                         listenhost = *argv;
310                         goto next_arg;
311                 } else if(strcmp(*argv, "-proxy") == 0) {
312                         if(argc < 2)
313                                 return usage("-proxy requires an argument", 0);
314                         argc--; argv++;
315                         proxyhost = *argv;
316                         goto next_arg;
317                 } else if(strcmp(*argv, "-maxtunnels") == 0) {
318                         if(argc < 2)
319                                 return usage("-maxtunnels requires an argument", 0);
320                         argc--; argv++;
321                         if(!parse_max_tunnels(*argv, &max_tunnels))
322                                 return 1;
323                         goto next_arg;
324                 } else if(strcmp(*argv, "-cacert") == 0) {
325                         if(argc < 2)
326                                 return usage("-cacert requires an argument", 0);
327                         argc--; argv++;
328                         if(strcmp(*argv, "NULL") == 0)
329                                 cacert = NULL;
330                         else
331                                 cacert = *argv;
332                         goto next_arg;
333                 } else if(strcmp(*argv, "-cert") == 0) {
334                         if(argc < 2)
335                                 return usage("-cert requires an argument", 0);
336                         argc--; argv++;
337                         if(strcmp(*argv, "NULL") == 0)
338                                 cert = NULL;
339                         else
340                                 cert = *argv;
341                         goto next_arg;
342                 } else if(strcmp(*argv, "-key") == 0) {
343                         if(argc < 2)
344                                 return usage("-key requires an argument", 0);
345                         argc--; argv++;
346                         if(strcmp(*argv, "NULL") == 0)
347                                 key = NULL;
348                         else
349                                 key = *argv;
350                         goto next_arg;
351                 } else if(strcmp(*argv, "-dcert") == 0) {
352                         if(argc < 2)
353                                 return usage("-dcert requires an argument", 0);
354                         argc--; argv++;
355                         if(strcmp(*argv, "NULL") == 0)
356                                 dcert = NULL;
357                         else
358                                 dcert = *argv;
359                         goto next_arg;
360                 } else if(strcmp(*argv, "-dkey") == 0) {
361                         if(argc < 2)
362                                 return usage("-dkey requires an argument", 0);
363                         argc--; argv++;
364                         if(strcmp(*argv, "NULL") == 0)
365                                 dkey = NULL;
366                         else
367                                 dkey = *argv;
368                         goto next_arg;
369                 } else if(strcmp(*argv, "-engine") == 0) {
370                         if(argc < 2)
371                                 return usage("-engine requires an argument", 0);
372                         argc--; argv++;
373                         engine_id = *argv;
374                         goto next_arg;
375                 } else if(strcmp(*argv, "-server") == 0) {
376                         if(argc < 2)
377                                 return usage("-server requires an argument", 0);
378                         argc--; argv++;
379                         if(!parse_server_mode(*argv, &server_mode))
380                                 return 1;
381                         goto next_arg;
382                 } else if(strcmp(*argv, "-cipher") == 0) {
383                         if(argc < 2)
384                                 return usage("-cipher requires an argument", 0);
385                         argc--; argv++;
386                         cipher_list = *argv;
387                         goto next_arg;
388                 } else if(strcmp(*argv, "-dh_file") == 0) {
389                         if(argc < 2)
390                                 return usage("-dh_file requires an argument", 0);
391                         if(dh_special)
392                                 return usage("cannot mix -dh_file with "
393                                                 "-dh_special", 0);
394                         argc--; argv++;
395                         dh_file = *argv;
396                         goto next_arg;
397                 } else if(strcmp(*argv, "-dh_special") == 0) {
398                         if(argc < 2)
399                                 return usage("-dh_special requires an argument", 0);
400                         if(dh_file)
401                                 return usage("cannot mix -dh_file with "
402                                                 "-dh_special", 0);
403                         argc--; argv++;
404                         if(!parse_dh_special(*argv, &dh_special))
405                                 return 1;
406                         goto next_arg;
407                 } else if(strcmp(*argv, "-out_state") == 0) {
408                         out_state = 1;
409                         goto next_arg;
410                 } else if(strcmp(*argv, "-out_verify") == 0) {
411                         if(argc < 2)
412                                 return usage("-out_verify requires an argument", 0);
413                         argc--; argv++;
414                         if(!parse_verify_level(*argv, &out_verify))
415                                 return 1;
416                         goto next_arg;
417                 } else if(strcmp(*argv, "-out_totals") == 0) {
418                         out_totals = 1;
419                         goto next_arg;
420                 } else if(strcmp(*argv, "-v_peer") == 0) {
421                         verify_mode |= SSL_VERIFY_PEER;
422                         goto next_arg;
423                 } else if(strcmp(*argv, "-v_strict") == 0) {
424                         verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
425                         goto next_arg;
426                 } else if(strcmp(*argv, "-v_once") == 0) {
427                         verify_mode |= SSL_VERIFY_CLIENT_ONCE;
428                         goto next_arg;
429                 } else if(strcmp(*argv, "-v_depth") == 0) {
430                         if(argc < 2)
431                                 return usage("-v_depth requires an argument", 0);
432                         argc--; argv++;
433                         if(!parse_verify_depth(*argv, &verify_depth))
434                                 return 1;
435                         goto next_arg;
436                 } else if((strcmp(*argv, "-h") == 0) ||
437                                 (strcmp(*argv, "-help") == 0) ||
438                                 (strcmp(*argv, "-?") == 0)) {
439                         fprintf(stderr, "%s\n", helpstring);
440                         return 0;
441                 } else
442                         return usage(*argv, 1);
443         }
444
445         /* Initialise network stuff */
446         if(!ip_initialise())
447                 return err_str0("ip_initialise failed");
448         err_str0("ip_initialise succeeded");
449         /* Create the SSL_CTX */
450         if((world.ssl_ctx = initialise_ssl_ctx(server_mode, engine_id,
451                         cacert, cert, key, dcert, dkey, cipher_list, dh_file,
452                         dh_special, out_state, out_verify, verify_mode,
453                         verify_depth)) == NULL)
454                 return err_str1("initialise_ssl_ctx(engine_id=%s) failed",
455                         (engine_id == NULL) ? "NULL" : engine_id);
456         err_str1("initialise_ssl_ctx(engine_id=%s) succeeded",
457                         (engine_id == NULL) ? "NULL" : engine_id);
458         /* Create the listener */
459         if((world.listen_fd = ip_create_listener(listenhost)) == -1)
460                 return err_str1("ip_create_listener(%s) failed", listenhost);
461         err_str1("ip_create_listener(%s) succeeded", listenhost);
462         if(!ip_parse_address(proxyhost, &proxy_ip, &proxy_port, 0))
463                 return err_str1("ip_parse_address(%s) failed", proxyhost);
464         err_str1("ip_parse_address(%s) succeeded", proxyhost);
465         fprintf(stderr, "Info - proxying to %d.%d.%d.%d:%d\n",
466                         (int)proxy_ip[0], (int)proxy_ip[1],
467                         (int)proxy_ip[2], (int)proxy_ip[3], (int)proxy_port);
468         fprintf(stderr, "Info - set maxtunnels to %d\n", (int)max_tunnels);
469         fprintf(stderr, "Info - set to operate as an SSL %s\n",
470                         (server_mode ? "server" : "client"));
471         /* Initialise the rest of the stuff */
472         world.tunnels_used = world.tunnels_size = 0;
473         world.tunnels = NULL;
474         world.server_mode = server_mode;
475         selector_init(&world.selector);
476
477 /* We're ready to loop */
478 main_loop:
479         /* Should we listen for *new* tunnels? */
480         if(world.tunnels_used < max_tunnels)
481                 selector_add_listener(&world.selector, world.listen_fd);
482         /* We should add in our existing tunnels */
483         for(loop = 0; loop < world.tunnels_used; loop++)
484                 selector_add_tunala(&world.selector, world.tunnels + loop);
485         /* Now do the select */
486         switch(selector_select(&world.selector)) {
487         case -1:
488                 fprintf(stderr, "selector_select returned a badness error.\n");
489                 abort();
490         case 0:
491                 fprintf(stderr, "Warn, selector_select returned 0 - signal??\n");
492                 goto main_loop;
493         default:
494                 break;
495         }
496         /* Accept new connection if we should and can */
497         if((world.tunnels_used < max_tunnels) && (selector_get_listener(
498                                         &world.selector, world.listen_fd,
499                                         &newfd) == 1)) {
500                 /* We have a new connection */
501                 if(!tunala_world_new_item(&world, newfd,
502                                         proxy_ip, proxy_port))
503                         fprintf(stderr, "tunala_world_new_item failed\n");
504                 else
505                         fprintf(stderr, "Info, new tunnel opened, now up to "
506                                         "%d\n", world.tunnels_used);
507         }
508         /* Give each tunnel its moment, note the while loop is because it makes
509          * the logic easier than with "for" to deal with an array that may shift
510          * because of deletes. */
511         loop = 0;
512         t_item = world.tunnels;
513         while(loop < world.tunnels_used) {
514                 if(!tunala_item_io(&world.selector, t_item)) {
515                         /* We're closing whether for reasons of an error or a
516                          * natural close. Don't increment loop or t_item because
517                          * the next item is moving to us! */
518                         if(!out_totals)
519                                 goto skip_totals;
520                         fprintf(stderr, "Tunnel closing, traffic stats follow\n");
521                         /* Display the encrypted (over the network) stats */
522                         fprintf(stderr, (server_mode ? io_stats_server_dirty :
523                                                 io_stats_client_dirty),
524                                 buffer_total_in(state_machine_get_buffer(
525                                                 &t_item->sm,SM_DIRTY_IN)),
526                                 buffer_total_out(state_machine_get_buffer(
527                                                 &t_item->sm,SM_DIRTY_OUT)));
528                         /* Display the local (tunnelled) stats. NB: Data we
529                          * *receive* is data sent *out* of the state_machine on
530                          * its 'clean' side. Hence the apparent back-to-front
531                          * OUT/IN mixup here :-) */
532                         fprintf(stderr, (server_mode ? io_stats_server_clean :
533                                                 io_stats_client_clean),
534                                 buffer_total_out(state_machine_get_buffer(
535                                                 &t_item->sm,SM_CLEAN_OUT)),
536                                 buffer_total_in(state_machine_get_buffer(
537                                                 &t_item->sm,SM_CLEAN_IN)));
538 skip_totals:
539                         tunala_world_del_item(&world, loop);
540                         fprintf(stderr, "Info, tunnel closed, down to %d\n",
541                                         world.tunnels_used);
542                 }
543                 else {
544                         /* Move to the next item */
545                         loop++;
546                         t_item++;
547                 }
548         }
549         goto main_loop;
550         /* Should never get here */
551         abort();
552         return 1;
553 }
554
555 /****************/
556 /* OpenSSL bits */
557 /****************/
558
559 static int ctx_set_cert(SSL_CTX *ctx, const char *cert, const char *key)
560 {
561         FILE *fp = NULL;
562         X509 *x509 = NULL;
563         EVP_PKEY *pkey = NULL;
564         int toret = 0; /* Assume an error */
565
566         /* cert */
567         if(cert) {
568                 if((fp = fopen(cert, "r")) == NULL) {
569                         fprintf(stderr, "Error opening cert file '%s'\n", cert);
570                         goto err;
571                 }
572                 if(!PEM_read_X509(fp, &x509, NULL, NULL)) {
573                         fprintf(stderr, "Error reading PEM cert from '%s'\n",
574                                         cert);
575                         goto err;
576                 }
577                 if(!SSL_CTX_use_certificate(ctx, x509)) {
578                         fprintf(stderr, "Error, cert in '%s' can not be used\n",
579                                         cert);
580                         goto err;
581                 }
582                 /* Clear the FILE* for reuse in the "key" code */
583                 fclose(fp);
584                 fp = NULL;
585                 fprintf(stderr, "Info, operating with cert in '%s'\n", cert);
586                 /* If a cert was given without matching key, we assume the same
587                  * file contains the required key. */
588                 if(!key)
589                         key = cert;
590         } else {
591                 if(key)
592                         fprintf(stderr, "Error, can't specify a key without a "
593                                         "corresponding certificate\n");
594                 else
595                         fprintf(stderr, "Error, ctx_set_cert called with "
596                                         "NULLs!\n");
597                 goto err;
598         }
599         /* key */
600         if(key) {
601                 if((fp = fopen(key, "r")) == NULL) {
602                         fprintf(stderr, "Error opening key file '%s'\n", key);
603                         goto err;
604                 }
605                 if(!PEM_read_PrivateKey(fp, &pkey, NULL, NULL)) {
606                         fprintf(stderr, "Error reading PEM key from '%s'\n",
607                                         key);
608                         goto err;
609                 }
610                 if(!SSL_CTX_use_PrivateKey(ctx, pkey)) {
611                         fprintf(stderr, "Error, key in '%s' can not be used\n",
612                                         key);
613                         goto err;
614                 }
615                 fprintf(stderr, "Info, operating with key in '%s'\n", key);
616         } else
617                 fprintf(stderr, "Info, operating without a cert or key\n");
618         /* Success */
619         toret = 1; err:
620         if(x509)
621                 X509_free(x509);
622         if(pkey)
623                 EVP_PKEY_free(pkey);
624         if(fp)
625                 fclose(fp);
626         return toret;
627 }
628
629 static int ctx_set_dh(SSL_CTX *ctx, const char *dh_file, const char *dh_special)
630 {
631         DH *dh = NULL;
632         FILE *fp = NULL;
633
634         if(dh_special) {
635                 if(strcmp(dh_special, "NULL") == 0)
636                         return 1;
637                 if(strcmp(dh_special, "standard") == 0) {
638                         if((dh = get_dh512()) == NULL) {
639                                 fprintf(stderr, "Error, can't parse 'standard'"
640                                                 " DH parameters\n");
641                                 return 0;
642                         }
643                         fprintf(stderr, "Info, using 'standard' DH parameters\n");
644                         goto do_it;
645                 }
646                 if(strcmp(dh_special, "generate") != 0)
647                         /* This shouldn't happen - screening values is handled
648                          * in main(). */
649                         abort();
650                 fprintf(stderr, "Info, generating DH parameters ... ");
651                 fflush(stderr);
652                 if((dh = DH_generate_parameters(512, DH_GENERATOR_5,
653                                         NULL, NULL)) == NULL) {
654                         fprintf(stderr, "error!\n");
655                         return 0;
656                 }
657                 fprintf(stderr, "complete\n");
658                 goto do_it;
659         }
660         /* So, we're loading dh_file */
661         if((fp = fopen(dh_file, "r")) == NULL) {
662                 fprintf(stderr, "Error, couldn't open '%s' for DH parameters\n",
663                                 dh_file);
664                 return 0;
665         }
666         dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
667         fclose(fp);
668         if(dh == NULL) {
669                 fprintf(stderr, "Error, could not parse DH parameters from '%s'\n",
670                                 dh_file);
671                 return 0;
672         }
673         fprintf(stderr, "Info, using DH parameters from file '%s'\n", dh_file);
674 do_it:
675         SSL_CTX_set_tmp_dh(ctx, dh);
676         DH_free(dh);
677         return 1;
678 }
679
680 static SSL_CTX *initialise_ssl_ctx(int server_mode, const char *engine_id,
681                 const char *CAfile, const char *cert, const char *key,
682                 const char *dcert, const char *dkey, const char *cipher_list,
683                 const char *dh_file, const char *dh_special, int out_state,
684                 int out_verify, int verify_mode, unsigned int verify_depth)
685 {
686         SSL_CTX *ctx, *ret = NULL;
687         SSL_METHOD *meth;
688         ENGINE *e = NULL;
689
690         OpenSSL_add_ssl_algorithms();
691         SSL_load_error_strings();
692
693         meth = (server_mode ? SSLv23_server_method() : SSLv23_client_method());
694         if(meth == NULL)
695                 goto err;
696         if(engine_id) {
697                 if((e = ENGINE_by_id(engine_id)) == NULL) {
698                         fprintf(stderr, "Error obtaining '%s' engine, openssl "
699                                         "errors follow\n", engine_id);
700                         goto err;
701                 }
702                 if(!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
703                         fprintf(stderr, "Error assigning '%s' engine, openssl "
704                                         "errors follow\n", engine_id);
705                         goto err;
706                 }
707                 ENGINE_free(e);
708         }
709         if((ctx = SSL_CTX_new(meth)) == NULL)
710                 goto err;
711         /* cacert */
712         if(CAfile) {
713                 if(!X509_STORE_load_locations(SSL_CTX_get_cert_store(ctx),
714                                         CAfile, NULL)) {
715                         fprintf(stderr, "Error loading CA cert(s) in '%s'\n",
716                                         CAfile);
717                         goto err;
718                 }
719                 fprintf(stderr, "Info, operating with CA cert(s) in '%s'\n",
720                                 CAfile);
721         } else
722                 fprintf(stderr, "Info, operating without a CA cert(-list)\n");
723         if(!SSL_CTX_set_default_verify_paths(ctx)) {
724                 fprintf(stderr, "Error setting default verify paths\n");
725                 goto err;
726         }
727
728         /* cert and key */
729         if((cert || key) && !ctx_set_cert(ctx, cert, key))
730                 goto err;
731         /* dcert and dkey */
732         if((dcert || dkey) && !ctx_set_cert(ctx, dcert, dkey))
733                 goto err;
734
735         /* cipher_list */
736         if(cipher_list) {
737                 if(!SSL_CTX_set_cipher_list(ctx, cipher_list)) {
738                         fprintf(stderr, "Error setting cipher list '%s'\n",
739                                         cipher_list);
740                         goto err;
741                 }
742                 fprintf(stderr, "Info, set cipher list '%s'\n", cipher_list);
743         } else
744                 fprintf(stderr, "Info, operating with default cipher list\n");
745
746         /* dh_file & dh_special */
747         if((dh_file || dh_special) && !ctx_set_dh(ctx, dh_file, dh_special))
748                 goto err;
749
750         /* out_state (output of SSL handshake states to screen). */
751         if(out_state)
752                 cb_ssl_info_set_output(stderr);
753
754         /* out_verify */
755         if(out_verify > 0) {
756                 cb_ssl_verify_set_output(stderr);
757                 cb_ssl_verify_set_level(out_verify);
758         }
759
760         /* verify_depth */
761         cb_ssl_verify_set_depth(verify_depth);
762
763         /* Success! (includes setting verify_mode) */
764         SSL_CTX_set_info_callback(ctx, cb_ssl_info);
765         SSL_CTX_set_verify(ctx, verify_mode, cb_ssl_verify);
766         ret = ctx;
767 err:
768         if(!ret) {
769                 ERR_print_errors_fp(stderr);
770                 if(ctx)
771                         SSL_CTX_free(ctx);
772         }
773         return ret;
774 }
775
776 /*****************/
777 /* Selector bits */
778 /*****************/
779
780 static void selector_sets_init(select_sets_t *s)
781 {
782         s->max = 0;
783         FD_ZERO(&s->reads);
784         FD_ZERO(&s->sends);
785         FD_ZERO(&s->excepts);
786 }
787 static void selector_init(tunala_selector_t *selector)
788 {
789         selector_sets_init(&selector->last_selected);
790         selector_sets_init(&selector->next_select);
791 }
792
793 #define SEL_EXCEPTS 0x00
794 #define SEL_READS   0x01
795 #define SEL_SENDS   0x02
796 static void selector_add_raw_fd(tunala_selector_t *s, int fd, int flags)
797 {
798         FD_SET(fd, &s->next_select.excepts);
799         if(flags & SEL_READS)
800                 FD_SET(fd, &s->next_select.reads);
801         if(flags & SEL_SENDS)
802                 FD_SET(fd, &s->next_select.sends);
803         /* Adjust "max" */
804         if(s->next_select.max < (fd + 1))
805                 s->next_select.max = fd + 1;
806 }
807
808 static void selector_add_listener(tunala_selector_t *selector, int fd)
809 {
810         selector_add_raw_fd(selector, fd, SEL_READS);
811 }
812
813 static void selector_add_tunala(tunala_selector_t *s, tunala_item_t *t)
814 {
815         /* Set clean read if sm.clean_in is not full */
816         if(t->clean_read != -1) {
817                 selector_add_raw_fd(s, t->clean_read,
818                         (buffer_full(state_machine_get_buffer(&t->sm,
819                                 SM_CLEAN_IN)) ? SEL_EXCEPTS : SEL_READS));
820         }
821         /* Set clean send if sm.clean_out is not empty */
822         if(t->clean_send != -1) {
823                 selector_add_raw_fd(s, t->clean_send,
824                         (buffer_empty(state_machine_get_buffer(&t->sm,
825                                 SM_CLEAN_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
826         }
827         /* Set dirty read if sm.dirty_in is not full */
828         if(t->dirty_read != -1) {
829                 selector_add_raw_fd(s, t->dirty_read,
830                         (buffer_full(state_machine_get_buffer(&t->sm,
831                                 SM_DIRTY_IN)) ? SEL_EXCEPTS : SEL_READS));
832         }
833         /* Set dirty send if sm.dirty_out is not empty */
834         if(t->dirty_send != -1) {
835                 selector_add_raw_fd(s, t->dirty_send,
836                         (buffer_empty(state_machine_get_buffer(&t->sm,
837                                 SM_DIRTY_OUT)) ? SEL_EXCEPTS : SEL_SENDS));
838         }
839 }
840
841 static int selector_select(tunala_selector_t *selector)
842 {
843         memcpy(&selector->last_selected, &selector->next_select,
844                         sizeof(select_sets_t));
845         selector_sets_init(&selector->next_select);
846         return select(selector->last_selected.max,
847                         &selector->last_selected.reads,
848                         &selector->last_selected.sends,
849                         &selector->last_selected.excepts, NULL);
850 }
851
852 /* This returns -1 for error, 0 for no new connections, or 1 for success, in
853  * which case *newfd is populated. */
854 static int selector_get_listener(tunala_selector_t *selector, int fd, int *newfd)
855 {
856         if(FD_ISSET(fd, &selector->last_selected.excepts))
857                 return -1;
858         if(!FD_ISSET(fd, &selector->last_selected.reads))
859                 return 0;
860         if((*newfd = ip_accept_connection(fd)) == -1)
861                 return -1;
862         return 1;
863 }
864
865 /************************/
866 /* "Tunala" world stuff */
867 /************************/
868
869 static int tunala_world_make_room(tunala_world_t *world)
870 {
871         unsigned int newsize;
872         tunala_item_t *newarray;
873
874         if(world->tunnels_used < world->tunnels_size)
875                 return 1;
876         newsize = (world->tunnels_size == 0 ? 16 :
877                         ((world->tunnels_size * 3) / 2));
878         if((newarray = malloc(newsize * sizeof(tunala_item_t))) == NULL)
879                 return 0;
880         memset(newarray, 0, newsize * sizeof(tunala_item_t));
881         if(world->tunnels_used > 0)
882                 memcpy(newarray, world->tunnels,
883                         world->tunnels_used * sizeof(tunala_item_t));
884         if(world->tunnels_size > 0)
885                 free(world->tunnels);
886         /* migrate */
887         world->tunnels = newarray;
888         world->tunnels_size = newsize;
889         return 1;
890 }
891
892 static int tunala_world_new_item(tunala_world_t *world, int fd,
893                 const unsigned char *ip, unsigned short port)
894 {
895         tunala_item_t *item;
896         int newfd;
897         SSL *new_ssl = NULL;
898
899         if(!tunala_world_make_room(world))
900                 return 0;
901         if((new_ssl = SSL_new(world->ssl_ctx)) == NULL) {
902                 fprintf(stderr, "Error creating new SSL\n");
903                 ERR_print_errors_fp(stderr);
904                 return 0;
905         }
906         item = world->tunnels + (world->tunnels_used++);
907         state_machine_init(&item->sm);
908         item->clean_read = item->clean_send =
909                 item->dirty_read = item->dirty_send = -1;
910         if((newfd = ip_create_connection_split(ip, port)) == -1)
911                 goto err;
912         /* Which way round? If we're a server, "fd" is the dirty side and the
913          * connection we open is the clean one. For a client, it's the other way
914          * around. */
915         if(world->server_mode) {
916                 item->dirty_read = item->dirty_send = fd;
917                 item->clean_read = item->clean_send = newfd;
918         } else {
919                 item->clean_read = item->clean_send = fd;
920                 item->dirty_read = item->dirty_send = newfd;
921         }
922         /* We use the SSL's "app_data" to indicate a call-back induced "kill" */
923         SSL_set_app_data(new_ssl, NULL);
924         if(!state_machine_set_SSL(&item->sm, new_ssl, world->server_mode))
925                 goto err;
926         return 1;
927 err:
928         tunala_world_del_item(world, world->tunnels_used - 1);
929         return 0;
930
931 }
932
933 static void tunala_world_del_item(tunala_world_t *world, unsigned int idx)
934 {
935         tunala_item_t *item = world->tunnels + idx;
936         if(item->clean_read != -1)
937                 close(item->clean_read);
938         if(item->clean_send != item->clean_read)
939                 close(item->clean_send);
940         item->clean_read = item->clean_send = -1;
941         if(item->dirty_read != -1)
942                 close(item->dirty_read);
943         if(item->dirty_send != item->dirty_read)
944                 close(item->dirty_send);
945         item->dirty_read = item->dirty_send = -1;
946         state_machine_close(&item->sm);
947         /* OK, now we fix the item array */
948         if(idx + 1 < world->tunnels_used)
949                 /* We need to scroll entries to the left */
950                 memmove(world->tunnels + idx,
951                                 world->tunnels + (idx + 1),
952                                 (world->tunnels_used - (idx + 1)) *
953                                         sizeof(tunala_item_t));
954         world->tunnels_used--;
955 }
956
957 static int tunala_item_io(tunala_selector_t *selector, tunala_item_t *item)
958 {
959         int c_r, c_s, d_r, d_s; /* Four boolean flags */
960
961         /* Take ourselves out of the gene-pool if there was an except */
962         if((item->clean_read != -1) && FD_ISSET(item->clean_read,
963                                 &selector->last_selected.excepts))
964                 return 0;
965         if((item->clean_send != -1) && FD_ISSET(item->clean_send,
966                                 &selector->last_selected.excepts))
967                 return 0;
968         if((item->dirty_read != -1) && FD_ISSET(item->dirty_read,
969                                 &selector->last_selected.excepts))
970                 return 0;
971         if((item->dirty_send != -1) && FD_ISSET(item->dirty_send,
972                                 &selector->last_selected.excepts))
973                 return 0;
974         /* Grab our 4 IO flags */
975         c_r = c_s = d_r = d_s = 0;
976         if(item->clean_read != -1)
977                 c_r = FD_ISSET(item->clean_read, &selector->last_selected.reads);
978         if(item->clean_send != -1)
979                 c_s = FD_ISSET(item->clean_send, &selector->last_selected.sends);
980         if(item->dirty_read != -1)
981                 d_r = FD_ISSET(item->dirty_read, &selector->last_selected.reads);
982         if(item->dirty_send != -1)
983                 d_s = FD_ISSET(item->dirty_send, &selector->last_selected.sends);
984         /* If no IO has happened for us, skip needless data looping */
985         if(!c_r && !c_s && !d_r && !d_s)
986                 return 1;
987         if(c_r)
988                 c_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
989                                 SM_CLEAN_IN), item->clean_read) <= 0);
990         if(c_s)
991                 c_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
992                                 SM_CLEAN_OUT), item->clean_send) <= 0);
993         if(d_r)
994                 d_r = (buffer_from_fd(state_machine_get_buffer(&item->sm,
995                                 SM_DIRTY_IN), item->dirty_read) <= 0);
996         if(d_s)
997                 d_s = (buffer_to_fd(state_machine_get_buffer(&item->sm,
998                                 SM_DIRTY_OUT), item->dirty_send) <= 0);
999         /* If any of the flags is non-zero, that means they need closing */
1000         if(c_r) {
1001                 close(item->clean_read);
1002                 if(item->clean_send == item->clean_read)
1003                         item->clean_send = -1;
1004                 item->clean_read = -1;
1005         }
1006         if(c_s && (item->clean_send != -1)) {
1007                 close(item->clean_send);
1008                 if(item->clean_send == item->clean_read)
1009                         item->clean_read = -1;
1010                 item->clean_send = -1;
1011         }
1012         if(d_r) {
1013                 close(item->dirty_read);
1014                 if(item->dirty_send == item->dirty_read)
1015                         item->dirty_send = -1;
1016                 item->dirty_read = -1;
1017         }
1018         if(d_s && (item->dirty_send != -1)) {
1019                 close(item->dirty_send);
1020                 if(item->dirty_send == item->dirty_read)
1021                         item->dirty_read = -1;
1022                 item->dirty_send = -1;
1023         }
1024         /* This function name is attributed to the term donated by David
1025          * Schwartz on openssl-dev, message-ID:
1026          * <NCBBLIEPOCNJOAEKBEAKEEDGLIAA.davids@webmaster.com>. :-) */
1027         if(!state_machine_churn(&item->sm))
1028                 /* If the SSL closes, it will also zero-out the _in buffers
1029                  * and will in future process just outgoing data. As and
1030                  * when the outgoing data has gone, it will return zero
1031                  * here to tell us to bail out. */
1032                 return 0;
1033         /* Otherwise, we return zero if both sides are dead. */
1034         if(((item->clean_read == -1) || (item->clean_send == -1)) &&
1035                         ((item->dirty_read == -1) || (item->dirty_send == -1)))
1036                 return 0;
1037         /* If only one side closed, notify the SSL of this so it can take
1038          * appropriate action. */
1039         if((item->clean_read == -1) || (item->clean_send == -1)) {
1040                 if(!state_machine_close_clean(&item->sm))
1041                         return 0;
1042         }
1043         if((item->dirty_read == -1) || (item->dirty_send == -1)) {
1044                 if(!state_machine_close_dirty(&item->sm))
1045                         return 0;
1046         }
1047         return 1;
1048 }
1049