Move prototype for platform_new_connection() to a header file so the
[u/mdw/putty] / proxy.c
1 /*
2 * Network proxy abstraction in PuTTY
3 *
4 * A proxy layer, if necessary, wedges itself between the network
5 * code and the higher level backend.
6 */
7
8 #include <assert.h>
9 #include <ctype.h>
10 #include <string.h>
11
12 #define DEFINE_PLUG_METHOD_MACROS
13 #include "putty.h"
14 #include "network.h"
15 #include "proxy.h"
16
17 #define do_proxy_dns(cfg) \
18 (cfg->proxy_dns == FORCE_ON || \
19 (cfg->proxy_dns == AUTO && \
20 cfg->proxy_type != PROXY_SOCKS4 && \
21 cfg->proxy_type != PROXY_SOCKS5))
22
23 /*
24 * Call this when proxy negotiation is complete, so that this
25 * socket can begin working normally.
26 */
27 void proxy_activate (Proxy_Socket p)
28 {
29 void *data;
30 int len;
31 long output_before, output_after;
32
33 p->state = PROXY_STATE_ACTIVE;
34
35 /* we want to ignore new receive events until we have sent
36 * all of our buffered receive data.
37 */
38 sk_set_frozen(p->sub_socket, 1);
39
40 /* how many bytes of output have we buffered? */
41 output_before = bufchain_size(&p->pending_oob_output_data) +
42 bufchain_size(&p->pending_output_data);
43 /* and keep track of how many bytes do not get sent. */
44 output_after = 0;
45
46 /* send buffered OOB writes */
47 while (bufchain_size(&p->pending_oob_output_data) > 0) {
48 bufchain_prefix(&p->pending_oob_output_data, &data, &len);
49 output_after += sk_write_oob(p->sub_socket, data, len);
50 bufchain_consume(&p->pending_oob_output_data, len);
51 }
52
53 /* send buffered normal writes */
54 while (bufchain_size(&p->pending_output_data) > 0) {
55 bufchain_prefix(&p->pending_output_data, &data, &len);
56 output_after += sk_write(p->sub_socket, data, len);
57 bufchain_consume(&p->pending_output_data, len);
58 }
59
60 /* if we managed to send any data, let the higher levels know. */
61 if (output_after < output_before)
62 plug_sent(p->plug, output_after);
63
64 /* if we were asked to flush the output during
65 * the proxy negotiation process, do so now.
66 */
67 if (p->pending_flush) sk_flush(p->sub_socket);
68
69 /* if the backend wanted the socket unfrozen, try to unfreeze.
70 * our set_frozen handler will flush buffered receive data before
71 * unfreezing the actual underlying socket.
72 */
73 if (!p->freeze)
74 sk_set_frozen((Socket)p, 0);
75 }
76
77 /* basic proxy socket functions */
78
79 static Plug sk_proxy_plug (Socket s, Plug p)
80 {
81 Proxy_Socket ps = (Proxy_Socket) s;
82 Plug ret = ps->plug;
83 if (p)
84 ps->plug = p;
85 return ret;
86 }
87
88 static void sk_proxy_close (Socket s)
89 {
90 Proxy_Socket ps = (Proxy_Socket) s;
91
92 sk_close(ps->sub_socket);
93 sfree(ps);
94 }
95
96 static int sk_proxy_write (Socket s, const char *data, int len)
97 {
98 Proxy_Socket ps = (Proxy_Socket) s;
99
100 if (ps->state != PROXY_STATE_ACTIVE) {
101 bufchain_add(&ps->pending_output_data, data, len);
102 return bufchain_size(&ps->pending_output_data);
103 }
104 return sk_write(ps->sub_socket, data, len);
105 }
106
107 static int sk_proxy_write_oob (Socket s, const char *data, int len)
108 {
109 Proxy_Socket ps = (Proxy_Socket) s;
110
111 if (ps->state != PROXY_STATE_ACTIVE) {
112 bufchain_clear(&ps->pending_output_data);
113 bufchain_clear(&ps->pending_oob_output_data);
114 bufchain_add(&ps->pending_oob_output_data, data, len);
115 return len;
116 }
117 return sk_write_oob(ps->sub_socket, data, len);
118 }
119
120 static void sk_proxy_flush (Socket s)
121 {
122 Proxy_Socket ps = (Proxy_Socket) s;
123
124 if (ps->state != PROXY_STATE_ACTIVE) {
125 ps->pending_flush = 1;
126 return;
127 }
128 sk_flush(ps->sub_socket);
129 }
130
131 static void sk_proxy_set_private_ptr (Socket s, void *ptr)
132 {
133 Proxy_Socket ps = (Proxy_Socket) s;
134 sk_set_private_ptr(ps->sub_socket, ptr);
135 }
136
137 static void * sk_proxy_get_private_ptr (Socket s)
138 {
139 Proxy_Socket ps = (Proxy_Socket) s;
140 return sk_get_private_ptr(ps->sub_socket);
141 }
142
143 static void sk_proxy_set_frozen (Socket s, int is_frozen)
144 {
145 Proxy_Socket ps = (Proxy_Socket) s;
146
147 if (ps->state != PROXY_STATE_ACTIVE) {
148 ps->freeze = is_frozen;
149 return;
150 }
151
152 /* handle any remaining buffered recv data first */
153 if (bufchain_size(&ps->pending_input_data) > 0) {
154 ps->freeze = is_frozen;
155
156 /* loop while we still have buffered data, and while we are
157 * unfrozen. the plug_receive call in the loop could result
158 * in a call back into this function refreezing the socket,
159 * so we have to check each time.
160 */
161 while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
162 void *data;
163 int len;
164 bufchain_prefix(&ps->pending_input_data, &data, &len);
165 plug_receive(ps->plug, 0, data, len);
166 bufchain_consume(&ps->pending_input_data, len);
167 }
168
169 /* if we're still frozen, we'll have to wait for another
170 * call from the backend to finish unbuffering the data.
171 */
172 if (ps->freeze) return;
173 }
174
175 sk_set_frozen(ps->sub_socket, is_frozen);
176 }
177
178 static const char * sk_proxy_socket_error (Socket s)
179 {
180 Proxy_Socket ps = (Proxy_Socket) s;
181 if (ps->error != NULL || ps->sub_socket == NULL) {
182 return ps->error;
183 }
184 return sk_socket_error(ps->sub_socket);
185 }
186
187 /* basic proxy plug functions */
188
189 static int plug_proxy_closing (Plug p, const char *error_msg,
190 int error_code, int calling_back)
191 {
192 Proxy_Plug pp = (Proxy_Plug) p;
193 Proxy_Socket ps = pp->proxy_socket;
194
195 if (ps->state != PROXY_STATE_ACTIVE) {
196 ps->closing_error_msg = error_msg;
197 ps->closing_error_code = error_code;
198 ps->closing_calling_back = calling_back;
199 return ps->negotiate(ps, PROXY_CHANGE_CLOSING);
200 }
201 return plug_closing(ps->plug, error_msg,
202 error_code, calling_back);
203 }
204
205 static int plug_proxy_receive (Plug p, int urgent, char *data, int len)
206 {
207 Proxy_Plug pp = (Proxy_Plug) p;
208 Proxy_Socket ps = pp->proxy_socket;
209
210 if (ps->state != PROXY_STATE_ACTIVE) {
211 /* we will lose the urgentness of this data, but since most,
212 * if not all, of this data will be consumed by the negotiation
213 * process, hopefully it won't affect the protocol above us
214 */
215 bufchain_add(&ps->pending_input_data, data, len);
216 ps->receive_urgent = urgent;
217 ps->receive_data = data;
218 ps->receive_len = len;
219 return ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
220 }
221 return plug_receive(ps->plug, urgent, data, len);
222 }
223
224 static void plug_proxy_sent (Plug p, int bufsize)
225 {
226 Proxy_Plug pp = (Proxy_Plug) p;
227 Proxy_Socket ps = pp->proxy_socket;
228
229 if (ps->state != PROXY_STATE_ACTIVE) {
230 ps->sent_bufsize = bufsize;
231 ps->negotiate(ps, PROXY_CHANGE_SENT);
232 return;
233 }
234 plug_sent(ps->plug, bufsize);
235 }
236
237 static int plug_proxy_accepting (Plug p, OSSocket sock)
238 {
239 Proxy_Plug pp = (Proxy_Plug) p;
240 Proxy_Socket ps = pp->proxy_socket;
241
242 if (ps->state != PROXY_STATE_ACTIVE) {
243 ps->accepting_sock = sock;
244 return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
245 }
246 return plug_accepting(ps->plug, sock);
247 }
248
249 /*
250 * This function can accept a NULL pointer as `addr', in which case
251 * it will only check the host name.
252 */
253 static int proxy_for_destination (SockAddr addr, char *hostname, int port,
254 const Config *cfg)
255 {
256 int s = 0, e = 0;
257 char hostip[64];
258 int hostip_len, hostname_len;
259 const char *exclude_list;
260
261 /*
262 * Check the host name and IP against the hard-coded
263 * representations of `localhost'.
264 */
265 if (!cfg->even_proxy_localhost &&
266 (sk_hostname_is_local(hostname) ||
267 (addr && sk_address_is_local(addr))))
268 return 0; /* do not proxy */
269
270 /* we want a string representation of the IP address for comparisons */
271 if (addr) {
272 sk_getaddr(addr, hostip, 64);
273 hostip_len = strlen(hostip);
274 } else
275 hostip_len = 0; /* placate gcc; shouldn't be required */
276
277 hostname_len = strlen(hostname);
278
279 exclude_list = cfg->proxy_exclude_list;
280
281 /* now parse the exclude list, and see if either our IP
282 * or hostname matches anything in it.
283 */
284
285 while (exclude_list[s]) {
286 while (exclude_list[s] &&
287 (isspace((unsigned char)exclude_list[s]) ||
288 exclude_list[s] == ',')) s++;
289
290 if (!exclude_list[s]) break;
291
292 e = s;
293
294 while (exclude_list[e] &&
295 (isalnum((unsigned char)exclude_list[e]) ||
296 exclude_list[e] == '-' ||
297 exclude_list[e] == '.' ||
298 exclude_list[e] == '*')) e++;
299
300 if (exclude_list[s] == '*') {
301 /* wildcard at beginning of entry */
302
303 if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
304 exclude_list + s + 1, e - s - 1) == 0) ||
305 strnicmp(hostname + hostname_len - (e - s - 1),
306 exclude_list + s + 1, e - s - 1) == 0)
307 return 0; /* IP/hostname range excluded. do not use proxy. */
308
309 } else if (exclude_list[e-1] == '*') {
310 /* wildcard at end of entry */
311
312 if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
313 strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
314 return 0; /* IP/hostname range excluded. do not use proxy. */
315
316 } else {
317 /* no wildcard at either end, so let's try an absolute
318 * match (ie. a specific IP)
319 */
320
321 if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
322 return 0; /* IP/hostname excluded. do not use proxy. */
323 if (strnicmp(hostname, exclude_list + s, e - s) == 0)
324 return 0; /* IP/hostname excluded. do not use proxy. */
325 }
326
327 s = e;
328
329 /* Make sure we really have reached the next comma or end-of-string */
330 while (exclude_list[s] &&
331 !isspace((unsigned char)exclude_list[s]) &&
332 exclude_list[s] != ',') s++;
333 }
334
335 /* no matches in the exclude list, so use the proxy */
336 return 1;
337 }
338
339 SockAddr name_lookup(char *host, int port, char **canonicalname,
340 const Config *cfg)
341 {
342 if (cfg->proxy_type != PROXY_NONE &&
343 do_proxy_dns(cfg) &&
344 proxy_for_destination(NULL, host, port, cfg)) {
345 *canonicalname = dupstr(host);
346 return sk_nonamelookup(host);
347 }
348
349 return sk_namelookup(host, canonicalname);
350 }
351
352 Socket new_connection(SockAddr addr, char *hostname,
353 int port, int privport,
354 int oobinline, int nodelay, Plug plug,
355 const Config *cfg)
356 {
357 static const struct socket_function_table socket_fn_table = {
358 sk_proxy_plug,
359 sk_proxy_close,
360 sk_proxy_write,
361 sk_proxy_write_oob,
362 sk_proxy_flush,
363 sk_proxy_set_private_ptr,
364 sk_proxy_get_private_ptr,
365 sk_proxy_set_frozen,
366 sk_proxy_socket_error
367 };
368
369 static const struct plug_function_table plug_fn_table = {
370 plug_proxy_closing,
371 plug_proxy_receive,
372 plug_proxy_sent,
373 plug_proxy_accepting
374 };
375
376 if (cfg->proxy_type != PROXY_NONE &&
377 proxy_for_destination(addr, hostname, port, cfg))
378 {
379 Proxy_Socket ret;
380 Proxy_Plug pplug;
381 SockAddr proxy_addr;
382 char *proxy_canonical_name;
383 Socket sret;
384
385 if ((sret = platform_new_connection(addr, hostname, port, privport,
386 oobinline, nodelay, plug, cfg)) !=
387 NULL)
388 return sret;
389
390 ret = snew(struct Socket_proxy_tag);
391 ret->fn = &socket_fn_table;
392 ret->cfg = *cfg; /* STRUCTURE COPY */
393 ret->plug = plug;
394 ret->remote_addr = addr;
395 ret->remote_port = port;
396
397 ret->error = NULL;
398 ret->pending_flush = 0;
399 ret->freeze = 0;
400
401 bufchain_init(&ret->pending_input_data);
402 bufchain_init(&ret->pending_output_data);
403 bufchain_init(&ret->pending_oob_output_data);
404
405 ret->sub_socket = NULL;
406 ret->state = PROXY_STATE_NEW;
407 ret->negotiate = NULL;
408
409 if (cfg->proxy_type == PROXY_HTTP) {
410 ret->negotiate = proxy_http_negotiate;
411 } else if (cfg->proxy_type == PROXY_SOCKS4) {
412 ret->negotiate = proxy_socks4_negotiate;
413 } else if (cfg->proxy_type == PROXY_SOCKS5) {
414 ret->negotiate = proxy_socks5_negotiate;
415 } else if (cfg->proxy_type == PROXY_TELNET) {
416 ret->negotiate = proxy_telnet_negotiate;
417 } else {
418 ret->error = "Proxy error: Unknown proxy method";
419 return (Socket) ret;
420 }
421
422 /* create the proxy plug to map calls from the actual
423 * socket into our proxy socket layer */
424 pplug = snew(struct Plug_proxy_tag);
425 pplug->fn = &plug_fn_table;
426 pplug->proxy_socket = ret;
427
428 /* look-up proxy */
429 proxy_addr = sk_namelookup(cfg->proxy_host,
430 &proxy_canonical_name);
431 if (sk_addr_error(proxy_addr) != NULL) {
432 ret->error = "Proxy error: Unable to resolve proxy host name";
433 return (Socket)ret;
434 }
435 sfree(proxy_canonical_name);
436
437 /* create the actual socket we will be using,
438 * connected to our proxy server and port.
439 */
440 ret->sub_socket = sk_new(proxy_addr, cfg->proxy_port,
441 privport, oobinline,
442 nodelay, (Plug) pplug);
443 if (sk_socket_error(ret->sub_socket) != NULL)
444 return (Socket) ret;
445
446 sk_addr_free(proxy_addr);
447
448 /* start the proxy negotiation process... */
449 sk_set_frozen(ret->sub_socket, 0);
450 ret->negotiate(ret, PROXY_CHANGE_NEW);
451
452 return (Socket) ret;
453 }
454
455 /* no proxy, so just return the direct socket */
456 return sk_new(addr, port, privport, oobinline, nodelay, plug);
457 }
458
459 Socket new_listener(char *srcaddr, int port, Plug plug, int local_host_only,
460 const Config *cfg)
461 {
462 /* TODO: SOCKS (and potentially others) support inbound
463 * TODO: connections via the proxy. support them.
464 */
465
466 return sk_newlistener(srcaddr, port, plug, local_host_only);
467 }
468
469 /* ----------------------------------------------------------------------
470 * HTTP CONNECT proxy type.
471 */
472
473 static int get_line_end (char * data, int len)
474 {
475 int off = 0;
476
477 while (off < len)
478 {
479 if (data[off] == '\n') {
480 /* we have a newline */
481 off++;
482
483 /* is that the only thing on this line? */
484 if (off <= 2) return off;
485
486 /* if not, then there is the possibility that this header
487 * continues onto the next line, if it starts with a space
488 * or a tab.
489 */
490
491 if (off + 1 < len &&
492 data[off+1] != ' ' &&
493 data[off+1] != '\t') return off;
494
495 /* the line does continue, so we have to keep going
496 * until we see an the header's "real" end of line.
497 */
498 off++;
499 }
500
501 off++;
502 }
503
504 return -1;
505 }
506
507 int proxy_http_negotiate (Proxy_Socket p, int change)
508 {
509 if (p->state == PROXY_STATE_NEW) {
510 /* we are just beginning the proxy negotiate process,
511 * so we'll send off the initial bits of the request.
512 * for this proxy method, it's just a simple HTTP
513 * request
514 */
515 char *buf, dest[512];
516
517 sk_getaddr(p->remote_addr, dest, lenof(dest));
518
519 buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
520 dest, p->remote_port, dest, p->remote_port);
521 sk_write(p->sub_socket, buf, strlen(buf));
522 sfree(buf);
523
524 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
525 char buf[sizeof(p->cfg.proxy_username)+sizeof(p->cfg.proxy_password)];
526 char buf2[sizeof(buf)*4/3 + 100];
527 int i, j, len;
528 sprintf(buf, "%s:%s", p->cfg.proxy_username, p->cfg.proxy_password);
529 len = strlen(buf);
530 sprintf(buf2, "Proxy-Authorization: Basic ");
531 for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
532 base64_encode_atom((unsigned char *)(buf+i),
533 (len-i > 3 ? 3 : len-i), buf2+j);
534 strcpy(buf2+j, "\r\n");
535 sk_write(p->sub_socket, buf2, strlen(buf2));
536 }
537
538 sk_write(p->sub_socket, "\r\n", 2);
539
540 p->state = 1;
541 return 0;
542 }
543
544 if (change == PROXY_CHANGE_CLOSING) {
545 /* if our proxy negotiation process involves closing and opening
546 * new sockets, then we would want to intercept this closing
547 * callback when we were expecting it. if we aren't anticipating
548 * a socket close, then some error must have occurred. we'll
549 * just pass those errors up to the backend.
550 */
551 return plug_closing(p->plug, p->closing_error_msg,
552 p->closing_error_code,
553 p->closing_calling_back);
554 }
555
556 if (change == PROXY_CHANGE_SENT) {
557 /* some (or all) of what we wrote to the proxy was sent.
558 * we don't do anything new, however, until we receive the
559 * proxy's response. we might want to set a timer so we can
560 * timeout the proxy negotiation after a while...
561 */
562 return 0;
563 }
564
565 if (change == PROXY_CHANGE_ACCEPTING) {
566 /* we should _never_ see this, as we are using our socket to
567 * connect to a proxy, not accepting inbound connections.
568 * what should we do? close the socket with an appropriate
569 * error message?
570 */
571 return plug_accepting(p->plug, p->accepting_sock);
572 }
573
574 if (change == PROXY_CHANGE_RECEIVE) {
575 /* we have received data from the underlying socket, which
576 * we'll need to parse, process, and respond to appropriately.
577 */
578
579 char *data, *datap;
580 int len;
581 int eol;
582
583 if (p->state == 1) {
584
585 int min_ver, maj_ver, status;
586
587 /* get the status line */
588 len = bufchain_size(&p->pending_input_data);
589 assert(len > 0); /* or we wouldn't be here */
590 data = snewn(len, char);
591 bufchain_fetch(&p->pending_input_data, data, len);
592
593 eol = get_line_end(data, len);
594 if (eol < 0) {
595 sfree(data);
596 return 1;
597 }
598
599 status = -1;
600 /* We can't rely on whether the %n incremented the sscanf return */
601 if (sscanf((char *)data, "HTTP/%i.%i %n",
602 &maj_ver, &min_ver, &status) < 2 || status == -1) {
603 plug_closing(p->plug, "Proxy error: HTTP response was absent",
604 PROXY_ERROR_GENERAL, 0);
605 sfree(data);
606 return 1;
607 }
608
609 /* remove the status line from the input buffer. */
610 bufchain_consume(&p->pending_input_data, eol);
611 if (data[status] != '2') {
612 /* error */
613 char *buf;
614 data[eol] = '\0';
615 while (eol > status &&
616 (data[eol-1] == '\r' || data[eol-1] == '\n'))
617 data[--eol] = '\0';
618 buf = dupprintf("Proxy error: %s", data+status);
619 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
620 sfree(buf);
621 sfree(data);
622 return 1;
623 }
624
625 sfree(data);
626
627 p->state = 2;
628 }
629
630 if (p->state == 2) {
631
632 /* get headers. we're done when we get a
633 * header of length 2, (ie. just "\r\n")
634 */
635
636 len = bufchain_size(&p->pending_input_data);
637 assert(len > 0); /* or we wouldn't be here */
638 data = snewn(len, char);
639 datap = data;
640 bufchain_fetch(&p->pending_input_data, data, len);
641
642 eol = get_line_end(datap, len);
643 if (eol < 0) {
644 sfree(data);
645 return 1;
646 }
647 while (eol > 2)
648 {
649 bufchain_consume(&p->pending_input_data, eol);
650 datap += eol;
651 len -= eol;
652 eol = get_line_end(datap, len);
653 }
654
655 if (eol == 2) {
656 /* we're done */
657 bufchain_consume(&p->pending_input_data, 2);
658 proxy_activate(p);
659 /* proxy activate will have dealt with
660 * whatever is left of the buffer */
661 sfree(data);
662 return 1;
663 }
664
665 sfree(data);
666 return 1;
667 }
668 }
669
670 plug_closing(p->plug, "Proxy error: unexpected proxy error",
671 PROXY_ERROR_UNEXPECTED, 0);
672 return 1;
673 }
674
675 /* ----------------------------------------------------------------------
676 * SOCKS proxy type.
677 */
678
679 /* SOCKS version 4 */
680 int proxy_socks4_negotiate (Proxy_Socket p, int change)
681 {
682 if (p->state == PROXY_CHANGE_NEW) {
683
684 /* request format:
685 * version number (1 byte) = 4
686 * command code (1 byte)
687 * 1 = CONNECT
688 * 2 = BIND
689 * dest. port (2 bytes) [network order]
690 * dest. address (4 bytes)
691 * user ID (variable length, null terminated string)
692 */
693
694 int length, type, namelen;
695 char *command, addr[4], hostname[512];
696
697 type = sk_addrtype(p->remote_addr);
698 if (type == ADDRTYPE_IPV6) {
699 plug_closing(p->plug, "Proxy error: SOCKS version 4 does"
700 " not support IPv6", PROXY_ERROR_GENERAL, 0);
701 return 1;
702 } else if (type == ADDRTYPE_IPV4) {
703 namelen = 0;
704 sk_addrcopy(p->remote_addr, addr);
705 } else { /* type == ADDRTYPE_NAME */
706 assert(type == ADDRTYPE_NAME);
707 sk_getaddr(p->remote_addr, hostname, lenof(hostname));
708 namelen = strlen(hostname) + 1; /* include the NUL */
709 addr[0] = addr[1] = addr[2] = 0;
710 addr[3] = 1;
711 }
712
713 length = strlen(p->cfg.proxy_username) + namelen + 9;
714 command = snewn(length, char);
715 strcpy(command + 8, p->cfg.proxy_username);
716
717 command[0] = 4; /* version 4 */
718 command[1] = 1; /* CONNECT command */
719
720 /* port */
721 command[2] = (char) (p->remote_port >> 8) & 0xff;
722 command[3] = (char) p->remote_port & 0xff;
723
724 /* address */
725 memcpy(command + 4, addr, 4);
726
727 /* hostname */
728 memcpy(command + 8 + strlen(p->cfg.proxy_username) + 1,
729 hostname, namelen);
730
731 sk_write(p->sub_socket, command, length);
732 sfree(command);
733
734 p->state = 1;
735 return 0;
736 }
737
738 if (change == PROXY_CHANGE_CLOSING) {
739 /* if our proxy negotiation process involves closing and opening
740 * new sockets, then we would want to intercept this closing
741 * callback when we were expecting it. if we aren't anticipating
742 * a socket close, then some error must have occurred. we'll
743 * just pass those errors up to the backend.
744 */
745 return plug_closing(p->plug, p->closing_error_msg,
746 p->closing_error_code,
747 p->closing_calling_back);
748 }
749
750 if (change == PROXY_CHANGE_SENT) {
751 /* some (or all) of what we wrote to the proxy was sent.
752 * we don't do anything new, however, until we receive the
753 * proxy's response. we might want to set a timer so we can
754 * timeout the proxy negotiation after a while...
755 */
756 return 0;
757 }
758
759 if (change == PROXY_CHANGE_ACCEPTING) {
760 /* we should _never_ see this, as we are using our socket to
761 * connect to a proxy, not accepting inbound connections.
762 * what should we do? close the socket with an appropriate
763 * error message?
764 */
765 return plug_accepting(p->plug, p->accepting_sock);
766 }
767
768 if (change == PROXY_CHANGE_RECEIVE) {
769 /* we have received data from the underlying socket, which
770 * we'll need to parse, process, and respond to appropriately.
771 */
772
773 if (p->state == 1) {
774 /* response format:
775 * version number (1 byte) = 4
776 * reply code (1 byte)
777 * 90 = request granted
778 * 91 = request rejected or failed
779 * 92 = request rejected due to lack of IDENTD on client
780 * 93 = request rejected due to difference in user ID
781 * (what we sent vs. what IDENTD said)
782 * dest. port (2 bytes)
783 * dest. address (4 bytes)
784 */
785
786 char data[8];
787
788 if (bufchain_size(&p->pending_input_data) < 8)
789 return 1; /* not got anything yet */
790
791 /* get the response */
792 bufchain_fetch(&p->pending_input_data, data, 8);
793
794 if (data[0] != 0) {
795 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
796 "unexpected reply code version",
797 PROXY_ERROR_GENERAL, 0);
798 return 1;
799 }
800
801 if (data[1] != 90) {
802
803 switch (data[1]) {
804 case 92:
805 plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
806 PROXY_ERROR_GENERAL, 0);
807 break;
808 case 93:
809 plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
810 PROXY_ERROR_GENERAL, 0);
811 break;
812 case 91:
813 default:
814 plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
815 PROXY_ERROR_GENERAL, 0);
816 break;
817 }
818
819 return 1;
820 }
821 bufchain_consume(&p->pending_input_data, 8);
822
823 /* we're done */
824 proxy_activate(p);
825 /* proxy activate will have dealt with
826 * whatever is left of the buffer */
827 return 1;
828 }
829 }
830
831 plug_closing(p->plug, "Proxy error: unexpected proxy error",
832 PROXY_ERROR_UNEXPECTED, 0);
833 return 1;
834 }
835
836 /* SOCKS version 5 */
837 int proxy_socks5_negotiate (Proxy_Socket p, int change)
838 {
839 if (p->state == PROXY_CHANGE_NEW) {
840
841 /* initial command:
842 * version number (1 byte) = 5
843 * number of available authentication methods (1 byte)
844 * available authentication methods (1 byte * previous value)
845 * authentication methods:
846 * 0x00 = no authentication
847 * 0x01 = GSSAPI
848 * 0x02 = username/password
849 * 0x03 = CHAP
850 */
851
852 char command[4];
853 int len;
854
855 command[0] = 5; /* version 5 */
856 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
857 command[1] = 2; /* two methods supported: */
858 command[2] = 0x00; /* no authentication */
859 command[3] = 0x02; /* username/password */
860 len = 4;
861 } else {
862 command[1] = 1; /* one methods supported: */
863 command[2] = 0x00; /* no authentication */
864 len = 3;
865 }
866
867 sk_write(p->sub_socket, command, len);
868
869 p->state = 1;
870 return 0;
871 }
872
873 if (change == PROXY_CHANGE_CLOSING) {
874 /* if our proxy negotiation process involves closing and opening
875 * new sockets, then we would want to intercept this closing
876 * callback when we were expecting it. if we aren't anticipating
877 * a socket close, then some error must have occurred. we'll
878 * just pass those errors up to the backend.
879 */
880 return plug_closing(p->plug, p->closing_error_msg,
881 p->closing_error_code,
882 p->closing_calling_back);
883 }
884
885 if (change == PROXY_CHANGE_SENT) {
886 /* some (or all) of what we wrote to the proxy was sent.
887 * we don't do anything new, however, until we receive the
888 * proxy's response. we might want to set a timer so we can
889 * timeout the proxy negotiation after a while...
890 */
891 return 0;
892 }
893
894 if (change == PROXY_CHANGE_ACCEPTING) {
895 /* we should _never_ see this, as we are using our socket to
896 * connect to a proxy, not accepting inbound connections.
897 * what should we do? close the socket with an appropriate
898 * error message?
899 */
900 return plug_accepting(p->plug, p->accepting_sock);
901 }
902
903 if (change == PROXY_CHANGE_RECEIVE) {
904 /* we have received data from the underlying socket, which
905 * we'll need to parse, process, and respond to appropriately.
906 */
907
908 if (p->state == 1) {
909
910 /* initial response:
911 * version number (1 byte) = 5
912 * authentication method (1 byte)
913 * authentication methods:
914 * 0x00 = no authentication
915 * 0x01 = GSSAPI
916 * 0x02 = username/password
917 * 0x03 = CHAP
918 * 0xff = no acceptable methods
919 */
920 char data[2];
921
922 if (bufchain_size(&p->pending_input_data) < 2)
923 return 1; /* not got anything yet */
924
925 /* get the response */
926 bufchain_fetch(&p->pending_input_data, data, 2);
927
928 if (data[0] != 5) {
929 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
930 PROXY_ERROR_GENERAL, 0);
931 return 1;
932 }
933
934 if (data[1] == 0x00) p->state = 2; /* no authentication needed */
935 else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
936 else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
937 else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
938 else {
939 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
940 PROXY_ERROR_GENERAL, 0);
941 return 1;
942 }
943 bufchain_consume(&p->pending_input_data, 2);
944 }
945
946 if (p->state == 7) {
947
948 /* password authentication reply format:
949 * version number (1 bytes) = 1
950 * reply code (1 byte)
951 * 0 = succeeded
952 * >0 = failed
953 */
954 char data[2];
955
956 if (bufchain_size(&p->pending_input_data) < 2)
957 return 1; /* not got anything yet */
958
959 /* get the response */
960 bufchain_fetch(&p->pending_input_data, data, 2);
961
962 if (data[0] != 1) {
963 plug_closing(p->plug, "Proxy error: SOCKS password "
964 "subnegotiation contained wrong version number",
965 PROXY_ERROR_GENERAL, 0);
966 return 1;
967 }
968
969 if (data[1] != 0) {
970
971 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
972 " password authentication",
973 PROXY_ERROR_GENERAL, 0);
974 return 1;
975 }
976
977 bufchain_consume(&p->pending_input_data, 2);
978 p->state = 2; /* now proceed as authenticated */
979 }
980
981 if (p->state == 2) {
982
983 /* request format:
984 * version number (1 byte) = 5
985 * command code (1 byte)
986 * 1 = CONNECT
987 * 2 = BIND
988 * 3 = UDP ASSOCIATE
989 * reserved (1 byte) = 0x00
990 * address type (1 byte)
991 * 1 = IPv4
992 * 3 = domainname (first byte has length, no terminating null)
993 * 4 = IPv6
994 * dest. address (variable)
995 * dest. port (2 bytes) [network order]
996 */
997
998 char command[512];
999 int len;
1000 int type;
1001
1002 type = sk_addrtype(p->remote_addr);
1003 if (type == ADDRTYPE_IPV4) {
1004 len = 10; /* 4 hdr + 4 addr + 2 trailer */
1005 command[3] = 1; /* IPv4 */
1006 sk_addrcopy(p->remote_addr, command+4);
1007 } else if (type == ADDRTYPE_IPV6) {
1008 len = 22; /* 4 hdr + 16 addr + 2 trailer */
1009 command[3] = 4; /* IPv6 */
1010 sk_addrcopy(p->remote_addr, command+4);
1011 } else {
1012 assert(type == ADDRTYPE_NAME);
1013 command[3] = 3;
1014 sk_getaddr(p->remote_addr, command+5, 256);
1015 command[4] = strlen(command+5);
1016 len = 7 + command[4]; /* 4 hdr, 1 len, N addr, 2 trailer */
1017 }
1018
1019 command[0] = 5; /* version 5 */
1020 command[1] = 1; /* CONNECT command */
1021 command[2] = 0x00;
1022
1023 /* port */
1024 command[len-2] = (char) (p->remote_port >> 8) & 0xff;
1025 command[len-1] = (char) p->remote_port & 0xff;
1026
1027 sk_write(p->sub_socket, command, len);
1028
1029 p->state = 3;
1030 return 1;
1031 }
1032
1033 if (p->state == 3) {
1034
1035 /* reply format:
1036 * version number (1 bytes) = 5
1037 * reply code (1 byte)
1038 * 0 = succeeded
1039 * 1 = general SOCKS server failure
1040 * 2 = connection not allowed by ruleset
1041 * 3 = network unreachable
1042 * 4 = host unreachable
1043 * 5 = connection refused
1044 * 6 = TTL expired
1045 * 7 = command not supported
1046 * 8 = address type not supported
1047 * reserved (1 byte) = x00
1048 * address type (1 byte)
1049 * 1 = IPv4
1050 * 3 = domainname (first byte has length, no terminating null)
1051 * 4 = IPv6
1052 * server bound address (variable)
1053 * server bound port (2 bytes) [network order]
1054 */
1055 char data[5];
1056 int len;
1057
1058 /* First 5 bytes of packet are enough to tell its length. */
1059 if (bufchain_size(&p->pending_input_data) < 5)
1060 return 1; /* not got anything yet */
1061
1062 /* get the response */
1063 bufchain_fetch(&p->pending_input_data, data, 5);
1064
1065 if (data[0] != 5) {
1066 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1067 PROXY_ERROR_GENERAL, 0);
1068 return 1;
1069 }
1070
1071 if (data[1] != 0) {
1072 char buf[256];
1073
1074 strcpy(buf, "Proxy error: ");
1075
1076 switch (data[1]) {
1077 case 1: strcat(buf, "General SOCKS server failure"); break;
1078 case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1079 case 3: strcat(buf, "Network unreachable"); break;
1080 case 4: strcat(buf, "Host unreachable"); break;
1081 case 5: strcat(buf, "Connection refused"); break;
1082 case 6: strcat(buf, "TTL expired"); break;
1083 case 7: strcat(buf, "Command not supported"); break;
1084 case 8: strcat(buf, "Address type not supported"); break;
1085 default: sprintf(buf+strlen(buf),
1086 "Unrecognised SOCKS error code %d",
1087 data[1]);
1088 break;
1089 }
1090 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1091
1092 return 1;
1093 }
1094
1095 /*
1096 * Eat the rest of the reply packet.
1097 */
1098 len = 6; /* first 4 bytes, last 2 */
1099 switch (data[3]) {
1100 case 1: len += 4; break; /* IPv4 address */
1101 case 4: len += 16; break;/* IPv6 address */
1102 case 3: len += (unsigned char)data[4]; break; /* domain name */
1103 default:
1104 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1105 "unrecognised address format",
1106 PROXY_ERROR_GENERAL, 0);
1107 return 1;
1108 }
1109 if (bufchain_size(&p->pending_input_data) < len)
1110 return 1; /* not got whole reply yet */
1111 bufchain_consume(&p->pending_input_data, len);
1112
1113 /* we're done */
1114 proxy_activate(p);
1115 return 1;
1116 }
1117
1118 if (p->state == 4) {
1119 /* TODO: Handle GSSAPI authentication */
1120 plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1121 PROXY_ERROR_GENERAL, 0);
1122 return 1;
1123 }
1124
1125 if (p->state == 5) {
1126 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
1127 char userpwbuf[514];
1128 int ulen, plen;
1129 ulen = strlen(p->cfg.proxy_username);
1130 if (ulen > 255) ulen = 255; if (ulen < 1) ulen = 1;
1131 plen = strlen(p->cfg.proxy_password);
1132 if (plen > 255) plen = 255; if (plen < 1) plen = 1;
1133 userpwbuf[0] = 1; /* version number of subnegotiation */
1134 userpwbuf[1] = ulen;
1135 memcpy(userpwbuf+2, p->cfg.proxy_username, ulen);
1136 userpwbuf[ulen+2] = plen;
1137 memcpy(userpwbuf+ulen+3, p->cfg.proxy_password, plen);
1138 sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
1139 p->state = 7;
1140 } else
1141 plug_closing(p->plug, "Proxy error: Server chose "
1142 "username/password authentication but we "
1143 "didn't offer it!",
1144 PROXY_ERROR_GENERAL, 0);
1145 return 1;
1146 }
1147
1148 if (p->state == 6) {
1149 /* TODO: Handle CHAP authentication */
1150 plug_closing(p->plug, "Proxy error: We don't support CHAP authentication",
1151 PROXY_ERROR_GENERAL, 0);
1152 return 1;
1153 }
1154
1155 }
1156
1157 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1158 PROXY_ERROR_UNEXPECTED, 0);
1159 return 1;
1160 }
1161
1162 /* ----------------------------------------------------------------------
1163 * `Telnet' proxy type.
1164 *
1165 * (This is for ad-hoc proxies where you connect to the proxy's
1166 * telnet port and send a command such as `connect host port'. The
1167 * command is configurable, since this proxy type is typically not
1168 * standardised or at all well-defined.)
1169 */
1170
1171 char *format_telnet_command(SockAddr addr, int port, const Config *cfg)
1172 {
1173 char *ret = NULL;
1174 int retlen = 0, retsize = 0;
1175 int so = 0, eo = 0;
1176 #define ENSURE(n) do { \
1177 if (retsize < retlen + n) { \
1178 retsize = retlen + n + 512; \
1179 ret = sresize(ret, retsize, char); \
1180 } \
1181 } while (0)
1182
1183 /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
1184 * %%, %host, %port, %user, and %pass
1185 */
1186
1187 while (cfg->proxy_telnet_command[eo] != 0) {
1188
1189 /* scan forward until we hit end-of-line,
1190 * or an escape character (\ or %) */
1191 while (cfg->proxy_telnet_command[eo] != 0 &&
1192 cfg->proxy_telnet_command[eo] != '%' &&
1193 cfg->proxy_telnet_command[eo] != '\\') eo++;
1194
1195 /* if we hit eol, break out of our escaping loop */
1196 if (cfg->proxy_telnet_command[eo] == 0) break;
1197
1198 /* if there was any unescaped text before the escape
1199 * character, send that now */
1200 if (eo != so) {
1201 ENSURE(eo - so);
1202 memcpy(ret + retlen, cfg->proxy_telnet_command + so, eo - so);
1203 retlen += eo - so;
1204 }
1205
1206 so = eo++;
1207
1208 /* if the escape character was the last character of
1209 * the line, we'll just stop and send it. */
1210 if (cfg->proxy_telnet_command[eo] == 0) break;
1211
1212 if (cfg->proxy_telnet_command[so] == '\\') {
1213
1214 /* we recognize \\, \%, \r, \n, \t, \x??.
1215 * anything else, we just send unescaped (including the \).
1216 */
1217
1218 switch (cfg->proxy_telnet_command[eo]) {
1219
1220 case '\\':
1221 ENSURE(1);
1222 ret[retlen++] = '\\';
1223 eo++;
1224 break;
1225
1226 case '%':
1227 ENSURE(1);
1228 ret[retlen++] = '%';
1229 eo++;
1230 break;
1231
1232 case 'r':
1233 ENSURE(1);
1234 ret[retlen++] = '\r';
1235 eo++;
1236 break;
1237
1238 case 'n':
1239 ENSURE(1);
1240 ret[retlen++] = '\n';
1241 eo++;
1242 break;
1243
1244 case 't':
1245 ENSURE(1);
1246 ret[retlen++] = '\t';
1247 eo++;
1248 break;
1249
1250 case 'x':
1251 case 'X':
1252 {
1253 /* escaped hexadecimal value (ie. \xff) */
1254 unsigned char v = 0;
1255 int i = 0;
1256
1257 for (;;) {
1258 eo++;
1259 if (cfg->proxy_telnet_command[eo] >= '0' &&
1260 cfg->proxy_telnet_command[eo] <= '9')
1261 v += cfg->proxy_telnet_command[eo] - '0';
1262 else if (cfg->proxy_telnet_command[eo] >= 'a' &&
1263 cfg->proxy_telnet_command[eo] <= 'f')
1264 v += cfg->proxy_telnet_command[eo] - 'a' + 10;
1265 else if (cfg->proxy_telnet_command[eo] >= 'A' &&
1266 cfg->proxy_telnet_command[eo] <= 'F')
1267 v += cfg->proxy_telnet_command[eo] - 'A' + 10;
1268 else {
1269 /* non hex character, so we abort and just
1270 * send the whole thing unescaped (including \x)
1271 */
1272 ENSURE(1);
1273 ret[retlen++] = '\\';
1274 eo = so + 1;
1275 break;
1276 }
1277
1278 /* we only extract two hex characters */
1279 if (i == 1) {
1280 ENSURE(1);
1281 ret[retlen++] = v;
1282 eo++;
1283 break;
1284 }
1285
1286 i++;
1287 v <<= 4;
1288 }
1289 }
1290 break;
1291
1292 default:
1293 ENSURE(2);
1294 memcpy(ret+retlen, cfg->proxy_telnet_command + so, 2);
1295 retlen += 2;
1296 eo++;
1297 break;
1298 }
1299 } else {
1300
1301 /* % escape. we recognize %%, %host, %port, %user, %pass.
1302 * anything else, we just send unescaped (including the %).
1303 */
1304
1305 if (cfg->proxy_telnet_command[eo] == '%') {
1306 ENSURE(1);
1307 ret[retlen++] = '%';
1308 eo++;
1309 }
1310 else if (strnicmp(cfg->proxy_telnet_command + eo,
1311 "host", 4) == 0) {
1312 char dest[512];
1313 int destlen;
1314 sk_getaddr(addr, dest, lenof(dest));
1315 destlen = strlen(dest);
1316 ENSURE(destlen);
1317 memcpy(ret+retlen, dest, destlen);
1318 retlen += destlen;
1319 eo += 4;
1320 }
1321 else if (strnicmp(cfg->proxy_telnet_command + eo,
1322 "port", 4) == 0) {
1323 char portstr[8], portlen;
1324 portlen = sprintf(portstr, "%i", port);
1325 ENSURE(portlen);
1326 memcpy(ret + retlen, portstr, portlen);
1327 retlen += portlen;
1328 eo += 4;
1329 }
1330 else if (strnicmp(cfg->proxy_telnet_command + eo,
1331 "user", 4) == 0) {
1332 int userlen = strlen(cfg->proxy_username);
1333 ENSURE(userlen);
1334 memcpy(ret+retlen, cfg->proxy_username, userlen);
1335 retlen += userlen;
1336 eo += 4;
1337 }
1338 else if (strnicmp(cfg->proxy_telnet_command + eo,
1339 "pass", 4) == 0) {
1340 int passlen = strlen(cfg->proxy_password);
1341 ENSURE(passlen);
1342 memcpy(ret+retlen, cfg->proxy_password, passlen);
1343 retlen += passlen;
1344 eo += 4;
1345 }
1346 else {
1347 /* we don't escape this, so send the % now, and
1348 * don't advance eo, so that we'll consider the
1349 * text immediately following the % as unescaped.
1350 */
1351 ENSURE(1);
1352 ret[retlen++] = '%';
1353 }
1354 }
1355
1356 /* resume scanning for additional escapes after this one. */
1357 so = eo;
1358 }
1359
1360 /* if there is any unescaped text at the end of the line, send it */
1361 if (eo != so) {
1362 ENSURE(eo - so);
1363 memcpy(ret + retlen, cfg->proxy_telnet_command + so, eo - so);
1364 retlen += eo - so;
1365 }
1366
1367 ENSURE(1);
1368 ret[retlen] = '\0';
1369 return ret;
1370
1371 #undef ENSURE
1372 }
1373
1374 int proxy_telnet_negotiate (Proxy_Socket p, int change)
1375 {
1376 if (p->state == PROXY_CHANGE_NEW) {
1377 char *formatted_cmd;
1378
1379 formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
1380 &p->cfg);
1381
1382 sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
1383 sfree(formatted_cmd);
1384
1385 p->state = 1;
1386 return 0;
1387 }
1388
1389 if (change == PROXY_CHANGE_CLOSING) {
1390 /* if our proxy negotiation process involves closing and opening
1391 * new sockets, then we would want to intercept this closing
1392 * callback when we were expecting it. if we aren't anticipating
1393 * a socket close, then some error must have occurred. we'll
1394 * just pass those errors up to the backend.
1395 */
1396 return plug_closing(p->plug, p->closing_error_msg,
1397 p->closing_error_code,
1398 p->closing_calling_back);
1399 }
1400
1401 if (change == PROXY_CHANGE_SENT) {
1402 /* some (or all) of what we wrote to the proxy was sent.
1403 * we don't do anything new, however, until we receive the
1404 * proxy's response. we might want to set a timer so we can
1405 * timeout the proxy negotiation after a while...
1406 */
1407 return 0;
1408 }
1409
1410 if (change == PROXY_CHANGE_ACCEPTING) {
1411 /* we should _never_ see this, as we are using our socket to
1412 * connect to a proxy, not accepting inbound connections.
1413 * what should we do? close the socket with an appropriate
1414 * error message?
1415 */
1416 return plug_accepting(p->plug, p->accepting_sock);
1417 }
1418
1419 if (change == PROXY_CHANGE_RECEIVE) {
1420 /* we have received data from the underlying socket, which
1421 * we'll need to parse, process, and respond to appropriately.
1422 */
1423
1424 /* we're done */
1425 proxy_activate(p);
1426 /* proxy activate will have dealt with
1427 * whatever is left of the buffer */
1428 return 1;
1429 }
1430
1431 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1432 PROXY_ERROR_UNEXPECTED, 0);
1433 return 1;
1434 }