1 /*-
2  * Copyright (c) 1999 Pierre Beyssac
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  */
27 
28 /* $Id: tunip.c,v 1.53 1999/09/21 22:20:40 beyssac Exp $ */
29 
30 #include <sys/types.h>
31 #include <sys/time.h>
32 #include <sys/socket.h>
33 #include <sys/stat.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <stdio.h>
38 #include <sys/ioctl.h>
39 #ifdef __DragonFly__
40 #include <net/tun/if_tun.h>
41 #else
42 #include <net/if_tun.h>
43 #endif
44 #include <netinet/in_systm.h>
45 #include <netinet/in.h>
46 #include <netinet/ip.h>
47 #include <netinet/ip_icmp.h>
48 #include <arpa/inet.h>
49 #include <netdb.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <syslog.h>
53 #include <time.h>
54 #include <ctype.h>
55 
56 #include <md5.h>
57 #include <sha.h>
58 #include <ripemd.h>
59 
60 #include <blowfish.h>
61 #include <cast.h>
62 #include <des.h>
63 #include <idea.h>
64 
65 #include "defs.h"
66 
67 #define _PATH_CONF              FILE_PREFIX "/etc/ipsec/pipsecd.conf"
68 #define _PATH_STARTUP           FILE_PREFIX "/etc/ipsec/startup"
69 #define _PATH_DEV_RANDOM	"/dev/random"
70 
71 #ifdef USE_ETHERTAP
72 /* Use ethertap device under Linux */
73 struct ethtap_header {
74     unsigned short padding;
75     unsigned char dst[6];
76     unsigned char src[6];
77     unsigned short type;
78 };
79 
80 struct ethtap_header ethtap;
81 
82 #define MAX_LINKHEADER	(sizeof(struct ethtap_header))
83 #else
84 #define MAX_LINKHEADER	0
85 #endif
86 
87 #define max(a,b)	((a)>(b)?(a):(b))
88 
89 #define MAX_HEADER	max(64,MAX_LINKHEADER)
90 #define MAX_SECRET	64
91 #define MAX_PACKET	4096
92 #define MAX_PEERS	16
93 
94 #define UDP_PORT	2001
95 
96 #ifdef USE_SYSTEM_HASH
97 #define MD5_Init		MD5Init
98 #define MD5_Update		MD5Update
99 #define MD5_Final		MD5Final
100 #define SHA1_Init		SHA1Init
101 #define SHA1_Update		SHA1Update
102 #define SHA1_Final		SHA1Final
103 #define RIPEMD160_Init		RIPEMD160Init
104 #define RIPEMD160_Update	RIPEMD160Update
105 #define RIPEMD160_Final		RIPEMD160Final
106 #endif
107 
108 unsigned char buf[MAX_HEADER+MAX_PACKET];
109 char *cmd;
110 
111 typedef union {
112     MD5_CTX md5;
113     SHA_CTX sha1;
114     RIPEMD160_CTX rmd160;
115 } hash_CTX;
116 
117 #define MAX_HASH_CTX	sizeof(hash_CTX)
118 #define MAX_HASH_DIGEST	20
119 
120 typedef struct hash_method {
121     struct hash_method *next;
122     char *name;
123     unsigned char size;
124     void (*hash_Init)(hash_CTX *context);
125     void (*hash_Update)(hash_CTX *context, const unsigned char *data,
126 		       unsigned int len);
127     void (*hash_Final)(unsigned char *digest, hash_CTX *context);
128 } hash_method_t;
129 
130 #define MAX_IV_SIZE	8
131 
132 typedef union {
133     BF_KEY bf;
134     DES_key_schedule des;
135     struct {
136 	DES_key_schedule k1;
137 	DES_key_schedule k2;
138 	DES_key_schedule k3;
139     } des3;
140     CAST_KEY cast;
141 #ifndef OPENSSL_NO_IDEA
142     IDEA_KEY_SCHEDULE idea;
143 #endif
144 } crypt_key;
145 
146 typedef struct crypt_method {
147     struct crypt_method *next;
148     char *name;
149     unsigned char iv_size, block_size;
150     void (*encrypt)(unsigned char *iv, crypt_key *ek,
151 		    unsigned char *t, unsigned int len);
152     void (*decrypt)(unsigned char *iv, crypt_key *dk,
153 		    unsigned char *ct, unsigned int len);
154     int (*setekey)(unsigned char *b, unsigned int len, crypt_key *k);
155     int (*setdkey)(unsigned char *b, unsigned int len, crypt_key *k);
156 } crypt_method_t;
157 
158 struct sa_desc {
159     struct sa_desc *next;
160 
161     struct sockaddr_in init;	/* initial and fallback remote address */
162     struct sockaddr_in dest;	/* current remote address */
163     struct sockaddr_in source;	/* local socket address we send packets from */
164     unsigned char use_fallback;	/* use initial address as fallback? */
165     unsigned char use_dest;	/* is dest address known yet? */
166 
167     unsigned long spi;		/* security parameters index */
168     unsigned long seq_id;	/* for replay protection (not implemented) */
169 
170     /* Encryption key */
171     unsigned char enc_secret[MAX_SECRET];
172     unsigned int enc_secret_size;
173     /* Preprocessed encryption key */
174     crypt_key enc_key;
175     /* Encryption method to use, or NULL */
176     crypt_method_t *cm;
177 
178     /* Authentication secret */
179     unsigned char auth_secret[MAX_SECRET];
180     unsigned int auth_secret_size;
181     /* Authentication method to use, or NULL */
182     hash_method_t *hm;
183 
184     /* Encapsulation method to use to send packets */
185     struct encap_method *em;
186 
187     /* flags */
188     unsigned char local, no_iv;
189     /* timeout counters */
190     time_t last_packet_sent, last_packet_recv, last_checkifaddr;
191 };
192 
193 struct tun_method {
194     unsigned int link_header_size;
195     unsigned char *link_header;
196 };
197 
198 struct peer_desc {
199     struct sa_desc *local_sa, *remote_sa;
200     int tun_fd;		/* file descriptor for associated tunnel device */
201     struct tun_method *tm;
202 };
203 
204 /* Size of sent hash (doesn't have to be the full hash) */
205 #define HMAC_SIZE	12
206 
207 /* UDP encap header. Currently tries to mimic IPSEC's AH header */
208 typedef struct udp_encap_header {
209     unsigned long spi;			/* security parameters index */
210     unsigned long seq_id;		/* sequence id (unimplemented) */
211     unsigned char hmac[HMAC_SIZE];	/* HMAC */
212 } udp_encap_header_t;
213 
214 /* ICMP "custom AH" encap header */
215 typedef struct icmp_encap_header {
216   /* ICMP fields */
217     unsigned char icmp_type;
218     unsigned char icmp_code;
219     unsigned short icmp_cksum;
220   /* Our custom fields */
221     unsigned long spi;			/* security parameters index */
222     unsigned long seq_id;		/* sequence id (unimplemented) */
223     unsigned char hmac[HMAC_SIZE];	/* HMAC */
224 } icmp_encap_header_t;
225 
226 /* A real AH header (RFC 2402) */
227 typedef struct ah_encap_header {
228     unsigned char next_header;
229     unsigned char payload_len;
230     unsigned short reserved;
231     unsigned long spi;			/* security parameters index */
232     unsigned long seq_id;		/* sequence id (unimplemented) */
233     unsigned char hmac[HMAC_SIZE];	/* HMAC */
234 } ah_encap_header_t;
235 
236 /* A real ESP header (RFC 2406) */
237 typedef struct esp_encap_header {
238     unsigned long spi;			/* security parameters index */
239     unsigned long seq_id;		/* sequence id (unimplemented) */
240     /* variable-length payload data + padding */
241     /* unsigned char next_header */
242     /* optional auth data */
243 } esp_encap_header_t;
244 
245 struct encap_method {
246     int fd;			/* file descriptor for relevant socket */
247     unsigned char *name;
248 
249     unsigned int fixed_header_size;
250 
251     /* Description of the packet being processed */
252     unsigned char *buf;
253     unsigned int bufsize, buflen, bufpayload, var_header_size;
254     struct sockaddr_in from; int fromlen;
255 
256     int (*recv)(struct encap_method *encap,
257 		unsigned char *buf, unsigned int bufsize,
258 		struct sockaddr_in *from);
259     int (*hmac_compute)(struct encap_method *encap,
260 			unsigned char do_store,
261 			struct in_addr *src_ip, hash_method_t *hm,
262 			unsigned char *secret, unsigned short secret_size);
263     struct peer_desc *(*peer_find)(struct encap_method *encap);
264     void (*send_peer)(struct encap_method *encap,
265 		      struct peer_desc *peer,
266 		      unsigned char *buf, unsigned int bufsize);
267     int (*recv_peer)(struct encap_method *encap,
268 		     struct in_addr *src_ip,
269 		     struct peer_desc *peer);
270 };
271 
272 /* Forward decl */
273 int hmac_udp_compute(struct encap_method *encap,
274 		     unsigned char do_store,
275 		     struct in_addr *src_ip, hash_method_t *hm,
276 		     unsigned char *secret, unsigned short secret_size);
277 int hmac_rawip_compute(struct encap_method *encap,
278 		       unsigned char do_store,
279 		       struct in_addr *src_ip, hash_method_t *hm,
280 		       unsigned char *secret, unsigned short secret_size);
281 int hmac_icmp_compute(struct encap_method *encap,
282 		      unsigned char do_store,
283 		      struct in_addr *src_ip, hash_method_t *hm,
284 		      unsigned char *secret, unsigned short secret_size);
285 void encap_udp_send_peer(struct encap_method *encap,
286 			 struct peer_desc *peer,
287 			 unsigned char *buf, unsigned int bufsize);
288 void encap_ah_send_peer(struct encap_method *encap,
289 			struct peer_desc *peer,
290 			unsigned char *buf, unsigned int bufsize);
291 void encap_esp_send_peer(struct encap_method *encap,
292 			 struct peer_desc *peer,
293 			 unsigned char *buf, unsigned int bufsize);
294 void encap_icmp_send_peer(struct encap_method *encap,
295 			  struct peer_desc *peer,
296 			  unsigned char *buf, unsigned int bufsize);
297 struct peer_desc *peer_find(unsigned long spi, struct encap_method *encap);
298 struct sa_desc *find_local_sa(unsigned long spi, struct encap_method *encap);
299 struct sa_desc *find_remote_sa(unsigned long spi, struct encap_method *encap);
300 int encap_hmac_recv_peer(struct encap_method *encap,
301 			 struct in_addr *src_ip,
302 			 struct peer_desc *peer);
303 int encap_esp_recv_peer(struct encap_method *encap,
304 			struct in_addr *src_ip,
305 			struct peer_desc *peer);
306 void blowfish_cbc_encrypt(unsigned char *iv, crypt_key *ek,
307 			  unsigned char *t, unsigned int len);
308 void blowfish_cbc_decrypt(unsigned char *iv, crypt_key *dk,
309 			  unsigned char *ct, unsigned int len);
310 int blowfish_setkey(unsigned char *b, unsigned int len, crypt_key *k);
311 void cast_cbc_encrypt(unsigned char *iv, crypt_key *ek,
312 		      unsigned char *t, unsigned int len);
313 void cast_cbc_decrypt(unsigned char *iv, crypt_key *dk,
314 		      unsigned char *ct, unsigned int len);
315 int cast_setkey(unsigned char *b, unsigned int len, crypt_key *k);
316 #ifndef OPENSSL_NO_IDEA
317 void my_idea_cbc_encrypt(unsigned char *iv, crypt_key *ek,
318 			 unsigned char *t, unsigned int len);
319 void my_idea_cbc_decrypt(unsigned char *iv, crypt_key *dk,
320 			 unsigned char *ct, unsigned int len);
321 int my_idea_set_encrypt_key(unsigned char *b, unsigned int len, crypt_key *k);
322 int my_idea_set_decrypt_key(unsigned char *b, unsigned int len, crypt_key *k);
323 #endif
324 void my_des_cbc_encrypt(unsigned char *iv, crypt_key *ek,
325 			unsigned char *t, unsigned int len);
326 void my_des_cbc_decrypt(unsigned char *iv, crypt_key *dk,
327 			unsigned char *ct, unsigned int len);
328 int my_des_setkey(unsigned char *b, unsigned int len, crypt_key *k);
329 void my_des3_cbc_encrypt(unsigned char *iv, crypt_key *ek,
330 			 unsigned char *t, unsigned int len);
331 void my_des3_cbc_decrypt(unsigned char *iv, crypt_key *dk,
332 			 unsigned char *ct, unsigned int len);
333 int my_des3_setkey(unsigned char *b, unsigned int len, crypt_key *k);
334 void null_encrypt(unsigned char *iv, crypt_key *ek,
335 		  unsigned char *t, unsigned int len);
336 void null_decrypt(unsigned char *iv, crypt_key *dk,
337 		  unsigned char *ct, unsigned int len);
338 int null_setkey(unsigned char *b, unsigned int len, crypt_key *k);
339 
340 /* Yuck! Global variables... */
341 
342 struct peer_desc peers[MAX_PEERS];
343 
344 struct tun_method tm_tun;
345 #ifdef USE_ETHERTAP
346 struct tun_method tm_tap;
347 #endif
348 
349 unsigned short peer_num = 0;
350 unsigned short sa_num = 0;
351 unsigned short ip_id;
352 
353 /* Descriptors for predefined encapsulation methods */
354 #define ENCAP_IPAH	0
355 #define ENCAP_UDP	1
356 #define ENCAP_IPESP	2
357 #define ENCAP_ICMP	3
358 #define ENCAP_MAX	4
359 struct encap_method encap_meth[ENCAP_MAX];
360 
361 /* Security associations lists */
362 struct sa_desc *local_sa_list = NULL;
363 struct sa_desc *remote_sa_list = NULL;
364 
365 /* Interval for keepalive probes */
366 int keepalive_recv = 600;
367 int keepalive_send = 200;
368 
369 int check_ifaddr = 60;
370 
371 /* IP protocol numbers */
372 int ipproto_esp = 50;
373 int ipproto_ah = 51;
374 
375 hash_method_t hash_md5 = {
376     NULL,
377     "hmac-md5-96", 16,
378     MD5_Init, MD5_Update, MD5_Final
379 };
380 hash_method_t hash_sha1 = {
381     &hash_md5,
382     "hmac-sha1-96", 20,
383     SHA1_Init, SHA1_Update, SHA1_Final
384 };
385 hash_method_t hash_ripemd160 = {
386     &hash_sha1,
387     "hmac-rmd160-96", 20,
388     RIPEMD160_Init, RIPEMD160_Update, RIPEMD160_Final
389 };
390 
391 hash_method_t *hash_list = &hash_ripemd160;
392 
393 #ifndef OPENSSL_NO_IDEA
394 crypt_method_t crypt_idea = {
395     NULL,
396     "idea_cbc", 8, 8,
397     my_idea_cbc_encrypt, my_idea_cbc_decrypt,
398     my_idea_set_encrypt_key, my_idea_set_decrypt_key
399 };
400 #endif
401 crypt_method_t crypt_cast = {
402 #ifndef OPENSSL_NO_IDEA
403     &crypt_idea,
404 #else
405     NULL,
406 #endif
407     "cast_cbc", 8, 8,
408     cast_cbc_encrypt, cast_cbc_decrypt,
409     cast_setkey, cast_setkey
410 };
411 crypt_method_t crypt_des3 = {
412     &crypt_cast,
413     "des3_cbc", 8, 8,
414     my_des3_cbc_encrypt, my_des3_cbc_decrypt,
415     my_des3_setkey, my_des3_setkey
416 };
417 crypt_method_t crypt_des = {
418     &crypt_des3,
419     "des_cbc", 8, 8,
420     my_des_cbc_encrypt, my_des_cbc_decrypt,
421     my_des_setkey, my_des_setkey
422 };
423 crypt_method_t crypt_bf = {
424     &crypt_des,
425     "blowfish_cbc", 8, 8,
426     blowfish_cbc_encrypt, blowfish_cbc_decrypt,
427     blowfish_setkey, blowfish_setkey
428 };
429 crypt_method_t crypt_null8 = {
430     &crypt_bf,
431     "null8", 8, 8,
432     null_encrypt, null_decrypt,
433     null_setkey, null_setkey
434 };
435 crypt_method_t crypt_null = {
436     &crypt_null8,
437     "null", 0, 1,
438     null_encrypt, null_decrypt,
439     null_setkey, null_setkey
440 };
441 
442 crypt_method_t *crypt_list = &crypt_null;
443 
444 unsigned char global_iv[MAX_IV_SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8 };
445 
446 #define encap_get_fd(e)	((e)->fd)
447 #define encap_recv(e,b,bs,f) \
448 	((e)->recv((e),(b),(bs),(f)))
449 #define encap_hmac_compute(e,s,hm,se,ss) \
450 	((e)->hmac_compute((e),1,(s),(hm),(se),(ss)))
451 #define encap_hmac_cmp(e,s,hm,se,ss) \
452 	((e)->hmac_compute((e),0,(s),(hm),(se),(ss)))
453 #define encap_peer_find(e) \
454 	((e)->peer_find((e)))
455 #define encap_send_peer(e,p,b,bs) \
456 	((e)->send_peer((e),(p),(b),(bs)))
457 #define encap_recv_peer(e,s,p) \
458 	((e)->recv_peer((e),(s),(p)))
459 
460 /*
461  * in_cksum --
462  *	Checksum routine for Internet Protocol family headers (C Version)
463  */
464 u_short
in_cksum(addr,len)465 in_cksum(addr, len)
466 	u_short *addr;
467 	int len;
468 {
469 	register int nleft = len;
470 	register u_short *w = addr;
471 	register int sum = 0;
472 	u_short answer = 0;
473 
474 	/*
475 	 * Our algorithm is simple, using a 32 bit accumulator (sum), we add
476 	 * sequential 16 bit words to it, and at the end, fold back all the
477 	 * carry bits from the top 16 bits into the lower 16 bits.
478 	 */
479 	while (nleft > 1)  {
480 		sum += *w++;
481 		nleft -= 2;
482 	}
483 
484 	/* mop up an odd byte, if necessary */
485 	if (nleft == 1) {
486 		*(u_char *)(&answer) = *(u_char *)w ;
487 		sum += answer;
488 	}
489 
490 	/* add back carry outs from top 16 bits to low 16 bits */
491 	sum = (sum >> 16) + (sum & 0xffff);	/* add hi 16 to low 16 */
492 	sum += (sum >> 16);			/* add carry */
493 	answer = ~sum;				/* truncate to 16 bits */
494 	return(answer);
495 }
496 
497 /*
498  * Find an encap method by name
499  */
find_encap(unsigned char * name)500 struct encap_method *find_encap(unsigned char *name)
501 {
502     int i;
503     for (i = 0; i < ENCAP_MAX; i++)
504         if (strcmp(encap_meth[i].name, name) == 0)
505 	    return encap_meth+i;
506     return NULL;
507 }
508 
509 /*
510  * Find a crypt method by name
511  */
find_crypt(unsigned char * name)512 crypt_method_t *find_crypt(unsigned char *name)
513 {
514     crypt_method_t *cp;
515     for (cp = crypt_list; cp; cp = cp->next)
516         if (strcmp(cp->name, name) == 0)
517 	    return cp;
518     return NULL;
519 }
520 
521 /*
522  * Find a hash method by name
523  */
find_hash(unsigned char * name)524 hash_method_t *find_hash(unsigned char *name)
525 {
526     hash_method_t *hp;
527     for (hp = hash_list; hp; hp = hp->next)
528         if (strcmp(hp->name, name) == 0)
529 	    return hp;
530     return NULL;
531 }
532 
533 /*
534  * Decapsulate from a UDP packet
535  */
encap_udp_recv(struct encap_method * encap,unsigned char * buf,unsigned int bufsize,struct sockaddr_in * from)536 int encap_udp_recv(struct encap_method *encap,
537 		   unsigned char *buf, unsigned int bufsize,
538 		   struct sockaddr_in *from)
539 {
540     int r;
541 
542     encap->fromlen = sizeof(encap->from);
543 
544     r = recvfrom(encap->fd, buf, bufsize, 0,
545 		 (struct sockaddr *)&encap->from, &encap->fromlen);
546     if (r == -1) {
547 	syslog(LOG_ERR, "recvfrom: %m");
548 	return -1;
549     }
550     if (r < encap->fixed_header_size) {
551         syslog(LOG_ALERT, "packet too short from %s",
552 		inet_ntoa(encap->from.sin_addr));
553 	return -1;
554     }
555     encap->buf = buf;
556     encap->bufsize = bufsize;
557     encap->buflen = r;
558     encap->bufpayload = 0;
559     *from = encap->from;
560     return r;
561 }
562 
563 /*
564  * Decapsulate from a raw IP packet
565  */
encap_rawip_recv(struct encap_method * encap,unsigned char * buf,unsigned int bufsize,struct sockaddr_in * from)566 int encap_rawip_recv(struct encap_method *encap,
567 		     unsigned char *buf, unsigned int bufsize,
568 		     struct sockaddr_in *from)
569 {
570     int r;
571     struct ip *p = (struct ip *)buf;
572 
573     encap->fromlen = sizeof(encap->from);
574 
575     r = recvfrom(encap->fd, buf, bufsize, 0,
576 		 (struct sockaddr *)&encap->from, &encap->fromlen);
577     if (r == -1) {
578 	syslog(LOG_ERR, "recvfrom: %m");
579 	return -1;
580     }
581     if (r < (p->ip_hl << 2)+encap->fixed_header_size) {
582         syslog(LOG_ALERT, "packet too short from %s",
583 		inet_ntoa(encap->from.sin_addr));
584 	return -1;
585     }
586 
587 #if 0
588     printf("raw got %d bytes\n", r);
589     for (i = 0; i < r; i++) {
590 	printf(" %02x", buf[i]);
591 	if ((i & 15) == 15) printf("\n");
592     }
593     printf("\n");
594 #endif
595 
596 #ifdef NEED_IPID_SWAP
597     p->ip_id = htons(p->ip_id);
598 #endif
599 #ifdef NEED_IPLEN_FIX
600     p->ip_len = r;
601 #else
602     p->ip_len = ntohs(p->ip_len);
603 #endif
604 
605     encap->buf = buf;
606     encap->buflen = r;
607     encap->bufpayload = (p->ip_hl << 2);
608     encap->bufsize = bufsize;
609     *from = encap->from;
610     return r;
611 }
612 
613 /*
614  * Decapsulate from a ICMP packet
615  */
encap_icmp_recv(struct encap_method * encap,unsigned char * buf,unsigned int bufsize,struct sockaddr_in * from)616 int encap_icmp_recv(struct encap_method *encap,
617 		    unsigned char *buf, unsigned int bufsize,
618 		    struct sockaddr_in *from)
619 {
620     int r;
621     struct ip *p = (struct ip *)buf;
622     struct icmp *ic;
623     encap->fromlen = sizeof(encap->from);
624 
625     r = recvfrom(encap->fd, buf, bufsize, 0,
626 		    (struct sockaddr *)&encap->from, &encap->fromlen);
627     if (r == -1) {
628 	syslog(LOG_ERR, "recvfrom: %m");
629 	return -1;
630     }
631 
632     /*
633      * Apparently, we only get packets with a correct ICMP checksum from
634      * the kernel.
635      */
636 
637     if (r < (p->ip_hl << 2)+sizeof(struct icmp))
638         /* Don't log (can be a reply to a ping, none of our business) */
639 	return -1;
640 
641     ic = (struct icmp *)(buf + (p->ip_hl << 2));
642     if (ic->icmp_type != ICMP_ECHOREPLY)
643         return -1;
644     if (ic->icmp_code != ipproto_ah) /* arbitrary value */
645         return -1;
646 
647     if (r < (p->ip_hl << 2)+encap->fixed_header_size) {
648         syslog(LOG_ALERT, "packet too short from %s",
649 		inet_ntoa(encap->from.sin_addr));
650 	return -1;
651     }
652 
653 #ifdef NEED_IPID_SWAP
654     p->ip_id = htons(p->ip_id);
655 #endif
656 #ifdef NEED_IPLEN_FIX
657     p->ip_len = r;
658 #else
659     p->ip_len = ntohs(p->ip_len);
660 #endif
661 
662     encap->buf = buf;
663     encap->buflen = r;
664     encap->bufpayload = (p->ip_hl << 2);
665     encap->bufsize = bufsize;
666     *from = encap->from;
667     return r;
668 }
669 
encap_udp_peer_find(struct encap_method * encap)670 struct peer_desc *encap_udp_peer_find(struct encap_method *encap)
671 {
672     udp_encap_header_t *eh;
673     eh = (udp_encap_header_t *)encap->buf;
674     return peer_find(ntohl(eh->spi), encap);
675 }
676 
encap_ah_peer_find(struct encap_method * encap)677 struct peer_desc *encap_ah_peer_find(struct encap_method *encap)
678 {
679     ah_encap_header_t *eh;
680     eh = (ah_encap_header_t *)(encap->buf + encap->bufpayload);
681     return peer_find(ntohl(eh->spi), encap);
682 }
683 
encap_esp_peer_find(struct encap_method * encap)684 struct peer_desc *encap_esp_peer_find(struct encap_method *encap)
685 {
686     esp_encap_header_t *eh;
687     eh = (esp_encap_header_t *)(encap->buf + encap->bufpayload);
688     return peer_find(ntohl(eh->spi), encap);
689 }
690 
encap_icmp_peer_find(struct encap_method * encap)691 struct peer_desc *encap_icmp_peer_find(struct encap_method *encap)
692 {
693     icmp_encap_header_t *eh;
694     eh = (icmp_encap_header_t *)(encap->buf + encap->bufpayload);
695     return peer_find(ntohl(eh->spi), encap);
696 }
697 
698 /*
699  * Decapsulate packet
700  */
encap_any_decap(struct encap_method * encap,int fd)701 int encap_any_decap(struct encap_method *encap, int fd)
702 {
703     encap->buflen
704       -= encap->bufpayload+encap->fixed_header_size+encap->var_header_size;
705     encap->buf
706       += encap->bufpayload+encap->fixed_header_size+encap->var_header_size;
707     if (encap->buflen == 0)
708         return 0;
709     return 1;
710 }
711 
tun_new(struct tun_method * this,unsigned link_header_size,unsigned char * link_header)712 void tun_new(struct tun_method *this,
713 	     unsigned link_header_size, unsigned char *link_header)
714 {
715     this->link_header_size = link_header_size;
716     this->link_header = link_header;
717 }
718 
719 /*
720  * Send decapsulated packet to tunnel device
721  */
tun_send_ip(struct tun_method * this,struct encap_method * encap,int fd)722 int tun_send_ip(struct tun_method *this, struct encap_method *encap, int fd)
723 {
724     int sent, i;
725 
726     if (this->link_header_size) {
727         encap->buflen += this->link_header_size;
728         encap->buf -= this->link_header_size;
729         memcpy(encap->buf, this->link_header, this->link_header_size);
730     }
731 #if 0
732     printf ("Packet sent to tun dev:");
733     for (i = 0; i < encap->buflen; i++) {
734       if (!(i % 16))
735         printf ("\n    ");
736       printf (" %02x", encap->buf[i]);
737     }
738     printf ("\n\n");
739 #endif
740     sent = write(fd, encap->buf, encap->buflen);
741     if (sent != encap->buflen)
742         syslog(LOG_ERR, "truncated in: %d -> %d\n", encap->buflen, sent);
743     return 1;
744 }
745 
746 /*
747  * Initialize encap_method structures for each method
748  */
encap_udp_new(struct encap_method * encap,unsigned short port)749 int encap_udp_new(struct encap_method *encap, unsigned short port)
750 {
751     int i;
752     struct sockaddr_in source;
753 
754     encap->fd = socket(PF_INET, SOCK_DGRAM, 0);
755     if (encap->fd == -1) {
756 	perror("socket(SOCK_DGRAM)");
757 	return -1;
758     }
759 
760     memset(&source, 0, sizeof source);
761     source.sin_addr.s_addr = INADDR_ANY;
762     source.sin_port = htons(port);
763     source.sin_family = AF_INET;
764 #ifdef HAVE_SA_LEN
765     source.sin_len = sizeof(&source);
766 #endif
767 
768     i = bind(encap->fd, (struct sockaddr *)&source, sizeof(source));
769     if (i == -1) {
770 	syslog(LOG_ERR, "bind: %m");
771 	return -1;
772     }
773     encap->name = "udp";
774     encap->recv = encap_udp_recv;
775     encap->hmac_compute = hmac_udp_compute;
776     encap->peer_find = encap_udp_peer_find;
777     encap->send_peer = encap_udp_send_peer;
778     encap->recv_peer = encap_hmac_recv_peer;
779     encap->fixed_header_size = sizeof(udp_encap_header_t);
780     encap->var_header_size = 0;
781     return 0;
782 }
783 
encap_ah_new(struct encap_method * encap,unsigned char proto)784 int encap_ah_new(struct encap_method *encap, unsigned char proto)
785 {
786 #ifdef IP_HDRINCL
787     int hincl = 1;
788 #endif
789 
790     encap->fd = socket(PF_INET, SOCK_RAW, proto);
791 
792     if (encap->fd == -1) {
793 	perror("socket(SOCK_RAW)");
794 	return -1;
795     }
796 #ifdef IP_HDRINCL
797     if (setsockopt(encap->fd, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl))
798 	== -1) {
799         perror("setsockopt(IP_HDRINCL)");
800 	close(encap->fd);
801 	return -1;
802     }
803 #endif
804     encap->name = "ipah";
805     encap->recv = encap_rawip_recv;
806     encap->hmac_compute = hmac_rawip_compute;
807     encap->peer_find = encap_ah_peer_find;
808     encap->send_peer = encap_ah_send_peer;
809     encap->recv_peer = encap_hmac_recv_peer;
810     encap->fixed_header_size = sizeof(ah_encap_header_t);
811     encap->var_header_size = 0;
812     return 0;
813 }
814 
encap_esp_new(struct encap_method * encap,unsigned char proto)815 int encap_esp_new(struct encap_method *encap, unsigned char proto)
816 {
817 #ifdef IP_HDRINCL
818     int hincl = 1;
819 #endif
820 
821     encap->fd = socket(PF_INET, SOCK_RAW, proto);
822 
823     if (encap->fd == -1) {
824 	perror("socket(SOCK_RAW)");
825 	return -1;
826     }
827 #ifdef IP_HDRINCL
828     if (setsockopt(encap->fd, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl))
829 	== -1) {
830         perror("setsockopt(IP_HDRINCL)");
831 	close(encap->fd);
832 	return -1;
833     }
834 #endif
835     encap->name = "ipesp";
836     encap->recv = encap_rawip_recv;
837     encap->hmac_compute = NULL;
838     encap->peer_find = encap_esp_peer_find;
839     encap->send_peer = encap_esp_send_peer;
840     encap->recv_peer = encap_esp_recv_peer;
841     encap->fixed_header_size = sizeof(esp_encap_header_t);
842     encap->var_header_size = 0;
843     return 0;
844 }
845 
encap_icmp_new(struct encap_method * encap,unsigned char proto)846 int encap_icmp_new(struct encap_method *encap, unsigned char proto)
847 {
848 #ifdef IP_HDRINCL
849     int hincl = 1;
850 #endif
851 
852     encap->fd = socket(PF_INET, SOCK_RAW, proto);
853 
854     if (encap->fd == -1) {
855 	perror("socket(SOCK_RAW)");
856 	return -1;
857     }
858 #ifdef IP_HDRINCL
859     if (setsockopt(encap->fd, IPPROTO_IP, IP_HDRINCL, &hincl, sizeof(hincl))
860 	== -1) {
861         perror("setsockopt(IP_HDRINCL)");
862 	close(encap->fd);
863 	return -1;
864     }
865 #endif
866     encap->name = "icmp";
867     encap->recv = encap_icmp_recv;
868     encap->hmac_compute = hmac_icmp_compute;
869     encap->peer_find = encap_icmp_peer_find;
870     encap->send_peer = encap_icmp_send_peer;
871     encap->recv_peer = encap_hmac_recv_peer;
872     encap->fixed_header_size = sizeof(icmp_encap_header_t);
873     encap->var_header_size = 0;
874     return 0;
875 }
876 
877 /*
878  * This is a hack to retrieve which local IP address the system would use
879  * as a source when sending packets to a given destination.
880  */
find_local_addr(struct sockaddr_in * dest,struct sockaddr_in * source)881 int find_local_addr(struct sockaddr_in *dest, struct sockaddr_in *source)
882 {
883     int addrlen;
884     struct sockaddr_in dest_socket;
885     int fd;
886 
887     fd = socket(PF_INET, SOCK_DGRAM, 0);
888     if (fd == -1) {
889 	syslog(LOG_ERR, "socket: %m");
890 	return -1;
891     }
892 
893     memset(&dest_socket, 0, sizeof(dest_socket));
894 
895     dest_socket.sin_family = AF_INET;
896 #ifdef HAVE_SA_LEN
897     dest_socket.sin_len = sizeof(dest_socket);
898 #endif
899     dest_socket.sin_addr = dest->sin_addr;
900     dest_socket.sin_port = htons(4444);
901 
902     if (connect(fd,
903 		(struct sockaddr *)&dest_socket, sizeof(dest_socket)) == -1) {
904 	syslog(LOG_ERR, "connect: %m");
905 	close(fd);
906 	return -1;
907     }
908 
909     addrlen = sizeof(*source);
910 
911     if (getsockname(fd, (struct sockaddr *)source, &addrlen) == -1) {
912 	syslog(LOG_ERR, "getsockname: %m");
913 	close(fd);
914 	return -1;
915     }
916     close(fd);
917     return 0;
918 }
919 
920 /*
921  * Retrieve and possibly update our local address to a given remote SA.
922  * Return 1 if changed, 0 if not, -1 if error.
923  */
update_sa_addr(struct sa_desc * p)924 int update_sa_addr(struct sa_desc *p)
925 {
926     struct sockaddr_in new_addr;
927 
928     if (find_local_addr(&p->dest, &new_addr) == -1) {
929 	syslog(LOG_ALERT,
930 		"can't find a local address for packets to %s",
931 		inet_ntoa(p->dest.sin_addr));
932 	return -1;
933     }
934     if (new_addr.sin_addr.s_addr != p->source.sin_addr.s_addr) {
935 	char addr1[16];
936 	p->source.sin_addr = new_addr.sin_addr;
937 	strcpy(addr1, inet_ntoa(p->dest.sin_addr));
938 	syslog(LOG_NOTICE,
939 		"local address for %s is %s", addr1,
940 		inet_ntoa(p->source.sin_addr));
941 	return 1;
942     }
943     return 0;
944 }
945 
946 /*
947  * Parse a secret hex string.
948  * Bug: the string should include an even number of digits.
949  */
parse_secret(unsigned char * secret,unsigned char * result)950 unsigned int parse_secret(unsigned char *secret, unsigned char *result)
951 {
952     unsigned char *p = result;
953     unsigned char *c = secret;
954     unsigned char hex, hex2;
955 
956     while (*c && p < result + MAX_SECRET) {
957 	if (!isxdigit(*c)) {
958 	    syslog(LOG_ERR, "illegal hex character '%c'", c);
959 	    return 0;
960 	}
961 	hex = *c - '0';
962 	if (*c >= 'a')
963 	    hex = *c - ('a'-10);
964 	else if (*c >= 'A')
965 	    hex = *c - ('A'-10);
966 	c++;
967 	if (!*c)
968 	    break;
969 	if (!isxdigit(*c)) {
970 	    syslog(LOG_ERR, "illegal hex character '%c'", c);
971 	    return 0;
972 	}
973 	hex2 = *c - '0';
974 	if (*c >= 'a')
975 	    hex2 = *c - ('a'-10);
976 	else if (*c >= 'A')
977 	    hex2 = *c - ('A'-10);
978 	c++;
979 	hex = hex*16 + hex2;
980 	*p++ = hex;
981     }
982     return p-result;
983 }
984 
985 /*
986  * Parse a configuration file
987  */
config_read(FILE * cf)988 void config_read(FILE *cf)
989 {
990     struct hostent *he;
991     struct sockaddr_in *dest, *init;
992     unsigned char line[4096];
993     unsigned int lineno;
994     time_t t;
995 
996     lineno = 0;
997     t = time(NULL);
998 
999     while (fgets(line, sizeof line, cf) != NULL) {
1000 	unsigned char *lp = line;
1001 	unsigned char *arg, *arg2;
1002 	line[strlen(line)-1] = '\0';
1003 
1004 	lineno++;
1005 
1006 	do arg = strsep(&lp, " \t"); while (arg && *arg == '\0');
1007 	if (arg == NULL || arg[0] == '#')
1008 	    continue;
1009 
1010 	do arg2 = strsep(&lp, " \t"); while (arg2 && *arg2 == '\0');
1011 	if (arg2 == NULL) {
1012 	    syslog(LOG_ALERT, "line %d too short", lineno);
1013 	    continue;
1014 	}
1015 
1016 	if (strcmp(arg, "sa") == 0) {
1017 	    int local;
1018 	    struct sa_desc *sa;
1019 	    struct encap_method *em;
1020 	    em = find_encap(arg2);
1021 	    if (em == NULL) {
1022 		syslog(LOG_ALERT, "Unknown encap format %s on line %d",
1023 			arg2, lineno);
1024 		continue;
1025 	    }
1026 
1027 	    sa = (struct sa_desc *)malloc(sizeof(struct sa_desc));
1028 
1029 	    sa->em = em;
1030 
1031 	    sa->hm = NULL;
1032 	    sa->cm = NULL;
1033 	    sa->enc_secret_size = 0;
1034 	    sa->auth_secret_size = 0;
1035 	    sa->spi = 0;
1036 	    sa->seq_id = 0;
1037 
1038 	    sa->last_packet_recv = t;
1039 	    sa->last_packet_sent = t;
1040 	    sa->last_checkifaddr = t;
1041 
1042 	    memset(&sa->init, 0, sizeof(sa->init));
1043 	    memset(&sa->dest, 0, sizeof(sa->dest));
1044 	    sa->use_fallback = 0;
1045 	    sa->use_dest = 0;
1046 	    sa->no_iv = 0;
1047 	    local = 1;
1048 
1049 	    for (;;) {
1050 		do arg = strsep(&lp, " \t"); while (arg && *arg == '\0');
1051 		if (arg == NULL)
1052 		    break;
1053 		arg2 = strchr(arg, '=');
1054 		if (arg2) {
1055 		    *arg2 = '\0';
1056 		    arg2++;
1057 		} else
1058 		    arg2 = "";
1059 		if (strcmp(arg, "enc") == 0) {
1060 		    sa->cm = find_crypt(arg2);
1061 		    if (sa->cm == NULL) {
1062 			syslog(LOG_ERR, "Unknown crypt method %s on line %d",
1063 				arg2, lineno);
1064 			continue;
1065 		    }
1066 		} else if (strcmp(arg, "noiv") == 0) {
1067 		    sa->no_iv = 1;
1068 		} else if (strcmp(arg, "dest") == 0) {
1069 		    he = gethostbyname(arg2);
1070 		    if (he == NULL) {
1071 			syslog(LOG_ALERT, "Unknown host %s on line %d",
1072 				arg2, lineno);
1073 			continue;
1074 		    }
1075 		    if (he->h_addrtype != AF_INET
1076 			|| he->h_length != sizeof(init->sin_addr.s_addr)) {
1077 			syslog(LOG_ALERT,
1078 				"Address type mismatch for host %s on line %d",
1079 				arg2, lineno);
1080 			continue;
1081 		    }
1082 
1083 		    memset(&sa->init, 0, sizeof(sa->init));
1084 		    memcpy((caddr_t)&sa->init.sin_addr, he->h_addr,
1085 			   sizeof(sa->init.sin_addr));
1086 		    sa->init.sin_port = htons(UDP_PORT);
1087 		    sa->init.sin_family = AF_INET;
1088 #ifdef HAVE_SA_LEN
1089 		    sa->init.sin_len = sizeof(dest);
1090 #endif
1091 		    sa->dest = sa->init;
1092 		    if (update_sa_addr(sa) == -1)
1093 			continue;
1094 		    sa->use_fallback = 1;
1095 		    sa->use_dest = 1;
1096 		    local = 0;
1097 		} else if (strcmp(arg, "ekey") == 0) {
1098 		    sa->enc_secret_size = parse_secret(arg2, sa->enc_secret);
1099 		    if (sa->enc_secret_size == 0) {
1100 			syslog(LOG_ALERT, "No crypt key on line %d", lineno);
1101 			continue;
1102 		    }
1103 		} else if (strcmp(arg, "akey") == 0) {
1104 		    sa->auth_secret_size = parse_secret(arg2, sa->auth_secret);
1105 		    if (sa->auth_secret_size == 0) {
1106 			syslog(LOG_ALERT, "No auth key on line %d", lineno);
1107 			continue;
1108 		    }
1109 		} else if (strcmp(arg, "spi") == 0) {
1110 		    sa->spi = atoi(arg2);
1111 		} else if (strcmp(arg, "auth") == 0) {
1112 		    sa->hm = find_hash(arg2);
1113 		    if (sa->hm == NULL) {
1114 			syslog(LOG_ALERT, "Unknown auth method %s on line %d",
1115 				arg2, lineno);
1116 			continue;
1117 		    }
1118 		} else {
1119 		    syslog(LOG_ALERT, "Unknown keyword %s on line %d",
1120 			    arg, lineno);
1121 		}
1122 	    }
1123 	    if (sa->cm) {
1124 	        int rsk;
1125 	        if (local)
1126 		    rsk = sa->cm->setdkey(sa->enc_secret,
1127 					  sa->enc_secret_size,
1128 					  &sa->enc_key);
1129 		else
1130 		    rsk = sa->cm->setekey(sa->enc_secret,
1131 					  sa->enc_secret_size,
1132 					  &sa->enc_key);
1133 		if (rsk != 0) {
1134 		      syslog(LOG_ALERT, "Invalid crypt key on line %d",
1135 			      lineno);
1136 		      free(sa);
1137 		      continue;
1138 		}
1139 	    }
1140 	    if (local) {
1141 		sa->next = local_sa_list;
1142 		local_sa_list = sa;
1143 	    } else {
1144 		sa->next = remote_sa_list;
1145 		remote_sa_list = sa;
1146 	    }
1147 	} else if (strcmp(arg, "if") == 0) {
1148 	    int fd;
1149 	    int i = 0;
1150 	    struct sa_desc *local_sa, *remote_sa;
1151 	    struct peer_desc *peer;
1152 
1153 	    fd = open(arg2, O_RDWR);
1154 	    if (fd == -1) {
1155 		perror(arg);
1156 		continue;
1157 	    }
1158 	    ioctl (fd, TUNSIFHEAD, &i);
1159 
1160 	    local_sa = NULL;
1161 	    remote_sa = NULL;
1162 
1163 	    peer = peers + peer_num;
1164 	    peer->tun_fd = fd;
1165 	    peer->local_sa = NULL;
1166 	    peer->remote_sa = NULL;
1167 	    peer->tm = &tm_tun;
1168 
1169 	    for (;;) {
1170 		do arg = strsep(&lp, " \t"); while (arg && *arg == '\0');
1171 		if (arg == NULL)
1172 		    break;
1173 		arg2 = strchr(arg, '=');
1174 		if (arg2) {
1175 		    *arg2 = '\0';
1176 		    arg2++;
1177 		} else
1178 		    arg2 = "";
1179 		if (strcmp(arg, "local_spi") == 0) {
1180 		    unsigned long spi = atoi(arg2);
1181 		    local_sa = find_local_sa(spi, NULL);
1182 		    if (local_sa == NULL) {
1183 			syslog(LOG_ALERT, "Unknown local SPI %ld on line %d",
1184 				spi, lineno);
1185 			continue;
1186 		    }
1187 		} else if (strcmp(arg, "remote_spi") == 0) {
1188 		    unsigned long spi = atoi(arg2);
1189 		    remote_sa = find_remote_sa(spi, NULL);
1190 		    if (remote_sa == NULL) {
1191 			syslog(LOG_ALERT, "Unknown remote SPI %ld on line %d",
1192 				spi, lineno);
1193 			continue;
1194 		    }
1195 #ifdef USE_ETHERTAP
1196 		} else if (strcmp(arg, "tap") == 0) {
1197 		    peer->tm = &tm_tap;
1198 		    continue;
1199 #endif
1200 		} else {
1201 		    syslog(LOG_ALERT, "Unknown keyword %s on line %d",
1202 			    arg, lineno);
1203 		}
1204 	    }
1205 	    if (!local_sa || !remote_sa) {
1206 		syslog(LOG_ALERT, "Local or remote SPI missing on line %d",
1207 			lineno);
1208 		if (local_sa)
1209 		    free(local_sa);
1210 		if (remote_sa)
1211 		    free(remote_sa);
1212 		continue;
1213 	    }
1214 	    peer->local_sa = local_sa;
1215 	    peer->remote_sa = remote_sa;
1216 	    peer_num++;
1217 	} else if (strcmp(arg, "keepalive_recv") == 0) {
1218 	    keepalive_recv = atoi(arg2);
1219 	} else if (strcmp(arg, "keepalive_send") == 0) {
1220 	    keepalive_send = atoi(arg2);
1221 	} else if (strcmp(arg, "checkifaddr") == 0) {
1222 	    check_ifaddr = atoi(arg2);
1223 	} else {
1224 	    syslog(LOG_ALERT, "unrecognized syntax on line %d", lineno);
1225 	}
1226     }
1227 }
1228 
1229 /*
1230  * Find the peer record associated with a given local SPI.
1231  */
peer_find(unsigned long spi,struct encap_method * encap)1232 struct peer_desc *peer_find(unsigned long spi, struct encap_method *encap)
1233 {
1234     unsigned short i;
1235     for (i = 0; i < peer_num; i++) {
1236 	if (peers[i].local_sa->spi == spi
1237 	    && peers[i].local_sa->em == encap)
1238 	    return peers+i;
1239     }
1240     syslog(LOG_ALERT, "unknown spi %ld", spi);
1241     return NULL;
1242 }
1243 
1244 /*
1245  * Find the SA record for a given local SPI.
1246  */
find_local_sa(unsigned long spi,struct encap_method * encap)1247 struct sa_desc *find_local_sa(unsigned long spi, struct encap_method *encap)
1248 {
1249     struct sa_desc *sap;
1250     for (sap = local_sa_list; sap; sap = sap->next)
1251 	if (sap->spi == spi && (encap == NULL || sap->em == encap))
1252 	    return sap;
1253     syslog(LOG_ALERT, "Unknown local SPI %ld", spi);
1254     return NULL;
1255 }
1256 
1257 /*
1258  * Find the SA record for a given remote SPI.
1259  */
find_remote_sa(unsigned long spi,struct encap_method * encap)1260 struct sa_desc *find_remote_sa(unsigned long spi, struct encap_method *encap)
1261 {
1262     struct sa_desc *sap;
1263     for (sap = remote_sa_list; sap; sap = sap->next)
1264 	if (sap->spi == spi && (encap == NULL || sap->em == encap))
1265 	    return sap;
1266     syslog(LOG_ALERT, "Unknown remote SPI %ld", spi);
1267     return NULL;
1268 }
1269 
1270 /*
1271  * Compute HMAC for an arbitrary stream of bytes
1272  */
hmac_compute(hash_method_t * hm,unsigned char * data,unsigned int data_size,unsigned char * digest,unsigned char do_store,unsigned char * secret,unsigned short secret_size)1273 int hmac_compute(hash_method_t *hm,
1274 		 unsigned char *data, unsigned int data_size,
1275 		 unsigned char *digest, unsigned char do_store,
1276 		 unsigned char *secret, unsigned short secret_size)
1277 {
1278     unsigned char hmac_digest[MAX_HASH_DIGEST];
1279     int i;
1280     hash_CTX hash_ctx;
1281 
1282     /* See RFC 2104 */
1283 
1284     /* XXX: this assumes sizeof(long) == 4 */
1285     unsigned long k_ipad[16];
1286     unsigned long k_opad[16];
1287 
1288     /* Prepare key pads */
1289     memset(k_ipad, 0, sizeof(k_ipad));
1290     memset(k_opad, 0, sizeof(k_opad));
1291     memcpy(k_ipad, secret, secret_size);
1292     memcpy(k_opad, secret, secret_size);
1293 
1294     for (i = 0; i < 16; i++) {
1295 	k_ipad[i] ^= 0x36363636;
1296 	k_opad[i] ^= 0x5c5c5c5c;
1297     }
1298 
1299     /* 1st pass */
1300     hm->hash_Init(&hash_ctx);
1301     hm->hash_Update(&hash_ctx, (char *)k_ipad, 64);
1302     hm->hash_Update(&hash_ctx, data, data_size);
1303     hm->hash_Final(hmac_digest, &hash_ctx);
1304 
1305     /* 2nd pass */
1306     hm->hash_Init(&hash_ctx);
1307     hm->hash_Update(&hash_ctx, (char *)k_opad, 64);
1308     hm->hash_Update(&hash_ctx, hmac_digest, hm->size);
1309     hm->hash_Final(hmac_digest, &hash_ctx);
1310 
1311     if (do_store) {
1312         memcpy(digest, hmac_digest, HMAC_SIZE);
1313         return 0;
1314     } else
1315         return memcmp(digest, hmac_digest, HMAC_SIZE);
1316 }
1317 
init_global_iv()1318 void init_global_iv()
1319 {
1320     struct random_pool {
1321 	unsigned char rand[MAX_IV_SIZE];
1322 	struct timeval t;
1323 	int pid;
1324 	int ppid;
1325 	int fd;
1326     } r;
1327     MD5_CTX ctx;
1328     unsigned char md5[16];
1329 
1330     gettimeofday(&r.t, NULL);
1331     r.pid = getpid();
1332     r.ppid = getppid();
1333     r.fd = open(_PATH_DEV_RANDOM, O_RDONLY);
1334     if (r.fd != -1) {
1335 	read(r.fd, r.rand, sizeof(r.rand));
1336 	close(r.fd);
1337     }
1338 
1339     MD5_Init(&ctx);
1340     MD5_Update(&ctx, (char *)&r, sizeof r);
1341     MD5_Final(md5, &ctx);
1342 
1343     memcpy(global_iv, md5, sizeof(global_iv));
1344 }
1345 
1346 /*
1347  * Compute HMAC for UDP encapsulation.
1348  * XXX: not really HMAC yet...
1349  */
hmac_udp_compute(struct encap_method * encap,unsigned char do_store,struct in_addr * src_ip,hash_method_t * hm,unsigned char * secret,unsigned short secret_size)1350 int hmac_udp_compute(struct encap_method *encap,
1351 		     unsigned char do_store,
1352 		     struct in_addr *src_ip, hash_method_t *hm,
1353 		     unsigned char *secret, unsigned short secret_size)
1354 {
1355     hash_CTX hash_ctx;
1356     unsigned char hmac_digest[MAX_HASH_DIGEST];
1357     udp_encap_header_t *eh = (udp_encap_header_t *)encap->buf;
1358 
1359     hm->hash_Init(&hash_ctx);
1360     hm->hash_Update(&hash_ctx, secret, secret_size);
1361     hm->hash_Update(&hash_ctx, (unsigned char *)src_ip, sizeof(*src_ip));
1362     hm->hash_Update(&hash_ctx, (unsigned char *)&eh->spi, sizeof(eh->spi));
1363     hm->hash_Update(&hash_ctx,
1364 		    (unsigned char *)&eh->seq_id, sizeof(eh->seq_id));
1365     hm->hash_Update(&hash_ctx,
1366 	      encap->buf+encap->fixed_header_size,
1367 	      encap->buflen-encap->fixed_header_size);
1368     hm->hash_Update(&hash_ctx, ":::", 3);
1369     hm->hash_Final(hmac_digest, &hash_ctx);
1370 
1371     if (do_store) {
1372         memcpy(eh->hmac, hmac_digest, HMAC_SIZE);
1373         return 0;
1374     } else
1375         return memcmp(eh->hmac, hmac_digest, HMAC_SIZE);
1376 }
1377 
1378 /*
1379  * Compute HMAC for ICMP encapsulation.
1380  * XXX: could be merged with hmac_rawip_compute
1381  */
hmac_icmp_compute(struct encap_method * encap,unsigned char do_store,struct in_addr * src_ip,hash_method_t * hm,unsigned char * secret,unsigned short secret_size)1382 int hmac_icmp_compute(struct encap_method *encap,
1383 		      unsigned char do_store,
1384 		      struct in_addr *src_ip, hash_method_t *hm,
1385 		      unsigned char *secret, unsigned short secret_size)
1386 {
1387     unsigned char hmac_save[HMAC_SIZE];
1388     icmp_encap_header_t *eh;
1389     struct ip *ip;
1390     struct icmp *icmp;
1391     int retval;
1392 
1393     unsigned char sip_ttl, sip_tos;
1394     unsigned short sip_sum, sip_off, sicmp_sum;
1395 
1396     ip = (struct ip *)encap->buf;
1397     icmp = (struct icmp *)(ip + 1);
1398     eh = (icmp_encap_header_t *)icmp;
1399 
1400     /* Save, then zero-out mutable fields before computing */
1401     sip_ttl = ip->ip_ttl;
1402     sip_sum = ip->ip_sum;
1403     sip_tos = ip->ip_tos;
1404     sip_off = ip->ip_off;
1405     sicmp_sum = icmp->icmp_cksum;
1406     if (!do_store)
1407         memcpy(hmac_save, eh->hmac, sizeof(eh->hmac));
1408     ip->ip_ttl = 0;
1409     ip->ip_sum = 0;
1410     ip->ip_tos = 0;
1411     ip->ip_off = 0;
1412     ip->ip_len = htons(ip->ip_len);
1413     memset(eh->hmac, 0, sizeof(eh->hmac));
1414     icmp->icmp_cksum = 0;
1415 
1416 #if 0
1417     printf("computing HMAC on:\n");
1418     for (i = 0; i < encap->buflen; i++) {
1419 	printf(" %02x", encap->buf[i]);
1420 	if ((i & 15) == 15) printf("\n");
1421     }
1422     printf("\n");
1423 #endif
1424 
1425     retval = hmac_compute(hm, encap->buf, encap->buflen,
1426 			  do_store?eh->hmac:hmac_save,
1427 			  do_store, secret, secret_size);
1428 
1429     /* Restore mutable fields */
1430     ip->ip_ttl = sip_ttl;
1431     ip->ip_sum = sip_sum;
1432     ip->ip_tos = sip_tos;
1433     ip->ip_off = sip_off;
1434     ip->ip_len = ntohs(ip->ip_len);
1435     icmp->icmp_cksum = sicmp_sum;
1436 
1437     if (!do_store)
1438         memcpy(eh->hmac, hmac_save, sizeof(eh->hmac));
1439 
1440     return retval;
1441 }
1442 
1443 /*
1444  * Compute HMAC for a IP_AH packet.
1445  */
hmac_rawip_compute(struct encap_method * encap,unsigned char do_store,struct in_addr * src_ip,hash_method_t * hm,unsigned char * secret,unsigned short secret_size)1446 int hmac_rawip_compute(struct encap_method *encap,
1447 		       unsigned char do_store,
1448 		       struct in_addr *src_ip, hash_method_t *hm,
1449 		       unsigned char *secret, unsigned short secret_size)
1450 {
1451     unsigned char hmac_save[HMAC_SIZE];
1452     ah_encap_header_t *eh;
1453     struct ip *ip;
1454     int retval;
1455 
1456     unsigned char sip_ttl, sip_tos;
1457     unsigned short sip_sum, sip_off;
1458 
1459     eh = (ah_encap_header_t *)(encap->buf + encap->bufpayload);
1460     ip = (struct ip *)encap->buf;
1461 
1462     /* Save, then zero-out mutable fields before computing */
1463     sip_ttl = ip->ip_ttl;
1464     sip_sum = ip->ip_sum;
1465     sip_tos = ip->ip_tos;
1466     sip_off = ip->ip_off;
1467     if (!do_store)
1468         memcpy(hmac_save, eh->hmac, sizeof(eh->hmac));
1469     ip->ip_ttl = 0;
1470     ip->ip_sum = 0;
1471     ip->ip_tos = 0;
1472     ip->ip_off = 0;
1473     ip->ip_len = htons(ip->ip_len);
1474     memset(eh->hmac, 0, sizeof(eh->hmac));
1475 
1476 #if 0
1477     printf("computing HMAC on:\n");
1478     for (i = 0; i < encap->buflen; i++) {
1479 	printf(" %02x", encap->buf[i]);
1480 	if ((i & 15) == 15) printf("\n");
1481     }
1482     printf("\n");
1483 #endif
1484 
1485     retval = hmac_compute(hm, encap->buf, encap->buflen,
1486 			  do_store?eh->hmac:hmac_save,
1487 			  do_store, secret, secret_size);
1488 
1489     /* Restore mutable fields */
1490     ip->ip_ttl = sip_ttl;
1491     ip->ip_sum = sip_sum;
1492     ip->ip_tos = sip_tos;
1493     ip->ip_off = sip_off;
1494     ip->ip_len = ntohs(ip->ip_len);
1495 
1496     if (!do_store)
1497         memcpy(eh->hmac, hmac_save, sizeof(eh->hmac));
1498 
1499     return retval;
1500 }
1501 
1502 /*
1503  * Encapsulate a packet in UDP and send to the peer.
1504  * "buf" should have exactly MAX_HEADER free bytes at its beginning
1505  * to account for encapsulation data (not counted in "size").
1506  */
encap_udp_send_peer(struct encap_method * encap,struct peer_desc * peer,unsigned char * buf,unsigned int bufsize)1507 void encap_udp_send_peer(struct encap_method *encap,
1508 			 struct peer_desc *peer,
1509 			 unsigned char *buf, unsigned int bufsize)
1510 {
1511     int sent;
1512     udp_encap_header_t *eh;
1513 
1514     /* Prepend our encapsulation header */
1515     encap->buf = buf + MAX_HEADER - encap->fixed_header_size;
1516     encap->buflen = bufsize + encap->fixed_header_size;
1517 
1518     eh = (udp_encap_header_t *)encap->buf;
1519     eh->spi = ntohl(peer->remote_sa->spi);
1520     eh->seq_id = htonl(++peer->remote_sa->seq_id);
1521 
1522     hmac_udp_compute(encap, 1,
1523 		     &peer->remote_sa->source.sin_addr, peer->remote_sa->hm,
1524 		     peer->remote_sa->auth_secret,
1525 		     peer->remote_sa->auth_secret_size);
1526 
1527     sent = sendto(encap->fd, encap->buf, encap->buflen, 0,
1528 		  (struct sockaddr *)&peer->remote_sa->dest,
1529 		  sizeof(peer->remote_sa->dest));
1530     if (sent == -1) {
1531 	syslog(LOG_ERR, "sendto: %m");
1532 	return;
1533     }
1534     if (sent != encap->buflen)
1535 	syslog(LOG_ALERT, "truncated out (%d out of %d)",
1536 		sent, encap->buflen);
1537 }
1538 
1539 /*
1540  * Encapsulate a packet in IP AH and send to the peer.
1541  * "buf" should have exactly MAX_HEADER free bytes at its beginning
1542  * to account for encapsulation data (not counted in "size").
1543  */
encap_ah_send_peer(struct encap_method * encap,struct peer_desc * peer,unsigned char * buf,unsigned int bufsize)1544 void encap_ah_send_peer(struct encap_method *encap,
1545 			struct peer_desc *peer,
1546 			unsigned char *buf, unsigned int bufsize)
1547 {
1548     int sent;
1549     ah_encap_header_t *eh;
1550     struct ip *tip, *ip;
1551 
1552     buf += MAX_HEADER;
1553 
1554     /* Keep a pointer to the old IP header */
1555     tip = (struct ip *)buf;
1556 
1557     encap->buf = buf;
1558     encap->buflen = bufsize;
1559 
1560     /* Prepend our encapsulation header and new IP header */
1561     encap->buf -= encap->fixed_header_size + sizeof(struct ip);
1562     encap->buflen += encap->fixed_header_size + sizeof(struct ip);
1563 
1564     encap->bufpayload = sizeof(struct ip);
1565 
1566     eh = (ah_encap_header_t *)(encap->buf + encap->bufpayload);
1567     ip = (struct ip *)(encap->buf);
1568 
1569     eh->spi = htonl(peer->remote_sa->spi);
1570     eh->seq_id = htonl(++peer->remote_sa->seq_id);
1571     eh->next_header = IPPROTO_IPIP;
1572     eh->payload_len = 4;
1573     eh->reserved = 0;
1574 
1575     /* Fill non-mutable fields */
1576     ip->ip_v = IPVERSION;
1577     ip->ip_hl = 5;
1578     ip->ip_len = encap->buflen;
1579     ip->ip_id = htons(ip_id++);
1580     ip->ip_p = ipproto_ah;
1581     ip->ip_src = peer->remote_sa->source.sin_addr;
1582     ip->ip_dst = peer->remote_sa->dest.sin_addr;
1583 
1584     hmac_rawip_compute(encap, 1,
1585 		       &peer->remote_sa->source.sin_addr,
1586 		       peer->remote_sa->hm,
1587 		       peer->remote_sa->auth_secret,
1588 		       peer->remote_sa->auth_secret_size);
1589 
1590     /* Fill mutable fields */
1591     ip->ip_tos = (bufsize < sizeof(struct ip)) ? 0 : tip->ip_tos;
1592     ip->ip_off = 0;
1593     ip->ip_ttl = IPDEFTTL;
1594     ip->ip_sum = 0;
1595 
1596     sent = sendto(encap->fd, encap->buf, encap->buflen, 0,
1597 		  (struct sockaddr *)&peer->remote_sa->dest,
1598 		  sizeof(peer->remote_sa->dest));
1599     if (sent == -1) {
1600 	syslog(LOG_ERR, "sendto: %m");
1601 	return;
1602     }
1603     if (sent != encap->buflen)
1604 	syslog(LOG_ALERT, "truncated out (%d out of %d)",
1605 		sent, encap->buflen);
1606 }
1607 
1608 /*
1609  * Encapsulate a packet in IP ESP and send to the peer.
1610  * "buf" should have exactly MAX_HEADER free bytes at its beginning
1611  * to account for encapsulation data (not counted in "size").
1612  */
encap_esp_send_peer(struct encap_method * encap,struct peer_desc * peer,unsigned char * buf,unsigned int bufsize)1613 void encap_esp_send_peer(struct encap_method *encap,
1614 			 struct peer_desc *peer,
1615 			 unsigned char *buf, unsigned int bufsize)
1616 {
1617     int sent;
1618     esp_encap_header_t *eh;
1619     struct ip *tip, *ip;
1620     unsigned char *iv, *cleartext;
1621     int i, padding;
1622     unsigned int cleartextlen;
1623     unsigned char impl_iv[MAX_IV_SIZE];
1624 
1625     buf += MAX_HEADER;
1626 
1627     /* Keep a pointer to the old IP header */
1628     tip = (struct ip *)buf;
1629 
1630     encap->buf = buf;
1631     encap->buflen = bufsize;
1632 
1633     /*
1634      * Add padding as necessary
1635      *
1636      * XXX: this should be checked, RFC 2406 section 2.4 is quite
1637      *	    obscure on that point.
1638      */
1639     padding = peer->remote_sa->cm->block_size
1640       - (encap->buflen+2)%peer->remote_sa->cm->block_size;
1641     if (padding == peer->remote_sa->cm->block_size)
1642         padding = 0;
1643 
1644     if ((encap->buflen+2+padding) & 3)
1645         /*
1646 	 * More padding needed to align padlen and next_header on
1647 	 * the rightmost 2 bytes of a long.
1648 	 */
1649         padding += 4 - ((encap->buflen+2+padding) & 3);
1650 
1651     for (i = 1; i <= padding; i++) {
1652         encap->buf[encap->buflen] = i;
1653 	encap->buflen++;
1654     }
1655 
1656     /* Add trailing padlen and next_header */
1657     encap->buf[encap->buflen++] = padding;
1658     encap->buf[encap->buflen++] = IPPROTO_IPIP;
1659 
1660     cleartext = buf;
1661     cleartextlen = encap->buflen;
1662 
1663     /* Prepend our encapsulation header and new IP header */
1664     if (peer->remote_sa->no_iv)
1665 	encap->var_header_size = encap->fixed_header_size;
1666     else
1667 	encap->var_header_size = encap->fixed_header_size
1668 				 + peer->remote_sa->cm->iv_size;
1669 
1670     encap->buf -= sizeof(struct ip) + encap->var_header_size;
1671     encap->buflen += sizeof(struct ip) + encap->var_header_size;
1672 
1673     encap->bufpayload = sizeof(struct ip);
1674 
1675     eh = (esp_encap_header_t *)(encap->buf + encap->bufpayload);
1676     ip = (struct ip *)(encap->buf);
1677     eh->spi = htonl(peer->remote_sa->spi);
1678     eh->seq_id = htonl(++peer->remote_sa->seq_id);
1679 
1680     if (peer->remote_sa->no_iv) {
1681 	/* Implicit IV (OpenBSD compatibility mode) */
1682 	iv = impl_iv;
1683 	memcpy(iv, &eh->seq_id, sizeof(eh->seq_id));
1684 	iv[4] = ~iv[0];
1685 	iv[5] = ~iv[1];
1686 	iv[6] = ~iv[2];
1687 	iv[7] = ~iv[3];
1688     } else {
1689 	/* Copy initialization vector in packet */
1690 	iv = (unsigned char *)(eh + 1);
1691 	memcpy(iv, global_iv, peer->remote_sa->cm->iv_size);
1692     }
1693 
1694     /* Fill non-mutable fields */
1695     ip->ip_v = IPVERSION;
1696     ip->ip_hl = 5;
1697     ip->ip_len = encap->buflen + (peer->remote_sa->hm?HMAC_SIZE:0);
1698     ip->ip_id = htons(ip_id++);
1699     ip->ip_p = ipproto_esp;
1700     ip->ip_src = peer->remote_sa->source.sin_addr;
1701     ip->ip_dst = peer->remote_sa->dest.sin_addr;
1702 
1703     /* Fill mutable fields */
1704     ip->ip_tos = (bufsize < sizeof(struct ip)) ? 0 : tip->ip_tos;
1705     ip->ip_off = 0;
1706     ip->ip_ttl = IPDEFTTL;
1707     ip->ip_sum = 0;
1708 
1709 #if 0
1710     printf("sending ESP packet (before crypt %d):\n", cleartextlen);
1711     for (i = 0; i < encap->buflen; i++)
1712         printf(" %02x", encap->buf[i]);
1713     printf("\n");
1714 #endif
1715 
1716     peer->remote_sa->cm->encrypt(global_iv, &peer->remote_sa->enc_key,
1717 				 cleartext, cleartextlen);
1718 
1719 #if 0
1720     printf("sending ESP packet (after crypt %d):\n", cleartextlen);
1721     for (i = 0; i < encap->buflen; i++)
1722         printf(" %02x", encap->buf[i]);
1723     printf("\n");
1724 #endif
1725 
1726     /* Handle optional authentication field */
1727     if (peer->remote_sa->hm) {
1728 #if 0
1729 	printf("sending ESP packet (before ah %d):\n", encap->buflen);
1730 	for (i = 0; i < encap->buflen; i++)
1731 	    printf(" %02x", encap->buf[i]);
1732 	printf("\n");
1733 #endif
1734 	hmac_compute(peer->remote_sa->hm,
1735 		     encap->buf+encap->bufpayload,
1736 		     encap->var_header_size+cleartextlen,
1737 		     encap->buf+encap->bufpayload
1738 		     +encap->var_header_size+cleartextlen,
1739 		     1,
1740 		     peer->remote_sa->auth_secret,
1741 		     peer->remote_sa->auth_secret_size);
1742 	encap->buflen += HMAC_SIZE;
1743 #if 0
1744 	printf("sending ESP packet (after ah %d):\n", encap->buflen);
1745 	for (i = 0; i < encap->buflen; i++)
1746 	    printf(" %02x", encap->buf[i]);
1747 	printf("\n");
1748 #endif
1749     }
1750 
1751     sent = sendto(encap->fd, encap->buf, encap->buflen, 0,
1752 		  (struct sockaddr *)&peer->remote_sa->dest,
1753 		  sizeof(peer->remote_sa->dest));
1754     if (sent == -1) {
1755 	syslog(LOG_ERR, "sendto: %m");
1756 	return;
1757     }
1758     if (sent != encap->buflen)
1759 	syslog(LOG_ALERT, "truncated out (%d out of %d)",
1760 		sent, encap->buflen);
1761 }
1762 
1763 /*
1764  * Encapsulate a packet in ICMP and send to the peer.
1765  * "buf" should have exactly MAX_HEADER free bytes at its beginning
1766  * to account for encapsulation data (not counted in "size").
1767  */
encap_icmp_send_peer(struct encap_method * encap,struct peer_desc * peer,unsigned char * buf,unsigned int bufsize)1768 void encap_icmp_send_peer(struct encap_method *encap,
1769 			  struct peer_desc *peer,
1770 			  unsigned char *buf, unsigned int bufsize)
1771 {
1772     int sent;
1773     icmp_encap_header_t *eh;
1774     struct ip *tip, *ip;
1775 
1776     buf += MAX_HEADER;
1777 
1778     /* Keep a pointer to the old IP header */
1779     tip = (struct ip *)buf;
1780 
1781     encap->buf = buf;
1782     encap->buflen = bufsize;
1783 
1784     /* Prepend our encapsulation header and new IP header */
1785     encap->buf -= encap->fixed_header_size + sizeof(struct ip);
1786     encap->buflen += encap->fixed_header_size + sizeof(struct ip);
1787 
1788     encap->bufpayload = sizeof(struct ip);
1789 
1790     eh = (icmp_encap_header_t *)(encap->buf + encap->bufpayload);
1791     ip = (struct ip *)(encap->buf);
1792 
1793     /* Fill non-mutable fields */
1794     ip->ip_v = IPVERSION;
1795     ip->ip_hl = 5;
1796     ip->ip_len = encap->buflen;
1797     ip->ip_id = htons(ip_id++);
1798     ip->ip_p = IPPROTO_ICMP;
1799     ip->ip_src = peer->remote_sa->source.sin_addr;
1800     ip->ip_dst = peer->remote_sa->dest.sin_addr;
1801 
1802     eh->icmp_type = ICMP_ECHOREPLY;
1803     eh->icmp_code = ipproto_ah; /* arbitrary */
1804     eh->icmp_cksum = 0;
1805     eh->spi = htonl(peer->remote_sa->spi);
1806     eh->seq_id = htonl(++peer->remote_sa->seq_id);
1807 
1808     hmac_icmp_compute(encap, 1,
1809 		      &peer->remote_sa->source.sin_addr,
1810 		      peer->remote_sa->hm,
1811 		      peer->remote_sa->auth_secret,
1812 		      peer->remote_sa->auth_secret_size);
1813 
1814     /* Fill mutable fields */
1815     ip->ip_tos = (bufsize < sizeof(struct ip)) ? 0 : tip->ip_tos;
1816     ip->ip_off = 0;
1817     ip->ip_ttl = IPDEFTTL;
1818     ip->ip_sum = 0;
1819 
1820     /* Fill ICMP checksum last */
1821     eh->icmp_cksum = in_cksum(encap->buf+sizeof(struct ip),
1822 			      encap->buflen-sizeof(struct ip));
1823 
1824     sent = sendto(encap->fd, encap->buf, encap->buflen, 0,
1825 		  (struct sockaddr *)&peer->remote_sa->dest,
1826 		  sizeof(peer->remote_sa->dest));
1827     if (sent == -1) {
1828 	syslog(LOG_ERR, "sendto: %m");
1829 	return;
1830     }
1831     if (sent != encap->buflen)
1832 	syslog(LOG_ALERT, "truncated out (%d out of %d)",
1833 		sent, encap->buflen);
1834 }
1835 
encap_hmac_recv_peer(struct encap_method * encap,struct in_addr * src_ip,struct peer_desc * peer)1836 int encap_hmac_recv_peer(struct encap_method *encap,
1837 			 struct in_addr *src_ip,
1838 			 struct peer_desc *peer)
1839 {
1840     if (encap_hmac_cmp(encap, src_ip,
1841 		       peer->local_sa->hm,
1842 		       peer->local_sa->auth_secret,
1843 		       peer->local_sa->auth_secret_size) != 0) {
1844 	syslog(LOG_ALERT, "HMAC mismatch from %s",
1845 		inet_ntoa(*src_ip));
1846 	return -1;
1847     }
1848     return 0;
1849 }
1850 
encap_esp_recv_peer(struct encap_method * encap,struct in_addr * src_ip,struct peer_desc * peer)1851 int encap_esp_recv_peer(struct encap_method *encap,
1852 			struct in_addr *src_ip,
1853 			struct peer_desc *peer)
1854 {
1855     unsigned int len, i;
1856     unsigned char padlen, next_header;
1857     unsigned char *pad;
1858     unsigned char impl_iv[MAX_IV_SIZE], *iv;
1859     struct esp_encap_header *eh;
1860 
1861     eh = (struct esp_encap_header *)(encap->buf + encap->bufpayload);
1862     if (peer->local_sa->no_iv) {
1863 	encap->var_header_size = 0;
1864 	iv = impl_iv;
1865 	memcpy(iv, &eh->seq_id, sizeof(eh->seq_id));
1866 	iv[4] = ~iv[0];
1867 	iv[5] = ~iv[1];
1868 	iv[6] = ~iv[2];
1869 	iv[7] = ~iv[3];
1870     } else {
1871 	encap->var_header_size = peer->local_sa->cm->iv_size;
1872 	iv = encap->buf + encap->bufpayload + encap->fixed_header_size;
1873     }
1874 
1875     len = encap->buflen - encap->bufpayload
1876         - encap->fixed_header_size - encap->var_header_size;
1877 
1878     if (len < 0) {
1879         syslog(LOG_ALERT, "Packet too short");
1880         return -1;
1881     }
1882 
1883     /* Handle optional authentication field */
1884     if (peer->local_sa->hm) {
1885 	len -= HMAC_SIZE;
1886 	if (hmac_compute(peer->local_sa->hm,
1887 			 encap->buf+encap->bufpayload,
1888 			 encap->fixed_header_size+encap->var_header_size+len,
1889 			 encap->buf+encap->bufpayload
1890 			 +encap->fixed_header_size+encap->var_header_size+len,
1891 			 0,
1892 			 peer->local_sa->auth_secret,
1893 			 peer->local_sa->auth_secret_size) != 0) {
1894 	    syslog(LOG_ALERT, "HMAC mismatch in ESP mode");
1895 	    return -1;
1896 	}
1897     }
1898 
1899     if ((len % peer->local_sa->cm->block_size) != 0) {
1900         syslog(LOG_ALERT,
1901 		"payload len %d not a multiple of algorithm block size %d",
1902 		len, peer->local_sa->cm->block_size);
1903 	return -1;
1904     }
1905 
1906 #if 0
1907     printf("receiving ESP packet (before decrypt):\n");
1908     for (i = 0; i < len; i++)
1909         printf(" %02x", encap->buf[encap->bufpayload
1910 				  +encap->fixed_header_size
1911 				  +encap->var_header_size+i]);
1912     printf("\n");
1913 #endif
1914 
1915     peer->local_sa->cm->decrypt(iv,
1916 				&peer->local_sa->enc_key,
1917 				encap->buf+encap->bufpayload
1918 				+encap->fixed_header_size
1919 				+encap->var_header_size,
1920 				len);
1921 
1922 #if 0
1923     printf("receiving ESP packet (after decrypt %d):\n", len);
1924     for (i = 0; i < len; i++)
1925         printf(" %02x", encap->buf[encap->bufpayload
1926 				  +encap->fixed_header_size
1927 				  +encap->var_header_size+i]);
1928     printf("\n");
1929 #endif
1930 
1931     padlen = encap->buf[encap->bufpayload
1932 		       +encap->fixed_header_size
1933 		       +encap->var_header_size+len-2];
1934     next_header = encap->buf[encap->bufpayload
1935 			    +encap->fixed_header_size
1936 			    +encap->var_header_size+len-1];
1937 
1938     if (padlen+2 > len) {
1939         syslog(LOG_ALERT, "Inconsistent padlen");
1940 	return -1;
1941     }
1942     if (next_header != IPPROTO_IPIP) {
1943         syslog(LOG_ALERT, "Inconsistent next_header %d", next_header);
1944 	return -1;
1945     }
1946 
1947 #if 0
1948     printf("pad len: %d, next_header: %d\n", padlen, next_header);
1949 #endif
1950     len -= padlen + 2;
1951 
1952     /* Check padding */
1953     pad = encap->buf + encap->bufpayload
1954         + encap->fixed_header_size
1955         + encap->var_header_size + len;
1956     for (i = 1; i <= padlen; i++) {
1957         if (*pad != i) {
1958 	    syslog(LOG_ALERT, "Bad padding");
1959 	    return -1;
1960         }
1961 	pad++;
1962     }
1963 
1964     return 0;
1965 }
1966 
blowfish_cbc_encrypt(unsigned char * iv,crypt_key * ek,unsigned char * t,unsigned int len)1967 void blowfish_cbc_encrypt(unsigned char *iv, crypt_key *ek,
1968 			  unsigned char *t, unsigned int len)
1969 {
1970     BF_cbc_encrypt(t, t, len, &ek->bf, iv, BF_ENCRYPT);
1971 }
1972 
blowfish_cbc_decrypt(unsigned char * iv,crypt_key * dk,unsigned char * ct,unsigned int len)1973 void blowfish_cbc_decrypt(unsigned char *iv, crypt_key *dk,
1974 			  unsigned char *ct, unsigned int len)
1975 {
1976     BF_cbc_encrypt(ct, ct, len, &dk->bf, iv, BF_DECRYPT);
1977 }
1978 
blowfish_setkey(unsigned char * b,unsigned int len,crypt_key * k)1979 int blowfish_setkey(unsigned char *b, unsigned int len, crypt_key *k)
1980 {
1981     BF_set_key(&k->bf, len, b);
1982     return 0;
1983 }
1984 
cast_cbc_encrypt(unsigned char * iv,crypt_key * ek,unsigned char * t,unsigned int len)1985 void cast_cbc_encrypt(unsigned char *iv, crypt_key *ek,
1986 		      unsigned char *t, unsigned int len)
1987 {
1988     CAST_cbc_encrypt(t, t, len, &ek->cast, iv, CAST_ENCRYPT);
1989 }
1990 
cast_cbc_decrypt(unsigned char * iv,crypt_key * dk,unsigned char * ct,unsigned int len)1991 void cast_cbc_decrypt(unsigned char *iv, crypt_key *dk,
1992 		      unsigned char *ct, unsigned int len)
1993 {
1994     CAST_cbc_encrypt(ct, ct, len, &dk->cast, iv, CAST_DECRYPT);
1995 }
1996 
cast_setkey(unsigned char * b,unsigned int len,crypt_key * k)1997 int cast_setkey(unsigned char *b, unsigned int len, crypt_key *k)
1998 {
1999     if (len != CAST_KEY_LENGTH)
2000 	return -1;
2001     CAST_set_key(&k->cast, len, b);
2002     return 0;
2003 }
2004 
2005 #ifndef OPENSSL_NO_IDEA
my_idea_cbc_encrypt(unsigned char * iv,crypt_key * ek,unsigned char * t,unsigned int len)2006 void my_idea_cbc_encrypt(unsigned char *iv, crypt_key *ek,
2007 			 unsigned char *t, unsigned int len)
2008 {
2009     idea_cbc_encrypt(t, t, len, &ek->idea, iv, IDEA_ENCRYPT);
2010 }
2011 
my_idea_cbc_decrypt(unsigned char * iv,crypt_key * dk,unsigned char * ct,unsigned int len)2012 void my_idea_cbc_decrypt(unsigned char *iv, crypt_key *dk,
2013 			 unsigned char *ct, unsigned int len)
2014 {
2015     idea_cbc_encrypt(ct, ct, len, &dk->idea, iv, IDEA_DECRYPT);
2016 }
2017 
my_idea_set_encrypt_key(unsigned char * b,unsigned int len,crypt_key * k)2018 int my_idea_set_encrypt_key(unsigned char *b, unsigned int len, crypt_key *k)
2019 {
2020     if (len != IDEA_KEY_LENGTH)
2021 	return -1;
2022     idea_set_encrypt_key(b, &k->idea);
2023     return 0;
2024 }
2025 
my_idea_set_decrypt_key(unsigned char * b,unsigned int len,crypt_key * k)2026 int my_idea_set_decrypt_key(unsigned char *b, unsigned int len, crypt_key *k)
2027 {
2028     if (len != IDEA_KEY_LENGTH)
2029 	return -1;
2030     idea_set_encrypt_key(b, &k->idea);
2031     idea_set_decrypt_key(&k->idea, &k->idea);
2032     return 0;
2033 }
2034 #endif
2035 
my_des_cbc_encrypt(unsigned char * iv,crypt_key * ek,unsigned char * t,unsigned int len)2036 void my_des_cbc_encrypt(unsigned char *iv, crypt_key *ek,
2037 			unsigned char *t, unsigned int len)
2038 {
2039     DES_cbc_encrypt(t, t, len, &ek->des, iv, DES_ENCRYPT);
2040 }
2041 
my_des_cbc_decrypt(unsigned char * iv,crypt_key * dk,unsigned char * ct,unsigned int len)2042 void my_des_cbc_decrypt(unsigned char *iv, crypt_key *dk,
2043 			unsigned char *ct, unsigned int len)
2044 {
2045 #if 0
2046     int i;
2047     printf("%d bytes to decrypt\n", len);
2048     for (i = 0; i < len; i++) printf(" %02x", ct[i]);
2049     printf("\n");
2050 #endif
2051     DES_cbc_encrypt(ct, ct, len, &dk->des, iv, DES_DECRYPT);
2052 #if 0
2053     printf("%d bytes after decrypt\n", len);
2054     for (i = 0; i < len; i++) printf(" %02x", ct[i]);
2055     printf("\n");
2056 #endif
2057 }
2058 
my_des_setkey(unsigned char * b,unsigned int len,crypt_key * k)2059 int my_des_setkey(unsigned char *b, unsigned int len, crypt_key *k)
2060 {
2061     if (len == 8)
2062 	return DES_set_key(b, &k->des);
2063     return -1;
2064 }
2065 
my_des3_cbc_encrypt(unsigned char * iv,crypt_key * ek,unsigned char * t,unsigned int len)2066 void my_des3_cbc_encrypt(unsigned char *iv, crypt_key *ek,
2067 			 unsigned char *t, unsigned int len)
2068 {
2069     DES_ede3_cbc_encrypt(t, t, len,
2070 			 &ek->des3.k1, &ek->des3.k2, &ek->des3.k3,
2071 			 iv, DES_ENCRYPT);
2072 }
2073 
my_des3_cbc_decrypt(unsigned char * iv,crypt_key * dk,unsigned char * ct,unsigned int len)2074 void my_des3_cbc_decrypt(unsigned char *iv, crypt_key *dk,
2075 			 unsigned char *ct, unsigned int len)
2076 {
2077     DES_ede3_cbc_encrypt(ct, ct, len,
2078 			 &dk->des3.k1, &dk->des3.k2, &dk->des3.k3,
2079 			 iv, DES_DECRYPT);
2080 }
2081 
my_des3_setkey(unsigned char * b,unsigned int len,crypt_key * k)2082 int my_des3_setkey(unsigned char *b, unsigned int len, crypt_key *k)
2083 {
2084     if (len != 24)
2085 	return -1;
2086 
2087     if (DES_set_key(b, &k->des3.k1) != 0)
2088 	return -1;
2089     if (DES_set_key(b+8, &k->des3.k2) != 0)
2090 	return -1;
2091     if (DES_set_key(b+16, &k->des3.k3) != 0)
2092 	return -1;
2093 
2094     return 0;
2095 }
2096 
null_encrypt(unsigned char * iv,crypt_key * ek,unsigned char * t,unsigned int len)2097 void null_encrypt(unsigned char *iv, crypt_key *ek,
2098 		  unsigned char *t, unsigned int len)
2099 {
2100     return;
2101 }
2102 
null_decrypt(unsigned char * iv,crypt_key * dk,unsigned char * ct,unsigned int len)2103 void null_decrypt(unsigned char *iv, crypt_key *dk,
2104 		      unsigned char *ct, unsigned int len)
2105 {
2106     return;
2107 }
2108 
null_setkey(unsigned char * b,unsigned int len,crypt_key * k)2109 int null_setkey(unsigned char *b, unsigned int len, crypt_key *k)
2110 {
2111     return 0;
2112 }
2113 
usage()2114 void usage()
2115 {
2116     fprintf(stderr, "%s: usage: [ -c CONFIG ] [ -s SCRIPT ]\n", cmd);
2117     exit(1);
2118 }
main(int argc,char ** argv)2119 int main(int argc, char **argv)
2120 {
2121     time_t t;
2122     fd_set fds;
2123     int pack, i;
2124     struct sockaddr_in from;
2125     struct stat sb;
2126     int ch;
2127     char *path_conf = _PATH_CONF;
2128     char *path_startup = _PATH_STARTUP;
2129 
2130     FILE *f;
2131 
2132     cmd=argv[0];
2133 
2134     openlog ("pipsecd", LOG_PID, LOG_DAEMON);
2135     syslog (LOG_NOTICE, "pipsecd starting");
2136 
2137     init_global_iv();
2138 
2139     tun_new(&tm_tun, NULL, 0);
2140 
2141 #ifdef USE_ETHERTAP
2142     memset(&ethtap, 0, sizeof(ethtap));
2143     ethtap.type = htons(0x0800);
2144     tun_new(&tm_tap, &ethtap, sizeof(ethtap));
2145 #endif
2146 
2147     if (encap_udp_new(&encap_meth[ENCAP_UDP], UDP_PORT) == -1)
2148 	exit(1);
2149     if (encap_ah_new(&encap_meth[ENCAP_IPAH], ipproto_ah) == -1)
2150 	exit(1);
2151     if (encap_esp_new(&encap_meth[ENCAP_IPESP], ipproto_esp) == -1)
2152 	exit(1);
2153     if (encap_icmp_new(&encap_meth[ENCAP_ICMP], IPPROTO_ICMP) == -1)
2154 	exit(1);
2155 
2156     while ((ch = getopt(argc, argv, "c:s:")) != -1) {
2157 	switch (ch) {
2158 	case 'c':
2159 	    path_conf = optarg;
2160 	    break;
2161 	case 's':
2162 	    path_startup = optarg;
2163 	    break;
2164 	case '?':
2165 	default:
2166 	    usage();
2167 	}
2168     }
2169 
2170     f = fopen(path_conf, "r");
2171     if (f == NULL) {
2172 	perror("configuration file");
2173 	exit(1);
2174     }
2175 
2176     config_read(f);
2177     fclose(f);
2178 
2179     /* Execute startup script, if any */
2180     if (stat(path_startup, &sb) == 0 && (sb.st_mode & 0400))
2181 	system(path_startup);
2182 
2183     /* Send a probe to every peer on startup */
2184     for (i = 0; i < peer_num; i++)
2185 	encap_send_peer(peers[i].remote_sa->em, peers+i, buf, 0);
2186 
2187     FD_ZERO(&fds);
2188 
2189     for (;;) {
2190 	struct timeval tv;
2191 
2192 	for (i = 0; i < ENCAP_MAX; i++)
2193 	    FD_SET(encap_get_fd(&encap_meth[i]), &fds);
2194 
2195 	for (i = 0; i < peer_num; i++)
2196 	    FD_SET(peers[i].tun_fd, &fds);
2197 
2198 	do {
2199 	    tv.tv_usec = 0;
2200 	    tv.tv_sec = keepalive_send;
2201 	    i = select(FD_SETSIZE, &fds, NULL, NULL, &tv);
2202 	    if (i == -1 && errno != EINTR)
2203 		syslog(LOG_ERR, "select: %m");
2204 	} while (i < 0);
2205 
2206 	t = time(NULL);
2207 
2208 	for (i = 0; i < peer_num; i++) {
2209 
2210 	    /* Handle checks on local interface addresses */
2211 	    if (t - peers[i].remote_sa->last_checkifaddr >= check_ifaddr) {
2212 		if (update_sa_addr(peers[i].remote_sa) == 1)
2213 		    /* Address changed, send a probe immediately */
2214 		    encap_send_peer(peers[i].remote_sa->em,
2215 				    peers+i, buf, 0);
2216 		peers[i].remote_sa->last_checkifaddr = t;
2217 	    }
2218 
2219 	    /* Handle timeout on packets sent to this peer */
2220 	    if (t - peers[i].remote_sa->last_packet_sent >= keepalive_send) {
2221 		/*
2222 		 * Send an empty packet to the other end of the tunnel,
2223 		 * just to say we're still here and let him update its
2224 		 * idea of our IP address.
2225 		 */
2226 		syslog(LOG_DEBUG, "sending update probe to peer %d", i);
2227 		encap_send_peer(peers[i].remote_sa->em, peers+i, buf, 0);
2228 
2229 		/* Update sent packet timeout */
2230 		peers[i].remote_sa->last_packet_sent = t;
2231 	    }
2232 
2233 	    /* Handle timeout on packets received from this peer */
2234 	    if (t - peers[i].remote_sa->last_packet_recv >= keepalive_recv) {
2235 		/* Back to fallback address, if any */
2236 		if (peers[i].remote_sa->use_fallback) {
2237 		    syslog(LOG_NOTICE,
2238 			   "using fallback address for peer %d", i);
2239 		    peers[i].remote_sa->dest = peers[i].remote_sa->init;
2240 		}
2241 		/* Check our local interface address for change */
2242 		update_sa_addr(peers[i].remote_sa);
2243 		/*
2244 		 * Send an empty packet to the other end of the tunnel,
2245 		 * just to say we're still here and let him update its
2246 		 * idea of our IP address.
2247 		 */
2248 		syslog(LOG_DEBUG, "sending update probe to peer %d", i);
2249 		encap_send_peer(peers[i].remote_sa->em, peers+i, buf, 0);
2250 
2251 		/* Update received packet timeout */
2252 		peers[i].remote_sa->last_packet_recv = t;
2253 	    }
2254 
2255 	    if (FD_ISSET(peers[i].tun_fd, &fds)) {
2256 
2257 		/* Receive a packet from the tunnel interface */
2258 		pack = read(peers[i].tun_fd,
2259 			    buf+MAX_HEADER-peers[i].tm->link_header_size,
2260 			    MAX_PACKET+peers[i].tm->link_header_size);
2261 		if (pack == -1) {
2262 		    syslog(LOG_ERR, "read: %m");
2263 		    continue;
2264 		}
2265 
2266 		if (peers[i].remote_sa->use_dest == 0) {
2267 		    syslog(LOG_NOTICE,
2268 			   "peer %d hasn't a known address yet", i);
2269 		    continue;
2270 		}
2271 
2272 		if (((struct ip *)(buf+MAX_HEADER))->ip_dst.s_addr
2273 		    == peers[i].remote_sa->dest.sin_addr.s_addr) {
2274 		    syslog(LOG_ALERT, "routing loop to %s",
2275 			    inet_ntoa(peers[i].remote_sa->dest.sin_addr));
2276 		    continue;
2277 		}
2278 
2279 		/* Encapsulate and send to the other end of the tunnel */
2280 		encap_send_peer(peers[i].remote_sa->em, peers+i, buf, pack);
2281 
2282 		/* Update sent packet timeout */
2283 		peers[i].remote_sa->last_packet_sent = t;
2284 	    }
2285 	}
2286 
2287 	for (i = 0; i < ENCAP_MAX; i++) {
2288 	    if (FD_ISSET(encap_get_fd(&encap_meth[i]), &fds)) {
2289 
2290 		/* Receive a packet from a socket */
2291 
2292 		struct peer_desc *peer;
2293 		struct encap_method *em;
2294 
2295 	        em = &encap_meth[i];
2296 
2297 		pack = encap_recv(em, buf, MAX_HEADER+MAX_PACKET, &from);
2298 		if (pack == -1)
2299 		    continue;
2300 
2301 		peer = encap_peer_find(em);
2302 		if (peer == NULL) {
2303 		    syslog(LOG_NOTICE, "unknown spi from %s",
2304 			    inet_ntoa(from.sin_addr));
2305 		    continue;
2306 		}
2307 
2308 		/* Check auth digest and/or decrypt */
2309 		if (encap_recv_peer(em, &from.sin_addr, peer) != 0)
2310 		    continue;
2311 
2312 		/* Check origin IP; update our copy if need be */
2313 		if (peer->remote_sa->use_dest == 0
2314 		    || from.sin_addr.s_addr
2315 		    != peer->remote_sa->dest.sin_addr.s_addr) {
2316 		    /* remote end changed address */
2317 		    char addr1[16];
2318 		    strcpy(addr1, inet_ntoa(peer->remote_sa->dest.sin_addr));
2319 		    syslog(LOG_NOTICE,
2320 			   "spi %ld: remote address changed from %s to %s",
2321 			   peer->remote_sa->spi,
2322 			   addr1,
2323 			   inet_ntoa(from.sin_addr));
2324 		    peer->remote_sa->dest.sin_addr.s_addr
2325 		      = from.sin_addr.s_addr;
2326 		    peer->remote_sa->use_dest = 1;
2327 		    update_sa_addr(peer->remote_sa);
2328 		}
2329 		/* Update received packet timeout */
2330 		peer->remote_sa->last_packet_recv = t;
2331 
2332 		if (encap_any_decap(em, peer->tun_fd) == 0)
2333 		    syslog(LOG_DEBUG, "received update probe from peer %d",
2334 			    peer - peers);
2335 		else
2336 		    /* Send the decapsulated packet to the tunnel interface */
2337 		    tun_send_ip(peer->tm, em, peer->tun_fd);
2338 	    }
2339 	}
2340     }
2341 }
2342