aboutsummaryrefslogtreecommitdiff
path: root/tools/plink/portfwd.c
blob: 545dfecd49376756e416da5a917d0ffd2b08ff30 (plain)
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/*
 * SSH port forwarding.
 */

#include <stdio.h>
#include <stdlib.h>

#include "putty.h"
#include "ssh.h"

#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif

struct PFwdPrivate {
    const struct plug_function_table *fn;
    /* the above variable absolutely *must* be the first in this structure */
    void *c;			       /* (channel) data used by ssh.c */
    void *backhandle;		       /* instance of SSH backend itself */
    /* Note that backhandle need not be filled in if c is non-NULL */
    Socket s;
    int throttled, throttle_override;
    int ready;
    /*
     * `dynamic' does double duty. It's set to 0 for an ordinary
     * forwarded port, and nonzero for SOCKS-style dynamic port
     * forwarding; but it also represents the state of the SOCKS
     * exchange.
     */
    int dynamic;
    /*
     * `hostname' and `port' are the real hostname and port, once
     * we know what we're connecting to; they're unused for this
     * purpose while conducting a local SOCKS exchange, which means
     * we can also use them as a buffer and pointer for reading
     * data from the SOCKS client.
     */
    char hostname[256+8];
    int port;
    /*
     * When doing dynamic port forwarding, we can receive
     * connection data before we are actually able to send it; so
     * we may have to temporarily hold some in a dynamically
     * allocated buffer here.
     */
    void *buffer;
    int buflen;
};

static void pfd_log(Plug plug, int type, SockAddr addr, int port,
		    const char *error_msg, int error_code)
{
    /* we have to dump these since we have no interface to logging.c */
}

static int pfd_closing(Plug plug, const char *error_msg, int error_code,
		       int calling_back)
{
    struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;

    if (error_msg) {
        /*
         * Socket error. Slam the connection instantly shut.
         */
        sshfwd_unclean_close(pr->c);
    } else {
        /*
         * Ordinary EOF received on socket. Send an EOF on the SSH
         * channel.
         */
        if (pr->c)
            sshfwd_write_eof(pr->c);
    }

    return 1;
}

static int pfd_receive(Plug plug, int urgent, char *data, int len)
{
    struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;
    if (pr->dynamic) {
	while (len--) {
	    /*
	     * Throughout SOCKS negotiation, "hostname" is re-used as a
	     * random protocol buffer with "port" storing the length.
	     */ 
	    if (pr->port >= lenof(pr->hostname)) {
		/* Request too long. */
		if ((pr->dynamic >> 12) == 4) {
		    /* Send back a SOCKS 4 error before closing. */
		    char data[8];
		    memset(data, 0, sizeof(data));
		    data[1] = 91;      /* generic `request rejected' */
		    sk_write(pr->s, data, 8);
		}
		pfd_close(pr->s);
		return 1;
	    }
	    pr->hostname[pr->port++] = *data++;

	    /*
	     * Now check what's in the buffer to see if it's a
	     * valid and complete message in the SOCKS exchange.
	     */
	    if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 4) &&
		pr->hostname[0] == 4) {
		/*
		 * SOCKS 4.
		 */
		if (pr->dynamic == 1)
		    pr->dynamic = 0x4000;
		if (pr->port < 2) continue;/* don't have command code yet */
		if (pr->hostname[1] != 1) {
		    /* Not CONNECT. */
		    /* Send back a SOCKS 4 error before closing. */
		    char data[8];
		    memset(data, 0, sizeof(data));
		    data[1] = 91;      /* generic `request rejected' */
		    sk_write(pr->s, data, 8);
		    pfd_close(pr->s);
		    return 1;
		}
		if (pr->port <= 8) continue; /* haven't started user/hostname */
		if (pr->hostname[pr->port-1] != 0)
		    continue;	       /* haven't _finished_ user/hostname */
		/*
		 * Now we have a full SOCKS 4 request. Check it to
		 * see if it's a SOCKS 4A request.
		 */
		if (pr->hostname[4] == 0 && pr->hostname[5] == 0 &&
		    pr->hostname[6] == 0 && pr->hostname[7] != 0) {
		    /*
		     * It's SOCKS 4A. So if we haven't yet
		     * collected the host name, we should continue
		     * waiting for data in order to do so; if we
		     * have, we can go ahead.
		     */
		    int len;
		    if (pr->dynamic == 0x4000) {
			pr->dynamic = 0x4001;
			pr->port = 8;      /* reset buffer to overwrite name */
			continue;
		    }
		    pr->hostname[0] = 0;   /* reply version code */
		    pr->hostname[1] = 90;   /* request granted */
		    sk_write(pr->s, pr->hostname, 8);
		    len= pr->port - 8;
		    pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
		    memmove(pr->hostname, pr->hostname + 8, len);
		    goto connect;
		} else {
		    /*
		     * It's SOCKS 4, which means we should format
		     * the IP address into the hostname string and
		     * then just go.
		     */
		    pr->hostname[0] = 0;   /* reply version code */
		    pr->hostname[1] = 90;   /* request granted */
		    sk_write(pr->s, pr->hostname, 8);
		    pr->port = GET_16BIT_MSB_FIRST(pr->hostname+2);
		    sprintf(pr->hostname, "%d.%d.%d.%d",
			    (unsigned char)pr->hostname[4],
			    (unsigned char)pr->hostname[5],
			    (unsigned char)pr->hostname[6],
			    (unsigned char)pr->hostname[7]);
		    goto connect;
		}
	    }

	    if ((pr->dynamic == 1 || (pr->dynamic >> 12) == 5) &&
		pr->hostname[0] == 5) {
		/*
		 * SOCKS 5.
		 */
		if (pr->dynamic == 1)
		    pr->dynamic = 0x5000;

		if (pr->dynamic == 0x5000) {
		    int i, method;
		    char data[2];
		    /*
		     * We're receiving a set of method identifiers.
		     */
		    if (pr->port < 2) continue;/* no method count yet */
		    if (pr->port < 2 + (unsigned char)pr->hostname[1])
			continue;      /* no methods yet */
		    method = 0xFF;     /* invalid */
		    for (i = 0; i < (unsigned char)pr->hostname[1]; i++)
			if (pr->hostname[2+i] == 0) {
			    method = 0;/* no auth */
			    break;
			}
		    data[0] = 5;
		    data[1] = method;
		    sk_write(pr->s, data, 2);
		    pr->dynamic = 0x5001;
		    pr->port = 0;      /* re-empty the buffer */
		    continue;
		}

		if (pr->dynamic == 0x5001) {
		    /*
		     * We're receiving a SOCKS request.
		     */
		    unsigned char reply[10]; /* SOCKS5 atyp=1 reply */
		    int atype, alen = 0;

		    /*
		     * Pre-fill reply packet.
		     * In all cases, we set BND.{HOST,ADDR} to 0.0.0.0:0
		     * (atyp=1) in the reply; if we succeed, we don't know
		     * the right answers, and if we fail, they should be
		     * ignored.
		     */
		    memset(reply, 0, lenof(reply));
		    reply[0] = 5; /* VER */
		    reply[3] = 1; /* ATYP = 1 (IPv4, 0.0.0.0:0) */

		    if (pr->port < 6) continue;
		    atype = (unsigned char)pr->hostname[3];
		    if (atype == 1)    /* IPv4 address */
			alen = 4;
		    if (atype == 4)    /* IPv6 address */
			alen = 16;
		    if (atype == 3)    /* domain name has leading length */
			alen = 1 + (unsigned char)pr->hostname[4];
		    if (pr->port < 6 + alen) continue;
		    if (pr->hostname[1] != 1 || pr->hostname[2] != 0) {
			/* Not CONNECT or reserved field nonzero - error */
			reply[1] = 1;	/* generic failure */
			sk_write(pr->s, (char *) reply, lenof(reply));
			pfd_close(pr->s);
			return 1;
		    }
		    /*
		     * Now we have a viable connect request. Switch
		     * on atype.
		     */
		    pr->port = GET_16BIT_MSB_FIRST(pr->hostname+4+alen);
		    if (atype == 1) {
			/* REP=0 (success) already */
			sk_write(pr->s, (char *) reply, lenof(reply));
			sprintf(pr->hostname, "%d.%d.%d.%d",
				(unsigned char)pr->hostname[4],
				(unsigned char)pr->hostname[5],
				(unsigned char)pr->hostname[6],
				(unsigned char)pr->hostname[7]);
			goto connect;
		    } else if (atype == 3) {
			/* REP=0 (success) already */
			sk_write(pr->s, (char *) reply, lenof(reply));
			memmove(pr->hostname, pr->hostname + 5, alen-1);
			pr->hostname[alen-1] = '\0';
			goto connect;
		    } else {
			/*
			 * Unknown address type. (FIXME: support IPv6!)
			 */
			reply[1] = 8;	/* atype not supported */
			sk_write(pr->s, (char *) reply, lenof(reply));
			pfd_close(pr->s);
			return 1;
		    }
		}
	    }

	    /*
	     * If we get here without either having done `continue'
	     * or `goto connect', it must be because there is no
	     * sensible interpretation of what's in our buffer. So
	     * close the connection rudely.
	     */
	    pfd_close(pr->s);
	    return 1;
	}
	return 1;

	/*
	 * We come here when we're ready to make an actual
	 * connection.
	 */
	connect:

	/*
	 * Freeze the socket until the SSH server confirms the
	 * connection.
	 */
	sk_set_frozen(pr->s, 1);

	pr->c = new_sock_channel(pr->backhandle, pr->s);
	if (pr->c == NULL) {
	    pfd_close(pr->s);
	    return 1;
	} else {
	    /* asks to forward to the specified host/port for this */
	    ssh_send_port_open(pr->c, pr->hostname, pr->port, "forwarding");
	}
	pr->dynamic = 0;

	/*
	 * If there's any data remaining in our current buffer,
	 * save it to be sent on pfd_confirm().
	 */
	if (len > 0) {
	    pr->buffer = snewn(len, char);
	    memcpy(pr->buffer, data, len);
	    pr->buflen = len;
	}
    }
    if (pr->ready) {
	if (sshfwd_write(pr->c, data, len) > 0) {
	    pr->throttled = 1;
	    sk_set_frozen(pr->s, 1);
	}
    }
    return 1;
}

static void pfd_sent(Plug plug, int bufsize)
{
    struct PFwdPrivate *pr = (struct PFwdPrivate *) plug;

    if (pr->c)
	sshfwd_unthrottle(pr->c, bufsize);
}

/*
 * Called when receiving a PORT OPEN from the server
 */
const char *pfd_newconnect(Socket *s, char *hostname, int port,
			   void *c, Conf *conf, int addressfamily)
{
    static const struct plug_function_table fn_table = {
	pfd_log,
	pfd_closing,
	pfd_receive,
	pfd_sent,
	NULL
    };

    SockAddr addr;
    const char *err;
    char *dummy_realhost;
    struct PFwdPrivate *pr;

    /*
     * Try to find host.
     */
    addr = name_lookup(hostname, port, &dummy_realhost, conf, addressfamily);
    if ((err = sk_addr_error(addr)) != NULL) {
	sk_addr_free(addr);
	return err;
    }

    /*
     * Open socket.
     */
    pr = snew(struct PFwdPrivate);
    pr->buffer = NULL;
    pr->fn = &fn_table;
    pr->throttled = pr->throttle_override = 0;
    pr->ready = 1;
    pr->c = c;
    pr->backhandle = NULL;	       /* we shouldn't need this */
    pr->dynamic = 0;

    pr->s = *s = new_connection(addr, dummy_realhost, port,
				0, 1, 0, 0, (Plug) pr, conf);
    if ((err = sk_socket_error(*s)) != NULL) {
	sfree(pr);
	return err;
    }

    sk_set_private_ptr(*s, pr);
    return NULL;
}

/*
 called when someone connects to the local port
 */

static int pfd_accepting(Plug p, OSSocket sock)
{
    static const struct plug_function_table fn_table = {
	pfd_log,
	pfd_closing,
	pfd_receive,
	pfd_sent,
	NULL
    };
    struct PFwdPrivate *pr, *org;
    Socket s;
    const char *err;

    org = (struct PFwdPrivate *)p;
    pr = snew(struct PFwdPrivate);
    pr->buffer = NULL;
    pr->fn = &fn_table;

    pr->c = NULL;
    pr->backhandle = org->backhandle;

    pr->s = s = sk_register(sock, (Plug) pr);
    if ((err = sk_socket_error(s)) != NULL) {
	sfree(pr);
	return err != NULL;
    }

    sk_set_private_ptr(s, pr);

    pr->throttled = pr->throttle_override = 0;
    pr->ready = 0;

    if (org->dynamic) {
	pr->dynamic = 1;
	pr->port = 0;		       /* "hostname" buffer is so far empty */
	sk_set_frozen(s, 0);	       /* we want to receive SOCKS _now_! */
    } else {
	pr->dynamic = 0;
	strcpy(pr->hostname, org->hostname);
	pr->port = org->port;	
	pr->c = new_sock_channel(org->backhandle, s);

	if (pr->c == NULL) {
	    sfree(pr);
	    return 1;
	} else {
	    /* asks to forward to the specified host/port for this */
	    ssh_send_port_open(pr->c, pr->hostname, pr->port, "forwarding");
	}
    }

    return 0;
}


/* Add a new forwarding from port -> desthost:destport
 sets up a listener on the local machine on (srcaddr:)port
 */
const char *pfd_addforward(char *desthost, int destport, char *srcaddr,
			   int port, void *backhandle, Conf *conf,
			   void **sockdata, int address_family)
{
    static const struct plug_function_table fn_table = {
	pfd_log,
	pfd_closing,
	pfd_receive,		       /* should not happen... */
	pfd_sent,		       /* also should not happen */
	pfd_accepting
    };

    const char *err;
    struct PFwdPrivate *pr;
    Socket s;

    /*
     * Open socket.
     */
    pr = snew(struct PFwdPrivate);
    pr->buffer = NULL;
    pr->fn = &fn_table;
    pr->c = NULL;
    if (desthost) {
	strcpy(pr->hostname, desthost);
	pr->port = destport;
	pr->dynamic = 0;
    } else
	pr->dynamic = 1;
    pr->throttled = pr->throttle_override = 0;
    pr->ready = 0;
    pr->backhandle = backhandle;

    pr->s = s = new_listener(srcaddr, port, (Plug) pr,
			     !conf_get_int(conf, CONF_lport_acceptall),
			     conf, address_family);
    if ((err = sk_socket_error(s)) != NULL) {
	sfree(pr);
	return err;
    }

    sk_set_private_ptr(s, pr);

    *sockdata = (void *)s;

    return NULL;
}

void pfd_close(Socket s)
{
    struct PFwdPrivate *pr;

    if (!s)
	return;

    pr = (struct PFwdPrivate *) sk_get_private_ptr(s);

    sfree(pr->buffer);
    sfree(pr);

    sk_close(s);
}

/*
 * Terminate a listener.
 */
void pfd_terminate(void *sv)
{
    pfd_close((Socket)sv);
}

void pfd_unthrottle(Socket s)
{
    struct PFwdPrivate *pr;
    if (!s)
	return;
    pr = (struct PFwdPrivate *) sk_get_private_ptr(s);

    pr->throttled = 0;
    sk_set_frozen(s, pr->throttled || pr->throttle_override);
}

void pfd_override_throttle(Socket s, int enable)
{
    struct PFwdPrivate *pr;
    if (!s)
	return;
    pr = (struct PFwdPrivate *) sk_get_private_ptr(s);

    pr->throttle_override = enable;
    sk_set_frozen(s, pr->throttled || pr->throttle_override);
}

/*
 * Called to send data down the raw connection.
 */
int pfd_send(Socket s, char *data, int len)
{
    if (s == NULL)
	return 0;
    return sk_write(s, data, len);
}

void pfd_send_eof(Socket s)
{
    sk_write_eof(s);
}

void pfd_confirm(Socket s)
{
    struct PFwdPrivate *pr;

    if (s == NULL)
	return;

    pr = (struct PFwdPrivate *) sk_get_private_ptr(s);
    pr->ready = 1;
    sk_set_frozen(s, 0);
    sk_write(s, NULL, 0);
    if (pr->buffer) {
	sshfwd_write(pr->c, pr->buffer, pr->buflen);
	sfree(pr->buffer);
	pr->buffer = NULL;
    }
}