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