Coverage Report

Created: 2026-12-01 06:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/socks.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
9
 *
10
 * This software is licensed as described in the file COPYING, which
11
 * you should have received as part of this distribution. The terms
12
 * are also available at https://curl.se/docs/copyright.html.
13
 *
14
 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15
 * copies of the Software, and permit persons to whom the Software is
16
 * furnished to do so, under the terms of the COPYING file.
17
 *
18
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19
 * KIND, either express or implied.
20
 *
21
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
26
#ifndef CURL_DISABLE_PROXY
27
28
#ifdef HAVE_NETINET_IN_H
29
#include <netinet/in.h>
30
#endif
31
#ifdef HAVE_ARPA_INET_H
32
#include <arpa/inet.h>
33
#endif
34
35
#include "urldata.h"
36
#include "bufq.h"
37
#include "cf-ip-happy.h"
38
#include "curl_addrinfo.h"
39
#include "curl_trc.h"
40
#include "select.h"
41
#include "cfilters.h"
42
#include "connect.h"
43
#include "socks.h"
44
#include "vdns/cf-dns.h"
45
#include "curlx/inet_pton.h"
46
47
/* for the (SOCKS) connect state machine */
48
enum socks_state_t {
49
  SOCKS_ST_INIT,
50
  /* SOCKS Version 4 states */
51
  SOCKS4_ST_START,
52
  SOCKS4_ST_RESOLVING,
53
  SOCKS4_ST_SEND,
54
  SOCKS4_ST_RECV,
55
  /* SOCKS Version 5 states */
56
  SOCKS5_ST_START,
57
  SOCKS5_ST_REQ0_SEND,
58
  SOCKS5_ST_RESP0_RECV, /* set up read */
59
  SOCKS5_ST_GSSAPI_INIT,
60
  SOCKS5_ST_AUTH_INIT, /* setup outgoing auth buffer */
61
  SOCKS5_ST_AUTH_SEND, /* send auth */
62
  SOCKS5_ST_AUTH_RECV, /* read auth response */
63
  SOCKS5_ST_REQ1_INIT,  /* init SOCKS "request" */
64
  SOCKS5_ST_RESOLVING,
65
  SOCKS5_ST_REQ1_SEND,
66
  SOCKS5_ST_RESP1_RECV,
67
  /* Terminal states, all SOCKS versions */
68
  SOCKS_ST_SUCCESS,
69
  SOCKS_ST_FAILED
70
};
71
72
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
73
static const char * const cf_socks_statename[] = {
74
  "SOCKS_INIT",
75
  "SOCKS4_START",
76
  "SOCKS4_RESOLVING",
77
  "SOCKS4_SEND",
78
  "SOCKS4_RECV",
79
  "SOCKS5_START",
80
  "SOCKS5_REQ0_SEND",
81
  "SOCKS5_RESP0_RECV",
82
  "SOCKS5_GSSAPI_INIT",
83
  "SOCKS5_AUTH_INIT",
84
  "SOCKS5_AUTH_SEND",
85
  "SOCKS5_AUTH_RECV",
86
  "SOCKS5_REQ1_INIT",
87
  "SOCKS5_RESOLVING",
88
  "SOCKS5_REQ1_SEND",
89
  "SOCKS5_RESP1_RECV",
90
  "SOCKS_SUCCESS",
91
  "SOCKS_FAILED"
92
};
93
#endif
94
95
0
#define SOCKS_CHUNK_SIZE    1024
96
0
#define SOCKS_CHUNKS        1
97
98
struct socks_ctx {
99
  enum socks_state_t state;
100
  struct bufq iobuf;
101
  struct Curl_peer *peer;
102
  struct Curl_peer *dest;
103
  struct Curl_creds *creds;
104
  CURLproxycode presult;
105
  uint8_t ip_version;
106
  uint8_t ipv_used;
107
  uint8_t proxy_type;
108
  unsigned char version;
109
  BIT(resolve_local);
110
  BIT(socks4a);
111
  BIT(socks5_addr_retried);
112
};
113
114
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
115
/*
116
 * Helper read-from-socket functions. Does the same as Curl_read() but it
117
 * blocks until all bytes amount of buffersize will be read. No more, no less.
118
 *
119
 * This is STUPID BLOCKING behavior. Only used by the SOCKS GSSAPI functions.
120
 */
121
CURLcode Curl_blockread_all(struct Curl_cfilter *cf,
122
                            struct Curl_easy *data,
123
                            char *buf,             /* store read data here */
124
                            size_t blen,           /* space in buf */
125
                            size_t *pnread)        /* amount bytes read */
126
{
127
  size_t nread = 0;
128
  CURLcode result;
129
130
  *pnread = 0;
131
  for(;;) {
132
    timediff_t timeout_ms = Curl_timeleft_ms(data);
133
    curl_socket_t sock = cf->chain->sock;
134
135
    if(timeout_ms < 0) {
136
      /* we already got the timeout */
137
      return CURLE_OPERATION_TIMEDOUT;
138
    }
139
    if(!timeout_ms)
140
      timeout_ms = TIMEDIFF_T_MAX;
141
    if(SOCKET_READABLE(sock, timeout_ms) <= 0)
142
      return CURLE_OPERATION_TIMEDOUT;
143
    result = Curl_conn_cf_recv(cf->next, data, buf, blen, &nread);
144
    if(result == CURLE_AGAIN)
145
      continue;
146
    else if(result)
147
      return result;
148
149
    if(blen == nread) {
150
      *pnread += nread;
151
      return CURLE_OK;
152
    }
153
    if(!nread) /* EOF */
154
      return CURLE_RECV_ERROR;
155
156
    buf += nread;
157
    blen -= nread;
158
    *pnread += nread;
159
  }
160
}
161
#endif
162
163
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
164
0
#define sxstate(x, c, d, y) socksstate(x, c, d, y, __LINE__)
165
#else
166
#define sxstate(x, c, d, y) socksstate(x, c, d, y)
167
#endif
168
169
/* always use this function to change state, to make debugging easier */
170
static void socksstate(struct socks_ctx *sx,
171
                       struct Curl_cfilter *cf,
172
                       struct Curl_easy *data,
173
                       enum socks_state_t state
174
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
175
                       , int lineno
176
#endif
177
)
178
0
{
179
0
  enum socks_state_t oldstate = sx->state;
180
181
0
  if(oldstate == state)
182
    /* do not bother when the new state is the same as the old state */
183
0
    return;
184
185
0
  sx->state = state;
186
187
0
#if defined(DEBUGBUILD) && defined(CURLVERBOSE)
188
0
  CURL_TRC_CF(data, cf, "[%s] -> [%s] (line %d)",
189
0
              cf_socks_statename[oldstate],
190
0
              cf_socks_statename[sx->state], lineno);
191
#else
192
  (void)cf;
193
  (void)data;
194
#endif
195
0
}
196
197
static CURLproxycode socks_failed(struct socks_ctx *sx,
198
                                  struct Curl_cfilter *cf,
199
                                  struct Curl_easy *data,
200
                                  CURLproxycode presult)
201
0
{
202
0
  sxstate(sx, cf, data, SOCKS_ST_FAILED);
203
0
  sx->presult = presult;
204
0
  return presult;
205
0
}
206
207
static CURLproxycode socks_flush(struct socks_ctx *sx,
208
                                 struct Curl_cfilter *cf,
209
                                 struct Curl_easy *data,
210
                                 bool *done)
211
0
{
212
0
  CURLcode result;
213
0
  size_t nwritten;
214
215
0
  *done = FALSE;
216
0
  while(!Curl_bufq_is_empty(&sx->iobuf)) {
217
0
    result = Curl_cf_send_bufq(cf->next, data, &sx->iobuf, NULL, 0,
218
0
                               &nwritten);
219
0
    if(result == CURLE_AGAIN)
220
0
      return CURLPX_OK;
221
0
    else if(result) {
222
0
      failf(data, "Failed to send SOCKS request: %s",
223
0
            curl_easy_strerror(result));
224
0
      return socks_failed(sx, cf, data, CURLPX_SEND_CONNECT);
225
0
    }
226
0
  }
227
0
  *done = TRUE;
228
0
  return CURLPX_OK;
229
0
}
230
231
static CURLproxycode socks_recv(struct socks_ctx *sx,
232
                                struct Curl_cfilter *cf,
233
                                struct Curl_easy *data,
234
                                size_t min_bytes,
235
                                bool *done)
236
0
{
237
0
  CURLcode result;
238
0
  size_t nread;
239
240
0
  *done = FALSE;
241
0
  while(Curl_bufq_len(&sx->iobuf) < min_bytes) {
242
0
    result = Curl_cf_recv_bufq(cf->next, data, &sx->iobuf,
243
0
                               min_bytes - Curl_bufq_len(&sx->iobuf),
244
0
                               &nread);
245
0
    if(result == CURLE_AGAIN)
246
0
      return CURLPX_OK;
247
0
    else if(result) {
248
0
      failf(data, "Failed to receive SOCKS response: %s",
249
0
            curl_easy_strerror(result));
250
0
      return CURLPX_RECV_CONNECT;
251
0
    }
252
0
    else if(!nread) { /* EOF */
253
0
      if(Curl_bufq_len(&sx->iobuf) < min_bytes) {
254
0
        failf(data, "Failed to receive SOCKS response, "
255
0
              "proxy closed connection");
256
0
        return CURLPX_RECV_CONNECT;
257
0
      }
258
0
      break;
259
0
    }
260
0
  }
261
0
  *done = TRUE;
262
0
  return CURLPX_OK;
263
0
}
264
265
static CURLproxycode socks4_req_add_hd(struct socks_ctx *sx,
266
                                       struct Curl_easy *data)
267
0
{
268
0
  unsigned char buf[4];
269
0
  size_t nwritten;
270
0
  CURLcode result;
271
272
0
  (void)data;
273
0
  buf[0] = 4; /* version (SOCKS4) */
274
0
  buf[1] = 1; /* connect */
275
0
  buf[2] = (unsigned char)((sx->dest->port >> 8) & 0xffU); /* MSB */
276
0
  buf[3] = (unsigned char)(sx->dest->port & 0xffU);        /* LSB */
277
278
0
  result = Curl_bufq_write(&sx->iobuf, buf, 4, &nwritten);
279
0
  if(result || (nwritten != 4))
280
0
    return CURLPX_SEND_REQUEST;
281
0
  return CURLPX_OK;
282
0
}
283
284
static CURLproxycode socks4_req_add_user(struct socks_ctx *sx,
285
                                         struct Curl_easy *data)
286
0
{
287
0
  CURLcode result;
288
0
  size_t nwritten;
289
290
0
  if(sx->creds) {
291
0
    size_t plen = strlen(sx->creds->user);
292
0
    if(plen > 255) {
293
      /* there is no real size limit to this field in the protocol, but
294
         SOCKS5 limits the proxy user field to 255 bytes and it seems likely
295
         that a longer field is either a mistake or malicious input */
296
0
      failf(data, "Too long SOCKS proxy username");
297
0
      return CURLPX_LONG_USER;
298
0
    }
299
    /* add proxy name WITH null-terminator */
300
0
    result = Curl_bufq_cwrite(&sx->iobuf, sx->creds->user, plen + 1,
301
0
                              &nwritten);
302
0
    if(result || (nwritten != (plen + 1)))
303
0
      return CURLPX_SEND_REQUEST;
304
0
  }
305
0
  else {
306
    /* empty username */
307
0
    unsigned char b = 0;
308
0
    result = Curl_bufq_write(&sx->iobuf, &b, 1, &nwritten);
309
0
    if(result || (nwritten != 1))
310
0
      return CURLPX_SEND_REQUEST;
311
0
  }
312
0
  return CURLPX_OK;
313
0
}
314
315
static CURLproxycode socks4_resolving(struct socks_ctx *sx,
316
                                      struct Curl_cfilter *cf,
317
                                      struct Curl_easy *data,
318
                                      bool *done)
319
0
{
320
0
  const struct Curl_addrinfo *ai = NULL;
321
0
  CURLcode result;
322
0
  size_t nwritten;
323
324
0
  *done = FALSE;
325
0
  result = Curl_dns_cf_addr_result(cf, sx->dest);
326
0
  if(result) {
327
0
    if(result != CURLE_AGAIN) {
328
0
      failf(data, "error %d resolving SOCKS destination %s:%u",
329
0
            (int)result, sx->dest->hostname, sx->dest->port);
330
0
      return CURLPX_RESOLVE_HOST;
331
0
    }
332
0
    return CURLPX_OK;
333
0
  }
334
335
0
  ai = Curl_dns_cf_get_ai(data, cf, sx->dest, AF_INET, 0);
336
0
  if(ai) {
337
0
    struct sockaddr_in *saddr_in;
338
0
    char ipbuf[64];
339
340
0
    sx->ipv_used = CURL_IPRESOLVE_V4;
341
0
    Curl_printable_address(ai, ipbuf, sizeof(ipbuf));
342
0
    CURL_TRC_CF(data, cf, "SOCKS4 connect to IPv4 %s (locally resolved)",
343
0
                ipbuf);
344
345
0
    saddr_in = (struct sockaddr_in *)(void *)ai->ai_addr;
346
0
    result = Curl_bufq_write(&sx->iobuf,
347
0
                             (unsigned char *)&saddr_in->sin_addr.s_addr, 4,
348
0
                             &nwritten);
349
350
0
    if(result || (nwritten != 4))
351
0
      return CURLPX_SEND_REQUEST;
352
0
  }
353
0
  else {
354
    /* No IPv4 address resolved */
355
0
    failf(data, "SOCKS4 connection to %s not supported", sx->dest->hostname);
356
0
    return CURLPX_RESOLVE_HOST;
357
0
  }
358
359
0
  *done = TRUE;
360
0
  return CURLPX_OK;
361
0
}
362
363
static CURLproxycode socks4_check_resp(struct socks_ctx *sx,
364
                                       struct Curl_cfilter *cf,
365
                                       struct Curl_easy *data)
366
0
{
367
0
  const unsigned char *resp;
368
0
  size_t rlen;
369
370
0
  if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < 8) {
371
0
    failf(data, "SOCKS4 reply is incomplete.");
372
0
    return CURLPX_RECV_CONNECT;
373
0
  }
374
375
0
  DEBUGASSERT(rlen == 8);
376
  /*
377
   * Response format
378
   *
379
   *     +----+----+----+----+----+----+----+----+
380
   *     | VN | CD | DSTPORT |      DSTIP        |
381
   *     +----+----+----+----+----+----+----+----+
382
   * # of bytes:  1    1      2              4
383
   *
384
   * VN is the version of the reply code and should be 0. CD is the result
385
   * code with one of the following values:
386
   *
387
   * 90: request granted
388
   * 91: request rejected or failed
389
   * 92: request rejected because SOCKS server cannot connect to
390
   *     identd on the client
391
   * 93: request rejected because the client program and identd
392
   *     report different user-ids
393
   */
394
395
  /* wrong version ? */
396
0
  if(resp[0]) {
397
0
    failf(data, "SOCKS4 reply has wrong version, version should be 0.");
398
0
    return CURLPX_BAD_VERSION;
399
0
  }
400
401
  /* Result */
402
0
  switch(resp[1]) {
403
0
  case 90:
404
0
    CURL_TRC_CF(data, cf, "SOCKS4%s request granted.", sx->socks4a ? "a" : "");
405
0
    Curl_bufq_skip(&sx->iobuf, 8);
406
0
    return CURLPX_OK;
407
0
  case 91:
408
0
    failf(data,
409
0
          "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)"
410
0
          ", request rejected or failed.",
411
0
          resp[4], resp[5], resp[6], resp[7],
412
0
          (unsigned int)((resp[2] << 8) | resp[3]), resp[1]);
413
0
    return CURLPX_REQUEST_FAILED;
414
0
  case 92:
415
0
    failf(data,
416
0
          "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)"
417
0
          ", request rejected because SOCKS server cannot connect to "
418
0
          "identd on the client.",
419
0
          resp[4], resp[5], resp[6], resp[7],
420
0
          (unsigned int)((resp[2] << 8) | resp[3]), resp[1]);
421
0
    return CURLPX_IDENTD;
422
0
  case 93:
423
0
    failf(data,
424
0
          "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)"
425
0
          ", request rejected because the client program and identd "
426
0
          "report different user-ids.",
427
0
          resp[4], resp[5], resp[6], resp[7],
428
0
          (unsigned int)((resp[2] << 8) | resp[3]), resp[1]);
429
0
    return CURLPX_IDENTD_DIFFER;
430
0
  default:
431
0
    failf(data,
432
0
          "[SOCKS] cannot complete SOCKS4 connection to %u.%u.%u.%u:%u. (%u)"
433
0
          ", Unknown.",
434
0
          resp[4], resp[5], resp[6], resp[7],
435
0
          (unsigned int)((resp[2] << 8) | resp[3]), resp[1]);
436
0
    return CURLPX_UNKNOWN_FAIL;
437
0
  }
438
0
}
439
440
/*
441
 * This function logs in to a SOCKS4 proxy and sends the specifics to the final
442
 * destination server.
443
 *
444
 * Reference :
445
 *   https://www.openssh.com/txt/socks4.protocol
446
 *
447
 * Note :
448
 *   Set protocol4a=true for  "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
449
 *   Nonsupport "Identification Protocol (RFC1413)"
450
 */
451
static CURLproxycode socks4_connect(struct Curl_cfilter *cf,
452
                                    struct socks_ctx *sx,
453
                                    struct Curl_easy *data)
454
0
{
455
0
  size_t nwritten;
456
0
  CURLproxycode presult;
457
0
  CURLcode result;
458
0
  bool done;
459
460
0
process_state:
461
0
  switch(sx->state) {
462
0
  case SOCKS_ST_INIT:
463
0
    sx->version = 4;
464
0
    sxstate(sx, cf, data, SOCKS4_ST_START);
465
0
    FALLTHROUGH();
466
467
0
  case SOCKS4_ST_START:
468
0
    Curl_bufq_reset(&sx->iobuf);
469
0
    sx->socks4a = (sx->proxy_type == CURLPROXY_SOCKS4A);
470
0
    sx->presult = CURLPX_OK;
471
472
    /* SOCKS4 can only do IPv4, insist! */
473
0
    sx->ip_version = CURL_IPRESOLVE_V4;
474
0
    CURL_TRC_CF(data, cf, "SOCKS4%s connecting to %s:%u",
475
0
                sx->socks4a ? "a" : "",
476
0
                sx->dest->hostname, sx->dest->port);
477
478
    /*
479
     * Compose socks4 request
480
     *
481
     * Request format
482
     *
483
     *     +----+----+----+----+----+----+----+----+----+----+....+----+
484
     *     | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
485
     *     +----+----+----+----+----+----+----+----+----+----+....+----+
486
     * # of bytes:  1    1      2              4           variable       1
487
     */
488
0
    presult = socks4_req_add_hd(sx, data);
489
0
    if(presult)
490
0
      return socks_failed(sx, cf, data, presult);
491
492
    /* DNS resolve only for SOCKS4, not SOCKS4a */
493
0
    if(!sx->resolve_local) {
494
      /* socks4a, not resolving locally, sends the hostname.
495
       * add an invalid address + user + hostname */
496
0
      unsigned char buf[4] = { 0, 0, 0, 1 };
497
0
      size_t hlen = strlen(sx->dest->hostname) + 1; /* including NUL */
498
499
0
      if(hlen > 255) {
500
0
        failf(data, "SOCKS4: too long hostname");
501
0
        return socks_failed(sx, cf, data, CURLPX_LONG_HOSTNAME);
502
0
      }
503
0
      result = Curl_bufq_write(&sx->iobuf, buf, 4, &nwritten);
504
0
      if(result || (nwritten != 4))
505
0
        return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST);
506
0
      presult = socks4_req_add_user(sx, data);
507
0
      if(presult)
508
0
        return socks_failed(sx, cf, data, presult);
509
0
      result = Curl_bufq_cwrite(&sx->iobuf, sx->dest->hostname, hlen,
510
0
                                &nwritten);
511
0
      if(result || (nwritten != hlen))
512
0
        return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST);
513
      /* request complete */
514
0
      sxstate(sx, cf, data, SOCKS4_ST_SEND);
515
0
      goto process_state;
516
0
    }
517
0
    sxstate(sx, cf, data, SOCKS4_ST_RESOLVING);
518
0
    FALLTHROUGH();
519
520
0
  case SOCKS4_ST_RESOLVING:
521
0
    presult = socks4_resolving(sx, cf, data, &done);
522
0
    if(presult)
523
0
      return socks_failed(sx, cf, data, presult);
524
0
    if(!done)
525
0
      return CURLPX_OK;
526
    /* append user */
527
0
    presult = socks4_req_add_user(sx, data);
528
0
    if(presult)
529
0
      return socks_failed(sx, cf, data, presult);
530
0
    sxstate(sx, cf, data, SOCKS4_ST_SEND);
531
0
    FALLTHROUGH();
532
533
0
  case SOCKS4_ST_SEND:
534
0
    presult = socks_flush(sx, cf, data, &done);
535
0
    if(presult)
536
0
      return socks_failed(sx, cf, data, presult);
537
0
    else if(!done)
538
0
      return CURLPX_OK;
539
0
    sxstate(sx, cf, data, SOCKS4_ST_RECV);
540
0
    FALLTHROUGH();
541
542
0
  case SOCKS4_ST_RECV:
543
    /* Receive 8-byte response */
544
0
    presult = socks_recv(sx, cf, data, 8, &done);
545
0
    if(presult)
546
0
      return socks_failed(sx, cf, data, presult);
547
0
    else if(!done)
548
0
      return CURLPX_OK;
549
0
    presult = socks4_check_resp(sx, cf, data);
550
0
    if(presult)
551
0
      return socks_failed(sx, cf, data, presult);
552
0
    sxstate(sx, cf, data, SOCKS_ST_SUCCESS);
553
0
    FALLTHROUGH();
554
555
0
  case SOCKS_ST_SUCCESS:
556
0
    return CURLPX_OK;
557
558
0
  case SOCKS_ST_FAILED:
559
0
    DEBUGASSERT(sx->presult);
560
0
    return sx->presult;
561
562
0
  default:
563
0
    DEBUGASSERT(0);
564
0
    return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST);
565
0
  }
566
0
}
567
568
static CURLproxycode socks5_req0_init(struct Curl_cfilter *cf,
569
                                      struct socks_ctx *sx,
570
                                      struct Curl_easy *data)
571
0
{
572
0
  const unsigned char auth = data->set.socks5auth;
573
0
  unsigned char req[5]; /* version + len + 3 possible auth methods */
574
0
  unsigned char nauths;
575
0
  size_t req_len, nwritten;
576
0
  CURLcode result;
577
578
  /* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */
579
0
  if(!sx->resolve_local && strlen(sx->dest->hostname) > 255) {
580
0
    failf(data, "SOCKS5: the destination hostname is too long to be "
581
0
          "resolved remotely by the proxy.");
582
0
    return CURLPX_LONG_HOSTNAME;
583
0
  }
584
585
0
  if(auth & ~(CURLAUTH_BASIC | CURLAUTH_GSSAPI))
586
0
    infof(data, "warning: unsupported value passed to "
587
0
          "CURLOPT_SOCKS5_AUTH: %u", auth);
588
0
  if(!(auth & CURLAUTH_BASIC))
589
    /* disable username/password auth */
590
0
    Curl_creds_unlink(&sx->creds);
591
592
0
  if(CF_IS_PRIMARY(cf))
593
    /* the reuse of this connection depends on how this negotiation ends */
594
0
    CF_CONN(cf)->bits.socks5_authenticated = FALSE;
595
596
0
  req[0] = 5;   /* version */
597
0
  nauths = 0;
598
0
  if(!data->set.socks5_auth_only) {
599
0
    ++nauths;
600
0
    req[1 + nauths] = 0; /* no authentication */
601
0
  }
602
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
603
  if(auth & CURLAUTH_GSSAPI) {
604
    ++nauths;
605
    req[1 + nauths] = 1; /* GSS-API */
606
  }
607
#endif
608
0
  if(sx->creds) {
609
0
    ++nauths;
610
0
    req[1 + nauths] = 2; /* username/password */
611
0
  }
612
0
  if(!nauths) {
613
0
    failf(data, "SOCKS5: no acceptable authentication method is available.");
614
0
    return CURLPX_NO_AUTH;
615
0
  }
616
0
  req[1] = nauths;
617
0
  req_len = 2 + nauths;
618
619
0
  result = Curl_bufq_write(&sx->iobuf, req, req_len, &nwritten);
620
0
  if(result || (nwritten != req_len))
621
0
    return CURLPX_SEND_REQUEST;
622
0
  return CURLPX_OK;
623
0
}
624
625
static CURLproxycode socks5_check_resp0(struct socks_ctx *sx,
626
                                        struct Curl_cfilter *cf,
627
                                        struct Curl_easy *data)
628
0
{
629
0
  const unsigned char *resp;
630
0
  unsigned char auth_mode;
631
0
  size_t rlen;
632
633
0
  if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < 2) {
634
0
    failf(data, "SOCKS5 initial reply is incomplete.");
635
0
    return CURLPX_RECV_CONNECT;
636
0
  }
637
638
0
  if(resp[0] != 5) {
639
0
    failf(data, "Received invalid version in initial SOCKS5 response.");
640
0
    return CURLPX_BAD_VERSION;
641
0
  }
642
643
0
  auth_mode = resp[1];
644
0
  Curl_bufq_skip(&sx->iobuf, 2);
645
646
0
  switch(auth_mode) {
647
0
  case 0:
648
0
    if(data->set.socks5_auth_only) {
649
0
      failf(data, "SOCKS5 proxy selected no authentication.");
650
0
      return CURLPX_NO_AUTH;
651
0
    }
652
    /* DONE! No authentication needed. Send request. */
653
0
    sxstate(sx, cf, data, SOCKS5_ST_REQ1_INIT);
654
0
    return CURLPX_OK;
655
0
  case 1:
656
0
    if(data->set.socks5auth & CURLAUTH_GSSAPI) {
657
0
      if(CF_IS_PRIMARY(cf))
658
0
        CF_CONN(cf)->bits.socks5_authenticated = TRUE;
659
0
      sxstate(sx, cf, data, SOCKS5_ST_GSSAPI_INIT);
660
0
      return CURLPX_OK;
661
0
    }
662
0
    failf(data, "SOCKS5 GSSAPI per-message authentication is not enabled.");
663
0
    return CURLPX_GSSAPI_PERMSG;
664
0
  case 2:
665
    /* regular name + password authentication */
666
0
    if(data->set.socks5auth & CURLAUTH_BASIC) {
667
0
      if(CF_IS_PRIMARY(cf))
668
0
        CF_CONN(cf)->bits.socks5_authenticated = TRUE;
669
0
      sxstate(sx, cf, data, SOCKS5_ST_AUTH_INIT);
670
0
      return CURLPX_OK;
671
0
    }
672
0
    failf(data, "BASIC authentication proposed but not enabled.");
673
0
    return CURLPX_NO_AUTH;
674
0
  case 255:
675
0
    failf(data, "No authentication method was acceptable.");
676
0
    return CURLPX_NO_AUTH;
677
0
  default:
678
0
    failf(data, "Unknown SOCKS5 mode attempted to be used by server.");
679
0
    return CURLPX_UNKNOWN_MODE;
680
0
  }
681
0
}
682
683
static CURLproxycode socks5_auth_init(struct Curl_cfilter *cf,
684
                                      struct socks_ctx *sx,
685
                                      struct Curl_easy *data)
686
0
{
687
  /* Needs username and password */
688
0
  size_t ulen = 0, plen = 0, nwritten;
689
0
  unsigned char buf[2];
690
0
  CURLcode result;
691
692
0
  if(sx->creds) {
693
0
    ulen = strlen(sx->creds->user);
694
0
    plen = strlen(sx->creds->passwd);
695
    /* the lengths must fit in a single byte */
696
0
    if(ulen > 255) {
697
0
      failf(data, "Excessive username length for proxy auth");
698
0
      return CURLPX_LONG_USER;
699
0
    }
700
0
    if(plen > 255) {
701
0
      failf(data, "Excessive password length for proxy auth");
702
0
      return CURLPX_LONG_PASSWD;
703
0
    }
704
0
  }
705
706
  /*   username/password request looks like
707
   * +----+------+----------+------+----------+
708
   * |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
709
   * +----+------+----------+------+----------+
710
   * | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
711
   * +----+------+----------+------+----------+
712
   */
713
0
  buf[0] = 1;    /* username/pw subnegotiation version */
714
0
  buf[1] = (unsigned char)ulen;
715
0
  result = Curl_bufq_write(&sx->iobuf, buf, 2, &nwritten);
716
0
  if(result || (nwritten != 2))
717
0
    return CURLPX_SEND_REQUEST;
718
0
  if(ulen) {
719
0
    result = Curl_bufq_cwrite(&sx->iobuf, sx->creds->user, ulen, &nwritten);
720
0
    if(result || (nwritten != ulen))
721
0
      return CURLPX_SEND_REQUEST;
722
0
  }
723
0
  buf[0] = (unsigned char)plen;
724
0
  result = Curl_bufq_write(&sx->iobuf, buf, 1, &nwritten);
725
0
  if(result || (nwritten != 1))
726
0
    return CURLPX_SEND_REQUEST;
727
0
  if(plen) {
728
0
    result = Curl_bufq_cwrite(&sx->iobuf, sx->creds->passwd, plen, &nwritten);
729
0
    if(result || (nwritten != plen))
730
0
      return CURLPX_SEND_REQUEST;
731
0
  }
732
0
  sxstate(sx, cf, data, SOCKS5_ST_AUTH_SEND);
733
0
  return CURLPX_OK;
734
0
}
735
736
static CURLproxycode socks5_check_auth_resp(struct socks_ctx *sx,
737
                                            struct Curl_cfilter *cf,
738
                                            struct Curl_easy *data)
739
0
{
740
0
  const unsigned char *resp;
741
0
  unsigned char auth_status;
742
0
  size_t rlen;
743
744
0
  (void)cf;
745
0
  if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < 2) {
746
0
    failf(data, "SOCKS5 sub-negotiation response incomplete.");
747
0
    return CURLPX_RECV_CONNECT;
748
0
  }
749
750
  /* ignore the first (VER) byte */
751
0
  auth_status = resp[1];
752
0
  if(auth_status) {
753
0
    failf(data, "User was rejected by the SOCKS5 server (%d %d).",
754
0
          resp[0], resp[1]);
755
0
    return CURLPX_USER_REJECTED;
756
0
  }
757
0
  Curl_bufq_skip(&sx->iobuf, 2);
758
0
  return CURLPX_OK;
759
0
}
760
761
static CURLproxycode socks5_req1_init(struct socks_ctx *sx,
762
                                      struct Curl_cfilter *cf,
763
                                      struct Curl_easy *data)
764
0
{
765
0
  unsigned char req[5];
766
0
  unsigned char ipbuf[16];
767
0
  const unsigned char *destination;
768
0
  unsigned char desttype, destlen, hdlen;
769
0
  size_t nwritten;
770
0
  CURLcode result;
771
772
0
  req[0] = 5; /* version (SOCKS5) */
773
0
  req[1] = 1; /* connect */
774
0
  req[2] = 0; /* must be zero */
775
0
  if(sx->resolve_local) {
776
    /* rest of request is added after resolving */
777
0
    result = Curl_bufq_write(&sx->iobuf, req, 3, &nwritten);
778
0
    if(result || (nwritten != 3))
779
0
      return CURLPX_SEND_REQUEST;
780
0
    return CURLPX_OK;
781
0
  }
782
783
  /* remote resolving, send what type+addr/string to resolve */
784
0
#ifdef USE_IPV6
785
0
  if(strchr(sx->dest->hostname, ':')) {
786
0
    desttype = 4;
787
0
    destination = ipbuf;
788
0
    destlen = 16;
789
0
    if(curlx_inet_pton(AF_INET6, sx->dest->hostname, ipbuf) != 1)
790
0
      return CURLPX_BAD_ADDRESS_TYPE;
791
0
  }
792
0
  else
793
0
#endif
794
0
  if(curlx_inet_pton(AF_INET, sx->dest->hostname, ipbuf) == 1) {
795
0
    desttype = 1;
796
0
    destination = ipbuf;
797
0
    destlen = 4;
798
0
  }
799
0
  else {
800
0
    const size_t hostname_len = strlen(sx->dest->hostname);
801
    /* socks5_req0_init() already rejects hostnames longer than 255 bytes, so
802
       this cast to unsigned char is safe. Assert to guard against future
803
       refactoring that might remove or reorder that earlier check. */
804
0
    DEBUGASSERT(hostname_len <= 255);
805
0
    desttype = 3;
806
0
    destination = (const unsigned char *)sx->dest->hostname;
807
0
    destlen = (unsigned char)hostname_len; /* 1-byte length */
808
0
  }
809
810
0
  req[3] = desttype;
811
0
  req[4] = destlen;
812
0
  hdlen = (desttype == 3) ? 5 : 4; /* no length byte for ip addresses */
813
0
  result = Curl_bufq_write(&sx->iobuf, req, hdlen, &nwritten);
814
0
  if(result || (nwritten != hdlen))
815
0
    return CURLPX_SEND_REQUEST;
816
0
  result = Curl_bufq_write(&sx->iobuf, destination, destlen, &nwritten);
817
0
  if(result || (nwritten != destlen))
818
0
    return CURLPX_SEND_REQUEST;
819
  /* PORT MSB+LSB */
820
0
  req[0] = (unsigned char)((sx->dest->port >> 8) & 0xff);
821
0
  req[1] = (unsigned char)(sx->dest->port & 0xff);
822
0
  result = Curl_bufq_write(&sx->iobuf, req, 2, &nwritten);
823
0
  if(result || (nwritten != 2))
824
0
    return CURLPX_SEND_REQUEST;
825
0
  CURL_TRC_CF(data, cf, "SOCKS5 connect to %s:%u (remotely resolved)",
826
0
              sx->dest->hostname, sx->dest->port);
827
0
  return CURLPX_OK;
828
0
}
829
830
static CURLproxycode socks5_resolving(struct socks_ctx *sx,
831
                                      struct Curl_cfilter *cf,
832
                                      struct Curl_easy *data,
833
                                      bool *done)
834
0
{
835
0
  const struct Curl_addrinfo *ai = NULL;
836
0
  char dest[MAX_IPADR_LEN];  /* printable address */
837
0
  const unsigned char *destination = NULL;
838
0
  unsigned char desttype = 1, destlen = 4;
839
0
  unsigned char req[2];
840
0
  CURLcode result;
841
0
  CURLproxycode presult = CURLPX_OK;
842
0
  size_t nwritten;
843
844
0
  *done = FALSE;
845
0
  result = Curl_dns_cf_addr_result(cf, sx->dest);
846
0
  if(result) {
847
0
    if(result != CURLE_AGAIN) {
848
0
      failf(data, "error %d resolving SOCKS destination %s:%u",
849
0
            (int)result, sx->dest->hostname, sx->dest->port);
850
0
      return CURLPX_RESOLVE_HOST;
851
0
    }
852
0
    return CURLPX_OK;
853
0
  }
854
855
0
#ifdef USE_IPV6
856
0
  if(sx->ip_version != CURL_IPRESOLVE_V4)
857
0
    ai = Curl_dns_cf_get_ai(data, cf, sx->dest, AF_INET6, 0);
858
0
#endif
859
0
  if(!ai && ((sx->ip_version != CURL_IPRESOLVE_V6) ||
860
0
             (!sx->socks5_addr_retried &&
861
0
              Curl_is_ipv4addr(sx->dest->hostname))))
862
0
    ai = Curl_dns_cf_get_ai(data, cf, sx->dest, AF_INET, 0);
863
864
0
  if(!ai) {
865
0
    failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.",
866
0
          sx->dest->hostname);
867
0
    presult = CURLPX_RESOLVE_HOST;
868
0
    goto out;
869
0
  }
870
871
0
  Curl_printable_address(ai, dest, sizeof(dest));
872
873
0
  if(ai->ai_family == AF_INET) {
874
0
    struct sockaddr_in *saddr_in;
875
0
    desttype = 1; /* ATYP: IPv4 = 1 */
876
0
    destlen = 4;
877
0
    saddr_in = (struct sockaddr_in *)(void *)ai->ai_addr;
878
0
    destination = (const unsigned char *)&saddr_in->sin_addr.s_addr;
879
0
    CURL_TRC_CF(data, cf, "SOCKS5 connect to %s:%u (locally resolved)",
880
0
                dest, sx->dest->port);
881
0
    sx->ipv_used = CURL_IPRESOLVE_V4;
882
0
  }
883
0
#ifdef USE_IPV6
884
0
  else if(ai->ai_family == AF_INET6) {
885
0
    struct sockaddr_in6 *saddr_in6;
886
0
    desttype = 4; /* ATYP: IPv6 = 4 */
887
0
    destlen = 16;
888
0
    saddr_in6 = (struct sockaddr_in6 *)(void *)ai->ai_addr;
889
0
    destination = (const unsigned char *)&saddr_in6->sin6_addr.s6_addr;
890
0
    CURL_TRC_CF(data, cf, "SOCKS5 connect to [%s]:%u (locally resolved)",
891
0
                dest, sx->dest->port);
892
0
    sx->ipv_used = CURL_IPRESOLVE_V6;
893
0
  }
894
0
#endif
895
896
0
  if(!destination) {
897
0
    failf(data, "SOCKS5 connection to %s not supported", dest);
898
0
    presult = CURLPX_RESOLVE_HOST;
899
0
    goto out;
900
0
  }
901
902
0
  req[0] = desttype;
903
0
  result = Curl_bufq_write(&sx->iobuf, req, 1, &nwritten);
904
0
  if(result || (nwritten != 1)) {
905
0
    presult = CURLPX_SEND_REQUEST;
906
0
    goto out;
907
0
  }
908
0
  result = Curl_bufq_write(&sx->iobuf, destination, destlen, &nwritten);
909
0
  if(result || (nwritten != destlen)) {
910
0
    presult = CURLPX_SEND_REQUEST;
911
0
    goto out;
912
0
  }
913
  /* PORT MSB+LSB */
914
0
  req[0] = (unsigned char)((sx->dest->port >> 8) & 0xffU);
915
0
  req[1] = (unsigned char)(sx->dest->port & 0xffU);
916
0
  result = Curl_bufq_write(&sx->iobuf, req, 2, &nwritten);
917
0
  if(result || (nwritten != 2)) {
918
0
    presult = CURLPX_SEND_REQUEST;
919
0
    goto out;
920
0
  }
921
922
0
out:
923
0
  *done = (presult == CURLPX_OK);
924
0
  return presult;
925
0
}
926
927
static CURLproxycode socks5_recv_resp1(struct socks_ctx *sx,
928
                                       struct Curl_cfilter *cf,
929
                                       struct Curl_easy *data,
930
                                       int *sx_code,
931
                                       bool *done)
932
0
{
933
0
  const unsigned char *resp;
934
0
  size_t rlen, resp_len = 8; /* minimum response length */
935
0
  CURLproxycode presult;
936
937
0
  *sx_code = 0;
938
0
  presult = socks_recv(sx, cf, data, resp_len, done);
939
0
  if(presult)
940
0
    return presult;
941
0
  else if(!*done)
942
0
    return CURLPX_OK;
943
944
0
  if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < resp_len) {
945
0
    failf(data, "SOCKS5 response is incomplete.");
946
0
    return CURLPX_RECV_CONNECT;
947
0
  }
948
949
  /* Response packet includes BND.ADDR is variable length parameter by RFC
950
     1928, so the response packet MUST be read until the end to avoid errors
951
     at subsequent protocol level.
952
953
     +----+-----+-------+------+----------+----------+
954
     |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
955
     +----+-----+-------+------+----------+----------+
956
     | 1  |  1  | 0x00  |  1   | Variable |    2     |
957
     +----+-----+-------+------+----------+----------+
958
959
     ATYP:
960
     o IPv4 address: 0x01, BND.ADDR = 4-byte
961
     o domain name:  0x03, BND.ADDR = [ 1-byte length, string ]
962
     o IPv6 address: 0x04, BND.ADDR = 16-byte
963
   */
964
0
  if(resp[0] != 5) { /* version */
965
0
    failf(data, "SOCKS5 reply has version %d, version should be 5.", resp[0]);
966
0
    return CURLPX_BAD_VERSION;
967
0
  }
968
0
  *sx_code = resp[1];
969
970
  /* Calculate real packet size */
971
0
  switch(resp[3]) {
972
0
  case 1: /* IPv4 */
973
0
    resp_len = 4 + 4 + 2;
974
0
    break;
975
0
  case 3: /* domain name */
976
0
    resp_len = 4 + 1 + resp[4] + 2; /* header, var length, var bytes, port */
977
0
    break;
978
0
  case 4: /* IPv6 */
979
0
    resp_len = 4 + 16 + 2;
980
0
    break;
981
0
  default:
982
0
    failf(data, "SOCKS5 reply has wrong address type.");
983
0
    return CURLPX_BAD_ADDRESS_TYPE;
984
0
  }
985
986
  /* receive the rest of the response */
987
0
  presult = socks_recv(sx, cf, data, resp_len, done);
988
0
  if(presult)
989
0
    return presult;
990
0
  else if(!*done)
991
0
    return CURLPX_OK;
992
993
0
  if(!Curl_bufq_peek(&sx->iobuf, &resp, &rlen) || rlen < resp_len) {
994
0
    failf(data, "SOCKS5 response is incomplete.");
995
0
    return CURLPX_RECV_CONNECT;
996
0
  }
997
998
  /* got it all */
999
0
  if(*sx_code) { /* Anything besides 0 is an error */
1000
0
    CURLproxycode rc = CURLPX_REPLY_UNASSIGNED;
1001
0
    CURL_TRC_CF(data, cf, "proxy replied with code=%d", *sx_code);
1002
0
    if(*sx_code < 9) {
1003
      /* RFC 1928 section 6 lists: */
1004
0
      static const CURLproxycode lookup[] = {
1005
0
        CURLPX_OK,
1006
0
        CURLPX_REPLY_GENERAL_SERVER_FAILURE,
1007
0
        CURLPX_REPLY_NOT_ALLOWED,
1008
0
        CURLPX_REPLY_NETWORK_UNREACHABLE,
1009
0
        CURLPX_REPLY_HOST_UNREACHABLE,
1010
0
        CURLPX_REPLY_CONNECTION_REFUSED,
1011
0
        CURLPX_REPLY_TTL_EXPIRED,
1012
0
        CURLPX_REPLY_COMMAND_NOT_SUPPORTED,
1013
0
        CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED,
1014
0
      };
1015
0
      rc = lookup[*sx_code];
1016
0
    }
1017
0
    return rc;
1018
0
  }
1019
0
  *done = TRUE;
1020
0
  return CURLPX_OK;
1021
0
}
1022
1023
/*
1024
 * This function logs in to a SOCKS5 proxy and sends the specifics to the final
1025
 * destination server.
1026
 */
1027
static CURLproxycode socks5_connect(struct Curl_cfilter *cf,
1028
                                    struct socks_ctx *sx,
1029
                                    struct Curl_easy *data,
1030
                                    bool *pretry)
1031
0
{
1032
0
  CURLproxycode presult;
1033
0
  bool done;
1034
1035
0
  *pretry = FALSE;
1036
1037
0
process_state:
1038
0
  CURL_TRC_CF(data, cf, "socks5_connect, state=%d", (int)sx->state);
1039
0
  switch(sx->state) {
1040
0
  case SOCKS_ST_INIT:
1041
0
    sx->version = 5;
1042
0
    Curl_bufq_reset(&sx->iobuf);
1043
0
    sxstate(sx, cf, data, SOCKS5_ST_START);
1044
0
    FALLTHROUGH();
1045
1046
0
  case SOCKS5_ST_START:
1047
0
    CURL_TRC_CF(data, cf, "SOCKS5: connecting to %s:%u",
1048
0
                sx->dest->hostname, sx->dest->port);
1049
0
    presult = socks5_req0_init(cf, sx, data);
1050
0
    if(presult)
1051
0
      return socks_failed(sx, cf, data, presult);
1052
0
    sxstate(sx, cf, data, SOCKS5_ST_REQ0_SEND);
1053
0
    FALLTHROUGH();
1054
1055
0
  case SOCKS5_ST_REQ0_SEND:
1056
0
    presult = socks_flush(sx, cf, data, &done);
1057
0
    if(presult)
1058
0
      return socks_failed(sx, cf, data, presult);
1059
0
    else if(!done)
1060
0
      return CURLPX_OK;
1061
    /* done sending! */
1062
0
    sxstate(sx, cf, data, SOCKS5_ST_RESP0_RECV);
1063
0
    FALLTHROUGH();
1064
1065
0
  case SOCKS5_ST_RESP0_RECV:
1066
0
    presult = socks_recv(sx, cf, data, 2, &done);
1067
0
    if(presult)
1068
0
      return socks_failed(sx, cf, data, presult);
1069
0
    else if(!done)
1070
0
      return CURLPX_OK;
1071
0
    presult = socks5_check_resp0(sx, cf, data);
1072
0
    if(presult)
1073
0
      return socks_failed(sx, cf, data, presult);
1074
    /* socks5_check_resp0() sets next socks state */
1075
0
    goto process_state;
1076
1077
0
  case SOCKS5_ST_GSSAPI_INIT: {
1078
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1079
    /* GSSAPI stuff done non-blocking */
1080
    CURLcode result = Curl_SOCKS5_gssapi_negotiate(cf, data, sx->creds);
1081
    if(result) {
1082
      failf(data, "Unable to negotiate SOCKS5 GSS-API context.");
1083
      return CURLPX_GSSAPI;
1084
    }
1085
    sxstate(sx, cf, data, SOCKS5_ST_REQ1_INIT);
1086
    goto process_state;
1087
#else
1088
0
    failf(data, "SOCKS5 GSSAPI per-message authentication is not supported.");
1089
0
    return socks_failed(sx, cf, data, CURLPX_GSSAPI_PERMSG);
1090
0
#endif
1091
0
  }
1092
1093
0
  case SOCKS5_ST_AUTH_INIT:
1094
0
    presult = socks5_auth_init(cf, sx, data);
1095
0
    if(presult)
1096
0
      return socks_failed(sx, cf, data, presult);
1097
0
    sxstate(sx, cf, data, SOCKS5_ST_AUTH_SEND);
1098
0
    FALLTHROUGH();
1099
1100
0
  case SOCKS5_ST_AUTH_SEND:
1101
0
    presult = socks_flush(sx, cf, data, &done);
1102
0
    if(presult)
1103
0
      return socks_failed(sx, cf, data, presult);
1104
0
    else if(!done)
1105
0
      return CURLPX_OK;
1106
0
    sxstate(sx, cf, data, SOCKS5_ST_AUTH_RECV);
1107
0
    FALLTHROUGH();
1108
1109
0
  case SOCKS5_ST_AUTH_RECV:
1110
0
    presult = socks_recv(sx, cf, data, 2, &done);
1111
0
    if(presult)
1112
0
      return socks_failed(sx, cf, data, presult);
1113
0
    else if(!done)
1114
0
      return CURLPX_OK;
1115
0
    presult = socks5_check_auth_resp(sx, cf, data);
1116
0
    if(presult)
1117
0
      return socks_failed(sx, cf, data, presult);
1118
    /* Everything is good so far, user was authenticated! */
1119
0
    sxstate(sx, cf, data, SOCKS5_ST_REQ1_INIT);
1120
0
    FALLTHROUGH();
1121
1122
0
  case SOCKS5_ST_REQ1_INIT:
1123
0
    presult = socks5_req1_init(sx, cf, data);
1124
0
    if(presult)
1125
0
      return socks_failed(sx, cf, data, presult);
1126
0
    if(!sx->resolve_local) {
1127
      /* we do not resolve, request is complete */
1128
0
      sxstate(sx, cf, data, SOCKS5_ST_REQ1_SEND);
1129
0
      goto process_state;
1130
0
    }
1131
0
    sxstate(sx, cf, data, SOCKS5_ST_RESOLVING);
1132
0
    FALLTHROUGH();
1133
1134
0
  case SOCKS5_ST_RESOLVING:
1135
0
    presult = socks5_resolving(sx, cf, data, &done);
1136
0
    if(presult)
1137
0
      return socks_failed(sx, cf, data, presult);
1138
0
    if(!done)
1139
0
      return CURLPX_OK;
1140
0
    sxstate(sx, cf, data, SOCKS5_ST_REQ1_SEND);
1141
0
    FALLTHROUGH();
1142
1143
0
  case SOCKS5_ST_REQ1_SEND:
1144
0
    presult = socks_flush(sx, cf, data, &done);
1145
0
    if(presult)
1146
0
      return socks_failed(sx, cf, data, presult);
1147
0
    else if(!done)
1148
0
      return CURLPX_OK;
1149
#if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
1150
    if(CF_CONN(cf)->socks5_gssapi_enctype) {
1151
      failf(data, "SOCKS5 GSS-API protection not yet implemented.");
1152
      return CURLPX_GSSAPI_PROTECTION;
1153
    }
1154
#endif
1155
0
    sxstate(sx, cf, data, SOCKS5_ST_RESP1_RECV);
1156
0
    FALLTHROUGH();
1157
1158
0
  case SOCKS5_ST_RESP1_RECV: {
1159
0
    int sx_code;
1160
0
    presult = socks5_recv_resp1(sx, cf, data, &sx_code, &done);
1161
0
    if((presult == CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED) &&
1162
0
       sx->resolve_local && !sx->socks5_addr_retried &&
1163
0
       !Curl_is_ipaddr(sx->dest->hostname) &&
1164
0
       (sx->ip_version == CURL_IPRESOLVE_WHATEVER)) {
1165
      /* Socks5 proxy could not initiate a connection with the passed
1166
       * ip family. Is there an alternative? */
1167
0
      uint8_t alt_ipv = (sx->ipv_used == CURL_IPRESOLVE_V6) ?
1168
0
                        CURL_IPRESOLVE_V4 : CURL_IPRESOLVE_V6;
1169
0
      if(Curl_dns_cf_get_ai(data, cf, sx->dest,
1170
0
         (alt_ipv == CURL_IPRESOLVE_V6) ? AF_INET6 : AF_INET, 0)) {
1171
0
        CURL_TRC_CF(data, cf, "proxy does not support %s, "
1172
0
                    "trying the other one",
1173
0
                    (alt_ipv == CURL_IPRESOLVE_V4) ? "ipv6" : "ipv4");
1174
0
        sx->socks5_addr_retried = TRUE;
1175
0
        sx->ip_version = alt_ipv;
1176
0
        *pretry = TRUE;
1177
0
        sxstate(sx, cf, data, SOCKS_ST_INIT);
1178
0
        return presult;
1179
0
      }
1180
0
    }
1181
0
    if(presult) {
1182
0
      failf(data, "cannot complete SOCKS5 connection to %s. (%d)",
1183
0
            sx->dest->hostname, sx_code);
1184
0
      return socks_failed(sx, cf, data, presult);
1185
0
    }
1186
0
    if(!done)
1187
0
      return CURLPX_OK;
1188
0
    CURL_TRC_CF(data, cf, "SOCKS5 request granted.");
1189
0
    sxstate(sx, cf, data, SOCKS_ST_SUCCESS);
1190
0
    FALLTHROUGH();
1191
0
  }
1192
1193
0
  case SOCKS_ST_SUCCESS:
1194
0
    return CURLPX_OK;
1195
1196
0
  case SOCKS_ST_FAILED:
1197
0
    DEBUGASSERT(sx->presult);
1198
0
    return sx->presult;
1199
1200
0
  default:
1201
0
    DEBUGASSERT(0);
1202
0
    return socks_failed(sx, cf, data, CURLPX_SEND_REQUEST);
1203
0
  }
1204
0
}
1205
1206
static void socks_proxy_ctx_free(struct socks_ctx *ctx)
1207
0
{
1208
0
  if(ctx) {
1209
0
    Curl_peer_unlink(&ctx->peer);
1210
0
    Curl_peer_unlink(&ctx->dest);
1211
0
    Curl_creds_unlink(&ctx->creds);
1212
0
    Curl_bufq_free(&ctx->iobuf);
1213
0
    curlx_free(ctx);
1214
0
  }
1215
0
}
1216
1217
/* After a TCP connection to the proxy has been verified, this function does
1218
   the next magic steps. If 'done' is not set TRUE, it is not done yet and
1219
   must be called again.
1220
1221
   Note: this function's sub-functions call failf() */
1222
static CURLcode socks_proxy_cf_connect(struct Curl_cfilter *cf,
1223
                                       struct Curl_easy *data,
1224
                                       bool *done)
1225
0
{
1226
0
  struct socks_ctx *ctx = cf->ctx;
1227
0
  CURLproxycode pxresult = CURLPX_OK;
1228
0
  CURLcode result;
1229
0
  bool retry = FALSE;
1230
1231
0
  if(cf->connected) {
1232
0
    *done = TRUE;
1233
0
    return CURLE_OK;
1234
0
  }
1235
1236
0
do_connect:
1237
0
  result = cf->next->cft->do_connect(cf->next, data, done);
1238
0
  if(result || !*done)
1239
0
    return result;
1240
1241
0
  switch(ctx->proxy_type) {
1242
0
  case CURLPROXY_SOCKS5:
1243
0
  case CURLPROXY_SOCKS5_HOSTNAME:
1244
0
    pxresult = socks5_connect(cf, ctx, data, &retry);
1245
0
    if(pxresult && retry) {
1246
      /* tear down the filters below and connect again to the socks proxy */
1247
0
      Curl_conn_cf_discard_chain(&cf->next, data);
1248
0
      result = Curl_cf_ip_happy_insert_after(
1249
0
        cf, data, ctx->peer, ctx->peer,
1250
0
        ctx->peer->unix_socket ? TRNSPRT_UNIX : TRNSPRT_TCP,
1251
0
        NULL, TRNSPRT_TCP);
1252
0
      if(!result) {
1253
0
        CURL_TRC_CF(data, cf, "opening new connection for retry");
1254
0
        goto do_connect;
1255
0
      }
1256
0
    }
1257
0
    break;
1258
1259
0
  case CURLPROXY_SOCKS4:
1260
0
  case CURLPROXY_SOCKS4A:
1261
0
    pxresult = socks4_connect(cf, ctx, data);
1262
0
    break;
1263
1264
0
  default:
1265
0
    DEBUGASSERT(0); /* should not come here, checked it at creation time */
1266
0
    result = CURLE_COULDNT_CONNECT;
1267
0
    goto out;
1268
0
  }
1269
1270
0
  if(pxresult) {
1271
0
    result = CURLE_PROXY;
1272
0
    data->info.pxcode = (uint8_t)pxresult;
1273
0
    goto out;
1274
0
  }
1275
0
  else if(ctx->state != SOCKS_ST_SUCCESS)
1276
0
    goto out;
1277
1278
0
#ifdef CURLVERBOSE
1279
0
  if(Curl_trc_is_verbose(data)) {
1280
0
    struct ip_quadruple ipquad;
1281
0
    bool is_ipv6;
1282
0
    if(!Curl_conn_cf_get_ip_info(cf->next, data, &is_ipv6, &ipquad))
1283
0
      infof(data, "Opened %sSOCKS connection from %s port %d to %s port %d "
1284
0
            "(via %s port %u)",
1285
0
            !CF_IS_PRIMARY(cf) ? "2nd " : "",
1286
0
            ipquad.local_ip, ipquad.local_port,
1287
0
            ctx->dest->hostname, ctx->dest->port,
1288
0
            ipquad.remote_ip, ipquad.remote_port);
1289
0
    else
1290
0
      infof(data, "Opened %sSOCKS connection",
1291
0
            !CF_IS_PRIMARY(cf) ? "2nd " : "");
1292
0
  }
1293
0
#endif
1294
0
  cf->connected = TRUE;
1295
1296
0
out:
1297
0
  *done = (bool)cf->connected;
1298
0
  if(*done || result)
1299
0
    Curl_creds_unlink(&ctx->creds);
1300
0
  return result;
1301
0
}
1302
1303
static CURLcode socks_cf_adjust_pollset(struct Curl_cfilter *cf,
1304
                                        struct Curl_easy *data,
1305
                                        struct easy_pollset *ps)
1306
0
{
1307
0
  struct socks_ctx *sx = cf->ctx;
1308
0
  CURLcode result = CURLE_OK;
1309
1310
0
  if(!cf->connected && sx) {
1311
    /* If we are not connected, the filter below is and has nothing
1312
     * to wait on, we determine what to wait for. */
1313
0
    curl_socket_t sock = cf->chain->sock;
1314
0
    switch(sx->state) {
1315
0
    case SOCKS4_ST_SEND:
1316
0
    case SOCKS5_ST_REQ0_SEND:
1317
0
    case SOCKS5_ST_AUTH_SEND:
1318
0
    case SOCKS5_ST_REQ1_SEND:
1319
0
      CURL_TRC_CF(data, cf, "adjust pollset out (%d)", (int)sx->state);
1320
0
      result = Curl_pollset_set_out_only(data, ps, sock);
1321
0
      break;
1322
0
    default:
1323
0
      CURL_TRC_CF(data, cf, "adjust pollset in (%d)", (int)sx->state);
1324
0
      result = Curl_pollset_set_in_only(data, ps, sock);
1325
0
      break;
1326
0
    }
1327
0
  }
1328
0
  return result;
1329
0
}
1330
1331
static void socks_proxy_cf_destroy(struct Curl_cfilter *cf,
1332
                                   struct Curl_easy *data)
1333
0
{
1334
0
  (void)data;
1335
0
  socks_proxy_ctx_free(cf->ctx);
1336
0
  cf->ctx = NULL;
1337
0
}
1338
1339
static CURLcode socks_cf_query(struct Curl_cfilter *cf,
1340
                               struct Curl_easy *data,
1341
                               int query, int *pres1, void *pres2)
1342
0
{
1343
0
  struct socks_ctx *sx = cf->ctx;
1344
1345
0
  switch(query) {
1346
0
  case CF_QUERY_HOST_PORT:
1347
0
    if(sx) {
1348
0
      *pres1 = sx->dest->port;
1349
0
      *((const char **)pres2) = sx->dest->hostname;
1350
0
      return CURLE_OK;
1351
0
    }
1352
0
    break;
1353
0
  case CF_QUERY_ALPN_NEGOTIATED: {
1354
0
    const char **palpn = pres2;
1355
0
    DEBUGASSERT(palpn);
1356
0
    *palpn = NULL;
1357
0
    return CURLE_OK;
1358
0
  }
1359
0
  default:
1360
0
    break;
1361
0
  }
1362
0
  return cf->next ?
1363
0
    cf->next->cft->query(cf->next, data, query, pres1, pres2) :
1364
0
    CURLE_UNKNOWN_OPTION;
1365
0
}
1366
1367
struct Curl_cftype Curl_cft_socks_proxy = {
1368
  "SOCKS",
1369
  CF_TYPE_IP_CONNECT | CF_TYPE_PROXY,
1370
  0,
1371
  socks_proxy_cf_destroy,
1372
  socks_proxy_cf_connect,
1373
  Curl_cf_def_shutdown,
1374
  socks_cf_adjust_pollset,
1375
  Curl_cf_def_data_pending,
1376
  Curl_cf_def_send,
1377
  Curl_cf_def_recv,
1378
  Curl_cf_def_cntrl,
1379
  Curl_cf_def_conn_is_alive,
1380
  Curl_cf_def_conn_keep_alive,
1381
  socks_cf_query,
1382
};
1383
1384
CURLcode Curl_cf_socks_proxy_insert_after(struct Curl_cfilter *cf_at,
1385
                                          struct Curl_easy *data,
1386
                                          struct Curl_peer *peer,
1387
                                          struct Curl_peer *dest,
1388
                                          uint8_t ip_version,
1389
                                          uint8_t proxy_type,
1390
                                          struct Curl_creds *creds)
1391
0
{
1392
0
  struct Curl_cfilter *cf;
1393
0
  struct socks_ctx *ctx;
1394
0
  bool resolve_local = FALSE;
1395
0
  uint8_t dns_queries = Curl_resolv_dns_queries(data, ip_version);
1396
0
  CURLcode result;
1397
1398
0
  if(!dest)
1399
0
    return CURLE_FAILED_INIT;
1400
1401
0
  switch(proxy_type) {
1402
0
  case CURLPROXY_SOCKS5:
1403
0
    resolve_local = TRUE;
1404
0
    break;
1405
0
  case CURLPROXY_SOCKS5_HOSTNAME:
1406
0
    break;
1407
0
  case CURLPROXY_SOCKS4:
1408
0
    resolve_local = TRUE;
1409
0
    dns_queries = (uint8_t)(dns_queries & ~CURL_DNSQ_AAAA);
1410
0
    break;
1411
0
  case CURLPROXY_SOCKS4A:
1412
0
    break;
1413
0
  default:
1414
0
    failf(data, "unknown proxytype %d option given", proxy_type);
1415
0
    return CURLE_COULDNT_CONNECT;
1416
0
  }
1417
1418
  /* NUL byte already part of struct size */
1419
0
  ctx = curlx_calloc(1, sizeof(*ctx));
1420
0
  if(!ctx) {
1421
0
    return CURLE_OUT_OF_MEMORY;
1422
0
  }
1423
1424
0
  Curl_peer_link(&ctx->peer, peer);
1425
0
  Curl_peer_link(&ctx->dest, dest);
1426
0
  ctx->ip_version = ip_version;
1427
0
  ctx->proxy_type = proxy_type;
1428
0
  ctx->resolve_local = resolve_local;
1429
0
  Curl_creds_link(&ctx->creds, creds);
1430
0
  Curl_bufq_init2(&ctx->iobuf, SOCKS_CHUNK_SIZE, SOCKS_CHUNKS,
1431
0
                  BUFQ_OPT_SOFT_LIMIT);
1432
1433
0
  result = Curl_cf_create(&cf, &Curl_cft_socks_proxy, ctx);
1434
0
  if(!result) {
1435
0
    Curl_conn_cf_insert_after(cf_at, cf);
1436
0
    if(ctx->resolve_local) {
1437
0
      result = Curl_dns_cf_add_addr_resolve(data, cf_at, ctx->dest,
1438
0
                                            dns_queries, TRNSPRT_TCP);
1439
0
    }
1440
0
  }
1441
0
  else
1442
0
    socks_proxy_ctx_free(ctx);
1443
0
  return result;
1444
0
}
1445
1446
#endif /* CURL_DISABLE_PROXY */