File: xio-socks5.c

package info (click to toggle)
socat 2.0.0~beta9-1
  • links: PTS
  • area: main
  • in suites: experimental
  • size: 3,740 kB
  • sloc: ansic: 30,875; sh: 11,630; makefile: 149
file content (505 lines) | stat: -rw-r--r-- 15,816 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/* source: xio-socks5.c */
/* Copyright Gerhard Rieger */
/* Published under the GNU General Public License V.2, see file COPYING */

/* this file contains the source for opening addresses of socks5 type */

#include "xiosysincludes.h"
#include "xioopen.h"
#include "xio-socket.h"
#include "xio-ipapp.h"

#include "xio-socks5.h"


#if WITH_SOCKS5

#define SOCKSPORT "1080"
#define SOCKS5_MAXLEN 512

static int 
   xioopen_socks5_client(int argc, const char *argv[],
			  struct opt *opts, int xioflags, xiofile_t *xfd,
			  unsigned groups, int dummy1, int dummy2,
			  int dummy3);

const struct optdesc opt_socks5_username  = { "socks5-username",  "socks5user", OPT_SOCKS5_USERNAME,  GROUP_SOCKS5, PH_LATE, TYPE_STRING,  OFUNC_SPEC };
const struct optdesc opt_socks5_password  = { "socks5-password",  "socks5pass", OPT_SOCKS5_PASSWORD,  GROUP_SOCKS5, PH_LATE, TYPE_STRING,  OFUNC_SPEC };

static const struct xioaddr_inter_desc xiointer_socks5_client = { XIOADDR_PROT, "socks5", 2, XIOBIT_ALL, GROUP_SOCKS5, XIOSHUT_DOWN, XIOCLOSE_CLOSE, xioopen_socks5_client, 0, 0, 0, XIOBIT_RDWR HELP(":<host>:<port>") };
const union xioaddr_desc *xioaddrs_socks5_client[] = {
   (union xioaddr_desc *)&xiointer_socks5_client, NULL };

/* read until buflen bytes received or EOF */
/* returns STAT_OK, STAT_RETRYLATER, or STAT_NOTRETRY */
static int xiosocks5_recvbytes(struct single *xfd,
			       uint8_t *buff, size_t buflen, int level) {
   size_t bytes;
   ssize_t result;

   bytes = 0;
   while (bytes >= 0) {	/* loop over answer chunks until complete or error */
      /* receive socks answer */
      Debug("waiting for data from peer");
      do {
	 result = Read(xfd->rfd, buff+bytes, buflen-bytes);
      } while (result < 0 && errno == EINTR);
      if (result < 0) {
	 Msg4(level, "read(%d, %p, "F_Zu"): %s",
	      xfd->rfd, buff+bytes, buflen-bytes,
	      strerror(errno));
	 if (Close(xfd->rfd) < 0) {
	    Warn2("close(%d): %s", xfd->rfd, strerror(errno));
	 }
	 if (Close(xfd->wfd) < 0) {
	    Warn2("close(%d): %s", xfd->wfd, strerror(errno));
	 }
	 return STAT_RETRYLATER;
      }
      if (result == 0) {
	 Msg(level, "read(): EOF during read of socks reply");
	 if (Close(xfd->rfd) < 0) {
	    Warn2("close(%d): %s", xfd->rfd, strerror(errno));
	 }
	 if (Close(xfd->wfd) < 0) {
	    Warn2("close(%d): %s", xfd->wfd, strerror(errno));
	 }
	 return STAT_RETRYLATER;
      }
      bytes += result;
      if (bytes == buflen) {
	 Debug1("received all "F_Zd" bytes", bytes);
	 break;
      }
      Debug2("received "F_Zd" bytes, waiting for "F_Zu" more bytes",
	     result, buflen-bytes);
   }
   if (result <= 0) {	/* we had a problem while reading socks answer */
      return STAT_RETRYLATER;	/* retry complete open cycle */
   }
   return STAT_OK;
}

static int xioopen_socks5_client(int argc, const char *argv[],
				 struct opt *opts, int xioflags,
				 xiofile_t *xxfd,
				 unsigned groups, int dummy1, int dummy2,
				 int dummy3) {
   /* we expect the form: host:port */
   xiosingle_t *xfd = &xxfd->stream;
   const char *targetname, *targetservice;
   int level;
   int result;

   if (argc != 3) {
      Error("SOCKS5 syntax: socks5-connect:<host>:<port>");	/*! UDP? */
      return STAT_NORETRY;
   }

   targetname = argv[1];
   targetservice = argv[2];

   applyopts(-1, opts, PH_INIT);
   applyopts_single(xfd, opts, PH_INIT);

#if 0
   result = _xioopen_socks5_prepare(a3, opts, &socksport, sockhead, &buflen);
   if (result != STAT_OK)  return result;
#endif

   if (xfd->rfd < 0) {
      Error("socks5 must be used as embedded address");
      return -1;
   }

   Notice2("opening connection to %s:%s using socks5",
	   targetname, targetservice);

   do {	/* loop over failed connect and socks-request attempts */

#if WITH_RETRY
      if (xfd->forever || xfd->retry) {
	 level = E_INFO;
      } else
#endif /* WITH_RETRY */
	 level = E_ERROR;

#if 0
      /* we try to resolve the target address _before_ connecting to the socks
	 server: this avoids unnecessary socks connects and timeouts */
      result =
	 _xioopen_socks5_connect0(xfd, targetname, sockhead, opts,
				  (ssize_t *)&buflen, level);
      switch (result) {
      case STAT_OK: break;
#if WITH_RETRY
      case STAT_RETRYLATER:
      case STAT_RETRYNOW:
	 if (xfd->forever || xfd->retry--) {
	    if (result == STAT_RETRYLATER)  Nanosleep(&xfd->intervall, NULL);
	    continue;
	 }
#endif /* WITH_RETRY */
      default:
	 return result;
      }
#endif

#if 0
     if (xfd->rfd < 0) {
      /* this cannot fork because we retrieved fork option above */
      result =
	 _xioopen_connect (xfd,
			   needbind?(struct sockaddr *)us:NULL, sizeof(*us),
			   (struct sockaddr *)them, sizeof(struct sockaddr_in),
			   opts, PF_INET, socktype, IPPROTO_TCP, lowport, level);
      switch (result) {
      case STAT_OK: break;
#if WITH_RETRY
      case STAT_RETRYLATER:
      case STAT_RETRYNOW:
	 if (xfd->forever || xfd->retry--) {
	    if (result == STAT_RETRYLATER)  Nanosleep(&xfd->intervall, NULL);
	    continue;
	 }
#endif /* WITH_RETRY */
      default:
	 return result;
      }
      xfd->rfd = xfd->wfd = xfd->fd;
     } else
#endif
	xfd->dtype = XIODATA_STREAM;

      result =
	_xioopen_socks5_connect(xfd, targetname, targetservice, opts, level);
      switch (result) {
      case STAT_OK: break;
#if WITH_RETRY
      case STAT_RETRYLATER:
      case STAT_RETRYNOW:
	 if (xfd->forever || xfd->retry--) {
	    if (result == STAT_RETRYLATER)  Nanosleep(&xfd->intervall, NULL);
	    continue;
	 }
#endif /* WITH_RETRY */
      default:
	 return result;
      }

      /*!*/
      applyopts(xfd->rfd, opts, PH_ALL);

      if ((result = _xio_openlate(xfd, opts)) < 0)
	 return result;

      {
	 break;
      }

   } while (true);	/* end of complete open loop - drop out on success */
   return 0;
}



/* perform socks5 client dialog on existing FD.
   Called within fork/retry loop, after connect() */
int _xioopen_socks5_connect(struct single *xfd,
			    const char *targetname, const char *targetservice,
			    struct opt *opts, int level) {
   uint16_t targetport;
   unsigned char sendbuff[SOCKS5_MAXLEN];  size_t sendlen;
   unsigned char recvbuff[SOCKS5_MAXLEN];
   struct socks5_method  *sendmethod;
   struct socks5_select  *recvselect;
   struct socks5_request *sendrequest;
   struct socks5_reply   *recvreply;
   size_t namelen;
   size_t addrlen;
   size_t readpos;
   char *emsg;
   int result;

   /* prepare */
   targetport    = parseport(targetservice, IPPROTO_TCP/*!*/);

   /* just the simplest authentications */
   sendmethod = (struct socks5_method *)sendbuff;
   sendmethod->version = 5;	/* protocol version */
   sendmethod->nmethods = 2;	/* number of proposed authentication types */
   sendmethod->methods[0] = SOCKS5_METHOD_NOAUTH;	/* no auth at all */
   sendmethod->methods[1] = SOCKS5_METHOD_USERPASS;	/* username/password */
   /*sendmethod->methods[2] = SOCKS5_METHOD_AVENTAIL;*/	/* Aventail Connect */
   sendlen = 2+sendmethod->nmethods;

   /* send socks header (target addr+port, +auth) */
   Info("sending socks5 identifier/method selection message");
   do {
      result = Write(xfd->wfd, sendmethod, sendlen);
   } while (result < 0 && errno == EINTR);
   if (result < 0) {
      Msg4(level, "write(%d, %p, "F_Zu"): %s",
	   xfd->wfd, sendmethod, sendlen, strerror(errno));
      if (Close(xfd->wfd) < 0) {
	 Warn2("close(%d): %s", xfd->wfd, strerror(errno));
      }
      if (Close(xfd->rfd) < 0) {
	 Warn2("close(%d): %s", xfd->rfd, strerror(errno));
      }
      return STAT_RETRYLATER;	/* retry complete open cycle */
   }

   Info1("waiting for socks5 select reply ("F_Zu" bytes)", SOCKS5_SELECT_LENGTH);
   if ((result =
	xiosocks5_recvbytes(xfd, recvbuff, SOCKS5_SELECT_LENGTH, level)) !=
       STAT_OK) {
      /* we had a problem while reading socks answer */
      /*! Close(); */
      return result;	/* ev. retry complete open cycle */
   }
   recvselect = (struct socks5_select *)recvbuff;
   Info2("socks5 select: {%u, %u}", recvselect->version, recvselect->method);
   if (recvselect->version != 5) {
      Error1("socks5: server protocol version is %u",
	     recvbuff[0]);
   }
   if (recvselect->method == SOCKS5_METHOD_NONE) {
      Error("socks5: server did not accept our authentication methods");
   }
   /*! check if selected methods is one of our proposals */

   switch (recvselect->method) {
   case SOCKS5_METHOD_NOAUTH:
      break;
   case SOCKS5_METHOD_USERPASS:
      if (xio_socks5_username_password(level, opts, xfd) < 0) {
	 Error("username/password not accepted");
      }
      break;
   default:
      Error("socks5 select: unimplemented authentication method selected");
      break;
   }

   sendrequest = (struct socks5_request *)sendbuff;
   sendrequest->version = SOCKS5_VERSION;
   sendrequest->command = SOCKS5_COMMAND_CONNECT;
   sendrequest->reserved = 0;
   sendrequest->addrtype = SOCKS5_ADDRTYPE_NAME;
   switch (sendrequest->addrtype) {
   case SOCKS5_ADDRTYPE_IPV4:
      break;
   case SOCKS5_ADDRTYPE_NAME:
      if ((namelen = strlen(targetname)) > 255) {
	 Error1("socks5: target name is longer than 255 bytes: \"%s\"",
		targetname);
      }
      sendrequest->destaddr[0] = strlen(targetname);
      *(sendrequest->destaddr+1) = '\0'; strncat(sendrequest->destaddr+1, targetname, sizeof(sendbuff)-5);
      break;
   case SOCKS5_ADDRTYPE_IPV6:
      break;
   default: Fatal("socks5: undefined address type in socks request");
   }
   *((uint16_t *)&sendrequest->destaddr[strlen(targetname)+1]) = targetport;
   sendlen = sizeof(struct socks5_request) + namelen + 2;

   /* send socks request (target addr+port, +auth) */
   Info("sending socks5 request selection");
   do {
      result = Write(xfd->wfd, sendrequest, sendlen);
   } while (result < 0 && errno == EINTR);
   if (result < 0) {
      Msg4(level, "write(%d, %p, "F_Zu"): %s",
	   xfd->wfd, sendmethod, sendlen, strerror(errno));
      if (Close(xfd->wfd) < 0) {
	 Warn2("close(%d): %s", xfd->wfd, strerror(errno));
      }
      if (Close(xfd->rfd) < 0) {
	 Warn2("close(%d): %s", xfd->rfd, strerror(errno));
      }
      return STAT_RETRYLATER;	/* retry complete open cycle */
   }

   Info("waiting for socks5 reply");
   recvreply = (struct socks5_reply *)recvbuff;
   if ((result =
	xiosocks5_recvbytes(xfd, recvbuff, SOCKS5_REPLY_LENGTH1, level))
       != STAT_OK) {
      /*! close... */
      return result;
   }
   if (recvreply->version != SOCKS5_VERSION) {
      Error1("socks5: version of reply is %d", recvreply->version);
   }
   switch (recvreply->reply) {
   case SOCKS5_REPLY_SUCCESS:     emsg = NULL; break;
   case SOCKS5_REPLY_FAILURE:     emsg = "general socks server failure"; break;
   case SOCKS5_REPLY_DENIED:      emsg = "connection not allowed by ruleset"; break;
   case SOCKS5_REPLY_NETUNREACH:  emsg = "network unreachable"; break;
   case SOCKS5_REPLY_HOSTUNREACH: emsg = "host unreachable"; break;
   case SOCKS5_REPLY_REFUSED:     emsg = "connection refused"; break;
   case SOCKS5_REPLY_TTLEXPIRED:  emsg = "TTL expired"; break;
   case SOCKS5_REPLY_CMDUNSUPP:   emsg = "command not supported"; break;
   case SOCKS5_REPLY_ADDRUNSUPP:  emsg = "address type not supported"; break;
   default:                       emsg = "undefined error code"; break;
   }
   if (recvreply->reply != SOCKS5_REPLY_SUCCESS) {
      Error1("socks5 reply: %s", emsg);
   }
   
   switch (recvreply->addrtype) {
   case SOCKS5_ADDRTYPE_IPV4:
      addrlen = 4;	/*!*/
      if ((result =
	   xiosocks5_recvbytes(xfd, recvbuff+SOCKS5_REPLY_LENGTH1, addrlen,
			       level))
	   != STAT_OK) {
	 /*! close... */
	 return result;
      }
      readpos = sizeof(recvreply)-1+4;
      break;
   case SOCKS5_ADDRTYPE_NAME:
      /* read 1 byte containing domain name length */
      if ((result =
	   xiosocks5_recvbytes(xfd, recvbuff+SOCKS5_REPLY_LENGTH1, 1, level))
	  != STAT_OK) {
	 /*! close... */
	 return result;
      }
      /* read domain name */
      if ((result =
	   xiosocks5_recvbytes(xfd, recvbuff+SOCKS5_REPLY_LENGTH1+1,
			       recvreply->destaddr[0], level))
	  != STAT_OK) {
	 /*! close... */
	 return result;
      }
      readpos = sizeof(recvreply)+recvreply->destaddr[0];
      addrlen = recvreply->destaddr[0]+1;
      break;
   case SOCKS5_ADDRTYPE_IPV6:
      addrlen = 16;	/*!*/
      if ((result =
	   xiosocks5_recvbytes(xfd, recvbuff+SOCKS5_REPLY_LENGTH1, addrlen,
			      level))
	  == EOF) {
	 /*! close... */
	 return result;
      }
      readpos = sizeof(recvreply)-1+4;
      break;
   default: Error("socks5: undefined address type in answer");
      addrlen = 0;
      readpos = sizeof(recvreply)-1;
   }
   if ((result =
	xiosocks5_recvbytes(xfd, recvbuff+readpos, 2, level))
        != STAT_OK) {
      /*! close... */
      return result;
   }

   /*! Infos(...); */
   return STAT_OK;
}

int xio_socks5_username_password(int level, struct opt *opts,
				 struct single *xfd) {
   /*!!! */
   unsigned char sendbuff[513];
   unsigned char *pos;
   char *username = NULL;
   char *password = NULL;
   unsigned char recvbuff[2];
   struct socks5_userpass_reply *reply;
   int result;

   retropt_string(opts, OPT_SOCKS5_USERNAME, (char **)&username);
   if (username == NULL) {
      Error("socks5: username required");
      return STAT_NORETRY;
   }
   retropt_string(opts, OPT_SOCKS5_PASSWORD, (char **)&password);
   if (password == NULL) {
      Error("socks5: password required");
      return STAT_NORETRY;
   }

   pos = sendbuff;
   *pos++ = SOCKS5_USERPASS_VERSION;
   *pos++ = strlen(username);
   *pos = '\0'; strncat(pos, username, 255);
   pos += strlen(username);
   *pos++ = strlen(password);
   *pos = '\0'; strncat(pos, password, 255);
   pos += strlen(password);

   result =
     xio_socks5_dialog(level, xfd, sendbuff, pos-sendbuff,
		       recvbuff, 2,
		       "username/password authentication");
   if (result != STAT_OK) {
      Msg(level, "socks5 username/password dialog failed");
      return result;
   }
   Info("socks5 username/password authentication succeeded");
   reply = (struct socks5_userpass_reply *)recvbuff;
   if (reply->version != SOCKS5_USERPASS_VERSION) {
      Msg(level, "socks5 username/password authentication version mismatch");
      return STAT_NORETRY;
   }
   if (reply->status != SOCKS5_REPLY_SUCCESS) {
      Msg(level, "socks5 username/password authentication failure");
      return STAT_RETRYLATER;
   }
   return STAT_OK;
}

int xio_socks5_dialog(int level, struct single *xfd,
		      unsigned char *sendbuff, size_t sendlen,
		      unsigned char *recvbuff, size_t recvlen,
		      const char *descr /* identifier/method selection */) {
   int result;

   /* send socks header (target addr+port, +auth) */
   Info1("sending socks5 %s message", descr);
   do {
      result = Write(xfd->wfd, sendbuff, sendlen);
   } while (result < 0 && errno == EINTR);
   if (result < 0) {
      Msg4(level, "write(%d, %p, "F_Zu"): %s",
	   xfd->wfd, sendbuff, sendlen, strerror(errno));
      if (Close(xfd->wfd) < 0) {
	 Warn2("close(%d): %s", xfd->wfd, strerror(errno));
      }
      if (Close(xfd->rfd) < 0) {
	 Warn2("close(%d): %s", xfd->rfd, strerror(errno));
      }
      return STAT_RETRYLATER;	/* retry complete open cycle */
   }

   Info2("waiting for socks5 %s reply ("F_Zu" bytes)",
	 descr, recvlen);
   if ((result =
	xiosocks5_recvbytes(xfd, recvbuff, recvlen, level))
       == EOF) {
      /* we had a problem while reading socks answer */
      /*! Close(); */
      return result;	/* retry complete open cycle */
   }
#if 0
   replyversion = ((struct socks5_version *)recvbuff)->version;
   Info1("socks5 server reply version: {%u}", replyversion);
   if (replyversion != SOCKS5_VERSION) {
      Error1("socks5: server protocol version is %u",
	     replyversion);
   }
#endif
   return 0;
}

#endif /* WITH_SOCKS5 */