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