aboutsummaryrefslogtreecommitdiffstats
path: root/packet-socks.c
blob: 3c6023a09c8206924451c6fd3e92fbbd2559223d (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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
/* packet-socks.c
 * Routines for socks versions 4 &5  packet dissection
 * Copyright 2000, Jeffrey C. Foster <jfoste@woodward.com>
 *
 * $Id: packet-socks.c,v 1.50 2003/12/04 05:57:53 gram Exp $
 *
 * Ethereal - Network traffic analyzer
 * By Gerald Combs <gerald@ethereal.com>
 * Copyright 1998 Gerald Combs
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 *
 * The Version 4 decode is based on SOCKS4.protocol and SOCKS4A.protocol.
 * The Version 5 decoder is based upon rfc-1928
 * The Version 5 User/Password authentication is based on rfc-1929.
 *
 * See http://www.socks.nec.com/socksprot.html for these and other documents
 *
 * Revisions:
 *
 * 2003-09-18 JCFoster Fixed problem with socks tunnel in socks tunnel
 *			causing heap overflow because of an infinite loop
 *			where the socks dissect was call over and over.
 *
 *			Also remove some old code marked with __JUNK__
 *
 * 2001-01-08 JCFoster Fixed problem with NULL pointer for hash data.
 *			Now test and exit if hash_info is null.
 */

/* Possible enhancements -
 *
 * Add GSS-API authentication per rfc-1961
 * Add CHAP authentication
 * Decode FLAG bits per
 * 	 http://www.socks.nec.com/draft/draft-ietf-aft-socks-pro-v-04.txt
 * In call_next_dissector, could load the destination address into the
 * 	pi structure before calling next dissector.
 * remove display_string or at least make it use protocol identifiers
 * socks_hash_entry_t needs to handle V5 address type and domain names
*/




#ifdef HAVE_CONFIG_H
# include "config.h"
#endif


#include <stdio.h>
#include <string.h>
#include <glib.h>

#include <epan/packet.h>
#include <epan/resolv.h>
#include "alignment.h"
#include <epan/conversation.h>

#include "packet-tcp.h"
#include "packet-udp.h"
#include <epan/strutil.h>


#define compare_packet(X) (X == (pinfo->fd->num))
#define get_packet_ptr	(pinfo->fd->num)
#define row_pointer_type guint32

#define TCP_PORT_SOCKS 1080


/**************** Socks commands ******************/

#define CONNECT_COMMAND		1
#define BIND_COMMAND		2
#define UDP_ASSOCIATE_COMMAND	3
#define PING_COMMAND		0x80
#define TRACERT_COMMAND		0x81


/********** V5 Authentication methods *************/

#define NO_AUTHENTICATION 	0
#define GSS_API_AUTHENTICATION 	1
#define USER_NAME_AUTHENTICATION 	2
#define CHAP_AUTHENTICATION 	3
#define AUTHENTICATION_FAILED 	0xff

/* 2003-09-18 JCFoster Fixed problem with socks tunnel in socks tunnel */

static int in_socks_dissector_flag = 0;		/* set to 1 to avoid recursive overflow */

/*********** Header field identifiers *************/

static int proto_socks = -1;

static int ett_socks = -1;
static int ett_socks_auth = -1;
static int ett_socks_name = -1;

static int hf_socks_ver = -1;
static int hf_socks_ip_dst = -1;
static int hf_socks_ip6_dst = -1;
static int hf_user_name = -1;
static int hf_socks_dstport = -1;
static int hf_socks_cmd = -1;
static int hf_socks_results = -1;
static int hf_socks_results_4 = -1;
static int hf_socks_results_5 = -1;


/************* Dissector handles ***********/

static dissector_handle_t socks_handle;
static dissector_handle_t socks_udp_handle;

/************* State Machine names ***********/

enum SockState {
	None = 0,
	Connecting,
	V4UserNameWait,
	V4NameWait,
	V5Command,
	V5Reply,
	V5BindReply,
	UserNameAuth,
	GssApiAuth,
	AuthReply,
	Done
};



typedef struct {
	int		state;
	int	 	version;
	int	 	command;
	int	 	grant;
	guint32 	port;
	guint32 	udp_port;
	guint32 	udp_remote_port;

	int		connect_offset;
	row_pointer_type 	v4_name_row;
	row_pointer_type	v4_user_name_row;
	row_pointer_type	connect_row;
	row_pointer_type	cmd_reply_row;
	row_pointer_type	bind_reply_row;
	row_pointer_type	command_row;
	row_pointer_type 	auth_method_row;
	row_pointer_type	user_name_auth_row;
	guint32 start_done_row;

	guint32	dst_addr;	/* this needs to handle IPv6 */
}socks_hash_entry_t;




static char *address_type_table[] = {
	"Unknown",
	"IPv4",
	"Unknown",
	"Domain Name",
	"IPv6",
	"Unknown"
};


/* String table for the V4 reply status messages */

static const value_string reply_table_v4[] = {
	{90, "Granted"},
	{91, "Rejected or Failed"},
	{92, "Rejected because SOCKS server cannot connect to identd on the client"},
	{93, "Rejected because the client program and identd report different user-ids"},
	{0, NULL}
};

/* String table for the V5 reply status messages */

static const value_string reply_table_v5[] = {
	{0, "Succeeded"},
	{1, "General SOCKS server failure"},
	{2, "Connection not allowed by ruleset"},
	{3, "Network unreachable"},
	{4, "Host unreachable"},
	{5, "Connection refused"},
	{6, "TTL expired"},
	{7, "Command not supported"},
	{8, "Address type not supported"},
	{0, NULL},
};

static const value_string cmd_strings[] = {
	{0, "Unknow"},
	{1, "Connect"},
	{2, "Bind"},
	{3, "UdpAssociate"},
	{0x80, "Ping"},
	{0x81, "Traceroute"},
	{0, NULL}
};

#define socks_hash_init_count 20
#define socks_hash_val_length (sizeof(socks_hash_entry_t))

static GMemChunk *socks_vals = NULL;


/************************* Support routines ***************************/


static int display_string(tvbuff_t *tvb, int offset,
	proto_tree *tree, char *label){

/* display a string with a length, characters encoding */
/* they are displayed under a tree with the name in Label variable */
/* return the length of the string and the length byte */


	proto_tree      *name_tree;
	proto_item      *ti;

	char temp[ 256];
	int length = tvb_get_guint8(tvb, offset);

	tvb_memcpy(tvb, (guint8 *)temp, offset+1, length);
	temp[ length ] = 0;

   	ti = proto_tree_add_text(tree, tvb, offset, length + 1,
   	 	"%s: %s" , label, temp);


	name_tree = proto_item_add_subtree(ti, ett_socks_name);

	proto_tree_add_text( name_tree, tvb, offset, 1, "Length: %u", length);

	++offset;

	proto_tree_add_text( name_tree, tvb, offset, length, "String: %s", temp);

	return length + 1;
}



static char *get_auth_method_name( guint Number){

/* return the name of the authenication method */

	if ( Number == 0) return "No authentication";
	if ( Number == 1) return "GSSAPI";
	if ( Number == 2) return "Username/Password";
	if ( Number == 3) return "Chap";
	if (( Number >= 4) && ( Number <= 0x7f))return "IANA assigned";
	if (( Number >= 0x80) && ( Number <= 0xfe)) return "private method";
	if ( Number == 0xff) return "no acceptable method";

	/* shouldn't reach here */

	return "Bad method number (not 0-0xff)";
}


static char *get_command_name( guint Number){

/* return the name of the command as a string */

	if ( Number == 0) return "Unknow";
	if ( Number == 1) return "Connect";
	if ( Number == 2) return "Bind";
	if ( Number == 3) return "UdpAssociate";
	if ( Number == 0x80) return "Ping";
	if ( Number == 0x81) return "Traceroute";
	return "Unknown";
}


static int display_address(tvbuff_t *tvb, int offset, proto_tree *tree) {

/* decode and display the v5 address, return offset of next byte */

	int a_type = tvb_get_guint8(tvb, offset);

	proto_tree_add_text( tree, tvb, offset, 1,
			"Address Type: %d (%s)", a_type,
			address_type_table[ MIN( (guint) a_type,
				array_length( address_type_table)-1) ]);

	++offset;

	if ( a_type == 1){		/* IPv4 address */
		proto_tree_add_item( tree, hf_socks_ip_dst, tvb, offset,
					4, FALSE);
		offset += 4;
	}
	else if ( a_type == 3){	/* domain name address */

		offset += display_string(tvb, offset, tree,
			"Remote name");
	}
	else if ( a_type == 4){	/* IPv6 address */
		proto_tree_add_item( tree, hf_socks_ip6_dst, tvb, offset,
				16, FALSE);
		offset += 16;
	}

	return offset;
}


static int get_address_v5(tvbuff_t *tvb, int offset,
	socks_hash_entry_t *hash_info) {

/* decode the v5 address and return offset of next byte */
/*XXX this needs to handle IPV6 and domain name addresses */


	int a_type = tvb_get_guint8(tvb, offset++);

	if ( a_type == 1){ 		/* IPv4 address */

	   	if ( hash_info)
	   		tvb_memcpy(tvb, (guint8 *)&hash_info->dst_addr,
	   		    offset, 4);
		offset += 4;
	}

	else if ( a_type == 4) 		/* IPv6 address */
		offset += 16;

	else if ( a_type == 3)	/* domain name address */
		offset += tvb_get_guint8(tvb, offset) + 1;
	return offset;
}


/********************* V5 UDP Associate handlers ***********************/

static void
socks_udp_dissector(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) {

/* Conversation dissector called from UDP dissector. Decode and display */
/* the socks header, the pass the rest of the data to the udp port 	*/
/* decode routine to  handle the payload.				*/

	int offset = 0;
	guint32 *ptr;
	socks_hash_entry_t *hash_info;
	conversation_t *conversation;
	proto_tree      *socks_tree;
	proto_item      *ti;

	conversation = find_conversation( &pinfo->src, &pinfo->dst, pinfo->ptype,
		pinfo->srcport, pinfo->destport, 0);

	g_assert( conversation);	/* should always find a conversation */

	hash_info = conversation_get_proto_data(conversation, proto_socks);

	if (check_col(pinfo->cinfo, COL_PROTOCOL))
		col_set_str(pinfo->cinfo, COL_PROTOCOL, "Socks");

	if (check_col(pinfo->cinfo, COL_INFO))
		col_add_fstr(pinfo->cinfo, COL_INFO, "Version: 5, UDP Associated packet");

	if ( tree) {
    		ti = proto_tree_add_protocol_format( tree, proto_socks, tvb,
    			offset, -1, "Socks" );

		socks_tree = proto_item_add_subtree(ti, ett_socks);

       		proto_tree_add_text( socks_tree, tvb, offset, 2, "Reserved");
		offset += 2;

       		proto_tree_add_text( socks_tree, tvb, offset, 1, "Fragment Number: %u", tvb_get_guint8(tvb, offset));
		++offset;


		offset = display_address( tvb, offset, socks_tree);
		hash_info->udp_remote_port = tvb_get_ntohs(tvb, offset);

		proto_tree_add_uint( socks_tree, hf_socks_dstport, tvb,
			offset, 2, hash_info->udp_remote_port);

		offset += 2;
	}
	else { 		/* no tree, skip past the socks header */
		offset += 3;
		offset = get_address_v5( tvb, offset, 0) + 2;
	}


/* set pi src/dst port and call the udp sub-dissector lookup */

	if ( pinfo->srcport == hash_info->port)
       		ptr = &pinfo->destport;
   	else
    		ptr = &pinfo->srcport;

        *ptr = hash_info->udp_remote_port;

	decode_udp_ports( tvb, offset, pinfo, tree, pinfo->srcport, pinfo->destport);

        *ptr = hash_info->udp_port;

}


static void
new_udp_conversation( socks_hash_entry_t *hash_info, packet_info *pinfo){

	conversation_t *conversation = conversation_new( &pinfo->src, &pinfo->dst,  PT_UDP,
			hash_info->udp_port, hash_info->port, 0);

	g_assert( conversation);

	conversation_add_proto_data(conversation, proto_socks, hash_info);
	conversation_set_dissector(conversation, socks_udp_handle);
}




/**************** Protocol Tree Display routines  ******************/

static void
display_socks_v4(tvbuff_t *tvb, int offset, packet_info *pinfo,
	proto_tree *tree, socks_hash_entry_t *hash_info) {


/* Display the protocol tree for the V4 version. This routine uses the	*/
/* stored conversation information to decide what to do with the row.	*/
/* Per packet information would have been better to do this, but we	*/
/* didn't have that when I wrote this. And I didn't expect this to get	*/
/* so messy.								*/


	guint command;

					/* Display command from client */
	if (compare_packet( hash_info->connect_row)){

		proto_tree_add_text( tree, tvb, offset, 1,
				"Version: %u", hash_info->version);
		++offset;
		command = tvb_get_guint8(tvb, offset);

		proto_tree_add_text( tree, tvb, offset, 1,
			"Command: %u (%s)", command,
				get_command_name( command));
		++offset;

						/* Do remote port	*/
		proto_tree_add_item( tree, hf_socks_dstport, tvb, offset, 2,
				FALSE);
		offset += 2;

						/* Do destination address */
		proto_tree_add_item( tree, hf_socks_ip_dst, tvb, offset,
				4, FALSE);

		offset += 4;

/*XXX check this, needs to do length checking	 */
/* Should perhaps do TCP reassembly as well */
		if ( tvb_offset_exists(tvb, offset)) {
						/* display user name 	*/
			proto_tree_add_string( tree, hf_user_name, tvb, offset,
				tvb_strsize(tvb, offset),
				tvb_get_ptr(tvb, offset, -1));
		}

	}
				/*Display command response from server*/

	else if ( compare_packet( hash_info->cmd_reply_row)){

		proto_tree_add_item( tree, hf_socks_ver, tvb, offset, 1,
				FALSE);
		++offset;
						/* Do results code	*/
		proto_tree_add_item( tree, hf_socks_results_4, tvb, offset, 1, FALSE);
		proto_tree_add_item_hidden(tree, hf_socks_results, tvb, offset, 1, FALSE);

		++offset;

						/* Do remote port	*/
		proto_tree_add_item( tree, hf_socks_dstport, tvb, offset, 2,
				FALSE);
		offset += 2;
						/* Do remote address	*/
		proto_tree_add_item( tree, hf_socks_ip_dst, tvb, offset, 4,
			FALSE);
	}

	else if ( compare_packet( hash_info->v4_user_name_row)){

/*XXX check this, needs to do length checking	 */
/* Should perhaps do TCP reassembly as well */
		if ( tvb_offset_exists(tvb, offset)) {
			proto_tree_add_text( tree, tvb, offset,
				tvb_strsize(tvb, offset),
				"User Name: %s", tvb_get_ptr(tvb, offset, -1));
		}
	}
}


static void
display_socks_v5(tvbuff_t *tvb, int offset, packet_info *pinfo,
	proto_tree *tree, socks_hash_entry_t *hash_info) {

/* Display the protocol tree for the version. This routine uses the	*/
/* stored conversation information to decide what to do with the row.	*/
/* Per packet information would have been better to do this, but we	*/
/* didn't have that when I wrote this. And I didn't expect this to get	*/
/* so messy.								*/

	unsigned int i, command;
	guint temp;
	char *AuthMethodStr;

	proto_tree_add_item( tree, hf_socks_ver, tvb, offset, 1, FALSE);
	++offset;

	if (compare_packet( hash_info->connect_row)){

		proto_tree      *AuthTree;
		proto_item      *ti;

		temp = tvb_get_guint8(tvb, offset);	/* Get Auth method count */
							/* build auth tree */
		ti = proto_tree_add_text( tree, tvb, offset, -1,
				"Client Authentication Methods");

		AuthTree = proto_item_add_subtree(ti, ett_socks_auth);

		proto_tree_add_text( AuthTree, tvb, offset, 1,
				"Count: %u", temp);
		++offset;

		for( i = 0; i  < temp; ++i) {

			AuthMethodStr = get_auth_method_name(
				tvb_get_guint8( tvb, offset));
			proto_tree_add_text( AuthTree, tvb, offset, 1,
				"Method[%u]: %u (%s)", i,
				tvb_get_guint8( tvb, offset), AuthMethodStr);
			++offset;
		}
		proto_item_set_end( ti, tvb, offset);
		return;
	}					/* Get accepted auth method */
	else if (compare_packet( hash_info->auth_method_row)) {

		proto_tree_add_text( tree, tvb, offset, 1,
			"Accepted Auth Method: 0x%0x (%s)", tvb_get_guint8( tvb, offset),
				get_auth_method_name( tvb_get_guint8( tvb, offset)));

		return;
	}					/* handle user/password auth */
	else if (compare_packet( hash_info->user_name_auth_row)) {

						/* process user name	*/
		offset += display_string( tvb, offset, tree,
				"User name");
						/* process password	*/
		offset += display_string( tvb, offset, tree,
				"Password");
	}
					/* command to the server */
					/* command response from server */
	else if ((compare_packet( hash_info->command_row)) ||
	         (compare_packet( hash_info->cmd_reply_row)) ||
	         (compare_packet( hash_info->bind_reply_row))){

		command = tvb_get_guint8(tvb, offset);

		if (compare_packet( hash_info->command_row))
			proto_tree_add_uint( tree, hf_socks_cmd, tvb, offset, 1,
			    command);

		else {
			proto_tree_add_item( tree, hf_socks_results_5, tvb, offset, 1, FALSE);
			proto_tree_add_item_hidden(tree, hf_socks_results, tvb, offset, 1, FALSE);
		}

		++offset;

		proto_tree_add_text( tree, tvb, offset, 1,
			"Reserved: 0x%0x (should = 0x00)", tvb_get_guint8(tvb, offset));
		++offset;

		offset = display_address(tvb, offset, tree);
/*XXX Add remote port for search somehow */
						/* Do remote port	*/
		proto_tree_add_text( tree, tvb, offset, 2,
				"%sPort: %u",
				(compare_packet( hash_info->bind_reply_row) ?
					"Remote Host " : ""),
				 tvb_get_ntohs(tvb, offset));
	}
}



/**************** Decoder State Machines ******************/


static guint
state_machine_v4( socks_hash_entry_t *hash_info, tvbuff_t *tvb,
	int offset, packet_info *pinfo) {

/* Decode V4 protocol.  This is done on the first pass through the 	*/
/* list.  Based upon the current state, decode the packet and determine	*/
/* what the next state should be.  If we had per packet information, 	*/
/* this would be the place to load them up.				*/

	if ( hash_info->state == None) {		/* new connection */

		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO, " Connect to server request");

		hash_info->state = Connecting;	/* change state		*/

		hash_info->command = tvb_get_guint8(tvb, offset + 1);
						/* get remote port	*/
		if ( hash_info->command == CONNECT_COMMAND)
			hash_info->port =  tvb_get_ntohs(tvb, offset + 2);
						/* get remote address	*/

		tvb_memcpy(tvb, (guint8 *)&hash_info->dst_addr, offset + 4, 4);

						/* save the packet pointer */
		hash_info->connect_row = get_packet_ptr;

						/* skip past this stuff	*/
		hash_info->connect_offset = offset + 8;

		offset += 8;

		if ( !tvb_offset_exists(tvb, offset)) {	/* if no user name */
							/* change state */
			hash_info->state = V4UserNameWait;
			/*
			 * XXX - add 1, or leave it alone?
			 * We were adding "strlen(...) + 1".
			 */
			hash_info->connect_offset += 1;
		} else {
			/*
			 * Add in the length of the user name.
			 * XXX - what if the user name is split between
			 * TCP segments?
			 */
			hash_info->connect_offset += tvb_strsize(tvb, offset);
		}

		if ( !hash_info->dst_addr){ 		/* if no dest address */
							/* if more data */
			if ( tvb_offset_exists(tvb, hash_info->connect_offset)) {
/*XXX copy remote name here ??? */
				hash_info->state = Connecting;
			}
			else
				hash_info->state = V4NameWait;
						}
						/* waiting for V4 user name */
	}else if ( hash_info->state == V4UserNameWait){

		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO, " Connect Request (User name)");

		hash_info->v4_user_name_row = get_packet_ptr;
/*XXX may need to check for domain name here */
		hash_info->state = Connecting;
	}
					/* waiting for V4 domain name	*/
	else if ( hash_info->state == V4NameWait){

		hash_info->v4_name_row = get_packet_ptr;
		hash_info->state = Connecting;

	}
	else if ( hash_info->state == Connecting){

		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO, " Connect Response");

						/* save packet pointer 	*/
		hash_info->cmd_reply_row = get_packet_ptr;
		hash_info->state = Done;		/* change state		*/
		offset = offset + 8;
	}

	return offset;
}



static void
state_machine_v5( socks_hash_entry_t *hash_info, tvbuff_t *tvb,
	int offset, packet_info *pinfo) {

/* Decode V5 protocol.  This is done on the first pass through the 	*/
/* list.  Based upon the current state, decode the packet and determine	*/
/* what the next state should be.  If we had per packet information, 	*/
/* this would be the place to load them up.				*/


	int temp;

	if ( hash_info->state == None) {

		if (check_col(pinfo->cinfo, COL_INFO))
			col_append_str(pinfo->cinfo, COL_INFO, " Connect to server request");

		hash_info->state = Connecting;	/* change state		*/
		hash_info->connect_row = get_packet_ptr;

		temp = tvb_get_guint8(tvb, offset + 1);
						/* skip past auth methods */
		offset = hash_info->connect_offset = offset + 1 + temp;
	}
	else if ( hash_info->state == Connecting){

		guint AuthMethod = tvb_get_guint8(tvb, offset + 1);

		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO, " Connect to server response");

		hash_info->auth_method_row = get_packet_ptr;

		if ( AuthMethod == NO_AUTHENTICATION)
			hash_info->state = V5Command;

		else if ( AuthMethod == USER_NAME_AUTHENTICATION)
			hash_info->state = UserNameAuth;

		else if ( AuthMethod == GSS_API_AUTHENTICATION)
/*XXX should be this 		hash_info->state = GssApiAuth; */
			hash_info->state = Done;

		else	hash_info->state = Done;	/*Auth failed or error*/

	}

	else if ( hash_info->state == V5Command) {	/* Handle V5 Command */

		guint temp;

		hash_info->command = tvb_get_guint8(tvb, offset + 1); /* get command */

		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_fstr(pinfo->cinfo, COL_INFO, " Command Request - %s",
	 			get_command_name(hash_info->command));

		hash_info->state = V5Reply;
		hash_info->command_row = get_packet_ptr;

		offset += 3;			/* skip to address type */

		offset = get_address_v5(tvb, offset, hash_info);

		temp = tvb_get_guint8(tvb, offset);

		if (( hash_info->command == CONNECT_COMMAND) ||
		    ( hash_info->command == UDP_ASSOCIATE_COMMAND))
						/* get remote port	*/
			hash_info->port =  tvb_get_ntohs(tvb, offset);
	}

	else if ( hash_info->state == V5Reply) {	/* V5 Command Reply */


		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_fstr(pinfo->cinfo, COL_INFO, " Command Response - %s",
	 			get_command_name(hash_info->command));

		hash_info->cmd_reply_row = get_packet_ptr;

		if (( hash_info->command == CONNECT_COMMAND) ||
		    (hash_info->command == PING_COMMAND) ||
		    (hash_info->command == TRACERT_COMMAND))
			hash_info->state = Done;

		else if ( hash_info->command == BIND_COMMAND)
			hash_info->state = V5BindReply;

		else if ( hash_info->command == UDP_ASSOCIATE_COMMAND){
			offset += 3;		/* skip to address type */
			offset = get_address_v5(tvb, offset, hash_info);

	/* save server udp port and create udp conversation */
			hash_info->udp_port =  tvb_get_ntohs(tvb, offset);

			if (!pinfo->fd->flags.visited)
				new_udp_conversation( hash_info, pinfo);

/*XXX may need else statement to handle unknows and generate error message */

		}
	}
	else if ( hash_info->state == V5BindReply) {	/* V5 Bind Second Reply */

		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO, " Command Response: Bind remote host info");

		hash_info->bind_reply_row = get_packet_ptr;
		hash_info->state = Done;
	}
	else if ( hash_info->state == UserNameAuth) {	/* Handle V5 User Auth*/
		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO,
	 			" User authentication response");

		hash_info->user_name_auth_row = get_packet_ptr;
		hash_info->state = AuthReply;

	}
	else if ( hash_info->state == AuthReply){	/* V5 User Auth reply */
		hash_info->cmd_reply_row = get_packet_ptr;
		if (check_col(pinfo->cinfo, COL_INFO))
	 		col_append_str(pinfo->cinfo, COL_INFO, " User authentication reply");
		hash_info->state = V5Command;
	}
}



static void
display_ping_and_tracert(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree, socks_hash_entry_t *hash_info) {

/* Display the ping/trace_route conversation */


       	const guchar    *data, *dataend;
       	const guchar   *lineend, *eol;
       	int             linelen;

					/* handle the end command */
       	if ( pinfo->destport == TCP_PORT_SOCKS){
		if (check_col(pinfo->cinfo, COL_INFO))
			col_append_str(pinfo->cinfo, COL_INFO, ", Terminate Request");

		if ( tree)
  			proto_tree_add_text(tree, tvb, offset, 1,
   				(hash_info->command  == PING_COMMAND) ?
	 			"Ping: End command" :
	   	 		"Traceroute: End command");
	}
       	else{ 		/* display the PING or Traceroute results */
		if (check_col(pinfo->cinfo, COL_INFO))
			col_append_str(pinfo->cinfo, COL_INFO, ", Results");

		if ( tree){
			proto_tree_add_text(tree, tvb, offset, -1,
   		 		(hash_info->command  == PING_COMMAND) ?
   		 		"Ping Results:" :
   	 			"Traceroute Results");

  	      		data = tvb_get_ptr(tvb, offset, -1);
        		dataend = data + tvb_length_remaining(tvb, offset);

       	        	while (data < dataend) {

              			lineend = find_line_end(data, dataend, &eol);
                		linelen = lineend - data;

       		                proto_tree_add_text( tree, tvb, offset, linelen,
       		                	"%s", format_text(data, linelen));
               		        offset += linelen;
                       		data = lineend;
                       	}
		}
	}
}



static void call_next_dissector(tvbuff_t *tvb, int offset, packet_info *pinfo,
	proto_tree *tree, socks_hash_entry_t *hash_info) {

/* Display the results for PING and TRACERT extensions or		*/
/* Call TCP dissector for the port that was passed during the	    	*/
/* connect process  						     	*/
/* Load pointer to pinfo->XXXport depending upon the direction,		*/
/* change pinfo port to the remote port, call next dissecotr to decode	*/
/* the payload, and restore the pinfo port after that is done.		*/

	guint32 *ptr;

 	if (( hash_info->command  == PING_COMMAND) ||
 	    ( hash_info->command  == TRACERT_COMMAND))

		display_ping_and_tracert(tvb, offset, pinfo, tree, hash_info);

   	else {		/* call the tcp port decoder to handle the payload */

/*XXX may want to load dest address here */

 		if ( pinfo->destport  == TCP_PORT_SOCKS)
        		ptr = &pinfo->destport;
	   	else
        		ptr = &pinfo->srcport;

	        *ptr = hash_info->port;

/* 2003-09-18 JCFoster Fixed problem with socks tunnel in socks tunnel */

		in_socks_dissector_flag = 1; /* avoid recursive overflow */

		decode_tcp_ports( tvb, offset, pinfo, tree, pinfo->srcport, pinfo->destport);

		in_socks_dissector_flag = 0; /* avoid recursive overflow */

	        *ptr = TCP_PORT_SOCKS;
	}
}



static void
dissect_socks(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) {

	int 		offset = 0;
	proto_tree      *socks_tree;
	proto_item      *ti;
	socks_hash_entry_t *hash_info;
	conversation_t *conversation;

/* 2003-09-18 JCFoster Fixed problem with socks tunnel in socks tunnel */

	/* avoid recursive overflow */

	if ( in_socks_dissector_flag) {
		return;
	}

	conversation = find_conversation( &pinfo->src, &pinfo->dst, pinfo->ptype,
		pinfo->srcport, pinfo->destport, 0);

	if ( !conversation){
		conversation = conversation_new( &pinfo->src, &pinfo->dst, pinfo->ptype,
			pinfo->srcport, pinfo->destport, 0);
	}
	hash_info = conversation_get_proto_data(conversation,proto_socks);
	if ( !hash_info){
    		hash_info = g_mem_chunk_alloc(socks_vals);
		hash_info->start_done_row = G_MAXINT;
    		hash_info->state = None;
		hash_info->port = 0;
		hash_info->version = tvb_get_guint8(tvb, offset); /* get version*/

		if (( hash_info->version != 4) && 	/* error test version */
		   ( hash_info->version != 5))
    			hash_info->state = Done;

		conversation_add_proto_data(conversation, proto_socks,
			hash_info);

						/* set dissector for now */
		conversation_set_dissector(conversation, socks_handle);
	}

/* display summary window information  */

	if (check_col(pinfo->cinfo, COL_PROTOCOL))
		col_set_str(pinfo->cinfo, COL_PROTOCOL, "Socks");

	if (check_col(pinfo->cinfo, COL_INFO)){
		if (( hash_info->version == 4) || ( hash_info->version == 5)){
			col_add_fstr(pinfo->cinfo, COL_INFO, "Version: %d",
				hash_info->version);
		}
		else			/* unknown version display error */
			col_set_str(pinfo->cinfo, COL_INFO, "Unknown");


		if ( hash_info->command == PING_COMMAND)
			col_append_str(pinfo->cinfo, COL_INFO, ", Ping Req");
		if ( hash_info->command == TRACERT_COMMAND)
			col_append_str(pinfo->cinfo, COL_INFO, ", Traceroute Req");

/*XXX		if ( hash_info->port != -1) */
		if ( hash_info->port != 0)
			col_append_fstr(pinfo->cinfo, COL_INFO, ", Remote Port: %u",
				hash_info->port);
	}


/* run state machine if needed */

	if ((hash_info->state != Done) && ( !pinfo->fd->flags.visited)){

		if ( hash_info->version == 4)
			state_machine_v4( hash_info, tvb, offset, pinfo);

		else if ( hash_info->version == 5)
			state_machine_v5( hash_info, tvb, offset, pinfo);

		if (hash_info->state == Done) { 	/* if done now 	*/
			hash_info->start_done_row = pinfo->fd->num;
		}
	}

/* if proto tree, decode and display */

	if (tree) {
    		ti = proto_tree_add_item( tree, proto_socks, tvb, offset, -1,
    			FALSE );

		socks_tree = proto_item_add_subtree(ti, ett_socks);

		if ( hash_info->version == 4)
			display_socks_v4(tvb, offset, pinfo, socks_tree,
				hash_info);

		else if ( hash_info->version == 5)
			display_socks_v5(tvb, offset, pinfo, socks_tree,
				hash_info);

				/* if past startup, add the faked stuff */
		if ( pinfo->fd->num >  hash_info->start_done_row){
						/*  add info to tree */
        		proto_tree_add_text( socks_tree, tvb, offset, 0,
        			"Command: %d (%s)", hash_info->command,
				get_command_name(hash_info->command));

			proto_tree_add_ipv4( socks_tree, hf_socks_ip_dst, tvb,
					offset, 0, hash_info->dst_addr);

				/* no fake address for ping & traceroute */

			if (( hash_info->command != PING_COMMAND) &&
			    ( hash_info->command != TRACERT_COMMAND)){
				proto_tree_add_uint( socks_tree, hf_socks_dstport, tvb,
					offset, 0, hash_info->port);
			}
		}

	}


/* call next dissector if ready */

	if ( pinfo->fd->num > hash_info->start_done_row){
		call_next_dissector(tvb, offset, pinfo, tree, hash_info);
	}
}



static void socks_reinit( void){

/* Do the cleanup work when a new pass through the packet list is	*/
/* performed. Reset the highest row seen counter and re-initialize the	*/
/* conversation memory chunks.						*/

  	if (socks_vals)
    		g_mem_chunk_destroy(socks_vals);

  	socks_vals = g_mem_chunk_new("socks_vals", socks_hash_val_length,
		socks_hash_init_count * socks_hash_val_length,
		G_ALLOC_AND_FREE);
}


void
proto_register_socks( void){

/*** Prep the socks protocol, register it and a initialization routine  */
/*	to clear the hash stuff.					*/


	static gint *ett[] = {
		&ett_socks,
		&ett_socks_auth,
		&ett_socks_name

	};

  	static hf_register_info hf[] = {


		{ &hf_socks_ver,
			{ "Version", "socks.version", FT_UINT8, BASE_DEC, NULL,
			 	0x0, "", HFILL
			}
		},
		{ &hf_socks_ip_dst,
			{ "Remote Address", "socks.dst", FT_IPv4, BASE_NONE, NULL,
			 	0x0, "", HFILL
			}
		},
		{ &hf_socks_ip6_dst,
			{ "Remote Address(ipv6)", "socks.dstV6", FT_IPv6, BASE_NONE, NULL,
			 	0x0, "", HFILL
			}
		},

                { &hf_user_name,
                	{ "User Name", "socks.username", FT_STRING, BASE_NONE,
                		 NULL, 0x0, "", HFILL
                	}
                },
		{ &hf_socks_dstport,
			{ "Remote Port", "socks.dstport", FT_UINT16,
				BASE_DEC, NULL, 0x0, "", HFILL
			}
		},
		{ &hf_socks_cmd,
			{ "Command", "socks.command", FT_UINT8,
				BASE_DEC,  VALS(cmd_strings), 0x0, "", HFILL
			}
		},
		{ &hf_socks_results_4,
			{ "Results(V4)", "socks.results_v4", FT_UINT8,
				BASE_DEC, VALS(reply_table_v4), 0x0, "", HFILL
			}
		},
		{ &hf_socks_results_5,
			{ "Results(V5)", "socks.results_v5", FT_UINT8,
				BASE_DEC, VALS(reply_table_v5), 0x0, "", HFILL
			}
		},
		{ &hf_socks_results,
			{ "Results(V5)", "socks.results", FT_UINT8,
				BASE_DEC, NULL, 0x0, "", HFILL
			}
		}

	};


   	proto_socks = proto_register_protocol (
   		"Socks Protocol", "Socks", "socks");

	proto_register_field_array(proto_socks, hf, array_length(hf));
	proto_register_subtree_array(ett, array_length(ett));

	register_init_routine( &socks_reinit);	/* register re-init routine */

	socks_udp_handle = create_dissector_handle(socks_udp_dissector,
	    proto_socks);
	socks_handle = create_dissector_handle(dissect_socks, proto_socks);
}


void
proto_reg_handoff_socks(void) {

	/* dissector install routine */

 	dissector_add("tcp.port", TCP_PORT_SOCKS, socks_handle);
}