remember_connection(): Remember the socks user name and password
[privoxy.git] / gateway.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/gateway.c,v $
4  *
5  * Purpose     :  Contains functions to connect to a server, possibly
6  *                using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
7  *                or SOCKS5 proxy).
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2017 the
10  *                Privoxy team. https://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  *********************************************************************/
35
36
37 #include "config.h"
38
39 #include <stdio.h>
40 #include <sys/types.h>
41
42 #ifndef _WIN32
43 #include <netinet/in.h>
44 #endif
45
46 #include <errno.h>
47 #include <string.h>
48 #include "assert.h"
49
50 #ifdef _WIN32
51 #include <winsock2.h>
52 #endif /* def _WIN32 */
53
54 #ifdef __BEOS__
55 #include <netdb.h>
56 #endif /* def __BEOS__ */
57
58 #include "project.h"
59 #include "jcc.h"
60 #include "errlog.h"
61 #include "jbsockets.h"
62 #include "gateway.h"
63 #include "miscutil.h"
64 #include "list.h"
65 #include "parsers.h"
66
67 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
68 #ifdef HAVE_POLL
69 #ifdef __GLIBC__
70 #include <sys/poll.h>
71 #else
72 #include <poll.h>
73 #endif /* def __GLIBC__ */
74 #endif /* HAVE_POLL */
75 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
76
77 static jb_socket socks4_connect(const struct forward_spec *fwd,
78                                 const char *target_host,
79                                 int target_port,
80                                 struct client_state *csp);
81
82 static jb_socket socks5_connect(const struct forward_spec *fwd,
83                                 const char *target_host,
84                                 int target_port,
85                                 struct client_state *csp);
86
87 enum {
88    SOCKS4_REQUEST_GRANTED        =  90,
89    SOCKS4_REQUEST_REJECT         =  91,
90    SOCKS4_REQUEST_IDENT_FAILED   =  92,
91    SOCKS4_REQUEST_IDENT_CONFLICT =  93
92 };
93
94 enum {
95    SOCKS5_REQUEST_GRANTED             = 0,
96    SOCKS5_REQUEST_FAILED              = 1,
97    SOCKS5_REQUEST_DENIED              = 2,
98    SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
99    SOCKS5_REQUEST_HOST_UNREACHABLE    = 4,
100    SOCKS5_REQUEST_CONNECTION_REFUSED  = 5,
101    SOCKS5_REQUEST_TTL_EXPIRED         = 6,
102    SOCKS5_REQUEST_PROTOCOL_ERROR      = 7,
103    SOCKS5_REQUEST_BAD_ADDRESS_TYPE    = 8
104 };
105
106 /* structure of a socks client operation */
107 struct socks_op {
108    unsigned char vn;          /* socks version number */
109    unsigned char cd;          /* command code */
110    unsigned char dstport[2];  /* destination port */
111    unsigned char dstip[4];    /* destination address */
112    char userid;               /* first byte of userid */
113    char padding[3];           /* make sure sizeof(struct socks_op) is endian-independent. */
114    /* more bytes of the userid follow, terminated by a NULL */
115 };
116
117 /* structure of a socks server reply */
118 struct socks_reply {
119    unsigned char vn;          /* socks version number */
120    unsigned char cd;          /* command code */
121    unsigned char dstport[2];  /* destination port */
122    unsigned char dstip[4];    /* destination address */
123 };
124
125 static const char socks_userid[] = "anonymous";
126
127 #ifdef FEATURE_CONNECTION_SHARING
128 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
129 #error Using FEATURE_CONNECTION_SHARING without FEATURE_CONNECTION_KEEP_ALIVE is impossible
130 #endif
131
132 #define MAX_REUSABLE_CONNECTIONS 100
133
134 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
135 static int mark_connection_unused(const struct reusable_connection *connection);
136
137 /*********************************************************************
138  *
139  * Function    :  initialize_reusable_connections
140  *
141  * Description :  Initializes the reusable_connection structures.
142  *                Must be called with connection_reuse_mutex locked.
143  *
144  * Parameters  : N/A
145  *
146  * Returns     : void
147  *
148  *********************************************************************/
149 extern void initialize_reusable_connections(void)
150 {
151    unsigned int slot = 0;
152
153 #if !defined(HAVE_POLL) && !defined(_WIN32)
154    log_error(LOG_LEVEL_INFO,
155       "Detecting already dead connections might not work "
156       "correctly on your platform. In case of problems, "
157       "unset the keep-alive-timeout option.");
158 #endif
159
160    for (slot = 0; slot < SZ(reusable_connection); slot++)
161    {
162       mark_connection_closed(&reusable_connection[slot]);
163    }
164
165    log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
166 }
167
168
169 /*********************************************************************
170  *
171  * Function    :  remember_connection
172  *
173  * Description :  Remembers a server connection for reuse later on.
174  *
175  * Parameters  :
176  *          1  :  connection = The server connection to remember.
177  *
178  * Returns     : void
179  *
180  *********************************************************************/
181 void remember_connection(const struct reusable_connection *connection)
182 {
183    unsigned int slot = 0;
184    int free_slot_found = FALSE;
185
186    assert(NULL != connection);
187    assert(connection->sfd != JB_INVALID_SOCKET);
188
189    if (mark_connection_unused(connection))
190    {
191       return;
192    }
193
194    privoxy_mutex_lock(&connection_reuse_mutex);
195
196    /* Find free socket slot. */
197    for (slot = 0; slot < SZ(reusable_connection); slot++)
198    {
199       if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
200       {
201          assert(reusable_connection[slot].in_use == 0);
202          log_error(LOG_LEVEL_CONNECT,
203             "Remembering socket %d for %s:%d in slot %d.",
204             connection->sfd, connection->host, connection->port, slot);
205          free_slot_found = TRUE;
206          break;
207       }
208    }
209
210    if (!free_slot_found)
211    {
212       log_error(LOG_LEVEL_CONNECT,
213         "No free slots found to remember socket for %s:%d. Last slot %d.",
214         connection->host, connection->port, slot);
215       privoxy_mutex_unlock(&connection_reuse_mutex);
216       close_socket(connection->sfd);
217       return;
218    }
219
220    assert(slot < SZ(reusable_connection));
221    assert(NULL != connection->host);
222    reusable_connection[slot].host = strdup_or_die(connection->host);
223    reusable_connection[slot].sfd = connection->sfd;
224    reusable_connection[slot].port = connection->port;
225    reusable_connection[slot].in_use = 0;
226    reusable_connection[slot].timestamp = connection->timestamp;
227    reusable_connection[slot].request_sent = connection->request_sent;
228    reusable_connection[slot].response_received = connection->response_received;
229    reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
230    reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
231
232    assert(reusable_connection[slot].gateway_host == NULL);
233    assert(reusable_connection[slot].gateway_port == 0);
234    assert(reusable_connection[slot].auth_username == NULL);
235    assert(reusable_connection[slot].auth_password == NULL);
236    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
237    assert(reusable_connection[slot].forward_host == NULL);
238    assert(reusable_connection[slot].forward_port == 0);
239
240    reusable_connection[slot].forwarder_type = connection->forwarder_type;
241    if (NULL != connection->gateway_host)
242    {
243       reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
244    }
245    else
246    {
247       reusable_connection[slot].gateway_host = NULL;
248    }
249    reusable_connection[slot].gateway_port = connection->gateway_port;
250    if (NULL != connection->auth_username)
251    {
252       reusable_connection[slot].auth_username = strdup_or_die(connection->auth_username);
253    }
254    else
255    {
256       reusable_connection[slot].auth_username = NULL;
257    }
258    if (NULL != connection->auth_password)
259    {
260       reusable_connection[slot].auth_password = strdup_or_die(connection->auth_password);
261    }
262    else
263    {
264       reusable_connection[slot].auth_password = NULL;
265    }
266
267    if (NULL != connection->forward_host)
268    {
269       reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
270    }
271    else
272    {
273       reusable_connection[slot].forward_host = NULL;
274    }
275    reusable_connection[slot].forward_port = connection->forward_port;
276
277    privoxy_mutex_unlock(&connection_reuse_mutex);
278 }
279 #endif /* def FEATURE_CONNECTION_SHARING */
280
281
282 /*********************************************************************
283  *
284  * Function    :  mark_connection_closed
285  *
286  * Description : Marks a reused connection closed.
287  *
288  * Parameters  :
289  *          1  :  closed_connection = The connection to mark as closed.
290  *
291  * Returns     : void
292  *
293  *********************************************************************/
294 void mark_connection_closed(struct reusable_connection *closed_connection)
295 {
296    closed_connection->in_use = FALSE;
297    closed_connection->sfd = JB_INVALID_SOCKET;
298    freez(closed_connection->host);
299    closed_connection->port = 0;
300    closed_connection->timestamp = 0;
301    closed_connection->request_sent = 0;
302    closed_connection->response_received = 0;
303    closed_connection->keep_alive_timeout = 0;
304    closed_connection->requests_sent_total = 0;
305    closed_connection->forwarder_type = SOCKS_NONE;
306    freez(closed_connection->gateway_host);
307    closed_connection->gateway_port = 0;
308    freez(closed_connection->auth_username);
309    freez(closed_connection->auth_password);
310    freez(closed_connection->forward_host);
311    closed_connection->forward_port = 0;
312 }
313
314
315 #ifdef FEATURE_CONNECTION_SHARING
316 /*********************************************************************
317  *
318  * Function    :  forget_connection
319  *
320  * Description :  Removes a previously remembered connection from
321  *                the list of reusable connections.
322  *
323  * Parameters  :
324  *          1  :  sfd = The socket belonging to the connection in question.
325  *
326  * Returns     : void
327  *
328  *********************************************************************/
329 void forget_connection(jb_socket sfd)
330 {
331    unsigned int slot = 0;
332
333    assert(sfd != JB_INVALID_SOCKET);
334
335    privoxy_mutex_lock(&connection_reuse_mutex);
336
337    for (slot = 0; slot < SZ(reusable_connection); slot++)
338    {
339       if (reusable_connection[slot].sfd == sfd)
340       {
341          assert(reusable_connection[slot].in_use);
342
343          log_error(LOG_LEVEL_CONNECT,
344             "Forgetting socket %d for %s:%d in slot %d.",
345             sfd, reusable_connection[slot].host,
346             reusable_connection[slot].port, slot);
347          mark_connection_closed(&reusable_connection[slot]);
348          break;
349       }
350    }
351
352    privoxy_mutex_unlock(&connection_reuse_mutex);
353
354 }
355 #endif /* def FEATURE_CONNECTION_SHARING */
356
357
358 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
359 /*********************************************************************
360  *
361  * Function    :  connection_detail_matches
362  *
363  * Description :  Helper function for connection_destination_matches().
364  *                Compares strings which can be NULL.
365  *
366  * Parameters  :
367  *          1  :  connection_detail = The connection detail to compare.
368  *          2  :  fowarder_detail = The forwarder detail to compare.
369  *
370  * Returns     :  TRUE for yes, FALSE otherwise.
371  *
372  *********************************************************************/
373 static int connection_detail_matches(const char *connection_detail,
374                                      const char *forwarder_detail)
375 {
376    if (connection_detail == NULL && forwarder_detail == NULL)
377    {
378       /* Both details are unset. */
379       return TRUE;
380    }
381
382    if ((connection_detail == NULL && forwarder_detail != NULL)
383     || (connection_detail != NULL && forwarder_detail == NULL))
384    {
385       /* Only one detail isn't set. */
386       return FALSE;
387    }
388
389    /* Both details are set, but do they match? */
390    return(!strcmpic(connection_detail, forwarder_detail));
391
392 }
393
394
395 /*********************************************************************
396  *
397  * Function    :  connection_destination_matches
398  *
399  * Description :  Determines whether a remembered connection can
400  *                be reused. That is, whether the destination and
401  *                the forwarding settings match.
402  *
403  * Parameters  :
404  *          1  :  connection = The connection to check.
405  *          2  :  http = The destination for the connection.
406  *          3  :  fwd  = The forwarder settings.
407  *
408  * Returns     :  TRUE for yes, FALSE otherwise.
409  *
410  *********************************************************************/
411 int connection_destination_matches(const struct reusable_connection *connection,
412                                    const struct http_request *http,
413                                    const struct forward_spec *fwd)
414 {
415    if ((connection->forwarder_type != fwd->type)
416     || (connection->gateway_port   != fwd->gateway_port)
417     || (connection->forward_port   != fwd->forward_port)
418     || (connection->port           != http->port))
419    {
420       return FALSE;
421    }
422
423    if (!connection_detail_matches(connection->gateway_host, fwd->gateway_host))
424    {
425       log_error(LOG_LEVEL_CONNECT,
426          "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
427          connection->gateway_host != NULL ? connection->gateway_host : "none",
428          fwd->gateway_host != NULL ? fwd->gateway_host : "none");
429       return FALSE;
430    }
431
432    if (!connection_detail_matches(connection->auth_username, fwd->auth_username))
433    {
434       log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
435          "Previous user name: %s. Current user name: %s",
436          connection->auth_username != NULL ? connection->auth_username : "none",
437          fwd->auth_username != NULL ? fwd->auth_username : "none");
438       return FALSE;
439    }
440
441    if (!connection_detail_matches(connection->auth_password, fwd->auth_password))
442    {
443       log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
444          "Previous password: %s. Current password: %s",
445          connection->auth_password != NULL ? connection->auth_password : "none",
446          fwd->auth_password != NULL ?  fwd->auth_password : "none");
447       return FALSE;
448    }
449
450    if (!connection_detail_matches(connection->forward_host, fwd->forward_host))
451    {
452       log_error(LOG_LEVEL_CONNECT,
453          "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
454          connection->forward_host != NULL ? connection->forward_host : "none",
455          fwd->forward_host != NULL ? fwd->forward_host : "none");
456       return FALSE;
457    }
458
459    return (!strcmpic(connection->host, http->host));
460
461 }
462 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
463
464
465 #ifdef FEATURE_CONNECTION_SHARING
466 /*********************************************************************
467  *
468  * Function    :  close_unusable_connections
469  *
470  * Description :  Closes remembered connections that have timed
471  *                out or have been closed on the other side.
472  *
473  * Parameters  :  none
474  *
475  * Returns     :  Number of connections that are still alive.
476  *
477  *********************************************************************/
478 int close_unusable_connections(void)
479 {
480    unsigned int slot = 0;
481    int connections_alive = 0;
482
483    privoxy_mutex_lock(&connection_reuse_mutex);
484
485    for (slot = 0; slot < SZ(reusable_connection); slot++)
486    {
487       if (!reusable_connection[slot].in_use
488          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
489       {
490          time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
491          time_t latency = (reusable_connection[slot].response_received -
492             reusable_connection[slot].request_sent) / 2;
493
494          if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
495          {
496             log_error(LOG_LEVEL_CONNECT,
497                "The connection to %s:%d in slot %d timed out. "
498                "Closing socket %d. Timeout is: %d. Assumed latency: %ld.",
499                reusable_connection[slot].host,
500                reusable_connection[slot].port, slot,
501                reusable_connection[slot].sfd,
502                reusable_connection[slot].keep_alive_timeout,
503                latency);
504             close_socket(reusable_connection[slot].sfd);
505             mark_connection_closed(&reusable_connection[slot]);
506          }
507          else if (!socket_is_still_alive(reusable_connection[slot].sfd))
508          {
509             log_error(LOG_LEVEL_CONNECT,
510                "The connection to %s:%d in slot %d is no longer usable. "
511                "Closing socket %d.", reusable_connection[slot].host,
512                reusable_connection[slot].port, slot,
513                reusable_connection[slot].sfd);
514             close_socket(reusable_connection[slot].sfd);
515             mark_connection_closed(&reusable_connection[slot]);
516          }
517          else
518          {
519             connections_alive++;
520          }
521       }
522    }
523
524    privoxy_mutex_unlock(&connection_reuse_mutex);
525
526    return connections_alive;
527
528 }
529
530
531 /*********************************************************************
532  *
533  * Function    :  get_reusable_connection
534  *
535  * Description :  Returns an open socket to a previously remembered
536  *                open connection (if there is one).
537  *
538  * Parameters  :
539  *          1  :  http = The destination for the connection.
540  *          2  :  fwd  = The forwarder settings.
541  *
542  * Returns     :  JB_INVALID_SOCKET => No reusable connection found,
543  *                otherwise a usable socket.
544  *
545  *********************************************************************/
546 static jb_socket get_reusable_connection(const struct http_request *http,
547                                          const struct forward_spec *fwd)
548 {
549    jb_socket sfd = JB_INVALID_SOCKET;
550    unsigned int slot = 0;
551
552    close_unusable_connections();
553
554    privoxy_mutex_lock(&connection_reuse_mutex);
555
556    for (slot = 0; slot < SZ(reusable_connection); slot++)
557    {
558       if (!reusable_connection[slot].in_use
559          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
560       {
561          if (connection_destination_matches(&reusable_connection[slot], http, fwd))
562          {
563             reusable_connection[slot].in_use = TRUE;
564             sfd = reusable_connection[slot].sfd;
565             log_error(LOG_LEVEL_CONNECT,
566                "Found reusable socket %d for %s:%d in slot %d. Timestamp made %ld "
567                "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
568                sfd, reusable_connection[slot].host, reusable_connection[slot].port,
569                slot, time(NULL) - reusable_connection[slot].timestamp,
570                reusable_connection[slot].keep_alive_timeout,
571                (int)(reusable_connection[slot].response_received -
572                reusable_connection[slot].request_sent),
573                reusable_connection[slot].requests_sent_total);
574             break;
575          }
576       }
577    }
578
579    privoxy_mutex_unlock(&connection_reuse_mutex);
580
581    return sfd;
582
583 }
584
585
586 /*********************************************************************
587  *
588  * Function    :  mark_connection_unused
589  *
590  * Description :  Gives a remembered connection free for reuse.
591  *
592  * Parameters  :
593  *          1  :  connection = The connection in question.
594  *
595  * Returns     :  TRUE => Socket found and marked as unused.
596  *                FALSE => Socket not found.
597  *
598  *********************************************************************/
599 static int mark_connection_unused(const struct reusable_connection *connection)
600 {
601    unsigned int slot = 0;
602    int socket_found = FALSE;
603
604    assert(connection->sfd != JB_INVALID_SOCKET);
605
606    privoxy_mutex_lock(&connection_reuse_mutex);
607
608    for (slot = 0; slot < SZ(reusable_connection); slot++)
609    {
610       if (reusable_connection[slot].sfd == connection->sfd)
611       {
612          assert(reusable_connection[slot].in_use);
613          socket_found = TRUE;
614          log_error(LOG_LEVEL_CONNECT,
615             "Marking open socket %d for %s:%d in slot %d as unused.",
616             connection->sfd, reusable_connection[slot].host,
617             reusable_connection[slot].port, slot);
618          reusable_connection[slot].in_use = 0;
619          reusable_connection[slot].timestamp = connection->timestamp;
620          break;
621       }
622    }
623
624    privoxy_mutex_unlock(&connection_reuse_mutex);
625
626    return socket_found;
627
628 }
629 #endif /* def FEATURE_CONNECTION_SHARING */
630
631
632 /*********************************************************************
633  *
634  * Function    :  forwarded_connect
635  *
636  * Description :  Connect to a specified web server, possibly via
637  *                a HTTP proxy and/or a SOCKS proxy.
638  *
639  * Parameters  :
640  *          1  :  fwd = the proxies to use when connecting.
641  *          2  :  http = the http request and apropos headers
642  *          3  :  csp = Current client state (buffers, headers, etc...)
643  *
644  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
645  *
646  *********************************************************************/
647 jb_socket forwarded_connect(const struct forward_spec *fwd,
648                             struct http_request *http,
649                             struct client_state *csp)
650 {
651    const char *dest_host;
652    int dest_port;
653    jb_socket sfd = JB_INVALID_SOCKET;
654
655 #ifdef FEATURE_CONNECTION_SHARING
656    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
657       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
658    {
659       sfd = get_reusable_connection(http, fwd);
660       if (JB_INVALID_SOCKET != sfd)
661       {
662          return sfd;
663       }
664    }
665 #endif /* def FEATURE_CONNECTION_SHARING */
666
667    /* Figure out if we need to connect to the web server or a HTTP proxy. */
668    if (fwd->forward_host)
669    {
670       /* HTTP proxy */
671       dest_host = fwd->forward_host;
672       dest_port = fwd->forward_port;
673    }
674    else
675    {
676       /* Web server */
677       dest_host = http->host;
678       dest_port = http->port;
679    }
680
681    /* Connect, maybe using a SOCKS proxy */
682    switch (fwd->type)
683    {
684       case SOCKS_NONE:
685       case FORWARD_WEBSERVER:
686          sfd = connect_to(dest_host, dest_port, csp);
687          break;
688       case SOCKS_4:
689       case SOCKS_4A:
690          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
691          break;
692       case SOCKS_5:
693       case SOCKS_5T:
694          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
695          break;
696       default:
697          /* Should never get here */
698          log_error(LOG_LEVEL_FATAL,
699             "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
700    }
701
702    if (JB_INVALID_SOCKET != sfd)
703    {
704       log_error(LOG_LEVEL_CONNECT,
705          "Created new connection to %s:%d on socket %d.",
706          http->host, http->port, sfd);
707    }
708
709    return sfd;
710
711 }
712
713
714 #ifdef FUZZ
715 /*********************************************************************
716  *
717  * Function    :  socks_fuzz
718  *
719  * Description :  Wrapper around socks[45]_connect() used for fuzzing.
720  *
721  * Parameters  :
722  *          1  :  csp = Current client state (buffers, headers, etc...)
723  *
724  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
725  *
726  *********************************************************************/
727 extern jb_err socks_fuzz(struct client_state *csp)
728 {
729    jb_socket socket;
730    static struct forward_spec fwd;
731    char target_host[] = "fuzz.example.org";
732    int target_port = 12345;
733
734    fwd.gateway_host = strdup_or_die("fuzz.example.org");
735    fwd.gateway_port = 12345;
736
737    fwd.type = SOCKS_4A;
738    socket = socks4_connect(&fwd, target_host, target_port, csp);
739
740    if (JB_INVALID_SOCKET != socket)
741    {
742       fwd.type = SOCKS_5;
743       socket = socks5_connect(&fwd, target_host, target_port, csp);
744    }
745
746    if (JB_INVALID_SOCKET == socket)
747    {
748       log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
749       return JB_ERR_PARSE;
750    }
751
752    log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
753
754    return JB_ERR_OK;
755
756 }
757 #endif
758
759 /*********************************************************************
760  *
761  * Function    :  socks4_connect
762  *
763  * Description :  Connect to the SOCKS server, and connect through
764  *                it to the specified server.   This handles
765  *                all the SOCKS negotiation, and returns a file
766  *                descriptor for a socket which can be treated as a
767  *                normal (non-SOCKS) socket.
768  *
769  *                Logged error messages are saved to csp->error_message
770  *                and later reused by error_response() for the CGI
771  *                message. strdup allocation failures are handled there.
772  *
773  * Parameters  :
774  *          1  :  fwd = Specifies the SOCKS proxy to use.
775  *          2  :  target_host = The final server to connect to.
776  *          3  :  target_port = The final port to connect to.
777  *          4  :  csp = Current client state (buffers, headers, etc...)
778  *
779  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
780  *
781  *********************************************************************/
782 static jb_socket socks4_connect(const struct forward_spec *fwd,
783                                 const char *target_host,
784                                 int target_port,
785                                 struct client_state *csp)
786 {
787    unsigned long web_server_addr;
788    char buf[BUFFER_SIZE];
789    struct socks_op    *c = (struct socks_op    *)buf;
790    struct socks_reply *s = (struct socks_reply *)buf;
791    size_t n;
792    size_t csiz;
793    jb_socket sfd;
794    int err = 0;
795    char *errstr = NULL;
796
797    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
798    {
799       /* XXX: Shouldn't the config file parser prevent this? */
800       errstr = "NULL gateway host specified.";
801       err = 1;
802    }
803
804    if (fwd->gateway_port <= 0)
805    {
806       errstr = "invalid gateway port specified.";
807       err = 1;
808    }
809
810    if (err)
811    {
812       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
813       csp->error_message = strdup(errstr);
814       errno = EINVAL;
815       return(JB_INVALID_SOCKET);
816    }
817
818    /* build a socks request for connection to the web server */
819
820    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
821
822    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
823
824    switch (fwd->type)
825    {
826       case SOCKS_4:
827          web_server_addr = resolve_hostname_to_ip(target_host);
828          if (web_server_addr == INADDR_NONE)
829          {
830             errstr = "could not resolve target host";
831             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
832             err = 1;
833          }
834          else
835          {
836             web_server_addr = htonl(web_server_addr);
837          }
838          break;
839       case SOCKS_4A:
840          web_server_addr = 0x00000001;
841          n = csiz + strlen(target_host) + 1;
842          if (n > sizeof(buf))
843          {
844             errno = EINVAL;
845             errstr = "buffer cbuf too small.";
846             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
847             err = 1;
848          }
849          else
850          {
851             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
852             /*
853              * What we forward to the socks4a server should have the
854              * size of socks_op, plus the length of the userid plus
855              * its \0 byte (which we don't have to add because the
856              * first byte of the userid is counted twice as it's also
857              * part of sock_op) minus the padding bytes (which are part
858              * of the userid as well), plus the length of the target_host
859              * (which is stored csiz bytes after the beginning of the buffer),
860              * plus another \0 byte.
861              */
862             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
863             csiz = n;
864          }
865          break;
866       default:
867          /* Should never get here */
868          log_error(LOG_LEVEL_FATAL,
869             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
870          /* Not reached */
871          return(JB_INVALID_SOCKET);
872    }
873
874    if (err)
875    {
876       csp->error_message = strdup(errstr);
877       return(JB_INVALID_SOCKET);
878    }
879
880    c->vn          = 4;
881    c->cd          = 1;
882    c->dstport[0]  = (unsigned char)((target_port       >> 8 ) & 0xff);
883    c->dstport[1]  = (unsigned char)((target_port            ) & 0xff);
884    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24) & 0xff);
885    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16) & 0xff);
886    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8) & 0xff);
887    c->dstip[3]    = (unsigned char)((web_server_addr        ) & 0xff);
888
889 #ifdef FUZZ
890    sfd = 0;
891 #else
892    /* pass the request to the socks server */
893    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
894
895    if (sfd == JB_INVALID_SOCKET)
896    {
897       /* The error an its reason have already been logged by connect_to()  */
898       return(JB_INVALID_SOCKET);
899    }
900    else if (write_socket(sfd, (char *)c, csiz))
901    {
902       errstr = "SOCKS4 negotiation write failed.";
903       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
904       err = 1;
905       close_socket(sfd);
906    }
907    else if (!data_is_available(sfd, csp->config->socket_timeout))
908    {
909       if (socket_is_still_alive(sfd))
910       {
911          errstr = "SOCKS4 negotiation timed out";
912       }
913       else
914       {
915          errstr = "SOCKS4 negotiation got aborted by the server";
916       }
917       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
918       err = 1;
919       close_socket(sfd);
920    }
921    else
922 #endif
923        if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
924    {
925       errstr = "SOCKS4 negotiation read failed.";
926       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
927       err = 1;
928       close_socket(sfd);
929    }
930
931    if (err)
932    {
933       csp->error_message = strdup(errstr);
934       return(JB_INVALID_SOCKET);
935    }
936
937    switch (s->cd)
938    {
939       case SOCKS4_REQUEST_GRANTED:
940          return(sfd);
941       case SOCKS4_REQUEST_REJECT:
942          errstr = "SOCKS request rejected or failed.";
943          errno = EINVAL;
944          break;
945       case SOCKS4_REQUEST_IDENT_FAILED:
946          errstr = "SOCKS request rejected because "
947             "SOCKS server cannot connect to identd on the client.";
948          errno = EACCES;
949          break;
950       case SOCKS4_REQUEST_IDENT_CONFLICT:
951          errstr = "SOCKS request rejected because "
952             "the client program and identd report "
953             "different user-ids.";
954          errno = EACCES;
955          break;
956       default:
957          errno = ENOENT;
958          snprintf(buf, sizeof(buf),
959             "SOCKS request rejected for reason code %d.", s->cd);
960          errstr = buf;
961    }
962
963    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
964    csp->error_message = strdup(errstr);
965    close_socket(sfd);
966
967    return(JB_INVALID_SOCKET);
968
969 }
970
971 /*********************************************************************
972  *
973  * Function    :  translate_socks5_error
974  *
975  * Description :  Translates a SOCKS errors to a string.
976  *
977  * Parameters  :
978  *          1  :  socks_error = The error code to translate.
979  *
980  * Returns     :  The string translation.
981  *
982  *********************************************************************/
983 static const char *translate_socks5_error(int socks_error)
984 {
985    switch (socks_error)
986    {
987       /* XXX: these should be more descriptive */
988       case SOCKS5_REQUEST_FAILED:
989          return "SOCKS5 request failed";
990       case SOCKS5_REQUEST_DENIED:
991          return "SOCKS5 request denied";
992       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
993          return "SOCKS5 network unreachable";
994       case SOCKS5_REQUEST_HOST_UNREACHABLE:
995          return "SOCKS5 destination host unreachable";
996       case SOCKS5_REQUEST_CONNECTION_REFUSED:
997          return "SOCKS5 connection refused";
998       case SOCKS5_REQUEST_TTL_EXPIRED:
999          return "SOCKS5 TTL expired";
1000       case SOCKS5_REQUEST_PROTOCOL_ERROR:
1001          return "SOCKS5 client protocol error";
1002       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1003          return "SOCKS5 domain names unsupported";
1004       case SOCKS5_REQUEST_GRANTED:
1005          return "everything's peachy";
1006       default:
1007          return "SOCKS5 negotiation protocol error";
1008    }
1009 }
1010
1011
1012 /*********************************************************************
1013  *
1014  * Function    :  socks5_connect
1015  *
1016  * Description :  Connect to the SOCKS server, and connect through
1017  *                it to the specified server.   This handles
1018  *                all the SOCKS negotiation, and returns a file
1019  *                descriptor for a socket which can be treated as a
1020  *                normal (non-SOCKS) socket.
1021  *
1022  * Parameters  :
1023  *          1  :  fwd = Specifies the SOCKS proxy to use.
1024  *          2  :  target_host = The final server to connect to.
1025  *          3  :  target_port = The final port to connect to.
1026  *          4  :  csp = Current client state (buffers, headers, etc...)
1027  *
1028  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
1029  *
1030  *********************************************************************/
1031 static jb_socket socks5_connect(const struct forward_spec *fwd,
1032                                 const char *target_host,
1033                                 int target_port,
1034                                 struct client_state *csp)
1035 {
1036 #define SIZE_SOCKS5_REPLY_IPV4 10
1037 #define SIZE_SOCKS5_REPLY_IPV6 22
1038 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
1039    int err = 0;
1040    char cbuf[300];
1041    char sbuf[SIZE_SOCKS5_REPLY_IPV6];
1042    size_t client_pos = 0;
1043    int server_size = 0;
1044    size_t hostlen = 0;
1045    jb_socket sfd;
1046    const char *errstr = NULL;
1047
1048    assert(fwd->gateway_host);
1049    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1050    {
1051       errstr = "NULL gateway host specified";
1052       err = 1;
1053    }
1054
1055    if (fwd->gateway_port <= 0)
1056    {
1057       /*
1058        * XXX: currently this can't happen because in
1059        * case of invalid gateway ports we use the defaults.
1060        * Of course we really shouldn't do that.
1061        */
1062       errstr = "invalid gateway port specified";
1063       err = 1;
1064    }
1065
1066    hostlen = strlen(target_host);
1067    if (hostlen > (size_t)255)
1068    {
1069       errstr = "target host name is longer than 255 characters";
1070       err = 1;
1071    }
1072
1073    if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1074    {
1075       /* Should never get here */
1076       log_error(LOG_LEVEL_FATAL,
1077          "SOCKS5 impossible internal error - bad SOCKS type");
1078       err = 1;
1079    }
1080
1081    if (err)
1082    {
1083       errno = EINVAL;
1084       assert(errstr != NULL);
1085       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1086       csp->error_message = strdup(errstr);
1087       return(JB_INVALID_SOCKET);
1088    }
1089
1090 #ifdef FUZZ
1091    sfd = 0;
1092    if (!err && read_socket(sfd, sbuf, 2) != 2)
1093 #else
1094    /* pass the request to the socks server */
1095    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1096
1097    if (sfd == JB_INVALID_SOCKET)
1098    {
1099       errstr = "socks5 server unreachable";
1100       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1101       /* Free the generic error message provided by connect_to() */
1102       freez(csp->error_message);
1103       csp->error_message = strdup(errstr);
1104       return(JB_INVALID_SOCKET);
1105    }
1106
1107    client_pos = 0;
1108    cbuf[client_pos++] = '\x05'; /* Version */
1109
1110    if (fwd->auth_username && fwd->auth_password)
1111    {
1112       cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1113       cbuf[client_pos++] = '\x02'; /* Username/password */
1114    }
1115    else
1116    {
1117       cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1118    }
1119    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1120
1121    if (write_socket(sfd, cbuf, client_pos))
1122    {
1123       errstr = "SOCKS5 negotiation write failed";
1124       csp->error_message = strdup(errstr);
1125       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1126       close_socket(sfd);
1127       return(JB_INVALID_SOCKET);
1128    }
1129    if (!data_is_available(sfd, csp->config->socket_timeout))
1130    {
1131       if (socket_is_still_alive(sfd))
1132       {
1133          errstr = "SOCKS5 negotiation timed out";
1134       }
1135       else
1136       {
1137          errstr = "SOCKS5 negotiation got aborted by the server";
1138       }
1139       err = 1;
1140    }
1141
1142    if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1143 #endif
1144    {
1145       errstr = "SOCKS5 negotiation read failed";
1146       err = 1;
1147    }
1148
1149    if (!err && (sbuf[0] != '\x05'))
1150    {
1151       errstr = "SOCKS5 negotiation protocol version error";
1152       err = 1;
1153    }
1154
1155    if (!err && (sbuf[1] == '\xff'))
1156    {
1157       errstr = "SOCKS5 authentication required";
1158       err = 1;
1159    }
1160
1161    if (!err && (sbuf[1] == '\x02'))
1162    {
1163       /* check cbuf overflow */
1164       size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1165       if (auth_len > sizeof(cbuf))
1166       {
1167          errstr = "SOCKS5 username and/or password too long";
1168          err = 1;
1169       }
1170
1171       if (!err)
1172       {
1173          client_pos = 0;
1174          cbuf[client_pos++] = '\x01'; /* Version */
1175          cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1176
1177          memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1178          client_pos += strlen(fwd->auth_username);
1179          cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1180          memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1181          client_pos += strlen(fwd->auth_password);
1182
1183          if (write_socket(sfd, cbuf, client_pos))
1184          {
1185             errstr = "SOCKS5 negotiation auth write failed";
1186             csp->error_message = strdup(errstr);
1187             log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1188             close_socket(sfd);
1189             return(JB_INVALID_SOCKET);
1190          }
1191
1192          if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1193          {
1194             errstr = "SOCKS5 negotiation auth read failed";
1195             err = 1;
1196          }
1197       }
1198
1199       if (!err && (sbuf[1] != '\x00'))
1200       {
1201          errstr = "SOCKS5 authentication failed";
1202          err = 1;
1203       }
1204    }
1205    else if (!err && (sbuf[1] != '\x00'))
1206    {
1207       errstr = "SOCKS5 negotiation protocol error";
1208       err = 1;
1209    }
1210
1211    if (err)
1212    {
1213       assert(errstr != NULL);
1214       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1215       csp->error_message = strdup(errstr);
1216       close_socket(sfd);
1217       errno = EINVAL;
1218       return(JB_INVALID_SOCKET);
1219    }
1220
1221    client_pos = 0;
1222    cbuf[client_pos++] = '\x05'; /* Version */
1223    cbuf[client_pos++] = '\x01'; /* TCP connect */
1224    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1225    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1226    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1227    assert(sizeof(cbuf) - client_pos > (size_t)255);
1228    /* Using strncpy because we really want the nul byte padding. */
1229    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1230    client_pos += (hostlen & 0xffu);
1231    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1232    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1233
1234 #ifndef FUZZ
1235    if (write_socket(sfd, cbuf, client_pos))
1236    {
1237       errstr = "SOCKS5 negotiation write failed";
1238       csp->error_message = strdup(errstr);
1239       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1240       close_socket(sfd);
1241       errno = EINVAL;
1242       return(JB_INVALID_SOCKET);
1243    }
1244
1245    /*
1246     * Optimistically send the HTTP request with the initial
1247     * SOCKS request if the user enabled the use of Tor extensions,
1248     * the CONNECT method isn't being used (in which case the client
1249     * doesn't send data until it gets our 200 response) and the
1250     * client request has actually been completely read already.
1251     */
1252    if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1253       && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1254    {
1255       char *client_headers = list_to_text(csp->headers);
1256       size_t header_length;
1257
1258       if (client_headers == NULL)
1259       {
1260          log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1261       }
1262       list_remove_all(csp->headers);
1263       header_length= strlen(client_headers);
1264
1265       log_error(LOG_LEVEL_CONNECT,
1266          "Optimistically sending %lu bytes of client headers intended for %s",
1267          header_length, csp->http->hostport);
1268
1269       if (write_socket(sfd, client_headers, header_length))
1270       {
1271          log_error(LOG_LEVEL_CONNECT,
1272             "optimistically writing header to: %s failed: %E", csp->http->hostport);
1273          freez(client_headers);
1274          return(JB_INVALID_SOCKET);
1275       }
1276       freez(client_headers);
1277       if (csp->expected_client_content_length != 0)
1278       {
1279          unsigned long long buffered_request_bytes =
1280             (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1281          log_error(LOG_LEVEL_CONNECT,
1282             "Optimistically sending %llu bytes of client body. Expected %llu",
1283             csp->expected_client_content_length, buffered_request_bytes);
1284          assert(csp->expected_client_content_length == buffered_request_bytes);
1285          if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1286          {
1287             log_error(LOG_LEVEL_CONNECT,
1288                "optimistically writing %llu bytes of client body to: %s failed: %E",
1289                buffered_request_bytes, csp->http->hostport);
1290             return(JB_INVALID_SOCKET);
1291          }
1292          clear_iob(csp->client_iob);
1293       }
1294    }
1295 #endif
1296
1297    server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1298    if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1299    {
1300       errstr = "SOCKS5 negotiation read failed";
1301    }
1302    else
1303    {
1304       if (sbuf[0] != '\x05')
1305       {
1306          errstr = "SOCKS5 negotiation protocol version error";
1307       }
1308       else if (sbuf[2] != '\x00')
1309       {
1310          errstr = "SOCKS5 negotiation protocol error";
1311       }
1312       else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1313       {
1314          errstr = translate_socks5_error(sbuf[1]);
1315       }
1316       else
1317       {
1318          if (sbuf[3] == '\x04')
1319          {
1320             /*
1321              * The address field contains an IPv6 address
1322              * which means we didn't get the whole reply
1323              * yet. Read and discard the rest of it to make
1324              * sure it isn't treated as HTTP data later on.
1325              */
1326             server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1327             if (server_size != SOCKS5_REPLY_DIFFERENCE)
1328             {
1329                errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1330             }
1331          }
1332          else if (sbuf[3] != '\x01')
1333          {
1334              errstr = "SOCKS5 reply contains unsupported address type";
1335          }
1336          if (errstr == NULL)
1337          {
1338             return(sfd);
1339          }
1340       }
1341    }
1342
1343    assert(errstr != NULL);
1344    csp->error_message = strdup(errstr);
1345    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1346    close_socket(sfd);
1347    errno = EINVAL;
1348
1349    return(JB_INVALID_SOCKET);
1350
1351 }
1352
1353 /*
1354   Local Variables:
1355   tab-width: 3
1356   end:
1357 */