Merge branch 'master' into 4.next
[exim.git] / src / src / transports / smtp_socks.c
CommitLineData
7eb6c37c
JH
1/*************************************************
2* Exim - an Internet mail transport agent *
3*************************************************/
4
5/* Copyright (c) Jeremy Harris 2015 */
6/* See the file NOTICE for conditions of use and distribution. */
7
8/* SOCKS version 5 proxy, client-mode */
9
10#include "../exim.h"
11#include "smtp.h"
12
f0989ec0 13#ifdef SUPPORT_SOCKS /* entire file */
7eb6c37c
JH
14
15#ifndef nelem
16# define nelem(arr) (sizeof(arr)/sizeof(*arr))
17#endif
18
19
20/* Defaults */
21#define SOCKS_PORT 1080
22#define SOCKS_TIMEOUT 5
7f06582c
JH
23#define SOCKS_WEIGHT 1
24#define SOCKS_PRIORITY 1
7eb6c37c
JH
25
26#define AUTH_NONE 0
27#define AUTH_NAME 2 /* user/password per RFC 1929 */
28#define AUTH_NAME_VER 1
29
30struct socks_err
31 {
32 uschar * reason;
33 int errcode;
34 } socks_errs[] =
35 {
36 {NULL, 0},
37 {US"general SOCKS server failure", EIO},
38 {US"connection not allowed by ruleset", EACCES},
39 {US"Network unreachable", ENETUNREACH},
40 {US"Host unreachable", EHOSTUNREACH},
41 {US"Connection refused", ECONNREFUSED},
42 {US"TTL expired", ECANCELED},
43 {US"Command not supported", EOPNOTSUPP},
44 {US"Address type not supported", EAFNOSUPPORT}
45 };
46
47typedef struct
48 {
7f06582c 49 const uschar * proxy_host;
7eb6c37c
JH
50 uschar auth_type; /* RFC 1928 encoding */
51 const uschar * auth_name;
52 const uschar * auth_pwd;
53 short port;
7f06582c 54 BOOL is_failed;
7eb6c37c 55 unsigned timeout;
7f06582c
JH
56 unsigned weight;
57 unsigned priority;
7eb6c37c
JH
58 } socks_opts;
59
60static void
61socks_option_defaults(socks_opts * sob)
62{
7f06582c
JH
63sob->proxy_host = NULL;
64sob->auth_type = AUTH_NONE;
65sob->auth_name = US"";
66sob->auth_pwd = US"";
67sob->is_failed = FALSE;
68sob->port = SOCKS_PORT;
69sob->timeout = SOCKS_TIMEOUT;
70sob->weight = SOCKS_WEIGHT;
71sob->priority = SOCKS_PRIORITY;
7eb6c37c
JH
72}
73
74static void
75socks_option(socks_opts * sob, const uschar * opt)
76{
77const uschar * s;
78
79if (Ustrncmp(opt, "auth=", 5) == 0)
80 {
81 opt += 5;
82 if (Ustrcmp(opt, "none") == 0) sob->auth_type = AUTH_NONE;
83 else if (Ustrcmp(opt, "name") == 0) sob->auth_type = AUTH_NAME;
84 }
85else if (Ustrncmp(opt, "name=", 5) == 0)
86 sob->auth_name = opt + 5;
87else if (Ustrncmp(opt, "pass=", 5) == 0)
88 sob->auth_pwd = opt + 5;
89else if (Ustrncmp(opt, "port=", 5) == 0)
90 sob->port = atoi(opt + 5);
91else if (Ustrncmp(opt, "tmo=", 4) == 0)
92 sob->timeout = atoi(opt + 4);
7f06582c
JH
93else if (Ustrncmp(opt, "pri=", 4) == 0)
94 sob->priority = atoi(opt + 4);
95else if (Ustrncmp(opt, "weight=", 7) == 0)
96 sob->weight = atoi(opt + 7);
7eb6c37c
JH
97return;
98}
99
100static int
101socks_auth(int fd, int method, socks_opts * sob, time_t tmo)
102{
103uschar * s;
104int len, i, j;
105
106switch(method)
107 {
108 default:
109 log_write(0, LOG_MAIN|LOG_PANIC,
110 "Unrecognised socks auth method %d", method);
111 return FAIL;
112 case AUTH_NONE:
113 return OK;
114 case AUTH_NAME:
e1d04f48 115 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" socks auth NAME '%s' '%s'\n",
7eb6c37c
JH
116 sob->auth_name, sob->auth_pwd);
117 i = Ustrlen(sob->auth_name);
118 j = Ustrlen(sob->auth_pwd);
119 s = string_sprintf("%c%c%.255s%c%.255s", AUTH_NAME_VER,
120 i, sob->auth_name, j, sob->auth_pwd);
121 len = i + j + 3;
122 HDEBUG(D_transport|D_acl|D_v)
123 {
124 int i;
e1d04f48 125 debug_printf_indent(" SOCKS>>");
7eb6c37c
JH
126 for (i = 0; i<len; i++) debug_printf(" %02x", s[i]);
127 debug_printf("\n");
128 }
1ccd5f67
JH
129 if (send(fd, s, len, 0) < 0)
130 return FAIL;
131#ifdef TCP_QUICKACK
132 (void) setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
133#endif
134 if (!fd_ready(fd, tmo-time(NULL)) || read(fd, s, 2) != 2)
7eb6c37c
JH
135 return FAIL;
136 HDEBUG(D_transport|D_acl|D_v)
e1d04f48 137 debug_printf_indent(" SOCKS<< %02x %02x\n", s[0], s[1]);
7eb6c37c
JH
138 if (s[0] == AUTH_NAME_VER && s[1] == 0)
139 {
e1d04f48 140 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" socks auth OK\n");
7eb6c37c
JH
141 return OK;
142 }
143
144 log_write(0, LOG_MAIN|LOG_PANIC, "socks auth failed");
145 errno = EPROTO;
146 return FAIL;
147 }
148}
149
150
151
7f06582c
JH
152/* Find a suitable proxy to use from the list.
153Possible common code with spamd_get_server() ?
154
155Return: index into proxy spec array, or -1
156*/
157
158static int
159socks_get_proxy(socks_opts * proxies, unsigned nproxies)
160{
161unsigned int i;
162socks_opts * sd;
163socks_opts * lim = &proxies[nproxies];
164long rnd, weights;
165unsigned pri;
166static BOOL srandomed = FALSE;
167
168if (nproxies == 1) /* shortcut, if we have only 1 server */
169 return (proxies[0].is_failed ? -1 : 0);
170
171/* init random */
172if (!srandomed)
173 {
174 struct timeval tv;
175 gettimeofday(&tv, NULL);
176 srandom((unsigned int)(tv.tv_usec/1000));
177 srandomed = TRUE;
178 }
179
180/* scan for highest pri */
181for (pri = 0, sd = proxies; sd < lim; sd++)
182 if (!sd->is_failed && sd->priority > pri)
183 pri = sd->priority;
184
185/* get sum of weights at this pri */
186for (weights = 0, sd = proxies; sd < lim; sd++)
187 if (!sd->is_failed && sd->priority == pri)
188 weights += sd->weight;
189if (weights == 0) /* all servers failed */
190 return -1;
191
192for (rnd = random() % weights, i = 0; i < nproxies; i++)
193 {
194 sd = &proxies[i];
195 if (!sd->is_failed && sd->priority == pri)
196 if ((rnd -= sd->weight) <= 0)
197 return i;
198 }
199
200log_write(0, LOG_MAIN|LOG_PANIC,
201 "%s unknown error (memory/cpu corruption?)", __FUNCTION__);
202return -1;
203}
204
205
206
7eb6c37c
JH
207/* Make a connection via a socks proxy
208
209Arguments:
210 host smtp target host
211 host_af address family
212 port remote tcp port number
213 interface local interface
214 tb transport
215 timeout connection timeout (zero for indefinite)
216
217Return value:
218 0 on success; -1 on failure, with errno set
219*/
220
221int
222socks_sock_connect(host_item * host, int host_af, int port, uschar * interface,
223 transport_instance * tb, int timeout)
7eb6c37c
JH
224{
225smtp_transport_options_block * ob =
226 (smtp_transport_options_block *)tb->options_block;
227const uschar * proxy_list;
228const uschar * proxy_spec;
229int sep = 0;
230int fd;
231time_t tmo;
232const uschar * state;
233uschar buf[24];
7f06582c
JH
234socks_opts proxies[32]; /* max #proxies handled */
235unsigned nproxies;
236socks_opts * sob;
237unsigned size;
0ab63f3d 238blob early_data;
7eb6c37c
JH
239
240if (!timeout) timeout = 24*60*60; /* use 1 day for "indefinite" */
241tmo = time(NULL) + timeout;
242
243if (!(proxy_list = expand_string(ob->socks_proxy)))
244 {
245 log_write(0, LOG_MAIN|LOG_PANIC, "Bad expansion for socks_proxy in %s",
246 tb->name);
247 return -1;
248 }
249
7f06582c
JH
250/* Read proxy list */
251
252for (nproxies = 0;
253 nproxies < nelem(proxies)
254 && (proxy_spec = string_nextinlist(&proxy_list, &sep, NULL, 0));
255 nproxies++)
7eb6c37c 256 {
7eb6c37c 257 int subsep = -' ';
7eb6c37c
JH
258 const uschar * option;
259
7f06582c
JH
260 socks_option_defaults(sob = &proxies[nproxies]);
261
262 if (!(sob->proxy_host = string_nextinlist(&proxy_spec, &subsep, NULL, 0)))
7eb6c37c
JH
263 {
264 /* paniclog config error */
265 return -1;
266 }
267
268 /*XXX consider global options eg. "hide socks_password = wibble" on the tpt */
7eb6c37c
JH
269 /* extract any further per-proxy options */
270 while ((option = string_nextinlist(&proxy_spec, &subsep, NULL, 0)))
7f06582c
JH
271 socks_option(sob, option);
272 }
273
0ab63f3d
JH
274/* Set up the socks protocol method-selection message,
275for sending on connection */
276
277state = US"method select";
278buf[0] = 5; buf[1] = 1; buf[2] = sob->auth_type;
279early_data.data = buf;
280early_data.len = 3;
281
7f06582c
JH
282/* Try proxies until a connection succeeds */
283
284for(;;)
285 {
286 int idx;
287 host_item proxy;
288 int proxy_af;
289
290 if ((idx = socks_get_proxy(proxies, nproxies)) < 0)
291 {
e1d04f48 292 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" no proxies left\n");
7f06582c
JH
293 errno = EBUSY;
294 return -1;
295 }
296 sob = &proxies[idx];
7eb6c37c
JH
297
298 /* bodge up a host struct for the proxy */
848214f7 299 proxy.address = proxy.name = sob->proxy_host;
7f06582c 300 proxy_af = Ustrchr(sob->proxy_host, ':') ? AF_INET6 : AF_INET;
7eb6c37c 301
7f06582c 302 if ((fd = smtp_sock_connect(&proxy, proxy_af, sob->port,
0ab63f3d 303 interface, tb, sob->timeout, &early_data)) >= 0)
e6d2a989
JH
304 {
305 proxy_local_address = string_copy(proxy.address);
306 proxy_local_port = sob->port;
7f06582c 307 break;
e6d2a989 308 }
7f06582c
JH
309
310 log_write(0, LOG_MAIN, "%s: %s", __FUNCTION__, strerror(errno));
311 sob->is_failed = TRUE;
312 }
313
314/* Do the socks protocol stuff */
7f06582c 315
e1d04f48 316HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" SOCKS>> 05 01 %02x\n", sob->auth_type);
7f06582c
JH
317
318/* expect method response */
319
1ccd5f67
JH
320#ifdef TCP_QUICKACK
321(void) setsockopt(fd, IPPROTO_TCP, TCP_QUICKACK, US &off, sizeof(off));
322#endif
323
7f06582c
JH
324if ( !fd_ready(fd, tmo-time(NULL))
325 || read(fd, buf, 2) != 2
326 )
327 goto rcv_err;
328HDEBUG(D_transport|D_acl|D_v)
e1d04f48 329 debug_printf_indent(" SOCKS<< %02x %02x\n", buf[0], buf[1]);
7f06582c
JH
330if ( buf[0] != 5
331 || socks_auth(fd, buf[1], sob, tmo) != OK
332 )
333 goto proxy_err;
334
335 {
336 union sockaddr_46 sin;
7eb6c37c
JH
337 (void) ip_addr(&sin, host_af, host->address, port);
338
339 /* send connect (ipver, ipaddr, port) */
7f06582c 340
7eb6c37c 341 buf[0] = 5; buf[1] = 1; buf[2] = 0; buf[3] = host_af == AF_INET6 ? 4 : 1;
7f06582c 342 #if HAVE_IPV6
7eb6c37c
JH
343 if (host_af == AF_INET6)
344 {
345 memcpy(buf+4, &sin.v6.sin6_addr, sizeof(sin.v6.sin6_addr));
346 memcpy(buf+4+sizeof(sin.v6.sin6_addr),
347 &sin.v6.sin6_port, sizeof(sin.v6.sin6_port));
348 size = 4+sizeof(sin.v6.sin6_addr)+sizeof(sin.v6.sin6_port);
349 }
350 else
7f06582c 351 #endif
7eb6c37c
JH
352 {
353 memcpy(buf+4, &sin.v4.sin_addr.s_addr, sizeof(sin.v4.sin_addr.s_addr));
354 memcpy(buf+4+sizeof(sin.v4.sin_addr.s_addr),
355 &sin.v4.sin_port, sizeof(sin.v4.sin_port));
356 size = 4+sizeof(sin.v4.sin_addr.s_addr)+sizeof(sin.v4.sin_port);
357 }
7f06582c 358 }
7eb6c37c 359
7f06582c
JH
360state = US"connect";
361HDEBUG(D_transport|D_acl|D_v)
362 {
363 int i;
e1d04f48 364 debug_printf_indent(" SOCKS>>");
7f06582c
JH
365 for (i = 0; i<size; i++) debug_printf(" %02x", buf[i]);
366 debug_printf("\n");
367 }
368if (send(fd, buf, size, 0) < 0)
369 goto snd_err;
7eb6c37c 370
7f06582c
JH
371/* expect conn-reply (success, local(ipver, addr, port))
372of same length as conn-request, or non-success fail code */
7eb6c37c 373
7f06582c
JH
374if ( !fd_ready(fd, tmo-time(NULL))
375 || (size = read(fd, buf, size)) < 2
376 )
377 goto rcv_err;
378HDEBUG(D_transport|D_acl|D_v)
379 {
380 int i;
e1d04f48 381 debug_printf_indent(" SOCKS>>");
7f06582c
JH
382 for (i = 0; i<size; i++) debug_printf(" %02x", buf[i]);
383 debug_printf("\n");
7eb6c37c 384 }
7f06582c
JH
385if ( buf[0] != 5
386 || buf[1] != 0
387 )
388 goto proxy_err;
389
e6d2a989
JH
390proxy_external_address = string_copy(
391 host_ntoa(buf[3] == 4 ? AF_INET6 : AF_INET, buf+4, NULL, NULL));
392proxy_external_port = ntohs(*((uint16_t *)(buf + (buf[3] == 4 ? 20 : 8))));
393proxy_session = TRUE;
394
7f06582c 395HDEBUG(D_transport|D_acl|D_v)
e1d04f48 396 debug_printf_indent(" proxy farside: [%s]:%d\n", proxy_external_address, proxy_external_port);
7f06582c
JH
397
398return fd;
7eb6c37c
JH
399
400snd_err:
e1d04f48 401 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" proxy snd_err %s: %s\n", state, strerror(errno));
7eb6c37c
JH
402 return -1;
403
404proxy_err:
405 {
406 struct socks_err * se =
407 buf[1] > nelem(socks_errs) ? NULL : socks_errs + buf[1];
408 HDEBUG(D_transport|D_acl|D_v)
e1d04f48 409 debug_printf_indent(" proxy %s: %s\n", state, se ? se->reason : US"unknown error code received");
7eb6c37c
JH
410 errno = se ? se->errcode : EPROTO;
411 }
412
413rcv_err:
e1d04f48 414 HDEBUG(D_transport|D_acl|D_v) debug_printf_indent(" proxy rcv_err %s: %s\n", state, strerror(errno));
7eb6c37c
JH
415 if (!errno) errno = EPROTO;
416 else if (errno == ENOENT) errno = ECONNABORTED;
417 return -1;
418}
419
420#endif /* entire file */
421/* vi: aw ai sw=2
422*/