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