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