2 * Network proxy abstraction in PuTTY
4 * A proxy layer, if necessary, wedges itself between the network
5 * code and the higher level backend.
12 #define DEFINE_PLUG_METHOD_MACROS
17 #define do_proxy_dns(cfg) \
18 (cfg->proxy_dns == FORCE_ON || \
19 (cfg->proxy_dns == AUTO && cfg->proxy_type != PROXY_SOCKS4))
22 * Call this when proxy negotiation is complete, so that this
23 * socket can begin working normally.
25 void proxy_activate (Proxy_Socket p)
29 long output_before, output_after;
31 p->state = PROXY_STATE_ACTIVE;
33 /* we want to ignore new receive events until we have sent
34 * all of our buffered receive data.
36 sk_set_frozen(p->sub_socket, 1);
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. */
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);
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);
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);
62 /* if we were asked to flush the output during
63 * the proxy negotiation process, do so now.
65 if (p->pending_flush) sk_flush(p->sub_socket);
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.
72 sk_set_frozen((Socket)p, 0);
75 /* basic proxy socket functions */
77 static Plug sk_proxy_plug (Socket s, Plug p)
79 Proxy_Socket ps = (Proxy_Socket) s;
86 static void sk_proxy_close (Socket s)
88 Proxy_Socket ps = (Proxy_Socket) s;
90 sk_close(ps->sub_socket);
91 sk_addr_free(ps->remote_addr);
95 static int sk_proxy_write (Socket s, const char *data, int len)
97 Proxy_Socket ps = (Proxy_Socket) s;
99 if (ps->state != PROXY_STATE_ACTIVE) {
100 bufchain_add(&ps->pending_output_data, data, len);
101 return bufchain_size(&ps->pending_output_data);
103 return sk_write(ps->sub_socket, data, len);
106 static int sk_proxy_write_oob (Socket s, const char *data, int len)
108 Proxy_Socket ps = (Proxy_Socket) s;
110 if (ps->state != PROXY_STATE_ACTIVE) {
111 bufchain_clear(&ps->pending_output_data);
112 bufchain_clear(&ps->pending_oob_output_data);
113 bufchain_add(&ps->pending_oob_output_data, data, len);
116 return sk_write_oob(ps->sub_socket, data, len);
119 static void sk_proxy_flush (Socket s)
121 Proxy_Socket ps = (Proxy_Socket) s;
123 if (ps->state != PROXY_STATE_ACTIVE) {
124 ps->pending_flush = 1;
127 sk_flush(ps->sub_socket);
130 static void sk_proxy_set_private_ptr (Socket s, void *ptr)
132 Proxy_Socket ps = (Proxy_Socket) s;
133 sk_set_private_ptr(ps->sub_socket, ptr);
136 static void * sk_proxy_get_private_ptr (Socket s)
138 Proxy_Socket ps = (Proxy_Socket) s;
139 return sk_get_private_ptr(ps->sub_socket);
142 static void sk_proxy_set_frozen (Socket s, int is_frozen)
144 Proxy_Socket ps = (Proxy_Socket) s;
146 if (ps->state != PROXY_STATE_ACTIVE) {
147 ps->freeze = is_frozen;
151 /* handle any remaining buffered recv data first */
152 if (bufchain_size(&ps->pending_input_data) > 0) {
153 ps->freeze = is_frozen;
155 /* loop while we still have buffered data, and while we are
156 * unfrozen. the plug_receive call in the loop could result
157 * in a call back into this function refreezing the socket,
158 * so we have to check each time.
160 while (!ps->freeze && bufchain_size(&ps->pending_input_data) > 0) {
164 bufchain_prefix(&ps->pending_input_data, &data, &len);
165 if (len > lenof(databuf))
166 len = lenof(databuf);
167 memcpy(databuf, data, len);
168 bufchain_consume(&ps->pending_input_data, len);
169 plug_receive(ps->plug, 0, databuf, len);
172 /* if we're still frozen, we'll have to wait for another
173 * call from the backend to finish unbuffering the data.
175 if (ps->freeze) return;
178 sk_set_frozen(ps->sub_socket, is_frozen);
181 static const char * sk_proxy_socket_error (Socket s)
183 Proxy_Socket ps = (Proxy_Socket) s;
184 if (ps->error != NULL || ps->sub_socket == NULL) {
187 return sk_socket_error(ps->sub_socket);
190 /* basic proxy plug functions */
192 static void plug_proxy_log(Plug plug, int type, SockAddr addr, int port,
193 const char *error_msg, int error_code)
195 Proxy_Plug pp = (Proxy_Plug) plug;
196 Proxy_Socket ps = pp->proxy_socket;
198 plug_log(ps->plug, type, addr, port, error_msg, error_code);
201 static int plug_proxy_closing (Plug p, const char *error_msg,
202 int error_code, int calling_back)
204 Proxy_Plug pp = (Proxy_Plug) p;
205 Proxy_Socket ps = pp->proxy_socket;
207 if (ps->state != PROXY_STATE_ACTIVE) {
208 ps->closing_error_msg = error_msg;
209 ps->closing_error_code = error_code;
210 ps->closing_calling_back = calling_back;
211 return ps->negotiate(ps, PROXY_CHANGE_CLOSING);
213 return plug_closing(ps->plug, error_msg,
214 error_code, calling_back);
217 static int plug_proxy_receive (Plug p, int urgent, char *data, int len)
219 Proxy_Plug pp = (Proxy_Plug) p;
220 Proxy_Socket ps = pp->proxy_socket;
222 if (ps->state != PROXY_STATE_ACTIVE) {
223 /* we will lose the urgentness of this data, but since most,
224 * if not all, of this data will be consumed by the negotiation
225 * process, hopefully it won't affect the protocol above us
227 bufchain_add(&ps->pending_input_data, data, len);
228 ps->receive_urgent = urgent;
229 ps->receive_data = data;
230 ps->receive_len = len;
231 return ps->negotiate(ps, PROXY_CHANGE_RECEIVE);
233 return plug_receive(ps->plug, urgent, data, len);
236 static void plug_proxy_sent (Plug p, int bufsize)
238 Proxy_Plug pp = (Proxy_Plug) p;
239 Proxy_Socket ps = pp->proxy_socket;
241 if (ps->state != PROXY_STATE_ACTIVE) {
242 ps->sent_bufsize = bufsize;
243 ps->negotiate(ps, PROXY_CHANGE_SENT);
246 plug_sent(ps->plug, bufsize);
249 static int plug_proxy_accepting (Plug p, OSSocket sock)
251 Proxy_Plug pp = (Proxy_Plug) p;
252 Proxy_Socket ps = pp->proxy_socket;
254 if (ps->state != PROXY_STATE_ACTIVE) {
255 ps->accepting_sock = sock;
256 return ps->negotiate(ps, PROXY_CHANGE_ACCEPTING);
258 return plug_accepting(ps->plug, sock);
262 * This function can accept a NULL pointer as `addr', in which case
263 * it will only check the host name.
265 static int proxy_for_destination (SockAddr addr, char *hostname, int port,
270 int hostip_len, hostname_len;
271 const char *exclude_list;
274 * Check the host name and IP against the hard-coded
275 * representations of `localhost'.
277 if (!cfg->even_proxy_localhost &&
278 (sk_hostname_is_local(hostname) ||
279 (addr && sk_address_is_local(addr))))
280 return 0; /* do not proxy */
282 /* we want a string representation of the IP address for comparisons */
284 sk_getaddr(addr, hostip, 64);
285 hostip_len = strlen(hostip);
287 hostip_len = 0; /* placate gcc; shouldn't be required */
289 hostname_len = strlen(hostname);
291 exclude_list = cfg->proxy_exclude_list;
293 /* now parse the exclude list, and see if either our IP
294 * or hostname matches anything in it.
297 while (exclude_list[s]) {
298 while (exclude_list[s] &&
299 (isspace((unsigned char)exclude_list[s]) ||
300 exclude_list[s] == ',')) s++;
302 if (!exclude_list[s]) break;
306 while (exclude_list[e] &&
307 (isalnum((unsigned char)exclude_list[e]) ||
308 exclude_list[e] == '-' ||
309 exclude_list[e] == '.' ||
310 exclude_list[e] == '*')) e++;
312 if (exclude_list[s] == '*') {
313 /* wildcard at beginning of entry */
315 if ((addr && strnicmp(hostip + hostip_len - (e - s - 1),
316 exclude_list + s + 1, e - s - 1) == 0) ||
317 strnicmp(hostname + hostname_len - (e - s - 1),
318 exclude_list + s + 1, e - s - 1) == 0)
319 return 0; /* IP/hostname range excluded. do not use proxy. */
321 } else if (exclude_list[e-1] == '*') {
322 /* wildcard at end of entry */
324 if ((addr && strnicmp(hostip, exclude_list + s, e - s - 1) == 0) ||
325 strnicmp(hostname, exclude_list + s, e - s - 1) == 0)
326 return 0; /* IP/hostname range excluded. do not use proxy. */
329 /* no wildcard at either end, so let's try an absolute
330 * match (ie. a specific IP)
333 if (addr && strnicmp(hostip, exclude_list + s, e - s) == 0)
334 return 0; /* IP/hostname excluded. do not use proxy. */
335 if (strnicmp(hostname, exclude_list + s, e - s) == 0)
336 return 0; /* IP/hostname excluded. do not use proxy. */
341 /* Make sure we really have reached the next comma or end-of-string */
342 while (exclude_list[s] &&
343 !isspace((unsigned char)exclude_list[s]) &&
344 exclude_list[s] != ',') s++;
347 /* no matches in the exclude list, so use the proxy */
351 SockAddr name_lookup(char *host, int port, char **canonicalname,
352 const Config *cfg, int addressfamily)
354 if (cfg->proxy_type != PROXY_NONE &&
356 proxy_for_destination(NULL, host, port, cfg)) {
357 *canonicalname = dupstr(host);
358 return sk_nonamelookup(host);
361 return sk_namelookup(host, canonicalname, addressfamily);
364 Socket new_connection(SockAddr addr, char *hostname,
365 int port, int privport,
366 int oobinline, int nodelay, int keepalive,
367 Plug plug, const Config *cfg)
369 static const struct socket_function_table socket_fn_table = {
375 sk_proxy_set_private_ptr,
376 sk_proxy_get_private_ptr,
378 sk_proxy_socket_error
381 static const struct plug_function_table plug_fn_table = {
389 if (cfg->proxy_type != PROXY_NONE &&
390 proxy_for_destination(addr, hostname, port, cfg))
395 char *proxy_canonical_name;
398 if ((sret = platform_new_connection(addr, hostname, port, privport,
399 oobinline, nodelay, keepalive,
404 ret = snew(struct Socket_proxy_tag);
405 ret->fn = &socket_fn_table;
406 ret->cfg = *cfg; /* STRUCTURE COPY */
408 ret->remote_addr = addr; /* will need to be freed on close */
409 ret->remote_port = port;
412 ret->pending_flush = 0;
415 bufchain_init(&ret->pending_input_data);
416 bufchain_init(&ret->pending_output_data);
417 bufchain_init(&ret->pending_oob_output_data);
419 ret->sub_socket = NULL;
420 ret->state = PROXY_STATE_NEW;
421 ret->negotiate = NULL;
423 if (cfg->proxy_type == PROXY_HTTP) {
424 ret->negotiate = proxy_http_negotiate;
425 } else if (cfg->proxy_type == PROXY_SOCKS4) {
426 ret->negotiate = proxy_socks4_negotiate;
427 } else if (cfg->proxy_type == PROXY_SOCKS5) {
428 ret->negotiate = proxy_socks5_negotiate;
429 } else if (cfg->proxy_type == PROXY_TELNET) {
430 ret->negotiate = proxy_telnet_negotiate;
432 ret->error = "Proxy error: Unknown proxy method";
436 /* create the proxy plug to map calls from the actual
437 * socket into our proxy socket layer */
438 pplug = snew(struct Plug_proxy_tag);
439 pplug->fn = &plug_fn_table;
440 pplug->proxy_socket = ret;
443 proxy_addr = sk_namelookup(cfg->proxy_host,
444 &proxy_canonical_name, cfg->addressfamily);
445 if (sk_addr_error(proxy_addr) != NULL) {
446 ret->error = "Proxy error: Unable to resolve proxy host name";
449 sfree(proxy_canonical_name);
451 /* create the actual socket we will be using,
452 * connected to our proxy server and port.
454 ret->sub_socket = sk_new(proxy_addr, cfg->proxy_port,
456 nodelay, keepalive, (Plug) pplug);
457 if (sk_socket_error(ret->sub_socket) != NULL)
460 /* start the proxy negotiation process... */
461 sk_set_frozen(ret->sub_socket, 0);
462 ret->negotiate(ret, PROXY_CHANGE_NEW);
467 /* no proxy, so just return the direct socket */
468 return sk_new(addr, port, privport, oobinline, nodelay, keepalive, plug);
471 Socket new_listener(char *srcaddr, int port, Plug plug, int local_host_only,
472 const Config *cfg, int addressfamily)
474 /* TODO: SOCKS (and potentially others) support inbound
475 * TODO: connections via the proxy. support them.
478 return sk_newlistener(srcaddr, port, plug, local_host_only, addressfamily);
481 /* ----------------------------------------------------------------------
482 * HTTP CONNECT proxy type.
485 static int get_line_end (char * data, int len)
491 if (data[off] == '\n') {
492 /* we have a newline */
495 /* is that the only thing on this line? */
496 if (off <= 2) return off;
498 /* if not, then there is the possibility that this header
499 * continues onto the next line, if it starts with a space
504 data[off+1] != ' ' &&
505 data[off+1] != '\t') return off;
507 /* the line does continue, so we have to keep going
508 * until we see an the header's "real" end of line.
519 int proxy_http_negotiate (Proxy_Socket p, int change)
521 if (p->state == PROXY_STATE_NEW) {
522 /* we are just beginning the proxy negotiate process,
523 * so we'll send off the initial bits of the request.
524 * for this proxy method, it's just a simple HTTP
527 char *buf, dest[512];
529 sk_getaddr(p->remote_addr, dest, lenof(dest));
531 buf = dupprintf("CONNECT %s:%i HTTP/1.1\r\nHost: %s:%i\r\n",
532 dest, p->remote_port, dest, p->remote_port);
533 sk_write(p->sub_socket, buf, strlen(buf));
536 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
537 char buf[sizeof(p->cfg.proxy_username)+sizeof(p->cfg.proxy_password)];
538 char buf2[sizeof(buf)*4/3 + 100];
540 sprintf(buf, "%s:%s", p->cfg.proxy_username, p->cfg.proxy_password);
542 sprintf(buf2, "Proxy-Authorization: Basic ");
543 for (i = 0, j = strlen(buf2); i < len; i += 3, j += 4)
544 base64_encode_atom((unsigned char *)(buf+i),
545 (len-i > 3 ? 3 : len-i), buf2+j);
546 strcpy(buf2+j, "\r\n");
547 sk_write(p->sub_socket, buf2, strlen(buf2));
550 sk_write(p->sub_socket, "\r\n", 2);
556 if (change == PROXY_CHANGE_CLOSING) {
557 /* if our proxy negotiation process involves closing and opening
558 * new sockets, then we would want to intercept this closing
559 * callback when we were expecting it. if we aren't anticipating
560 * a socket close, then some error must have occurred. we'll
561 * just pass those errors up to the backend.
563 return plug_closing(p->plug, p->closing_error_msg,
564 p->closing_error_code,
565 p->closing_calling_back);
568 if (change == PROXY_CHANGE_SENT) {
569 /* some (or all) of what we wrote to the proxy was sent.
570 * we don't do anything new, however, until we receive the
571 * proxy's response. we might want to set a timer so we can
572 * timeout the proxy negotiation after a while...
577 if (change == PROXY_CHANGE_ACCEPTING) {
578 /* we should _never_ see this, as we are using our socket to
579 * connect to a proxy, not accepting inbound connections.
580 * what should we do? close the socket with an appropriate
583 return plug_accepting(p->plug, p->accepting_sock);
586 if (change == PROXY_CHANGE_RECEIVE) {
587 /* we have received data from the underlying socket, which
588 * we'll need to parse, process, and respond to appropriately.
597 int min_ver, maj_ver, status;
599 /* get the status line */
600 len = bufchain_size(&p->pending_input_data);
601 assert(len > 0); /* or we wouldn't be here */
602 data = snewn(len+1, char);
603 bufchain_fetch(&p->pending_input_data, data, len);
605 * We must NUL-terminate this data, because Windows
606 * sscanf appears to require a NUL at the end of the
607 * string because it strlens it _first_. Sigh.
611 eol = get_line_end(data, len);
618 /* We can't rely on whether the %n incremented the sscanf return */
619 if (sscanf((char *)data, "HTTP/%i.%i %n",
620 &maj_ver, &min_ver, &status) < 2 || status == -1) {
621 plug_closing(p->plug, "Proxy error: HTTP response was absent",
622 PROXY_ERROR_GENERAL, 0);
627 /* remove the status line from the input buffer. */
628 bufchain_consume(&p->pending_input_data, eol);
629 if (data[status] != '2') {
633 while (eol > status &&
634 (data[eol-1] == '\r' || data[eol-1] == '\n'))
636 buf = dupprintf("Proxy error: %s", data+status);
637 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
650 /* get headers. we're done when we get a
651 * header of length 2, (ie. just "\r\n")
654 len = bufchain_size(&p->pending_input_data);
655 assert(len > 0); /* or we wouldn't be here */
656 data = snewn(len, char);
658 bufchain_fetch(&p->pending_input_data, data, len);
660 eol = get_line_end(datap, len);
667 bufchain_consume(&p->pending_input_data, eol);
670 eol = get_line_end(datap, len);
675 bufchain_consume(&p->pending_input_data, 2);
677 /* proxy activate will have dealt with
678 * whatever is left of the buffer */
688 plug_closing(p->plug, "Proxy error: unexpected proxy error",
689 PROXY_ERROR_UNEXPECTED, 0);
693 /* ----------------------------------------------------------------------
697 /* SOCKS version 4 */
698 int proxy_socks4_negotiate (Proxy_Socket p, int change)
700 if (p->state == PROXY_CHANGE_NEW) {
703 * version number (1 byte) = 4
704 * command code (1 byte)
707 * dest. port (2 bytes) [network order]
708 * dest. address (4 bytes)
709 * user ID (variable length, null terminated string)
712 int length, type, namelen;
713 char *command, addr[4], hostname[512];
715 type = sk_addrtype(p->remote_addr);
716 if (type == ADDRTYPE_IPV6) {
717 plug_closing(p->plug, "Proxy error: SOCKS version 4 does"
718 " not support IPv6", PROXY_ERROR_GENERAL, 0);
720 } else if (type == ADDRTYPE_IPV4) {
722 sk_addrcopy(p->remote_addr, addr);
723 } else { /* type == ADDRTYPE_NAME */
724 assert(type == ADDRTYPE_NAME);
725 sk_getaddr(p->remote_addr, hostname, lenof(hostname));
726 namelen = strlen(hostname) + 1; /* include the NUL */
727 addr[0] = addr[1] = addr[2] = 0;
731 length = strlen(p->cfg.proxy_username) + namelen + 9;
732 command = snewn(length, char);
733 strcpy(command + 8, p->cfg.proxy_username);
735 command[0] = 4; /* version 4 */
736 command[1] = 1; /* CONNECT command */
739 command[2] = (char) (p->remote_port >> 8) & 0xff;
740 command[3] = (char) p->remote_port & 0xff;
743 memcpy(command + 4, addr, 4);
746 memcpy(command + 8 + strlen(p->cfg.proxy_username) + 1,
749 sk_write(p->sub_socket, command, length);
756 if (change == PROXY_CHANGE_CLOSING) {
757 /* if our proxy negotiation process involves closing and opening
758 * new sockets, then we would want to intercept this closing
759 * callback when we were expecting it. if we aren't anticipating
760 * a socket close, then some error must have occurred. we'll
761 * just pass those errors up to the backend.
763 return plug_closing(p->plug, p->closing_error_msg,
764 p->closing_error_code,
765 p->closing_calling_back);
768 if (change == PROXY_CHANGE_SENT) {
769 /* some (or all) of what we wrote to the proxy was sent.
770 * we don't do anything new, however, until we receive the
771 * proxy's response. we might want to set a timer so we can
772 * timeout the proxy negotiation after a while...
777 if (change == PROXY_CHANGE_ACCEPTING) {
778 /* we should _never_ see this, as we are using our socket to
779 * connect to a proxy, not accepting inbound connections.
780 * what should we do? close the socket with an appropriate
783 return plug_accepting(p->plug, p->accepting_sock);
786 if (change == PROXY_CHANGE_RECEIVE) {
787 /* we have received data from the underlying socket, which
788 * we'll need to parse, process, and respond to appropriately.
793 * version number (1 byte) = 4
794 * reply code (1 byte)
795 * 90 = request granted
796 * 91 = request rejected or failed
797 * 92 = request rejected due to lack of IDENTD on client
798 * 93 = request rejected due to difference in user ID
799 * (what we sent vs. what IDENTD said)
800 * dest. port (2 bytes)
801 * dest. address (4 bytes)
806 if (bufchain_size(&p->pending_input_data) < 8)
807 return 1; /* not got anything yet */
809 /* get the response */
810 bufchain_fetch(&p->pending_input_data, data, 8);
813 plug_closing(p->plug, "Proxy error: SOCKS proxy responded with "
814 "unexpected reply code version",
815 PROXY_ERROR_GENERAL, 0);
823 plug_closing(p->plug, "Proxy error: SOCKS server wanted IDENTD on client",
824 PROXY_ERROR_GENERAL, 0);
827 plug_closing(p->plug, "Proxy error: Username and IDENTD on client don't agree",
828 PROXY_ERROR_GENERAL, 0);
832 plug_closing(p->plug, "Proxy error: Error while communicating with proxy",
833 PROXY_ERROR_GENERAL, 0);
839 bufchain_consume(&p->pending_input_data, 8);
843 /* proxy activate will have dealt with
844 * whatever is left of the buffer */
849 plug_closing(p->plug, "Proxy error: unexpected proxy error",
850 PROXY_ERROR_UNEXPECTED, 0);
854 /* SOCKS version 5 */
855 int proxy_socks5_negotiate (Proxy_Socket p, int change)
857 if (p->state == PROXY_CHANGE_NEW) {
860 * version number (1 byte) = 5
861 * number of available authentication methods (1 byte)
862 * available authentication methods (1 byte * previous value)
863 * authentication methods:
864 * 0x00 = no authentication
866 * 0x02 = username/password
873 command[0] = 5; /* version 5 */
874 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
875 command[2] = 0x00; /* no authentication */
877 proxy_socks5_offerencryptedauth (command, &len);
878 command[len++] = 0x02; /* username/password */
879 command[1] = len - 2; /* Number of methods supported */
881 command[1] = 1; /* one methods supported: */
882 command[2] = 0x00; /* no authentication */
886 sk_write(p->sub_socket, command, len);
892 if (change == PROXY_CHANGE_CLOSING) {
893 /* if our proxy negotiation process involves closing and opening
894 * new sockets, then we would want to intercept this closing
895 * callback when we were expecting it. if we aren't anticipating
896 * a socket close, then some error must have occurred. we'll
897 * just pass those errors up to the backend.
899 return plug_closing(p->plug, p->closing_error_msg,
900 p->closing_error_code,
901 p->closing_calling_back);
904 if (change == PROXY_CHANGE_SENT) {
905 /* some (or all) of what we wrote to the proxy was sent.
906 * we don't do anything new, however, until we receive the
907 * proxy's response. we might want to set a timer so we can
908 * timeout the proxy negotiation after a while...
913 if (change == PROXY_CHANGE_ACCEPTING) {
914 /* we should _never_ see this, as we are using our socket to
915 * connect to a proxy, not accepting inbound connections.
916 * what should we do? close the socket with an appropriate
919 return plug_accepting(p->plug, p->accepting_sock);
922 if (change == PROXY_CHANGE_RECEIVE) {
923 /* we have received data from the underlying socket, which
924 * we'll need to parse, process, and respond to appropriately.
930 * version number (1 byte) = 5
931 * authentication method (1 byte)
932 * authentication methods:
933 * 0x00 = no authentication
935 * 0x02 = username/password
937 * 0xff = no acceptable methods
941 if (bufchain_size(&p->pending_input_data) < 2)
942 return 1; /* not got anything yet */
944 /* get the response */
945 bufchain_fetch(&p->pending_input_data, data, 2);
948 plug_closing(p->plug, "Proxy error: SOCKS proxy returned unexpected version",
949 PROXY_ERROR_GENERAL, 0);
953 if (data[1] == 0x00) p->state = 2; /* no authentication needed */
954 else if (data[1] == 0x01) p->state = 4; /* GSSAPI authentication */
955 else if (data[1] == 0x02) p->state = 5; /* username/password authentication */
956 else if (data[1] == 0x03) p->state = 6; /* CHAP authentication */
958 plug_closing(p->plug, "Proxy error: SOCKS proxy did not accept our authentication",
959 PROXY_ERROR_GENERAL, 0);
962 bufchain_consume(&p->pending_input_data, 2);
967 /* password authentication reply format:
968 * version number (1 bytes) = 1
969 * reply code (1 byte)
975 if (bufchain_size(&p->pending_input_data) < 2)
976 return 1; /* not got anything yet */
978 /* get the response */
979 bufchain_fetch(&p->pending_input_data, data, 2);
982 plug_closing(p->plug, "Proxy error: SOCKS password "
983 "subnegotiation contained wrong version number",
984 PROXY_ERROR_GENERAL, 0);
990 plug_closing(p->plug, "Proxy error: SOCKS proxy refused"
991 " password authentication",
992 PROXY_ERROR_GENERAL, 0);
996 bufchain_consume(&p->pending_input_data, 2);
997 p->state = 2; /* now proceed as authenticated */
1000 if (p->state == 8) {
1002 ret = proxy_socks5_handlechap(p);
1003 if (ret) return ret;
1006 if (p->state == 2) {
1009 * version number (1 byte) = 5
1010 * command code (1 byte)
1014 * reserved (1 byte) = 0x00
1015 * address type (1 byte)
1017 * 3 = domainname (first byte has length, no terminating null)
1019 * dest. address (variable)
1020 * dest. port (2 bytes) [network order]
1027 type = sk_addrtype(p->remote_addr);
1028 if (type == ADDRTYPE_IPV4) {
1029 len = 10; /* 4 hdr + 4 addr + 2 trailer */
1030 command[3] = 1; /* IPv4 */
1031 sk_addrcopy(p->remote_addr, command+4);
1032 } else if (type == ADDRTYPE_IPV6) {
1033 len = 22; /* 4 hdr + 16 addr + 2 trailer */
1034 command[3] = 4; /* IPv6 */
1035 sk_addrcopy(p->remote_addr, command+4);
1037 assert(type == ADDRTYPE_NAME);
1039 sk_getaddr(p->remote_addr, command+5, 256);
1040 command[4] = strlen(command+5);
1041 len = 7 + command[4]; /* 4 hdr, 1 len, N addr, 2 trailer */
1044 command[0] = 5; /* version 5 */
1045 command[1] = 1; /* CONNECT command */
1049 command[len-2] = (char) (p->remote_port >> 8) & 0xff;
1050 command[len-1] = (char) p->remote_port & 0xff;
1052 sk_write(p->sub_socket, command, len);
1058 if (p->state == 3) {
1061 * version number (1 bytes) = 5
1062 * reply code (1 byte)
1064 * 1 = general SOCKS server failure
1065 * 2 = connection not allowed by ruleset
1066 * 3 = network unreachable
1067 * 4 = host unreachable
1068 * 5 = connection refused
1070 * 7 = command not supported
1071 * 8 = address type not supported
1072 * reserved (1 byte) = x00
1073 * address type (1 byte)
1075 * 3 = domainname (first byte has length, no terminating null)
1077 * server bound address (variable)
1078 * server bound port (2 bytes) [network order]
1083 /* First 5 bytes of packet are enough to tell its length. */
1084 if (bufchain_size(&p->pending_input_data) < 5)
1085 return 1; /* not got anything yet */
1087 /* get the response */
1088 bufchain_fetch(&p->pending_input_data, data, 5);
1091 plug_closing(p->plug, "Proxy error: SOCKS proxy returned wrong version number",
1092 PROXY_ERROR_GENERAL, 0);
1099 strcpy(buf, "Proxy error: ");
1102 case 1: strcat(buf, "General SOCKS server failure"); break;
1103 case 2: strcat(buf, "Connection not allowed by ruleset"); break;
1104 case 3: strcat(buf, "Network unreachable"); break;
1105 case 4: strcat(buf, "Host unreachable"); break;
1106 case 5: strcat(buf, "Connection refused"); break;
1107 case 6: strcat(buf, "TTL expired"); break;
1108 case 7: strcat(buf, "Command not supported"); break;
1109 case 8: strcat(buf, "Address type not supported"); break;
1110 default: sprintf(buf+strlen(buf),
1111 "Unrecognised SOCKS error code %d",
1115 plug_closing(p->plug, buf, PROXY_ERROR_GENERAL, 0);
1121 * Eat the rest of the reply packet.
1123 len = 6; /* first 4 bytes, last 2 */
1125 case 1: len += 4; break; /* IPv4 address */
1126 case 4: len += 16; break;/* IPv6 address */
1127 case 3: len += (unsigned char)data[4]; break; /* domain name */
1129 plug_closing(p->plug, "Proxy error: SOCKS proxy returned "
1130 "unrecognised address format",
1131 PROXY_ERROR_GENERAL, 0);
1134 if (bufchain_size(&p->pending_input_data) < len)
1135 return 1; /* not got whole reply yet */
1136 bufchain_consume(&p->pending_input_data, len);
1143 if (p->state == 4) {
1144 /* TODO: Handle GSSAPI authentication */
1145 plug_closing(p->plug, "Proxy error: We don't support GSSAPI authentication",
1146 PROXY_ERROR_GENERAL, 0);
1150 if (p->state == 5) {
1151 if (p->cfg.proxy_username[0] || p->cfg.proxy_password[0]) {
1152 char userpwbuf[514];
1154 ulen = strlen(p->cfg.proxy_username);
1155 if (ulen > 255) ulen = 255; if (ulen < 1) ulen = 1;
1156 plen = strlen(p->cfg.proxy_password);
1157 if (plen > 255) plen = 255; if (plen < 1) plen = 1;
1158 userpwbuf[0] = 1; /* version number of subnegotiation */
1159 userpwbuf[1] = ulen;
1160 memcpy(userpwbuf+2, p->cfg.proxy_username, ulen);
1161 userpwbuf[ulen+2] = plen;
1162 memcpy(userpwbuf+ulen+3, p->cfg.proxy_password, plen);
1163 sk_write(p->sub_socket, userpwbuf, ulen + plen + 3);
1166 plug_closing(p->plug, "Proxy error: Server chose "
1167 "username/password authentication but we "
1169 PROXY_ERROR_GENERAL, 0);
1173 if (p->state == 6) {
1175 ret = proxy_socks5_selectchap(p);
1176 if (ret) return ret;
1181 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1182 PROXY_ERROR_UNEXPECTED, 0);
1186 /* ----------------------------------------------------------------------
1187 * `Telnet' proxy type.
1189 * (This is for ad-hoc proxies where you connect to the proxy's
1190 * telnet port and send a command such as `connect host port'. The
1191 * command is configurable, since this proxy type is typically not
1192 * standardised or at all well-defined.)
1195 char *format_telnet_command(SockAddr addr, int port, const Config *cfg)
1198 int retlen = 0, retsize = 0;
1200 #define ENSURE(n) do { \
1201 if (retsize < retlen + n) { \
1202 retsize = retlen + n + 512; \
1203 ret = sresize(ret, retsize, char); \
1207 /* we need to escape \\, \%, \r, \n, \t, \x??, \0???,
1208 * %%, %host, %port, %user, and %pass
1211 while (cfg->proxy_telnet_command[eo] != 0) {
1213 /* scan forward until we hit end-of-line,
1214 * or an escape character (\ or %) */
1215 while (cfg->proxy_telnet_command[eo] != 0 &&
1216 cfg->proxy_telnet_command[eo] != '%' &&
1217 cfg->proxy_telnet_command[eo] != '\\') eo++;
1219 /* if we hit eol, break out of our escaping loop */
1220 if (cfg->proxy_telnet_command[eo] == 0) break;
1222 /* if there was any unescaped text before the escape
1223 * character, send that now */
1226 memcpy(ret + retlen, cfg->proxy_telnet_command + so, eo - so);
1232 /* if the escape character was the last character of
1233 * the line, we'll just stop and send it. */
1234 if (cfg->proxy_telnet_command[eo] == 0) break;
1236 if (cfg->proxy_telnet_command[so] == '\\') {
1238 /* we recognize \\, \%, \r, \n, \t, \x??.
1239 * anything else, we just send unescaped (including the \).
1242 switch (cfg->proxy_telnet_command[eo]) {
1246 ret[retlen++] = '\\';
1252 ret[retlen++] = '%';
1258 ret[retlen++] = '\r';
1264 ret[retlen++] = '\n';
1270 ret[retlen++] = '\t';
1277 /* escaped hexadecimal value (ie. \xff) */
1278 unsigned char v = 0;
1283 if (cfg->proxy_telnet_command[eo] >= '0' &&
1284 cfg->proxy_telnet_command[eo] <= '9')
1285 v += cfg->proxy_telnet_command[eo] - '0';
1286 else if (cfg->proxy_telnet_command[eo] >= 'a' &&
1287 cfg->proxy_telnet_command[eo] <= 'f')
1288 v += cfg->proxy_telnet_command[eo] - 'a' + 10;
1289 else if (cfg->proxy_telnet_command[eo] >= 'A' &&
1290 cfg->proxy_telnet_command[eo] <= 'F')
1291 v += cfg->proxy_telnet_command[eo] - 'A' + 10;
1293 /* non hex character, so we abort and just
1294 * send the whole thing unescaped (including \x)
1297 ret[retlen++] = '\\';
1302 /* we only extract two hex characters */
1318 memcpy(ret+retlen, cfg->proxy_telnet_command + so, 2);
1325 /* % escape. we recognize %%, %host, %port, %user, %pass.
1326 * %proxyhost, %proxyport. Anything else we just send
1327 * unescaped (including the %).
1330 if (cfg->proxy_telnet_command[eo] == '%') {
1332 ret[retlen++] = '%';
1335 else if (strnicmp(cfg->proxy_telnet_command + eo,
1339 sk_getaddr(addr, dest, lenof(dest));
1340 destlen = strlen(dest);
1342 memcpy(ret+retlen, dest, destlen);
1346 else if (strnicmp(cfg->proxy_telnet_command + eo,
1348 char portstr[8], portlen;
1349 portlen = sprintf(portstr, "%i", port);
1351 memcpy(ret + retlen, portstr, portlen);
1355 else if (strnicmp(cfg->proxy_telnet_command + eo,
1357 int userlen = strlen(cfg->proxy_username);
1359 memcpy(ret+retlen, cfg->proxy_username, userlen);
1363 else if (strnicmp(cfg->proxy_telnet_command + eo,
1365 int passlen = strlen(cfg->proxy_password);
1367 memcpy(ret+retlen, cfg->proxy_password, passlen);
1371 else if (strnicmp(cfg->proxy_telnet_command + eo,
1372 "proxyhost", 4) == 0) {
1373 int phlen = strlen(cfg->proxy_host);
1375 memcpy(ret+retlen, cfg->proxy_host, phlen);
1379 else if (strnicmp(cfg->proxy_telnet_command + eo,
1380 "proxyport", 4) == 0) {
1383 sprintf(pport, "%d", cfg->proxy_port);
1384 pplen = strlen(cfg->proxy_host);
1386 memcpy(ret+retlen, pport, pplen);
1391 /* we don't escape this, so send the % now, and
1392 * don't advance eo, so that we'll consider the
1393 * text immediately following the % as unescaped.
1396 ret[retlen++] = '%';
1400 /* resume scanning for additional escapes after this one. */
1404 /* if there is any unescaped text at the end of the line, send it */
1407 memcpy(ret + retlen, cfg->proxy_telnet_command + so, eo - so);
1418 int proxy_telnet_negotiate (Proxy_Socket p, int change)
1420 if (p->state == PROXY_CHANGE_NEW) {
1421 char *formatted_cmd;
1423 formatted_cmd = format_telnet_command(p->remote_addr, p->remote_port,
1426 sk_write(p->sub_socket, formatted_cmd, strlen(formatted_cmd));
1427 sfree(formatted_cmd);
1433 if (change == PROXY_CHANGE_CLOSING) {
1434 /* if our proxy negotiation process involves closing and opening
1435 * new sockets, then we would want to intercept this closing
1436 * callback when we were expecting it. if we aren't anticipating
1437 * a socket close, then some error must have occurred. we'll
1438 * just pass those errors up to the backend.
1440 return plug_closing(p->plug, p->closing_error_msg,
1441 p->closing_error_code,
1442 p->closing_calling_back);
1445 if (change == PROXY_CHANGE_SENT) {
1446 /* some (or all) of what we wrote to the proxy was sent.
1447 * we don't do anything new, however, until we receive the
1448 * proxy's response. we might want to set a timer so we can
1449 * timeout the proxy negotiation after a while...
1454 if (change == PROXY_CHANGE_ACCEPTING) {
1455 /* we should _never_ see this, as we are using our socket to
1456 * connect to a proxy, not accepting inbound connections.
1457 * what should we do? close the socket with an appropriate
1460 return plug_accepting(p->plug, p->accepting_sock);
1463 if (change == PROXY_CHANGE_RECEIVE) {
1464 /* we have received data from the underlying socket, which
1465 * we'll need to parse, process, and respond to appropriately.
1470 /* proxy activate will have dealt with
1471 * whatever is left of the buffer */
1475 plug_closing(p->plug, "Proxy error: Unexpected proxy error",
1476 PROXY_ERROR_UNEXPECTED, 0);