-
Notifications
You must be signed in to change notification settings - Fork 11
/
zebedee.c
9064 lines (7633 loc) · 223 KB
/
zebedee.c
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
/*
** This file is part of "zebedee".
**
** Copyright 1999-2005 by Neil Winton. All rights reserved.
**
** 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., 675 Mass Ave, Cambridge, MA 02139, USA.
**
** For further details on "zebedee" see http://www.winton.org.uk/zebedee/
**
*/
char *zebedee_c_rcsid = "$Id: zebedee.c,v 1.49 2005-09-02 22:20:23 ndwinton Exp $";
#define RELEASE_STR "2.5.7"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <errno.h>
#include <time.h>
#include <ctype.h>
#include <fcntl.h>
#include <signal.h>
#ifdef USE_GMP_LIBRARY
#include "gmp.h"
#else
#include "huge.h"
/*
** Zebedee originally used the GMP library (and this can still be enabled
** by defining USE_GMP_LIBRARY) but for reasons of portability it now uses
** the "Huge" number routines bundled with the Zebedee distribution. GMP
** is a very high-quality library but is hard to port to non-UN*X/gcc
** environments.
**
** The function calls used in the code are, however, still GMP-compatible
** through the use of the following macro definitions.
*/
typedef Huge *mpz_t;
#define mpz_init(z)
#define mpz_init_set_str(z, s, n) (z = huge_from_string(s, NULL, n))
#define mpz_powm(k, g, e, m) (k = huge_powmod(g, e, m))
#define mpz_get_str(p, n, z) huge_format(z, n)
#define mpz_clear(z) huge_free(z)
#endif
#include "blowfish.h"
#include "zlib.h"
#ifndef DONT_HAVE_BZIP2
#include "bzlib.h"
#endif
#include "sha.h"
#ifdef __CYGWIN__
#undef WIN32
#endif
/*
** Named mutex values (see mutexLock/Unlock)
*/
#define MUTEX_IO 0 /* Mutex to protect stdio and other library calls */
#define MUTEX_KEYLIST 1 /* Mutex to protect key list access */
#define MUTEX_TOKEN 2 /* Mutex to protect token allocation/access */
#define MUTEX_HNDLIST 3 /* Mutex to protect UDP handler list access */
#define MUTEX_ACTIVE 4 /* Mutex to protect count of active handlers */
#define MUTEX_MAX 5 /* How many mutexes will we use? */
/*
** Named condition variables
*/
#define COND_ACTIVE 0 /* Condition for change in active handler count */
#define COND_MAX 1 /* How many condition variables? */
/* BUG COMPATIBILITY -- REMOVE FOR PRODUCTION RELEASE */
#define BUGHTONL(x) (BugCompatibility == 251 ? (x) : htonl(x))
#define BUGNTOHL(x) (BugCompatibility == 251 ? (x) : ntohl(x))
#ifdef WIN32
/*
** Windows-specific include files and macros
*/
#ifndef FD_SETSIZE
/*
** This allows us to manipulate up to 512 sockets in a select call (i.e.
** handle up to about 250 simultaneous tunnels). It can be overridden at
** compile time.
*/
#define FD_SETSIZE 512
#endif
#include <windows.h>
#include <io.h>
#include <winsock.h>
#include <process.h>
#include <mmsystem.h>
#include "getopt.h"
#define DFLT_SHELL "c:\\winnt\\system32\\cmd.exe"
#define getpid() GetCurrentProcessId()
#define FILE_SEP_CHAR '\\'
#define snprintf _snprintf
#define vsnprintf _vsnprintf
#define strcasecmp _stricmp
#define ETIMEDOUT WSAETIMEDOUT
#define EWOULDBLOCK WSAEWOULDBLOCK
#define EINPROGRESS WSAEINPROGRESS
/*
** Winsock state data
*/
static struct WSAData WsaState;
/*
** Global Mutexes and Condition Variables
*/
CRITICAL_SECTION Mutex[MUTEX_MAX];
HANDLE Condition[COND_MAX];
extern void svcRun(char *name, VOID (*function)(VOID *), VOID *arg);
extern int svcInstall(char *name, char *configFile);
extern int svcRemove(char *name);
#else /* !WIN32 */
#include <sys/types.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/socket.h>
#ifndef DONT_HAVE_SELECT_H
#include <sys/select.h>
#endif
#include <sys/stat.h>
#include <sys/wait.h>
#include <dirent.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <syslog.h>
#ifdef USE_UDP_SPOOFING
#include <libnet.h>
#endif
#include <pwd.h>
#ifndef INADDR_NONE
#define INADDR_NONE 0xffffffff
#endif
#ifdef USE_IPv6
#ifndef s6_addr32
#ifdef __sun__
#define s6_addr32 _S6_un._S6_u32
#endif /* __sun__ */
#if defined(__FreeBSD__) || defined(__APPLE__)
#define s6_addr32 __u6_addr.__u6_addr32
#endif /* defined(__FreeBSD__) || defined(__APPLE__) */
#endif /* s6_addr32 */
#endif /* USE_IPv6 */
#define DFLT_SHELL "/bin/sh"
#define FILE_SEP_CHAR '/'
#define closesocket(fd) close((fd))
#ifdef HAVE_PTHREADS
#include <pthread.h>
pthread_mutex_t Mutex[MUTEX_MAX];
pthread_cond_t Condition[COND_MAX];
pthread_attr_t ThreadAttr;
#endif
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
/**************************\
** **
** Constants and Macros **
** **
\**************************/
#define MAX_BUF_SIZE 16383 /* Maximum network buffer size (< 2^14) */
#define DFLT_BUF_SIZE 8192 /* Default network buffer size */
#define MAX_LINE_SIZE 1024 /* Maximum file line size */
#define MAX_KEY_BYTES ((BF_ROUNDS + 2)*4) /* Maximum size of Blowfish key */
#define MIN_KEY_BYTES 5 /* Minimum key length */
#define MAX_LISTEN 5 /* Depth of listen queue */
#define MAX_INCLUDE 5 /* Maximum depth of include files */
#define MAX_KEYGEN_LEVEL 2 /* Maximum key generation strength level */
#define HASH_STR_SIZE 41 /* Size of SHA hash string including null */
#define TIMESTAMP_SIZE 20 /* Size of YYYY-dd-mm-HH:MM:SS timestamp */
#define CHALLENGE_SIZE 4 /* Size of challenge data */
#define THE_ANSWER 42 /* To Life, the Universe and Everything */
#define CHALLENGE_SIZE 4 /* Size of challenge data */
#define NONCE_SIZE 8 /* Size of nonce data */
#ifndef THREAD_STACK_SIZE
#define THREAD_STACK_SIZE 65536 /* Stack size for threads */
#endif
#define MIN_THREAD_STACK_KB 16 /* Minimum allowable thread stack in kb */
#define CMP_OVERHEAD 250 /* Maximum overhead on 16k message */
#define CMP_MINIMUM 32 /* Minimum message size to attempt compression */
#if defined(USE_IPv6)
#define IP_BUF_SIZE INET6_ADDRSTRLEN /* Size of buffer for IP address string */
#else
#define IP_BUF_SIZE 16 /* Size of buffer for IP address string */
#endif
/*
** Information about the compression algorithm and level is encoded in
** a single unsigned short value. The high 8 bits are the algorithm and
** the low eight bits the level. Note that the values used ensure that
** taken as a 16-bit quantity all bzip2 values are greater than all
** zlib values. This fact is used so that, in effect, bzip2 compression
** is considered "stronger" than zlib.
*/
#define CMPTYPE_ZLIB 0x0
#define CMPTYPE_BZIP2 0x1
#define GET_CMPTYPE(z) (((z) >> 8) & 0xff)
#define SET_CMPTYPE(z, t) ((z) | ((t) << 8))
#define GET_CMPLEVEL(z) ((z) & 0xff)
#define SET_CMPLEVEL(z, l) ((z) | ((l) & 0xff))
/*
** Each message that Zebedee transmits is preceded by an unsigned short
** value (in big-endian format). The top two bits flag whether the message
** is encrypted and compressed. The lower 14 bits define the payload size
** (which must be no greater than MAX_BUF_SIZE).
*/
#define FLAG_COMPRESSED 0x1
#define FLAG_ENCRYPTED 0x2
#define CHECKSUM_NONE 0
#define CHECKSUM_ADLER 1
#define CHECKSUM_CRC32 2
#define CHECKSUM_SHA 3
#define CHECKSUM_MAX CHECKSUM_SHA
#define CHECKSUM_ADLER_LEN 4 /* ADLER32 32-bit checksum */
#define CHECKSUM_CRC32_LEN 4 /* CRC32 32-bit checksum */
#define CHECKSUM_SHA_LEN 20 /* SHA 160-bit message digest */
#define CHECKSUM_MAX_LEN CHECKSUM_SHA_LEN /* Max message digest */
#define CHECKSUM_INVALID 0xffff
#define GET_FLAGS(x) (((x) >> 14) & 0x3)
#define SET_FLAGS(x, f) ((x) | ((f) << 14))
#define GET_SIZE(x) ((x) & 0x3fff)
#define DFLT_GENERATOR "2" /* Default generator value */
#define DFLT_MODULUS /* Default modulus value */ \
"f488fd584e49dbcd20b49de49107366b336c380d451d0f7c88b31c7c5b2d8ef6" \
"f3c923c043f0a55b188d8ebb558cb85d38d334fd7c175743a31d186cde33212c" \
"b52aff3ce1b1294018118d7c84a70a72d686c40319c807297aca950cd9969fab" \
"d00a509b0246d3083d66a45d419f9c7cbd894b221926baaba25ec355e92f78c7"
#define DFLT_CMP_LEVEL SET_CMPLEVEL(CMPTYPE_ZLIB, 6)
#define DFLT_KEY_BITS 128 /* Default key size */
#define DFLT_TCP_PORT 0x2EBD /* Port on which TCP-mode server listens */
#define DFLT_UDP_PORT 0x2BDE /* Port on which UDP-mode server listens */
#define DFLT_KEY_LIFETIME 3600 /* Reuseable keys last an hour */
#define DFLT_TCP_TIMEOUT 0 /* Default never close idle TCP tunnels */
#define DFLT_UDP_TIMEOUT 300 /* Close UDP tunnels after 5 mins */
#define DFLT_CONNECT_TIMEOUT 300 /* Timeout for making/accepting connection */
#define PROTOCOL_V100 0x0100 /* The original and base */
#define PROTOCOL_V101 0x0101 /* Extended buffer size */
#define PROTOCOL_V102 0x0102 /* Optionally omit key exchange */
#define PROTOCOL_V200 0x0200 /* Header, UDP and reusable key support */
#define PROTOCOL_V201 0x0201 /* Remote target selection (IPv4 only) */
#define PROTOCOL_V202 0x0202 /* Lock of protocol negotiation, checksum and source based targetting */
#define PROTOCOL_V203 0x0203 /* Support IPv6 address format for remote target selection */
#if defined(USE_IPv6)
#define DFLT_PROTOCOL PROTOCOL_V203
#define ADDR_FAMILY_IP4 0x0
#define ADDR_FAMILY_IP6 0x1
#else
#define DFLT_PROTOCOL PROTOCOL_V202
#endif
#define TOKEN_NEW 0xffffffff /* Request new token allocation */
#define TOKEN_EXPIRE_GRACE 10 /* CurrentToken valid until this close to expiry */
#define HDR_SIZE_V200 22 /* Size of V200 protocol header message */
#define HDR_SIZE_V201 26 /* Size of V201 protocol header message */
#define HDR_SIZE_V202 28 /* Size of V202 protocol header message */
#define HDR_SIZE_V203 (HDR_SIZE_V202 - 4 + 2 + 16) /* Size of V203 protocol header message */
#define HDR_SIZE_MIN HDR_SIZE_V200
#define HDR_SIZE_MAX HDR_SIZE_V203
#define HDR_OFFSET_FLAGS 0 /* Offset of flags (TCP vs UDP) */
#define HDR_OFFSET_MAXSIZE 2 /* Offset of max message size */
#define HDR_OFFSET_CMPINFO 4 /* Offset of compression info */
#define HDR_OFFSET_PORT 6 /* Offset of port request */
#define HDR_OFFSET_KEYLEN 8 /* Offset of key length */
#define HDR_OFFSET_TOKEN 10 /* Offset of key token */
#define HDR_OFFSET_NONCE 14 /* Offset of nonce value */
#define HDR_OFFSET_TARGET 22 /* Offset of target host address */
#if defined(USE_IPv6)
#define HDR_OFFSET_CHECKSUM_V203 (26 - 4 + sizeof(sa_family_t) + 16) /* Offset of checksum type */
#endif
#define HDR_OFFSET_CHECKSUM 26 /* Offset of checksum type */
#define HDR_FLAG_UDPMODE 0x1 /* Operate in UDP mode */
#define ENDPTLIST_TCP 0x1 /* TCP-type port list */
#define ENDPTLIST_UDP 0x2 /* UDP-type port list */
#define ENDPTLIST_ANY (ENDPTLIST_TCP | ENDPTLIST_UDP)
/***************************\
** **
** Data Type Definitions **
** **
\***************************/
/*
** This puts different kinds of IP addresses in one place.
** Here we can put IPv4 and IPv6 addresses.
*/
typedef union sockaddr_union {
struct sockaddr sa;
struct sockaddr_in in;
#if defined(USE_IPv6)
struct sockaddr_in6 in6;
#endif
} SOCKADDR_UNION;
/*
** The BFState_t structure holds all the state information necessary
** to encrypt one data-stream (unidirectional).
*/
#define INIT_IVEC "Time4Bed" /* ... said Zebedee. Boing! */
typedef struct
{
BF_KEY key;
unsigned char iVec[8];
int pos;
unsigned char cryptBuf[MAX_BUF_SIZE];
}
BFState_t;
/*
** The EndPtList_t structure holds the information about a network end-point,
** or range of similar end-point with ports from "lo" to "hi". A single
** end-point value has both hi and lo set the same. A linked list of these
** structures holds information about a set of ranges.
**
** The host element holds the name of the host associated with the end-
** point, addr the matching IP address and addrList, a list of alias
** addresses. The mask is used if an address mask was specified. The type
** is a bitmask combination of ENDPTLIST_TCP and ENDPTLIST_UDP. The idFile
** is the name of the identity file that should be checked for connections
** to this endpoint. If peer is not NULL then it is a list of valid
** peer connections for this endpoint.
*/
typedef struct EndPtList_s
{
unsigned short lo;
unsigned short hi;
char *host;
SOCKADDR_UNION addr;
SOCKADDR_UNION *addrList;
struct EndPtList_s *next;
unsigned short mask;
unsigned short type;
char *idFile;
struct EndPtList_s *peer;
}
EndPtList_t;
/*
** The MsgBuf_t is the general buffer used by the low-level readMessage
** and writeMessage routines. It holds (nearly) all of the state for
** a single connection.
*/
typedef struct MsgBuf_s
{
unsigned short maxSize; /* Max size of data buffer read/writes */
unsigned short size; /* Size of current message */
unsigned char data[MAX_BUF_SIZE + CHECKSUM_MAX_LEN]; /* Data buffer */
unsigned char tmp[MAX_BUF_SIZE + CMP_OVERHEAD + CHECKSUM_MAX_LEN]; /* Temporary work space */
unsigned short cmpInfo; /* Compression level and type */
BFState_t *bfRead; /* Encryption context for reads */
BFState_t *bfWrite; /* Encryption context for writes */
unsigned long readCount; /* Number of reads */
unsigned long bytesIn; /* Actual data bytes from network */
unsigned long expBytesIn; /* Expanded data bytes in */
unsigned long writeCount; /* Number of writes */
unsigned long bytesOut; /* Actual data bytes to network */
unsigned long expBytesOut; /* Expanded data bytes out */
unsigned short checksumLevel; /* Current checksum mode, 0 if none */
unsigned short checksumLen; /* Current checksum length, 0 if none */
unsigned char inSeed[CHECKSUM_MAX_LEN]; /* Seed for input checksum */
unsigned char outSeed[CHECKSUM_MAX_LEN]; /* Seed for output checksum */
}
MsgBuf_t;
/*
** These enumerated type values are used to indicate the destination of
** log messages.
*/
typedef enum
{
LOGFILE_NULL,
LOGFILE_SYSLOG,
LOGFILE_LOCAL
}
LogType_t;
/*
** The KeyInfo_t structure holds the mapping between a key "token" value
** used to request the reuse of a previously established shared secret
** key and the key value itself. These structures are strung together in
** a doubly linked list.
*/
typedef struct KeyInfo_s
{
unsigned long token;
char *key;
time_t expiry;
struct KeyInfo_s *prev;
struct KeyInfo_s *next;
}
KeyInfo_t;
/*
** This structure is used to pass the arguments to the main "handler"
** thread routines (client() and server()).
*/
typedef struct FnArgs_s
{
int fd;
unsigned short port;
SOCKADDR_UNION addr;
int listenFd;
int inLine;
int udpMode;
}
FnArgs_t;
/*
** This structure is used in UDP mode to find the local socket for
** the handler for traffic coming from a specific client.
*/
typedef struct HndInfo_s
{
unsigned long id;
int fd;
SOCKADDR_UNION fromAddr;
SOCKADDR_UNION localAddr;
struct HndInfo_s *prev;
struct HndInfo_s *next;
}
HndInfo_t;
/*****************\
** **
** Global Data **
** **
\*****************/
/*
** Note: Although this data is global most of it is not protected by mutex
** locks because once set in the start-up phases of the program it is
** read-only by the rest of the routines.
*/
FILE *LogFileP = NULL; /* File handle for log file (NULL => stderr) */
LogType_t LogFileType = LOGFILE_LOCAL; /* Type of log file */
unsigned short LogLevel = 1; /* Message verbosity level */
char *Program = "zebedee"; /* Program name (argv[0]) */
char *Generator = ""; /* DH generator hex string ("" => default) */
char *Modulus = ""; /* DH modulus hex string ("" => default) */
char *PrivateKey = NULL; /* Private key hex string */
unsigned short KeyLength = DFLT_KEY_BITS; /* Key length in bits */
unsigned short MinKeyLength = 0; /* Minimum allowed key length */
unsigned short CompressInfo = DFLT_CMP_LEVEL; /* Compression type and level */
int IsDetached = 1; /* Flag true if program should run detached */
int IsServer = 0; /* Flag true if program is a server */
int Debug = 0; /* Debug mode -- single threaded server */
char *CommandString = NULL; /* Command string to execute (client) */
unsigned short ServerPort = 0; /* Port on which server listens */
EndPtList_t *ClientPorts = NULL; /* Ports on which client listens */
EndPtList_t *TargetPorts = NULL; /* Target port to which to tunnel */
char *ServerHost = NULL; /* Name of host on which server runs */
char *TargetHost = "localhost"; /* Default host to which tunnels are targeted */
char *IdentityFile = NULL; /* Name of identity file to check, if any */
EndPtList_t *AllowedTargets = NULL; /* List of allowed target hosts/ports */
EndPtList_t *AllowedDefault = NULL; /* List of default allowed redirection ports */
EndPtList_t *AllowedPeers = NULL; /* List of allowed peer addresses/ports */
char *KeyGenCmd = NULL; /* Key generator command string */
unsigned short KeyGenLevel = MAX_KEYGEN_LEVEL; /* Key generation strength level */
int LockProtocol = 0; /* Is procol negotiation locked? */
int DropUnknownProtocol = 0; /* Allow any request? */
int TimestampLog = 0; /* Should messages have timestamps? */
int MultiUse = 1; /* Client handles multiple connections? */
unsigned short MaxBufSize = DFLT_BUF_SIZE; /* Maximum buffer size */
unsigned long CurrentToken = 0; /* Client reuseable key token */
unsigned short KeyLifetime = DFLT_KEY_LIFETIME; /* Key lifetime in seconds */
unsigned short ChecksumLevel = CHECKSUM_CRC32; /* Type of checksum embedded in the message. Default CRC32 */
unsigned short MinChecksumLevel = CHECKSUM_NONE;
int UdpMode = 0; /* Run in UDP mode */
int TcpMode = 1; /* Run in TCP mode */
unsigned short TcpTimeout = DFLT_TCP_TIMEOUT; /* TCP inactivity timeout */
unsigned short UdpTimeout = DFLT_UDP_TIMEOUT; /* UDP inactivity timeout */
char *SourceIp = NULL; /* source IP address */
char *ListenIp = NULL; /* IP address on which to listen */
int ListenMode = 0; /* True if client waits for server connection */
char *ClientHost = NULL; /* Server initiates connection to client */
int ListenSock = -1; /* Socket on which to listen for server */
unsigned short ServerConnectTimeout = DFLT_CONNECT_TIMEOUT; /* Timeout for server connections */
unsigned short AcceptConnectTimeout = DFLT_CONNECT_TIMEOUT; /* Timeout for client to accept connections */
unsigned short TargetConnectTimeout = DFLT_CONNECT_TIMEOUT; /* Timeout for connection to target */
unsigned short ConnectAttempts = 1; /* Number of server-initiated connection attempts */
unsigned short ReadTimeout = 0; /* Timeout for remote data reads */
int ActiveCount = 0; /* Count of active handlers */
char *ProxyHost = NULL; /* HTTP proxy host, if used */
char *ProxyAuth = NULL; /* HTTP proxy username:password, if used */
unsigned short ProxyPort = 0; /* HTTP proxy port, if used */
int Transparent = 0; /* Try to propagate the client IP address */
char *FieldSeparator = NULL; /* Input field separator character */
char *SharedKey = NULL; /* Static shared secret key */
char *SharedKeyGenCmd = NULL; /* Command to generate shared secret key */
int DumpData = 0; /* Dump out message contents only if true */
#ifndef WIN32
uid_t ProcessUID = -1; /* User id to run zebedee process if started as root */
gid_t ProcessGID = -1; /* Group id to run zebedee process if started as root */
#endif
long ThreadStackSize = THREAD_STACK_SIZE; /* As it says */
unsigned short BugCompatibility = 0; /* Be nice to development users */
unsigned short MaxConnections = 0; /* Maximum number of simultaneous connections */
int IPv4Only = 0;
extern char *optarg; /* From getopt */
extern int optind; /* From getopt */
/*
** The following global data-structure ARE modified during normal operation
** and are protected by mutexes.
**
** The ClientKeyList and ServerKeyList are protected by the MUTEX_KEYLIST
** and the HandlerList by MUTEX_HNDLIST.
*/
KeyInfo_t ClientKeyList = { 0, NULL, (time_t)0, NULL, NULL };
/* Client-side list of token->key mappings */
KeyInfo_t ServerKeyList = { 0, NULL, (time_t)0, NULL, NULL };
/* Server-side list of token->key mappings */
HndInfo_t HandlerList; /* List of address to handler mappings */
/*************************\
** **
** Function Prototypes **
** **
\*************************/
void threadInit(void);
void mutexInit(void);
void mutexLock(int num);
void mutexUnlock(int num);
void conditionInit(void);
void conditionSignal(int num);
void conditionWait(int condNum, int mutexNum);
unsigned long threadPid(void);
unsigned long threadTid(void);
int incrActiveCount(int num);
void waitForInactivity(void);
void logToSystemLog(unsigned short level, char *msg);
void timestamp(char *timeBuf, int local);
void message(unsigned short level, int err, char *fmt, ...);
void dumpData(const char *prefix, unsigned char *data, unsigned short size);
int readData(int fd, unsigned char *buffer, unsigned short size);
int readUShort(int fd, unsigned short *resultP);
int writeData(int fd, unsigned char *buffer, unsigned short size);
int writeUShort(int fd, unsigned short value);
MsgBuf_t *makeMsgBuf(unsigned short maxSize, unsigned short cmpInfo, unsigned short checksumLevel);
void freeMsgBuf(MsgBuf_t *msg);
void getMsgBuf(MsgBuf_t *msg, void *buffer, unsigned short size);
void setMsgBuf(MsgBuf_t *msg, void *buffer, unsigned short size);
int readMessage(int fd, MsgBuf_t *msg, unsigned short thisSize);
int writeMessage(int fd, MsgBuf_t *msg);
int requestResponse(int fd, unsigned short request, unsigned short *responseP);
int getHostAddress(const char *host, SOCKADDR_UNION *addrP, SOCKADDR_UNION **addrList, unsigned short *maskP);
char *ipString(SOCKADDR_UNION addr, char *buf);
int makeConnection(const char *host, const unsigned short port, int udpMode, int useProxy, SOCKADDR_UNION *fromAddrP, SOCKADDR_UNION *toAddrP, unsigned short timeout);
int proxyConnection(const char *host, const unsigned short port, SOCKADDR_UNION *localAddrP, unsigned short timeout);
int sendSpoofed(int fd, char *buf, int len, SOCKADDR_UNION *toAddrP, SOCKADDR_UNION *fromAddrP);
int makeListener(unsigned short *portP, char *listenIp, int udpMode, int listenQueue);
void setNoLinger(int fd);
void setKeepAlive(int fd);
void setNonBlocking(int fd, unsigned long nonBlock);
int acceptConnection(int listenFd, const char *host, int loop, unsigned short timeout);
int socketIsUsable(int sock);
void headerSetUShort(unsigned char *hdrBuf, unsigned short value, int offset);
void headerSetULong(unsigned char *hdrBuf, unsigned long value, int offset);
unsigned short headerGetUShort(unsigned char *hdrBuf, int offset);
unsigned long headerGetULong(unsigned char *hdrBuf, int offset);
BFState_t *setupBlowfish(char *keyStr, unsigned short keyBits);
char *generateKey(SOCKADDR_UNION *peerAddrP, SOCKADDR_UNION *targetAddrP, unsigned short targetPort);
char *runKeyGenCommand(char *keyGenCmd, SOCKADDR_UNION *peerAddrP, SOCKADDR_UNION *targetAddrP, unsigned short targetPort);
void generateNonce(unsigned char *);
char *generateSessionKey(char *secretKey, unsigned char *cNonce, unsigned char *sNonce, unsigned short bits);
unsigned short hexStrToBits(char *hexStr, unsigned short bits, unsigned char *bitVec);
char *diffieHellman(char *genStr, char *modStr, char *expStr);
void makeChallenge(unsigned char *challenge);
void challengeAnswer(unsigned char *challenge);
int clientPerformChallenge(int serverFd, MsgBuf_t *msg);
int serverPerformChallenge(int clientFd, MsgBuf_t *msg);
void freeKeyInfo(KeyInfo_t *info);
char *findKeyByToken(KeyInfo_t *list, unsigned long token, SOCKADDR_UNION *peerAddrP, SOCKADDR_UNION *targetAddrP, unsigned short targetPort);
void addKeyInfoToList(KeyInfo_t *list, unsigned long token, char *key);
unsigned long generateToken(KeyInfo_t *list, unsigned long oldToken);
unsigned long getCurrentToken(void);
int spawnCommand(unsigned short port, char *cmdFormat);
int filterLoop(int localFd, int remoteFd, MsgBuf_t *msgBuf,
SOCKADDR_UNION *toAddrP, SOCKADDR_UNION *fromAddrP,
int replyFd, int udpMode);
void hashStrings(char *hashBuf, ...);
void hashFile(char *hashBuf, char *fileName);
int checkIdentity(char *idFile, char *generator, char *modulus, char *key);
char *generateIdentity(char *generator, char *modulus, char *exponent);
unsigned long spawnHandler(void (*handler)(FnArgs_t *), int listenFd, int clientFd, int inLine, SOCKADDR_UNION *addrP, int udpMode);
int findHandler(SOCKADDR_UNION *fromAddrP, SOCKADDR_UNION *localAddrP);
void addHandler(SOCKADDR_UNION *fromAddrP, unsigned long id, int fd, SOCKADDR_UNION *localAddrP);
void removeHandler(SOCKADDR_UNION *addrP);
void clientListener(EndPtList_t *localPorts);
int makeClientListeners(EndPtList_t *ports, fd_set *listenSetP, int udpMode);
void client(FnArgs_t *argP);
void prepareToDetach(void);
void makeDetached(void);
void serverListener(unsigned short *portPtr);
void serverInitiator(unsigned short *portPtr);
int allowRedirect(unsigned short port, SOCKADDR_UNION *addrP, SOCKADDR_UNION *peerAddrP, int udpMode, char **hostP, char **idFileP);
int checkPeerForSocket(int fd, SOCKADDR_UNION *addrP);
int checkPeerAddress(SOCKADDR_UNION *addrP, EndPtList_t *peerList);
int countPorts(EndPtList_t *list);
unsigned short mapPort(unsigned short localPort, char **hostP, SOCKADDR_UNION *addrP);
void server(FnArgs_t *argP);
unsigned short scanPortRange(const char *str, unsigned short *loP,
unsigned short *hiP, unsigned short *typeP);
void setBoolean(char *value, int *resultP);
void setUShort(char *value, unsigned short *resultP);
void setPort(char *value, unsigned short *resultP);
EndPtList_t *newEndPtList(unsigned short lo, unsigned short hi, char *host, char *idFile, char *peer, unsigned short type);
EndPtList_t *allocEndPtList(unsigned short lo, unsigned short hi, char *host, char *idFile, char *peer, SOCKADDR_UNION *addrP, SOCKADDR_UNION *addrList, unsigned short mask, unsigned short type);
void setEndPtList(char *value, EndPtList_t **listP, char *host, char *idFile, char *peer, int zeroOk);
void setTarget(char *value);
void setChecksum(char *value, unsigned short *resultP);
void setTunnel(char *value);
void setAllowedPeer(char *value, EndPtList_t *peerList);
void setString(char *value, char **resultP);
void setLogFile(char *newFile);
void setCmpInfo(char *value, unsigned short *resultP);
void setStackSize(char *value);
void setRunAsUser(const char *user);
void readConfigFile(const char *fileName, int level);
int parseConfigLine(const char *lineBuf, int level);
char *cleanHexString(char *str);
void usage(void);
void sigpipeCatcher(int sig);
void sigchldCatcher(int sig);
void sigusr1Catcher(int sig);
void runAsUser(const char *user);
void switchUser(void);
int cmpAddr(SOCKADDR_UNION *a1, SOCKADDR_UNION *a2, unsigned short mask);
/*************************************\
** **
** Thread Synchronisation Routines **
** **
\*************************************/
/*
** threadInit
**
** Set up global mutexes, condition variables and thread attributes. Must
** be called before any other thread routines.
*/
void
threadInit(void)
{
mutexInit();
conditionInit();
#if defined(HAVE_PTHREADS)
pthread_attr_init(&ThreadAttr);
pthread_attr_setstacksize(&ThreadAttr, (size_t)ThreadStackSize);
pthread_attr_setdetachstate(&ThreadAttr, PTHREAD_CREATE_DETACHED);
#endif
}
/*
** mutexInit
**
** Initialise global mutexes.
*/
void
mutexInit(void)
{
#if defined(WIN32)
int i;
for (i = 0; i < MUTEX_MAX; i++)
{
InitializeCriticalSection(&(Mutex[i]));
}
#elif defined(HAVE_PTHREADS)
int i;
for (i = 0; i < MUTEX_MAX; i++)
{
pthread_mutex_init(&(Mutex[i]), NULL);
}
#endif
}
/*
** mutexLock
**
** Lock a global mutex
*/
void
mutexLock(int num)
{
assert(num < MUTEX_MAX);
#if defined(WIN32)
EnterCriticalSection(&(Mutex[num]));
#elif defined(HAVE_PTHREADS)
pthread_mutex_lock(&(Mutex[num]));
#endif
}
/*
** mutexUnlock
**
** Unlock a global mutex
*/
void
mutexUnlock(int num)
{
assert(num < MUTEX_MAX);
#if defined(WIN32)
LeaveCriticalSection(&(Mutex[num]));
#elif defined(HAVE_PTHREADS)
pthread_mutex_unlock(&(Mutex[num]));
#endif
}
/*
** conditionInit
**
** Initialise global condition variables.
*/
void
conditionInit(void)
{
#if defined(WIN32)
int i;
for (i = 0; i < COND_MAX; i++)
{
Condition[i] = CreateEvent(NULL, /* No security attributes */
TRUE, /* Manual reset */
FALSE, /* Initially cleared */
NULL); /* No name */
}
#elif defined(HAVE_PTHREADS)
int i;
for (i = 0; i < COND_MAX; i++)
{
pthread_cond_init(&(Condition[i]), NULL);
}
#endif
}
/*
** conditionSignal
**
** Signal a condition variable
*/
void
conditionSignal(int num)
{
assert(num < COND_MAX);
#if defined(WIN32)
PulseEvent(Condition[num]);
#elif defined(HAVE_PTHREADS)
pthread_cond_broadcast(&(Condition[num]));
#endif
}
/*
** conditionWait
**
** Wait on a condition variable. Note the specified mutex must be held
** before calling this routine. It will also be held on exit.
*/
void
conditionWait(int condNum, int mutexNum)
{
assert(condNum < COND_MAX && mutexNum < MUTEX_MAX);
#if defined(WIN32)
LeaveCriticalSection(&(Mutex[mutexNum]));
WaitForSingleObject(Condition[condNum], INFINITE);
EnterCriticalSection(&(Mutex[mutexNum]));
#elif defined(HAVE_PTHREADS)
pthread_cond_wait(&(Condition[condNum]), &(Mutex[mutexNum]));
#endif
}
/*
** threadPid
**
** Return the current process ID
*/
unsigned long
threadPid(void)
{
#ifdef WIN32
return (unsigned long)GetCurrentProcessId();
#else
return (unsigned long)getpid();
#endif
}
/*
** threadTid
**
** Return the current thread ID
*/
unsigned long
threadTid(void)
{
#ifdef WIN32
return (unsigned long)GetCurrentThreadId();
#elif defined(HAVE_PTHREADS)
return (unsigned long)pthread_self();
#else
return 0;
#endif
}
/*
** incrActiveCount
**
** This increments or decrements the count of active handler threads.
** If the count reaches zero it also signals the COND_ACTIVE condition
** variable.
*/
int
incrActiveCount(int num)
{
mutexLock(MUTEX_ACTIVE);
ActiveCount += num;
if (ActiveCount == 0)
{
conditionSignal(COND_ACTIVE);
}
mutexUnlock(MUTEX_ACTIVE);
return ActiveCount;
}
/*
** waitForInactivity
**
** This routine blocks until the "ActiveCount" global variable reaches
** zero, indicating no more running handler threads.
*/
void
waitForInactivity(void)
{
#if defined(WIN32) || defined(HAVE_PTHREADS)
mutexLock(MUTEX_ACTIVE);
while (ActiveCount)
{
conditionWait(COND_ACTIVE, MUTEX_ACTIVE);
}
mutexUnlock(MUTEX_ACTIVE);
#else
while (waitpid(-1, NULL, 0) > 0 || errno != ECHILD) /* Wait for children */;
#endif
}
/*********************\
** **
** Message Logging **
** **
\*********************/
/*
** timestamp
**
** Generate a time-stamp string
*/
void
timestamp(char *timeBuf, int local)
{
time_t now;
struct tm *tmPtr;
/* localtime()/gmtime are not thread-safe */
mutexLock(MUTEX_IO);
time(&now);
if (local)
{
tmPtr = localtime(&now);
}
else
{
tmPtr = gmtime(&now);
}
strftime(timeBuf, TIMESTAMP_SIZE, "%Y-%m-%d-%H:%M:%S", tmPtr);
mutexUnlock(MUTEX_IO);
}
/*
** logToSystemLog
**
** Write a message to the system logging facility. On Windows it goes to
** the system application event log. Elsewhere is uses syslog().
*/
void
logToSystemLog(unsigned short level, char *msg)
{
#ifdef WIN32
HANDLE eventHandle;
char *strings[2];
eventHandle = RegisterEventSource(NULL, Program);