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