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