1 /*-
2  * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
3  *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
4  *                           Internet Initiative Japan, Inc (IIJ)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $OpenBSD: ip.c,v 1.37 2004/05/30 22:23:53 tedu Exp $
29  */
30 
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <netinet/in_systm.h>
35 #include <netinet/ip.h>
36 #ifndef NOINET6
37 #include <netinet/icmp6.h>
38 #include <netinet/ip6.h>
39 #endif
40 #include <netinet/ip_icmp.h>
41 #include <netinet/udp.h>
42 #include <netinet/tcp.h>
43 #include <sys/un.h>
44 
45 #include <errno.h>
46 #include <netdb.h>
47 #include <stdio.h>
48 #include <string.h>
49 #include <termios.h>
50 #include <unistd.h>
51 
52 #include "layer.h"
53 #include "proto.h"
54 #include "mbuf.h"
55 #include "log.h"
56 #include "defs.h"
57 #include "timer.h"
58 #include "fsm.h"
59 #include "lqr.h"
60 #include "hdlc.h"
61 #include "throughput.h"
62 #include "iplist.h"
63 #include "slcompress.h"
64 #include "ncpaddr.h"
65 #include "ip.h"
66 #include "ipcp.h"
67 #include "filter.h"
68 #include "descriptor.h"
69 #include "lcp.h"
70 #include "ccp.h"
71 #include "link.h"
72 #include "mp.h"
73 #ifndef NORADIUS
74 #include "radius.h"
75 #endif
76 #include "ipv6cp.h"
77 #include "ncp.h"
78 #include "bundle.h"
79 #include "tun.h"
80 
81 
82 #define OPCODE_QUERY	0
83 #define OPCODE_IQUERY	1
84 #define OPCODE_STATUS	2
85 
86 struct dns_header {
87   u_short id;
88   unsigned qr : 1;
89   unsigned opcode : 4;
90   unsigned aa : 1;
91   unsigned tc : 1;
92   unsigned rd : 1;
93   unsigned ra : 1;
94   unsigned z : 3;
95   unsigned rcode : 4;
96   u_short qdcount;
97   u_short ancount;
98   u_short nscount;
99   u_short arcount;
100 };
101 
102 static const char *
dns_Qclass2Txt(u_short qclass)103 dns_Qclass2Txt(u_short qclass)
104 {
105   static char failure[6];
106   struct {
107     u_short id;
108     const char *txt;
109   } qtxt[] = {
110     /* rfc1035 */
111     { 1, "IN" }, { 2, "CS" }, { 3, "CH" }, { 4, "HS" }, { 255, "*" }
112   };
113   int f;
114 
115   for (f = 0; f < sizeof qtxt / sizeof *qtxt; f++)
116     if (qtxt[f].id == qclass)
117       return qtxt[f].txt;
118 
119   return HexStr(qclass, failure, sizeof failure);
120 }
121 
122 static const char *
dns_Qtype2Txt(u_short qtype)123 dns_Qtype2Txt(u_short qtype)
124 {
125   static char failure[6];
126   struct {
127     u_short id;
128     const char *txt;
129   } qtxt[] = {
130     /* rfc1035/rfc1700 */
131     { 1, "A" }, { 2, "NS" }, { 3, "MD" }, { 4, "MF" }, { 5, "CNAME" },
132     { 6, "SOA" }, { 7, "MB" }, { 8, "MG" }, { 9, "MR" }, { 10, "NULL" },
133     { 11, "WKS" }, { 12, "PTR" }, { 13, "HINFO" }, { 14, "MINFO" },
134     { 15, "MX" }, { 16, "TXT" }, { 17, "RP" }, { 18, "AFSDB" },
135     { 19, "X25" }, { 20, "ISDN" }, { 21, "RT" }, { 22, "NSAP" },
136     { 23, "NSAP-PTR" }, { 24, "SIG" }, { 25, "KEY" }, { 26, "PX" },
137     { 27, "GPOS" }, { 28, "AAAA" }, { 252, "AXFR" }, { 253, "MAILB" },
138     { 254, "MAILA" }, { 255, "*" }
139   };
140   int f;
141 
142   for (f = 0; f < sizeof qtxt / sizeof *qtxt; f++)
143     if (qtxt[f].id == qtype)
144       return qtxt[f].txt;
145 
146   return HexStr(qtype, failure, sizeof failure);
147 }
148 
149 static __inline int
PortMatch(int op,u_short pport,u_short rport)150 PortMatch(int op, u_short pport, u_short rport)
151 {
152   switch (op) {
153   case OP_EQ:
154     return pport == rport;
155   case OP_GT:
156     return pport > rport;
157   case OP_LT:
158     return pport < rport;
159   default:
160     return 0;
161   }
162 }
163 
164 /*
165  * Return a text string representing the cproto protocol number.
166  *
167  * The purpose of this routine is calculate this result, for
168  * the many times it is needed in FilterCheck, only on demand
169  * (i.e. when the corresponding logging functions are invoked).
170  *
171  * This optimization saves, over the previous implementation, which
172  * calculated prototxt at the beginning of FilterCheck, an
173  * open/read/close system call sequence per packet, approximately
174  * halving the ppp system overhead and reducing the overall (u + s)
175  * time by 38%.
176  *
177  * The caching performed here is just a side effect.
178  */
179 static const char *
prototxt(int cproto)180 prototxt(int cproto)
181 {
182   static int oproto = -1;
183   static char protobuff[16] = "-1";
184   struct protoent *pe;
185 
186   if (cproto == oproto)
187     return protobuff;
188   if ((pe = getprotobynumber(cproto)) == NULL)
189     snprintf(protobuff, sizeof protobuff, "%d", cproto);
190   else
191     snprintf(protobuff, sizeof protobuff, "%s", pe->p_name);
192   oproto = cproto;
193   return (protobuff);
194 }
195 
196 /*
197  * Check a packet against the given filter
198  * Returns 0 to accept the packet, non-zero to drop the packet.
199  * If psecs is not NULL, populate it with the timeout associated
200  * with the filter rule matched.
201  *
202  * If filtering is enabled, the initial fragment of a datagram must
203  * contain the complete protocol header, and subsequent fragments
204  * must not attempt to over-write it.
205  *
206  * One (and only one) of pip or pip6 must be set.
207  */
208 int
FilterCheck(const unsigned char * packet,u_int32_t family,const struct filter * filter,unsigned * psecs)209 FilterCheck(const unsigned char *packet, u_int32_t family,
210             const struct filter *filter, unsigned *psecs)
211 {
212   int gotinfo;			/* true if IP payload decoded */
213   int cproto;			/* IPPROTO_* protocol number if (gotinfo) */
214   int estab, syn, finrst;	/* TCP state flags if (gotinfo) */
215   u_short sport, dport;		/* src, dest port from packet if (gotinfo) */
216   int n;			/* filter rule to process */
217   int len;			/* bytes used in dbuff */
218   int didname;			/* true if filter header printed */
219   int match;			/* true if condition matched */
220   int mindata;			/* minimum data size or zero */
221   const struct filterent *fp = filter->rule;
222   char dbuff[100], dstip[16];
223   struct ncpaddr srcaddr, dstaddr;
224   const char *payload;		/* IP payload */
225   int datalen;			/* IP datagram length */
226 
227   if (fp->f_action == A_NONE)
228     return 0;		/* No rule is given. Permit this packet */
229 
230 #ifndef NOINET6
231   if (family == AF_INET6) {
232     const struct ip6_hdr *pip6 = (const struct ip6_hdr *)packet;
233 
234     ncpaddr_setip6(&srcaddr, &pip6->ip6_src);
235     ncpaddr_setip6(&dstaddr, &pip6->ip6_dst);
236     datalen = ntohs(pip6->ip6_plen);
237     payload = packet + sizeof *pip6;
238     cproto = pip6->ip6_nxt;
239   } else
240 #endif
241   {
242     /*
243      * Deny any packet fragment that tries to over-write the header.
244      * Since we no longer have the real header available, punt on the
245      * largest normal header - 20 bytes for TCP without options, rounded
246      * up to the next possible fragment boundary.  Since the smallest
247      * `legal' MTU is 576, and the smallest recommended MTU is 296, any
248      * fragmentation within this range is dubious at best
249      */
250     const struct ip *pip = (const struct ip *)packet;
251 
252     len = ntohs(pip->ip_off) & IP_OFFMASK;	/* fragment offset */
253     if (len > 0) {		/* Not first fragment within datagram */
254       if (len < (24 >> 3)) {	/* don't allow fragment to over-write header */
255         log_Printf(LogFILTER, " error: illegal header\n");
256         return 1;
257       }
258       /* permit fragments on in and out filter */
259       if (!filter->fragok) {
260         log_Printf(LogFILTER, " error: illegal fragmentation\n");
261         return 1;
262       } else
263         return 0;
264     }
265 
266     ncpaddr_setip4(&srcaddr, pip->ip_src);
267     ncpaddr_setip4(&dstaddr, pip->ip_dst);
268     datalen = ntohs(pip->ip_len) - (pip->ip_hl << 2);
269     payload = packet + (pip->ip_hl << 2);
270     cproto = pip->ip_p;
271   }
272 
273   gotinfo = estab = syn = finrst = didname = 0;
274   sport = dport = 0;
275 
276   for (n = 0; n < MAXFILTERS; ) {
277     if (fp->f_action == A_NONE) {
278       n++;
279       fp++;
280       continue;
281     }
282 
283     if (!didname) {
284       log_Printf(LogDEBUG, "%s filter:\n", filter->name);
285       didname = 1;
286     }
287 
288     match = 0;
289 
290     if ((ncprange_family(&fp->f_src) == AF_UNSPEC ||
291          ncprange_contains(&fp->f_src, &srcaddr)) &&
292         (ncprange_family(&fp->f_dst) == AF_UNSPEC ||
293          ncprange_contains(&fp->f_dst, &dstaddr))) {
294       if (fp->f_proto != 0) {
295         if (!gotinfo) {
296           const struct tcphdr *th;
297           const struct udphdr *uh;
298           const struct icmp *ih;
299 #ifndef NOINET6
300           const struct icmp6_hdr *ih6;
301 #endif
302           mindata = 0;
303           sport = dport = 0;
304           estab = syn = finrst = -1;
305 
306           switch (cproto) {
307           case IPPROTO_ICMP:
308             mindata = 8;	/* ICMP must be at least 8 octets */
309             ih = (const struct icmp *)payload;
310             sport = ntohs(ih->icmp_type);
311             if (log_IsKept(LogDEBUG))
312               snprintf(dbuff, sizeof dbuff, "sport = %d", sport);
313             break;
314 
315 #ifndef NOINET6
316           case IPPROTO_ICMPV6:
317             mindata = 8;	/* ICMP must be at least 8 octets */
318             ih6 = (const struct icmp6_hdr *)payload;
319             sport = ntohs(ih6->icmp6_type);
320             if (log_IsKept(LogDEBUG))
321               snprintf(dbuff, sizeof dbuff, "sport = %d", sport);
322             break;
323 #endif
324 
325           case IPPROTO_IGMP:
326             mindata = 8;	/* IGMP uses 8-octet messages */
327             break;
328 
329 #ifdef IPPROTO_GRE
330           case IPPROTO_GRE:
331             mindata = 2;	/* GRE uses 2-octet+ messages */
332             break;
333 #endif
334 #ifdef IPPROTO_OSPFIGP
335           case IPPROTO_OSPFIGP:
336             mindata = 8;	/* IGMP uses 8-octet messages */
337             break;
338 #endif
339 #ifndef NOINET6
340           case IPPROTO_IPV6:
341             mindata = 20;	/* RFC2893 Section 3.5: 5 * 32bit words */
342             break;
343 #endif
344 
345           case IPPROTO_UDP:
346             mindata = 8;	/* UDP header is 8 octets */
347             uh = (const struct udphdr *)payload;
348             sport = ntohs(uh->uh_sport);
349             dport = ntohs(uh->uh_dport);
350             if (log_IsKept(LogDEBUG))
351               snprintf(dbuff, sizeof dbuff, "sport = %d, dport = %d",
352                        sport, dport);
353             break;
354 
355           case IPPROTO_TCP:
356             th = (const struct tcphdr *)payload;
357             /*
358              * TCP headers are variable length.  The following code
359              * ensures that the TCP header length isn't de-referenced if
360              * the datagram is too short
361              */
362             if (datalen < 20 || datalen < (th->th_off << 2)) {
363               log_Printf(LogFILTER, " error: TCP header incorrect\n");
364               return 1;
365             }
366             sport = ntohs(th->th_sport);
367             dport = ntohs(th->th_dport);
368             estab = (th->th_flags & TH_ACK);
369             syn = (th->th_flags & TH_SYN);
370             finrst = (th->th_flags & (TH_FIN|TH_RST));
371             if (log_IsKept(LogDEBUG)) {
372               if (!estab)
373                 snprintf(dbuff, sizeof dbuff,
374                          "flags = %02x, sport = %d, dport = %d",
375                          th->th_flags, sport, dport);
376               else
377                 *dbuff = '\0';
378             }
379             break;
380           default:
381             break;
382           }
383 
384           if (datalen < mindata) {
385             log_Printf(LogFILTER, " error: proto %s must be at least"
386                        " %d octets\n", prototxt(cproto), mindata);
387             return 1;
388           }
389 
390           if (log_IsKept(LogDEBUG)) {
391             if (estab != -1) {
392               len = strlen(dbuff);
393               snprintf(dbuff + len, sizeof dbuff - len,
394                        ", estab = %d, syn = %d, finrst = %d",
395                        estab, syn, finrst);
396             }
397             log_Printf(LogDEBUG, " Filter: proto = %s, %s\n", prototxt(cproto),
398 		dbuff);
399           }
400           gotinfo = 1;
401         }
402 
403         if (log_IsKept(LogDEBUG)) {
404           if (fp->f_srcop != OP_NONE) {
405             snprintf(dbuff, sizeof dbuff, ", src %s %d",
406                      filter_Op2Nam(fp->f_srcop), fp->f_srcport);
407             len = strlen(dbuff);
408           } else
409             len = 0;
410           if (fp->f_dstop != OP_NONE) {
411             snprintf(dbuff + len, sizeof dbuff - len,
412                      ", dst %s %d", filter_Op2Nam(fp->f_dstop),
413                      fp->f_dstport);
414           } else if (!len)
415             *dbuff = '\0';
416 
417           log_Printf(LogDEBUG, "  rule = %d: Address match, "
418                      "check against proto %d%s, action = %s\n",
419                      n, fp->f_proto, dbuff, filter_Action2Nam(fp->f_action));
420         }
421 
422         if (cproto == fp->f_proto) {
423           if ((fp->f_srcop == OP_NONE ||
424                PortMatch(fp->f_srcop, sport, fp->f_srcport)) &&
425               (fp->f_dstop == OP_NONE ||
426                PortMatch(fp->f_dstop, dport, fp->f_dstport)) &&
427               (fp->f_estab == 0 || estab) &&
428               (fp->f_syn == 0 || syn) &&
429               (fp->f_finrst == 0 || finrst)) {
430             match = 1;
431           }
432         }
433       } else {
434         /* Address is matched and no protocol specified. Make a decision. */
435         log_Printf(LogDEBUG, "  rule = %d: Address match, action = %s\n", n,
436                    filter_Action2Nam(fp->f_action));
437         match = 1;
438       }
439     } else
440       log_Printf(LogDEBUG, "  rule = %d: Address mismatch\n", n);
441 
442     if (match != fp->f_invert) {
443       /* Take specified action */
444       if (fp->f_action < A_NONE)
445         fp = &filter->rule[n = fp->f_action];
446       else {
447         if (fp->f_action == A_PERMIT) {
448           if (psecs != NULL)
449             *psecs = fp->timeout;
450           if (strcmp(filter->name, "DIAL") == 0) {
451             /* If dial filter then even print out accept packets */
452             if (log_IsKept(LogFILTER)) {
453               snprintf(dstip, sizeof dstip, "%s", ncpaddr_ntoa(&dstaddr));
454               log_Printf(LogFILTER, "%sbound rule = %d accept %s "
455                          "src = %s:%d dst = %s:%d\n", filter->name, n,
456 			 prototxt(cproto), ncpaddr_ntoa(&srcaddr),
457 			 sport, dstip, dport);
458             }
459           }
460           return 0;
461         } else {
462           if (log_IsKept(LogFILTER)) {
463             snprintf(dstip, sizeof dstip, "%s", ncpaddr_ntoa(&dstaddr));
464             log_Printf(LogFILTER,
465                        "%sbound rule = %d deny %s src = %s/%d dst = %s/%d\n",
466                        filter->name, n, prototxt(cproto),
467                        ncpaddr_ntoa(&srcaddr), sport, dstip, dport);
468           }
469           return 1;
470         }		/* Explict match.  Deny this packet */
471       }
472     } else {
473       n++;
474       fp++;
475     }
476   }
477 
478   if (log_IsKept(LogFILTER)) {
479     snprintf(dstip, sizeof dstip, "%s", ncpaddr_ntoa(&dstaddr));
480     log_Printf(LogFILTER,
481                "%sbound rule = implicit deny %s src = %s/%d dst = %s/%d\n",
482                filter->name, prototxt(cproto), ncpaddr_ntoa(&srcaddr), sport,
483                dstip, dport);
484   }
485 
486   return 1;		/* No rule matched, deny this packet */
487 }
488 
489 static void
ip_LogDNS(const struct udphdr * uh,const char * direction)490 ip_LogDNS(const struct udphdr *uh, const char *direction)
491 {
492   struct dns_header header;
493   const u_short *pktptr;
494   const u_char *ptr;
495   u_short *hptr, tmp;
496   int len;
497 
498   ptr = (const char *)uh + sizeof *uh;
499   len = ntohs(uh->uh_ulen) - sizeof *uh;
500   if (len < sizeof header + 5)		/* rfc1024 */
501     return;
502 
503   pktptr = (const u_short *)ptr;
504   hptr = (u_short *)&header;
505   ptr += sizeof header;
506   len -= sizeof header;
507 
508   while (pktptr < (const u_short *)ptr) {
509     *hptr++ = ntohs(*pktptr);		/* Careful of macro side-effects ! */
510     pktptr++;
511   }
512 
513   if (header.opcode == OPCODE_QUERY && header.qr == 0) {
514     /* rfc1035 */
515     char namewithdot[MAXHOSTNAMELEN + 1], *n;
516     const char *qtype, *qclass;
517     const u_char *end;
518 
519     n = namewithdot;
520     end = ptr + len - 4;
521     if (end - ptr >= sizeof namewithdot)
522       end = ptr + sizeof namewithdot - 1;
523     while (ptr < end) {
524       len = *ptr++;
525       if (len > end - ptr)
526         len = end - ptr;
527       if (n != namewithdot)
528         *n++ = '.';
529       memcpy(n, ptr, len);
530       ptr += len;
531       n += len;
532     }
533     *n = '\0';
534 
535     if (log_IsKept(LogDNS)) {
536       memcpy(&tmp, end, sizeof tmp);
537       qtype = dns_Qtype2Txt(ntohs(tmp));
538       memcpy(&tmp, end + 2, sizeof tmp);
539       qclass = dns_Qclass2Txt(ntohs(tmp));
540 
541       log_Printf(LogDNS, "%sbound query %s %s %s\n",
542                  direction, qclass, qtype, namewithdot);
543     }
544   }
545 }
546 
547 /*
548  * Check if the given packet matches the given filter.
549  * One of pip or pip6 must be set.
550  */
551 int
PacketCheck(struct bundle * bundle,u_int32_t family,const unsigned char * packet,int nb,struct filter * filter,const char * prefix,unsigned * psecs)552 PacketCheck(struct bundle *bundle, u_int32_t family,
553             const unsigned char *packet, int nb, struct filter *filter,
554             const char *prefix, unsigned *psecs)
555 {
556   static const char *const TcpFlags[] = {
557     "FIN", "SYN", "RST", "PSH", "ACK", "URG"
558   };
559   const struct tcphdr *th;
560   const struct udphdr *uh;
561   const struct icmp *icmph;
562 #ifndef NOINET6
563   const struct icmp6_hdr *icmp6h;
564 #endif
565   const unsigned char *payload;
566   struct ncpaddr srcaddr, dstaddr;
567   int cproto, mask, len, n, pri, logit, loglen, result;
568   char logbuf[200];
569   int datalen, frag;
570   u_char tos;
571 
572   logit = (log_IsKept(LogTCPIP) || log_IsKept(LogDNS)) &&
573           (!filter || filter->logok);
574   loglen = 0;
575   pri = 0;
576 
577 #ifndef NOINET6
578   if (family == AF_INET6) {
579     const struct ip6_hdr *pip6 = (const struct ip6_hdr *)packet;
580 
581     ncpaddr_setip6(&srcaddr, &pip6->ip6_src);
582     ncpaddr_setip6(&dstaddr, &pip6->ip6_dst);
583     datalen = ntohs(pip6->ip6_plen);
584     payload = packet + sizeof *pip6;
585     cproto = pip6->ip6_nxt;
586     tos = 0;					/* XXX: pip6->ip6_vfc >> 4 ? */
587     frag = 0;					/* XXX: ??? */
588   } else
589 #endif
590   {
591     const struct ip *pip = (const struct ip *)packet;
592 
593     ncpaddr_setip4(&srcaddr, pip->ip_src);
594     ncpaddr_setip4(&dstaddr, pip->ip_dst);
595     datalen = ntohs(pip->ip_len) - (pip->ip_hl << 2);
596     payload = packet + (pip->ip_hl << 2);
597     cproto = pip->ip_p;
598     tos = pip->ip_tos;
599     frag = ntohs(pip->ip_off) & IP_OFFMASK;
600   }
601 
602   uh = NULL;
603 
604   if (logit && loglen < sizeof logbuf) {
605     if (prefix)
606       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s", prefix);
607     else if (filter)
608       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s ", filter->name);
609     else
610       snprintf(logbuf + loglen, sizeof logbuf - loglen, "  ");
611     loglen += strlen(logbuf + loglen);
612   }
613 
614   switch (cproto) {
615   case IPPROTO_ICMP:
616     if (logit && loglen < sizeof logbuf) {
617       len = datalen - sizeof *icmph;
618       icmph = (const struct icmp *)payload;
619       snprintf(logbuf + loglen, sizeof logbuf - loglen,
620                "ICMP: %s:%d ---> ", ncpaddr_ntoa(&srcaddr), icmph->icmp_type);
621       loglen += strlen(logbuf + loglen);
622       snprintf(logbuf + loglen, sizeof logbuf - loglen,
623                "%s (%d/%d)", ncpaddr_ntoa(&dstaddr), len, nb);
624       loglen += strlen(logbuf + loglen);
625     }
626     break;
627 
628 #ifndef NOINET6
629   case IPPROTO_ICMPV6:
630     if (logit && loglen < sizeof logbuf) {
631       len = datalen - sizeof *icmp6h;
632       icmp6h = (const struct icmp6_hdr *)payload;
633       snprintf(logbuf + loglen, sizeof logbuf - loglen,
634                "ICMP: %s:%d ---> ", ncpaddr_ntoa(&srcaddr), icmp6h->icmp6_type);
635       loglen += strlen(logbuf + loglen);
636       snprintf(logbuf + loglen, sizeof logbuf - loglen,
637                "%s (%d/%d)", ncpaddr_ntoa(&dstaddr), len, nb);
638       loglen += strlen(logbuf + loglen);
639     }
640     break;
641 #endif
642 
643   case IPPROTO_UDP:
644     uh = (const struct udphdr *)payload;
645     if (tos == IPTOS_LOWDELAY && bundle->ncp.cfg.urgent.tos)
646       pri++;
647 
648     if (!frag && ncp_IsUrgentUdpPort(&bundle->ncp, ntohs(uh->uh_sport),
649                                      ntohs(uh->uh_dport)))
650       pri++;
651 
652     if (logit && loglen < sizeof logbuf) {
653       len = datalen - sizeof *uh;
654       snprintf(logbuf + loglen, sizeof logbuf - loglen,
655                "UDP: %s:%d ---> ", ncpaddr_ntoa(&srcaddr), ntohs(uh->uh_sport));
656       loglen += strlen(logbuf + loglen);
657       snprintf(logbuf + loglen, sizeof logbuf - loglen,
658                "%s:%d (%d/%d)", ncpaddr_ntoa(&dstaddr), ntohs(uh->uh_dport),
659                len, nb);
660       loglen += strlen(logbuf + loglen);
661     }
662 
663     if (Enabled(bundle, OPT_FILTERDECAP) &&
664         payload[sizeof *uh] == HDLC_ADDR &&
665         payload[sizeof *uh + 1] == HDLC_UI) {
666       u_short proto;
667       const char *type;
668 
669       memcpy(&proto, payload + sizeof *uh + 2, sizeof proto);
670       type = NULL;
671 
672       switch (ntohs(proto)) {
673         case PROTO_IP:
674           snprintf(logbuf + loglen, sizeof logbuf - loglen, " contains ");
675           result = PacketCheck(bundle, AF_INET, payload + sizeof *uh + 4,
676                                nb - (payload - packet) - sizeof *uh - 4, filter,
677                                logbuf, psecs);
678           if (result != -2)
679               return result;
680           type = "IP";
681           break;
682 
683         case PROTO_VJUNCOMP: type = "compressed VJ";   break;
684         case PROTO_VJCOMP:   type = "uncompressed VJ"; break;
685         case PROTO_MP:       type = "Multi-link"; break;
686         case PROTO_ICOMPD:   type = "Individual link CCP"; break;
687         case PROTO_COMPD:    type = "CCP"; break;
688         case PROTO_IPCP:     type = "IPCP"; break;
689         case PROTO_LCP:      type = "LCP"; break;
690         case PROTO_PAP:      type = "PAP"; break;
691         case PROTO_CBCP:     type = "CBCP"; break;
692         case PROTO_LQR:      type = "LQR"; break;
693         case PROTO_CHAP:     type = "CHAP"; break;
694       }
695       if (type) {
696         snprintf(logbuf + loglen, sizeof logbuf - loglen,
697                  " - %s data", type);
698         loglen += strlen(logbuf + loglen);
699       }
700     }
701 
702     break;
703 
704 #ifdef IPPROTO_GRE
705   case IPPROTO_GRE:
706     if (logit && loglen < sizeof logbuf) {
707       snprintf(logbuf + loglen, sizeof logbuf - loglen,
708           "GRE: %s ---> ", ncpaddr_ntoa(&srcaddr));
709       loglen += strlen(logbuf + loglen);
710       snprintf(logbuf + loglen, sizeof logbuf - loglen,
711               "%s (%d/%d)", ncpaddr_ntoa(&dstaddr), datalen, nb);
712       loglen += strlen(logbuf + loglen);
713     }
714     break;
715 #endif
716 
717 #ifdef IPPROTO_OSPFIGP
718   case IPPROTO_OSPFIGP:
719     if (logit && loglen < sizeof logbuf) {
720       snprintf(logbuf + loglen, sizeof logbuf - loglen,
721                "OSPF: %s ---> ", ncpaddr_ntoa(&srcaddr));
722       loglen += strlen(logbuf + loglen);
723       snprintf(logbuf + loglen, sizeof logbuf - loglen,
724                "%s (%d/%d)", ncpaddr_ntoa(&dstaddr), datalen, nb);
725       loglen += strlen(logbuf + loglen);
726     }
727     break;
728 #endif
729 
730 #ifndef NOINET6
731   case IPPROTO_IPV6:
732     if (logit && loglen < sizeof logbuf) {
733       snprintf(logbuf + loglen, sizeof logbuf - loglen,
734                "IPv6: %s ---> ", ncpaddr_ntoa(&srcaddr));
735       loglen += strlen(logbuf + loglen);
736       snprintf(logbuf + loglen, sizeof logbuf - loglen,
737                "%s (%d/%d)", ncpaddr_ntoa(&dstaddr), datalen, nb);
738       loglen += strlen(logbuf + loglen);
739     }
740 
741     if (Enabled(bundle, OPT_FILTERDECAP)) {
742       snprintf(logbuf + loglen, sizeof logbuf - loglen, " contains ");
743       result = PacketCheck(bundle, AF_INET6, payload, nb - (payload - packet),
744                            filter, logbuf, psecs);
745       if (result != -2)
746         return result;
747     }
748     break;
749 #endif
750 
751   case IPPROTO_IPIP:
752     if (logit && loglen < sizeof logbuf) {
753       snprintf(logbuf + loglen, sizeof logbuf - loglen,
754                "IPIP: %s ---> ", ncpaddr_ntoa(&srcaddr));
755       loglen += strlen(logbuf + loglen);
756       snprintf(logbuf + loglen, sizeof logbuf - loglen,
757                "%s", ncpaddr_ntoa(&dstaddr));
758       loglen += strlen(logbuf + loglen);
759     }
760 
761     if (Enabled(bundle, OPT_FILTERDECAP) &&
762         ((const struct ip *)payload)->ip_v == 4) {
763       snprintf(logbuf + loglen, sizeof logbuf - loglen, " contains ");
764       result = PacketCheck(bundle, AF_INET, payload, nb - (payload - packet),
765                            filter, logbuf, psecs);
766       if (result != -2)
767         return result;
768     }
769     break;
770 
771   case IPPROTO_ESP:
772     if (logit && loglen < sizeof logbuf) {
773       snprintf(logbuf + loglen, sizeof logbuf - loglen,
774                "ESP: %s ---> ", ncpaddr_ntoa(&srcaddr));
775       loglen += strlen(logbuf + loglen);
776       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s, spi %p",
777                ncpaddr_ntoa(&dstaddr), payload);
778       loglen += strlen(logbuf + loglen);
779     }
780     break;
781 
782   case IPPROTO_AH:
783     if (logit && loglen < sizeof logbuf) {
784       snprintf(logbuf + loglen, sizeof logbuf - loglen,
785                "AH: %s ---> ", ncpaddr_ntoa(&srcaddr));
786       loglen += strlen(logbuf + loglen);
787       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s, spi %p",
788                ncpaddr_ntoa(&dstaddr), payload + sizeof(u_int32_t));
789       loglen += strlen(logbuf + loglen);
790     }
791     break;
792 
793   case IPPROTO_IGMP:
794     if (logit && loglen < sizeof logbuf) {
795       uh = (const struct udphdr *)payload;
796       snprintf(logbuf + loglen, sizeof logbuf - loglen,
797                "IGMP: %s:%d ---> ", ncpaddr_ntoa(&srcaddr),
798                ntohs(uh->uh_sport));
799       loglen += strlen(logbuf + loglen);
800       snprintf(logbuf + loglen, sizeof logbuf - loglen,
801                "%s:%d", ncpaddr_ntoa(&dstaddr), ntohs(uh->uh_dport));
802       loglen += strlen(logbuf + loglen);
803     }
804     break;
805 
806   case IPPROTO_TCP:
807     th = (const struct tcphdr *)payload;
808     if (tos == IPTOS_LOWDELAY && bundle->ncp.cfg.urgent.tos)
809       pri++;
810 
811     if (!frag && ncp_IsUrgentTcpPort(&bundle->ncp, ntohs(th->th_sport),
812                                      ntohs(th->th_dport)))
813       pri++;
814 
815     if (logit && loglen < sizeof logbuf) {
816       len = datalen - (th->th_off << 2);
817       snprintf(logbuf + loglen, sizeof logbuf - loglen,
818            "TCP: %s:%d ---> ", ncpaddr_ntoa(&srcaddr), ntohs(th->th_sport));
819       loglen += strlen(logbuf + loglen);
820       snprintf(logbuf + loglen, sizeof logbuf - loglen,
821                "%s:%d", ncpaddr_ntoa(&dstaddr), ntohs(th->th_dport));
822       loglen += strlen(logbuf + loglen);
823       n = 0;
824       for (mask = TH_FIN; mask != 0x40; mask <<= 1) {
825         if (th->th_flags & mask) {
826           snprintf(logbuf + loglen, sizeof logbuf - loglen, " %s", TcpFlags[n]);
827           loglen += strlen(logbuf + loglen);
828         }
829         n++;
830       }
831       snprintf(logbuf + loglen, sizeof logbuf - loglen,
832                "  seq:%lx  ack:%lx (%d/%d)",
833                (u_long)ntohl(th->th_seq), (u_long)ntohl(th->th_ack), len, nb);
834       loglen += strlen(logbuf + loglen);
835       if ((th->th_flags & TH_SYN) && nb > 40) {
836         const u_short *sp;
837 
838         sp = (const u_short *)(payload + 20);
839         if (ntohs(sp[0]) == 0x0204) {
840           snprintf(logbuf + loglen, sizeof logbuf - loglen,
841                    " MSS = %d", ntohs(sp[1]));
842           loglen += strlen(logbuf + loglen);
843         }
844       }
845     }
846     break;
847 
848   default:
849     if (prefix)
850       return -2;
851 
852     if (logit && loglen < sizeof logbuf) {
853       snprintf(logbuf + loglen, sizeof logbuf - loglen,
854                "<%d>: %s ---> ", cproto, ncpaddr_ntoa(&srcaddr));
855       loglen += strlen(logbuf + loglen);
856       snprintf(logbuf + loglen, sizeof logbuf - loglen,
857                "%s (%d)", ncpaddr_ntoa(&dstaddr), nb);
858       loglen += strlen(logbuf + loglen);
859     }
860     break;
861   }
862 
863   if (filter && FilterCheck(packet, family, filter, psecs)) {
864     if (logit)
865       log_Printf(LogTCPIP, "%s - BLOCKED\n", logbuf);
866     result = -1;
867   } else {
868     /* Check Keep Alive filter */
869     if (logit && log_IsKept(LogTCPIP)) {
870       unsigned alivesecs;
871 
872       alivesecs = 0;
873       if (filter &&
874           FilterCheck(packet, family, &bundle->filter.alive, &alivesecs))
875         log_Printf(LogTCPIP, "%s - NO KEEPALIVE\n", logbuf);
876       else if (psecs != NULL) {
877         if(*psecs == 0)
878           *psecs = alivesecs;
879         if (*psecs) {
880           if (*psecs != alivesecs)
881             log_Printf(LogTCPIP, "%s - (timeout = %d / ALIVE = %d secs)\n",
882                        logbuf, *psecs, alivesecs);
883           else
884             log_Printf(LogTCPIP, "%s - (timeout = %d secs)\n", logbuf, *psecs);
885         } else
886           log_Printf(LogTCPIP, "%s\n", logbuf);
887       }
888     }
889     result = pri;
890   }
891 
892   if (filter && uh && ntohs(uh->uh_dport) == 53 && log_IsKept(LogDNS))
893     ip_LogDNS(uh, filter->name);
894 
895   return result;
896 }
897 
898 static int
ip_Input(struct bundle * bundle,struct link * l,struct mbuf * bp,u_int32_t af)899 ip_Input(struct bundle *bundle, struct link *l, struct mbuf *bp, u_int32_t af)
900 {
901   int nb, nw;
902   struct tun_data tun;
903   char *data;
904   unsigned secs, alivesecs;
905 
906   nb = m_length(bp);
907   if (nb > sizeof tun.data) {
908     log_Printf(LogWARN, "ip_Input: %s: Packet too large (got %d, max %d)\n",
909                l->name, nb, (int)(sizeof tun.data));
910     m_freem(bp);
911     return 0;
912   }
913   mbuf_Read(bp, tun.data, nb);
914 
915   secs = 0;
916   if (PacketCheck(bundle, af, tun.data, nb, &bundle->filter.in,
917                   NULL, &secs) < 0)
918     return 0;
919 
920   alivesecs = 0;
921   if (!FilterCheck(tun.data, af, &bundle->filter.alive, &alivesecs)) {
922     if (secs == 0)
923       secs = alivesecs;
924     bundle_StartIdleTimer(bundle, secs);
925   }
926 
927   if (bundle->dev.header) {
928     tun.header.family = htonl(af);
929     nb += sizeof tun - sizeof tun.data;
930     data = (char *)&tun;
931   } else
932     data = tun.data;
933 
934   nw = write(bundle->dev.fd, data, nb);
935   if (nw != nb) {
936     if (nw == -1)
937       log_Printf(LogERROR, "ip_Input: %s: wrote %d, got %s\n",
938                  l->name, nb, strerror(errno));
939     else
940       log_Printf(LogERROR, "ip_Input: %s: wrote %d, got %d\n", l->name, nb, nw);
941   }
942 
943   return nb;
944 }
945 
946 struct mbuf *
ipv4_Input(struct bundle * bundle,struct link * l,struct mbuf * bp)947 ipv4_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
948 {
949   int nb;
950 
951   if (bundle->ncp.ipcp.fsm.state != ST_OPENED) {
952     log_Printf(LogWARN, "ipv4_Input: IPCP not open - packet dropped\n");
953     m_freem(bp);
954     return NULL;
955   }
956 
957   m_settype(bp, MB_IPIN);
958 
959   nb = ip_Input(bundle, l, bp, AF_INET);
960   ipcp_AddInOctets(&bundle->ncp.ipcp, nb);
961 
962   return NULL;
963 }
964 
965 #ifndef NOINET6
966 struct mbuf *
ipv6_Input(struct bundle * bundle,struct link * l,struct mbuf * bp)967 ipv6_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
968 {
969   int nb;
970 
971   if (bundle->ncp.ipv6cp.fsm.state != ST_OPENED) {
972     log_Printf(LogWARN, "ipv6_Input: IPV6CP not open - packet dropped\n");
973     m_freem(bp);
974     return NULL;
975   }
976 
977   m_settype(bp, MB_IPV6IN);
978 
979   nb = ip_Input(bundle, l, bp, AF_INET6);
980   ipv6cp_AddInOctets(&bundle->ncp.ipv6cp, nb);
981 
982   return NULL;
983 }
984 #endif
985