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