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