xref: /freebsd/usr.sbin/ppp/ip.c (revision 52847614)
1 /*
2  *		PPP IP Protocol Interface
3  *
4  *	    Written by Toshiharu OHNO (tony-o@iij.ad.jp)
5  *
6  *   Copyright (C) 1993, Internet Initiative Japan, Inc. All rights reserverd.
7  *
8  * Redistribution and use in source and binary forms are permitted
9  * provided that the above copyright notice and this paragraph are
10  * duplicated in all such forms and that any documentation,
11  * advertising materials, and other materials related to such
12  * distribution and use acknowledge that the software was developed
13  * by the Internet Initiative Japan.  The name of the
14  * IIJ may not be used to endorse or promote products derived
15  * from this software without specific prior written permission.
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19  *
20  * $FreeBSD$
21  *
22  *	TODO:
23  *		o Return ICMP message for filterd packet
24  *		  and optionaly record it into log.
25  */
26 #include <sys/param.h>
27 #include <sys/socket.h>
28 #include <netinet/in.h>
29 #include <netinet/in_systm.h>
30 #include <netinet/ip.h>
31 #include <netinet/ip_icmp.h>
32 #include <netinet/udp.h>
33 #include <netinet/tcp.h>
34 #include <arpa/inet.h>
35 #include <sys/un.h>
36 
37 #include <errno.h>
38 #include <stdio.h>
39 #include <string.h>
40 #include <termios.h>
41 #include <unistd.h>
42 
43 #include "layer.h"
44 #include "proto.h"
45 #include "mbuf.h"
46 #include "log.h"
47 #include "defs.h"
48 #include "timer.h"
49 #include "fsm.h"
50 #include "lqr.h"
51 #include "hdlc.h"
52 #include "throughput.h"
53 #include "iplist.h"
54 #include "slcompress.h"
55 #include "ipcp.h"
56 #include "filter.h"
57 #include "descriptor.h"
58 #include "lcp.h"
59 #include "ccp.h"
60 #include "link.h"
61 #include "mp.h"
62 #ifndef NORADIUS
63 #include "radius.h"
64 #endif
65 #include "bundle.h"
66 #include "tun.h"
67 #include "ip.h"
68 
69 
70 #define OPCODE_QUERY	0
71 #define OPCODE_IQUERY	1
72 #define OPCODE_STATUS	2
73 
74 struct dns_header {
75   u_short id;
76   unsigned qr : 1;
77   unsigned opcode : 4;
78   unsigned aa : 1;
79   unsigned tc : 1;
80   unsigned rd : 1;
81   unsigned ra : 1;
82   unsigned z : 3;
83   unsigned rcode : 4;
84   u_short qdcount;
85   u_short ancount;
86   u_short nscount;
87   u_short arcount;
88 };
89 
90 static const char *
91 dns_Qclass2Txt(u_short qclass)
92 {
93   static char failure[6];
94   struct {
95     u_short id;
96     const char *txt;
97   } qtxt[] = {
98     /* rfc1035 */
99     { 1, "IN" }, { 2, "CS" }, { 3, "CH" }, { 4, "HS" }, { 255, "*" }
100   };
101   int f;
102 
103   for (f = 0; f < sizeof qtxt / sizeof *qtxt; f++)
104     if (qtxt[f].id == qclass)
105       return qtxt[f].txt;
106 
107   return HexStr(qclass, failure, sizeof failure);
108 }
109 
110 static const char *
111 dns_Qtype2Txt(u_short qtype)
112 {
113   static char failure[6];
114   struct {
115     u_short id;
116     const char *txt;
117   } qtxt[] = {
118     /* rfc1035/rfc1700 */
119     { 1, "A" }, { 2, "NS" }, { 3, "MD" }, { 4, "MF" }, { 5, "CNAME" },
120     { 6, "SOA" }, { 7, "MB" }, { 8, "MG" }, { 9, "MR" }, { 10, "NULL" },
121     { 11, "WKS" }, { 12, "PTR" }, { 13, "HINFO" }, { 14, "MINFO" },
122     { 15, "MX" }, { 16, "TXT" }, { 17, "RP" }, { 18, "AFSDB" },
123     { 19, "X25" }, { 20, "ISDN" }, { 21, "RT" }, { 22, "NSAP" },
124     { 23, "NSAP-PTR" }, { 24, "SIG" }, { 25, "KEY" }, { 26, "PX" },
125     { 27, "GPOS" }, { 28, "AAAA" }, { 252, "AXFR" }, { 253, "MAILB" },
126     { 254, "MAILA" }, { 255, "*" }
127   };
128   int f;
129 
130   for (f = 0; f < sizeof qtxt / sizeof *qtxt; f++)
131     if (qtxt[f].id == qtype)
132       return qtxt[f].txt;
133 
134   return HexStr(qtype, failure, sizeof failure);
135 }
136 
137 static __inline int
138 PortMatch(int op, u_short pport, u_short rport)
139 {
140   switch (op) {
141   case OP_EQ:
142     return pport == rport;
143   case OP_GT:
144     return pport > rport;
145   case OP_LT:
146     return pport < rport;
147   default:
148     return 0;
149   }
150 }
151 
152 /*
153  *  Check a packet against a defined filter
154  *  Returns 0 to accept the packet, non-zero to drop the packet
155  *
156  *  If filtering is enabled, the initial fragment of a datagram must
157  *  contain the complete protocol header, and subsequent fragments
158  *  must not attempt to over-write it.
159  */
160 static int
161 FilterCheck(const struct ip *pip, const struct filter *filter, unsigned *psecs)
162 {
163   int gotinfo;			/* true if IP payload decoded */
164   int cproto;			/* P_* protocol type if (gotinfo) */
165   int estab, syn, finrst;	/* TCP state flags if (gotinfo) */
166   u_short sport, dport;		/* src, dest port from packet if (gotinfo) */
167   int n;			/* filter rule to process */
168   int len;			/* bytes used in dbuff */
169   int didname;			/* true if filter header printed */
170   int match;			/* true if condition matched */
171   const struct filterent *fp = filter->rule;
172   char dbuff[100], dstip[16];
173 
174   if (fp->f_action == A_NONE)
175     return 0;		/* No rule is given. Permit this packet */
176 
177   /*
178    * Deny any packet fragment that tries to over-write the header.
179    * Since we no longer have the real header available, punt on the
180    * largest normal header - 20 bytes for TCP without options, rounded
181    * up to the next possible fragment boundary.  Since the smallest
182    * `legal' MTU is 576, and the smallest recommended MTU is 296, any
183    * fragmentation within this range is dubious at best
184    */
185   len = ntohs(pip->ip_off) & IP_OFFMASK;	/* fragment offset */
186   if (len > 0) {		/* Not first fragment within datagram */
187     if (len < (24 >> 3)) {	/* don't allow fragment to over-write header */
188       log_Printf(LogFILTER, " error: illegal header\n");
189       return 1;
190     }
191     /* permit fragments on in and out filter */
192     if (!filter->fragok) {
193       log_Printf(LogFILTER, " error: illegal fragmentation\n");
194       return 1;
195     } else
196       return 0;
197   }
198 
199   cproto = gotinfo = estab = syn = finrst = didname = 0;
200   sport = dport = 0;
201   for (n = 0; n < MAXFILTERS; ) {
202     if (fp->f_action == A_NONE) {
203       n++;
204       fp++;
205       continue;
206     }
207 
208     if (!didname) {
209       log_Printf(LogDEBUG, "%s filter:\n", filter->name);
210       didname = 1;
211     }
212 
213     match = 0;
214     if (!((pip->ip_src.s_addr ^ fp->f_src.ipaddr.s_addr) &
215           fp->f_src.mask.s_addr) &&
216         !((pip->ip_dst.s_addr ^ fp->f_dst.ipaddr.s_addr) &
217           fp->f_dst.mask.s_addr)) {
218       if (fp->f_proto != P_NONE) {
219         if (!gotinfo) {
220           const char *ptop = (const char *) pip + (pip->ip_hl << 2);
221           const struct tcphdr *th;
222           const struct udphdr *uh;
223           const struct icmp *ih;
224           int datalen;	/* IP datagram length */
225 
226           datalen = ntohs(pip->ip_len) - (pip->ip_hl << 2);
227           switch (pip->ip_p) {
228           case IPPROTO_ICMP:
229             cproto = P_ICMP;
230             if (datalen < 8) {	/* ICMP must be at least 8 octets */
231               log_Printf(LogFILTER, " error: ICMP must be at least 8 octets\n");
232               return 1;
233             }
234 
235             ih = (const struct icmp *) ptop;
236             sport = ih->icmp_type;
237             estab = syn = finrst = -1;
238             if (log_IsKept(LogDEBUG))
239               snprintf(dbuff, sizeof dbuff, "sport = %d", sport);
240             break;
241           case IPPROTO_IGMP:
242             cproto = P_IGMP;
243             if (datalen < 8) {	/* IGMP uses 8-octet messages */
244               log_Printf(LogFILTER, " error: IGMP must be at least 8 octets\n");
245               return 1;
246             }
247             estab = syn = finrst = -1;
248             sport = ntohs(0);
249             break;
250 #ifdef IPPROTO_GRE
251           case IPPROTO_GRE:
252             cproto = P_GRE;
253             if (datalen < 2) {    /* GRE uses 2-octet+ messages */
254               log_Printf(LogFILTER, " error: GRE must be at least 2 octets\n");
255               return 1;
256             }
257             estab = syn = finrst = -1;
258             sport = ntohs(0);
259             break;
260 #endif
261 #ifdef IPPROTO_OSPFIGP
262           case IPPROTO_OSPFIGP:
263             cproto = P_OSPF;
264             if (datalen < 8) {	/* IGMP uses 8-octet messages */
265               log_Printf(LogFILTER, " error: IGMP must be at least 8 octets\n");
266               return 1;
267             }
268             estab = syn = finrst = -1;
269             sport = ntohs(0);
270             break;
271 #endif
272           case IPPROTO_ESP:
273             cproto = P_ESP;
274             estab = syn = finrst = -1;
275             sport = ntohs(0);
276             break;
277           case IPPROTO_AH:
278             cproto = P_AH;
279             estab = syn = finrst = -1;
280             sport = ntohs(0);
281             break;
282           case IPPROTO_UDP:
283           case IPPROTO_IPIP:
284             cproto = P_UDP;
285             if (datalen < 8) {	/* UDP header is 8 octets */
286               log_Printf(LogFILTER, " error: UDP must be at least 8 octets\n");
287               return 1;
288             }
289 
290             uh = (const struct udphdr *) ptop;
291             sport = ntohs(uh->uh_sport);
292             dport = ntohs(uh->uh_dport);
293             estab = syn = finrst = -1;
294             if (log_IsKept(LogDEBUG))
295               snprintf(dbuff, sizeof dbuff, "sport = %d, dport = %d",
296                        sport, dport);
297             break;
298           case IPPROTO_TCP:
299             cproto = P_TCP;
300             th = (const struct tcphdr *) ptop;
301             /* TCP headers are variable length.  The following code
302              * ensures that the TCP header length isn't de-referenced if
303              * the datagram is too short
304              */
305             if (datalen < 20 || datalen < (th->th_off << 2)) {
306               log_Printf(LogFILTER, " error: TCP header incorrect\n");
307               return 1;
308             }
309             sport = ntohs(th->th_sport);
310             dport = ntohs(th->th_dport);
311             estab = (th->th_flags & TH_ACK);
312             syn = (th->th_flags & TH_SYN);
313             finrst = (th->th_flags & (TH_FIN|TH_RST));
314             if (log_IsKept(LogDEBUG)) {
315               if (!estab)
316                 snprintf(dbuff, sizeof dbuff,
317                          "flags = %02x, sport = %d, dport = %d",
318                          th->th_flags, sport, dport);
319               else
320                 *dbuff = '\0';
321             }
322             break;
323           default:
324             log_Printf(LogFILTER, " error: unknown protocol\n");
325             return 1;		/* We'll block unknown type of packet */
326           }
327 
328           if (log_IsKept(LogDEBUG)) {
329             if (estab != -1) {
330               len = strlen(dbuff);
331               snprintf(dbuff + len, sizeof dbuff - len,
332                        ", estab = %d, syn = %d, finrst = %d",
333                        estab, syn, finrst);
334             }
335             log_Printf(LogDEBUG, " Filter: proto = %s, %s\n",
336                        filter_Proto2Nam(cproto), dbuff);
337           }
338           gotinfo = 1;
339         }
340         if (log_IsKept(LogDEBUG)) {
341           if (fp->f_srcop != OP_NONE) {
342             snprintf(dbuff, sizeof dbuff, ", src %s %d",
343                      filter_Op2Nam(fp->f_srcop), fp->f_srcport);
344             len = strlen(dbuff);
345           } else
346             len = 0;
347           if (fp->f_dstop != OP_NONE) {
348             snprintf(dbuff + len, sizeof dbuff - len,
349                      ", dst %s %d", filter_Op2Nam(fp->f_dstop),
350                      fp->f_dstport);
351           } else if (!len)
352             *dbuff = '\0';
353 
354           log_Printf(LogDEBUG, "  rule = %d: Address match, "
355                      "check against proto %s%s, action = %s\n",
356                      n, filter_Proto2Nam(fp->f_proto),
357                      dbuff, filter_Action2Nam(fp->f_action));
358         }
359 
360         if (cproto == fp->f_proto) {
361           if ((fp->f_srcop == OP_NONE ||
362                PortMatch(fp->f_srcop, sport, fp->f_srcport)) &&
363               (fp->f_dstop == OP_NONE ||
364                PortMatch(fp->f_dstop, dport, fp->f_dstport)) &&
365               (fp->f_estab == 0 || estab) &&
366               (fp->f_syn == 0 || syn) &&
367               (fp->f_finrst == 0 || finrst)) {
368             match = 1;
369           }
370         }
371       } else {
372         /* Address is matched and no protocol specified. Make a decision. */
373         log_Printf(LogDEBUG, "  rule = %d: Address match, action = %s\n", n,
374                    filter_Action2Nam(fp->f_action));
375         match = 1;
376       }
377     } else
378       log_Printf(LogDEBUG, "  rule = %d: Address mismatch\n", n);
379 
380     if (match != fp->f_invert) {
381       /* Take specified action */
382       if (fp->f_action < A_NONE)
383         fp = &filter->rule[n = fp->f_action];
384       else {
385         if (fp->f_action == A_PERMIT) {
386           if (psecs != NULL)
387             *psecs = fp->timeout;
388           if (strcmp(filter->name, "DIAL") == 0) {
389             /* If dial filter then even print out accept packets */
390             if (log_IsKept(LogFILTER)) {
391               snprintf(dstip, sizeof dstip, "%s", inet_ntoa(pip->ip_dst));
392               log_Printf(LogFILTER, "%sbound rule = %d accept %s "
393                          "src = %s/%d dst = %s/%d\n",
394                          filter->name, n, filter_Proto2Nam(cproto),
395                          inet_ntoa(pip->ip_src), sport, dstip, dport);
396             }
397           }
398           return 0;
399         } else {
400           if (log_IsKept(LogFILTER)) {
401             snprintf(dstip, sizeof dstip, "%s", inet_ntoa(pip->ip_dst));
402             log_Printf(LogFILTER,
403                        "%sbound rule = %d deny %s src = %s/%d dst = %s/%d\n",
404                        filter->name, n, filter_Proto2Nam(cproto),
405                        inet_ntoa(pip->ip_src), sport, dstip, dport);
406           }
407           return 1;
408         }		/* Explict math.  Deny this packet */
409       }
410     } else {
411       n++;
412       fp++;
413     }
414   }
415 
416   if (log_IsKept(LogFILTER)) {
417     snprintf(dstip, sizeof dstip, "%s", inet_ntoa(pip->ip_dst));
418     log_Printf(LogFILTER,
419                "%sbound rule = implicit deny %s src = %s/%d dst = %s/%d\n",
420                filter->name, filter_Proto2Nam(cproto),
421                inet_ntoa(pip->ip_src), sport, dstip, dport);
422   }
423 
424   return 1;		/* No rule is mached. Deny this packet */
425 }
426 
427 #ifdef notdef
428 static void
429 IcmpError(struct ip *pip, int code)
430 {
431   struct mbuf *bp;
432 
433   if (pip->ip_p != IPPROTO_ICMP) {
434     bp = m_get(m_len, MB_IPIN);
435     memcpy(MBUF_CTOP(bp), ptr, m_len);
436     vj_SendFrame(bp);
437     ipcp_AddOutOctets(m_len);
438   }
439 }
440 #endif
441 
442 static void
443 ip_LogDNS(const struct udphdr *uh, const char *direction)
444 {
445   struct dns_header header;
446   const u_short *pktptr;
447   const u_char *ptr;
448   u_short *hptr;
449   int len;
450 
451   ptr = (const char *)uh + sizeof *uh;
452   len = ntohs(uh->uh_ulen) - sizeof *uh;
453   if (len < sizeof header + 5)		/* rfc1024 */
454     return;
455 
456   pktptr = (const u_short *)ptr;
457   hptr = (u_short *)&header;
458   ptr += sizeof header;
459   len -= sizeof header;
460 
461   while (pktptr < (const u_short *)ptr) {
462     *hptr++ = ntohs(*pktptr);		/* Careful of macro side-effects ! */
463     pktptr++;
464   }
465 
466   if (header.opcode == OPCODE_QUERY && header.qr == 0) {
467     /* rfc1035 */
468     char name[MAXHOSTNAMELEN + 1], *n;
469     const char *qtype, *qclass;
470     const u_char *end;
471 
472     n = name;
473     end = ptr + len - 4;
474     if (end - ptr >= sizeof name)
475       end = ptr + sizeof name - 1;
476     while (ptr < end) {
477       len = *ptr++;
478       if (len > end - ptr)
479         len = end - ptr;
480       if (n != name)
481         *n++ = '.';
482       memcpy(n, ptr, len);
483       ptr += len;
484       n += len;
485     }
486     *n = '\0';
487     qtype = dns_Qtype2Txt(ntohs(*(const u_short *)end));
488     qclass = dns_Qclass2Txt(ntohs(*(const u_short *)(end + 2)));
489 
490     log_Printf(LogDNS, "%sbound query %s %s %s\n",
491                direction, qclass, qtype, name);
492   }
493 }
494 
495 /*
496  *  For debugging aid.
497  */
498 int
499 PacketCheck(struct bundle *bundle, unsigned char *cp, int nb,
500             struct filter *filter, const char *prefix, unsigned *psecs)
501 {
502   static const char *const TcpFlags[] = {
503     "FIN", "SYN", "RST", "PSH", "ACK", "URG"
504   };
505   struct ip *pip;
506   struct tcphdr *th;
507   struct udphdr *uh;
508   struct icmp *icmph;
509   unsigned char *ptop;
510   int mask, len, n, pri, logit, loglen, result;
511   char logbuf[200];
512 
513   logit = (log_IsKept(LogTCPIP) || log_IsKept(LogDNS)) &&
514           (!filter || filter->logok);
515   loglen = 0;
516   pri = 0;
517 
518   pip = (struct ip *)cp;
519   uh = NULL;
520 
521   if (logit && loglen < sizeof logbuf) {
522     if (prefix)
523       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s", prefix);
524     else if (filter)
525       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s ", filter->name);
526     else
527       snprintf(logbuf + loglen, sizeof logbuf - loglen, "  ");
528     loglen += strlen(logbuf + loglen);
529   }
530   ptop = (cp + (pip->ip_hl << 2));
531 
532   switch (pip->ip_p) {
533   case IPPROTO_ICMP:
534     if (logit && loglen < sizeof logbuf) {
535       len = ntohs(pip->ip_len) - (pip->ip_hl << 2) - sizeof *icmph;
536       icmph = (struct icmp *) ptop;
537       snprintf(logbuf + loglen, sizeof logbuf - loglen,
538                "ICMP: %s:%d ---> ", inet_ntoa(pip->ip_src), icmph->icmp_type);
539       loglen += strlen(logbuf + loglen);
540       snprintf(logbuf + loglen, sizeof logbuf - loglen,
541                "%s:%d (%d/%d)", inet_ntoa(pip->ip_dst), icmph->icmp_type,
542                len, nb);
543       loglen += strlen(logbuf + loglen);
544     }
545     break;
546 
547   case IPPROTO_UDP:
548     uh = (struct udphdr *) ptop;
549     if (pip->ip_tos == IPTOS_LOWDELAY && bundle->ncp.ipcp.cfg.urgent.tos)
550       pri++;
551 
552     if ((ntohs(pip->ip_off) & IP_OFFMASK) == 0 &&
553         ipcp_IsUrgentUdpPort(&bundle->ncp.ipcp, ntohs(uh->uh_sport),
554                           ntohs(uh->uh_dport)))
555       pri++;
556 
557     if (logit && loglen < sizeof logbuf) {
558       len = ntohs(pip->ip_len) - (pip->ip_hl << 2) - sizeof *uh;
559       snprintf(logbuf + loglen, sizeof logbuf - loglen,
560                "UDP: %s:%d ---> ", inet_ntoa(pip->ip_src), ntohs(uh->uh_sport));
561       loglen += strlen(logbuf + loglen);
562       snprintf(logbuf + loglen, sizeof logbuf - loglen,
563                "%s:%d (%d/%d)", inet_ntoa(pip->ip_dst), ntohs(uh->uh_dport),
564                len, nb);
565       loglen += strlen(logbuf + loglen);
566     }
567 
568     if (Enabled(bundle, OPT_FILTERDECAP) &&
569         ptop[sizeof *uh] == HDLC_ADDR && ptop[sizeof *uh + 1] == HDLC_UI) {
570       u_short proto;
571       const char *type;
572 
573       memcpy(&proto, ptop + sizeof *uh + 2, sizeof proto);
574       type = NULL;
575 
576       switch (ntohs(proto)) {
577         case PROTO_IP:
578           snprintf(logbuf + loglen, sizeof logbuf - loglen, " contains ");
579           result = PacketCheck(bundle, ptop + sizeof *uh + 4,
580                                nb - (ptop - cp) - sizeof *uh - 4, filter,
581                                logbuf, psecs);
582           if (result != -2)
583               return result;
584           type = "IP";
585           break;
586 
587         case PROTO_VJUNCOMP: type = "compressed VJ";   break;
588         case PROTO_VJCOMP:   type = "uncompressed VJ"; break;
589         case PROTO_MP:       type = "Multi-link"; break;
590         case PROTO_ICOMPD:   type = "Individual link CCP"; break;
591         case PROTO_COMPD:    type = "CCP"; break;
592         case PROTO_IPCP:     type = "IPCP"; break;
593         case PROTO_LCP:      type = "LCP"; break;
594         case PROTO_PAP:      type = "PAP"; break;
595         case PROTO_CBCP:     type = "CBCP"; break;
596         case PROTO_LQR:      type = "LQR"; break;
597         case PROTO_CHAP:     type = "CHAP"; break;
598       }
599       if (type) {
600         snprintf(logbuf + loglen, sizeof logbuf - loglen,
601                  " - %s data", type);
602         loglen += strlen(logbuf + loglen);
603       }
604     }
605 
606     break;
607 
608 #ifdef IPPROTO_GRE
609   case IPPROTO_GRE:
610     if (logit && loglen < sizeof logbuf) {
611       len = ntohs(pip->ip_len) - (pip->ip_hl << 2);
612       snprintf(logbuf + loglen, sizeof logbuf - loglen,
613           "GRE: %s ---> ", inet_ntoa(pip->ip_src));
614       loglen += strlen(logbuf + loglen);
615       snprintf(logbuf + loglen, sizeof logbuf - loglen,
616               "%s (%d/%d)", inet_ntoa(pip->ip_dst), len, nb);
617       loglen += strlen(logbuf + loglen);
618     }
619     break;
620 #endif
621 
622 #ifdef IPPROTO_OSPFIGP
623   case IPPROTO_OSPFIGP:
624     if (logit && loglen < sizeof logbuf) {
625       len = ntohs(pip->ip_len) - (pip->ip_hl << 2);
626       snprintf(logbuf + loglen, sizeof logbuf - loglen,
627                "OSPF: %s ---> ", inet_ntoa(pip->ip_src));
628       loglen += strlen(logbuf + loglen);
629       snprintf(logbuf + loglen, sizeof logbuf - loglen,
630                "%s (%d/%d)", inet_ntoa(pip->ip_dst), len, nb);
631       loglen += strlen(logbuf + loglen);
632     }
633     break;
634 #endif
635 
636   case IPPROTO_IPIP:
637     if (logit && loglen < sizeof logbuf) {
638       uh = (struct udphdr *) ptop;
639       snprintf(logbuf + loglen, sizeof logbuf - loglen,
640                "IPIP: %s:%d ---> ", inet_ntoa(pip->ip_src),
641                ntohs(uh->uh_sport));
642       loglen += strlen(logbuf + loglen);
643       snprintf(logbuf + loglen, sizeof logbuf - loglen,
644                "%s:%d", inet_ntoa(pip->ip_dst), ntohs(uh->uh_dport));
645       loglen += strlen(logbuf + loglen);
646     }
647     break;
648 
649   case IPPROTO_ESP:
650     if (logit && loglen < sizeof logbuf) {
651       snprintf(logbuf + loglen, sizeof logbuf - loglen,
652                "ESP: %s ---> ", inet_ntoa(pip->ip_src));
653       loglen += strlen(logbuf + loglen);
654       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s, spi %p",
655                inet_ntoa(pip->ip_dst), ptop);
656       loglen += strlen(logbuf + loglen);
657     }
658     break;
659 
660   case IPPROTO_AH:
661     if (logit && loglen < sizeof logbuf) {
662       snprintf(logbuf + loglen, sizeof logbuf - loglen,
663                "AH: %s ---> ", inet_ntoa(pip->ip_src));
664       loglen += strlen(logbuf + loglen);
665       snprintf(logbuf + loglen, sizeof logbuf - loglen, "%s, spi %p",
666                inet_ntoa(pip->ip_dst), ptop + sizeof(u_int32_t));
667       loglen += strlen(logbuf + loglen);
668     }
669     break;
670 
671   case IPPROTO_IGMP:
672     if (logit && loglen < sizeof logbuf) {
673       uh = (struct udphdr *) ptop;
674       snprintf(logbuf + loglen, sizeof logbuf - loglen,
675                "IGMP: %s:%d ---> ", inet_ntoa(pip->ip_src),
676                ntohs(uh->uh_sport));
677       loglen += strlen(logbuf + loglen);
678       snprintf(logbuf + loglen, sizeof logbuf - loglen,
679                "%s:%d", inet_ntoa(pip->ip_dst), ntohs(uh->uh_dport));
680       loglen += strlen(logbuf + loglen);
681     }
682     break;
683 
684   case IPPROTO_TCP:
685     th = (struct tcphdr *) ptop;
686     if (pip->ip_tos == IPTOS_LOWDELAY && bundle->ncp.ipcp.cfg.urgent.tos)
687       pri++;
688 
689     if ((ntohs(pip->ip_off) & IP_OFFMASK) == 0 &&
690         ipcp_IsUrgentTcpPort(&bundle->ncp.ipcp, ntohs(th->th_sport),
691                           ntohs(th->th_dport)))
692       pri++;
693 
694     if (logit && loglen < sizeof logbuf) {
695       len = ntohs(pip->ip_len) - (pip->ip_hl << 2) - (th->th_off << 2);
696       snprintf(logbuf + loglen, sizeof logbuf - loglen,
697            "TCP: %s:%d ---> ", inet_ntoa(pip->ip_src), ntohs(th->th_sport));
698       loglen += strlen(logbuf + loglen);
699       snprintf(logbuf + loglen, sizeof logbuf - loglen,
700                "%s:%d", inet_ntoa(pip->ip_dst), ntohs(th->th_dport));
701       loglen += strlen(logbuf + loglen);
702       n = 0;
703       for (mask = TH_FIN; mask != 0x40; mask <<= 1) {
704         if (th->th_flags & mask) {
705           snprintf(logbuf + loglen, sizeof logbuf - loglen, " %s", TcpFlags[n]);
706           loglen += strlen(logbuf + loglen);
707         }
708         n++;
709       }
710       snprintf(logbuf + loglen, sizeof logbuf - loglen,
711                "  seq:%lx  ack:%lx (%d/%d)",
712                (u_long)ntohl(th->th_seq), (u_long)ntohl(th->th_ack), len, nb);
713       loglen += strlen(logbuf + loglen);
714       if ((th->th_flags & TH_SYN) && nb > 40) {
715         u_short *sp;
716 
717         ptop += 20;
718         sp = (u_short *) ptop;
719         if (ntohs(sp[0]) == 0x0204) {
720           snprintf(logbuf + loglen, sizeof logbuf - loglen,
721                    " MSS = %d", ntohs(sp[1]));
722           loglen += strlen(logbuf + loglen);
723         }
724       }
725     }
726     break;
727 
728   default:
729     if (prefix)
730       return -2;
731   }
732 
733   if (filter && FilterCheck(pip, filter, psecs)) {
734     if (logit)
735       log_Printf(LogTCPIP, "%s - BLOCKED\n", logbuf);
736 #ifdef notdef
737     if (direction == 0)
738       IcmpError(pip, pri);
739 #endif
740     result = -1;
741   } else {
742     /* Check Keep Alive filter */
743     if (logit && log_IsKept(LogTCPIP)) {
744       unsigned alivesecs;
745 
746       alivesecs = 0;
747       if (filter && FilterCheck(pip, &bundle->filter.alive, &alivesecs))
748         log_Printf(LogTCPIP, "%s - NO KEEPALIVE\n", logbuf);
749       else if (psecs != NULL) {
750         if(*psecs == 0)
751           *psecs = alivesecs;
752         if (*psecs) {
753           if (*psecs != alivesecs)
754             log_Printf(LogTCPIP, "%s - (timeout = %d / ALIVE = %d secs)\n",
755                        logbuf, *psecs, alivesecs);
756           else
757             log_Printf(LogTCPIP, "%s - (timeout = %d secs)\n", logbuf, *psecs);
758         } else
759           log_Printf(LogTCPIP, "%s\n", logbuf);
760       }
761     }
762     result = pri;
763   }
764 
765   if (filter && uh && ntohs(uh->uh_dport) == 53 && log_IsKept(LogDNS))
766     ip_LogDNS(uh, filter->name);
767 
768   return result;
769 }
770 
771 struct mbuf *
772 ip_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
773 {
774   int nb, nw;
775   struct tun_data tun;
776   struct ip *pip;
777   char *data;
778   unsigned secs, alivesecs;
779 
780   if (bundle->ncp.ipcp.fsm.state != ST_OPENED) {
781     log_Printf(LogWARN, "ip_Input: IPCP not open - packet dropped\n");
782     m_freem(bp);
783     return NULL;
784   }
785 
786   m_settype(bp, MB_IPIN);
787   nb = m_length(bp);
788   if (nb > sizeof tun.data) {
789     log_Printf(LogWARN, "ip_Input: %s: Packet too large (got %d, max %d)\n",
790                l->name, nb, (int)(sizeof tun.data));
791     m_freem(bp);
792     return NULL;
793   }
794   mbuf_Read(bp, tun.data, nb);
795 
796   secs = 0;
797   if (PacketCheck(bundle, tun.data, nb, &bundle->filter.in, NULL, &secs) < 0)
798     return NULL;
799 
800   pip = (struct ip *)tun.data;
801   alivesecs = 0;
802   if (!FilterCheck(pip, &bundle->filter.alive, &alivesecs)) {
803     if (secs == 0)
804       secs = alivesecs;
805     bundle_StartIdleTimer(bundle, secs);
806   }
807 
808   ipcp_AddInOctets(&bundle->ncp.ipcp, nb);
809 
810   if (bundle->dev.header) {
811     tun.header.family = htonl(AF_INET);
812     nb += sizeof tun - sizeof tun.data;
813     data = (char *)&tun;
814   } else
815     data = tun.data;
816 
817   nw = write(bundle->dev.fd, data, nb);
818   if (nw != nb) {
819     if (nw == -1)
820       log_Printf(LogERROR, "ip_Input: %s: wrote %d, got %s\n",
821                  l->name, nb, strerror(errno));
822     else
823       log_Printf(LogERROR, "ip_Input: %s: wrote %d, got %d\n", l->name, nb, nw);
824   }
825 
826   return NULL;
827 }
828 
829 void
830 ip_Enqueue(struct ipcp *ipcp, int pri, char *ptr, int count)
831 {
832   struct mbuf *bp;
833 
834   if (pri < 0 || pri >= IPCP_QUEUES(ipcp))
835     log_Printf(LogERROR, "Can't store in ip queue %d\n", pri);
836   else {
837     /*
838      * We allocate an extra 6 bytes, four at the front and two at the end.
839      * This is an optimisation so that we need to do less work in
840      * m_prepend() in acf_LayerPush() and proto_LayerPush() and
841      * appending in hdlc_LayerPush().
842      */
843     bp = m_get(count + 6, MB_IPOUT);
844     bp->m_offset += 4;
845     bp->m_len -= 6;
846     memcpy(MBUF_CTOP(bp), ptr, count);
847     m_enqueue(ipcp->Queue + pri, bp);
848   }
849 }
850 
851 void
852 ip_DeleteQueue(struct ipcp *ipcp)
853 {
854   struct mqueue *queue;
855 
856   for (queue = ipcp->Queue; queue < ipcp->Queue + IPCP_QUEUES(ipcp); queue++)
857     while (queue->top)
858       m_freem(m_dequeue(queue));
859 }
860 
861 size_t
862 ip_QueueLen(struct ipcp *ipcp)
863 {
864   struct mqueue *queue;
865   size_t result;
866 
867   result = 0;
868   for (queue = ipcp->Queue; queue < ipcp->Queue + IPCP_QUEUES(ipcp); queue++)
869     result += queue->len;
870 
871   return result;
872 }
873 
874 int
875 ip_PushPacket(struct link *l, struct bundle *bundle)
876 {
877   struct ipcp *ipcp = &bundle->ncp.ipcp;
878   struct mqueue *queue;
879   struct mbuf *bp;
880   struct ip *pip;
881   int m_len;
882   u_int32_t secs = 0;
883   unsigned alivesecs = 0;
884 
885   if (ipcp->fsm.state != ST_OPENED)
886     return 0;
887 
888   queue = ipcp->Queue + IPCP_QUEUES(ipcp) - 1;
889   do {
890     if (queue->top) {
891       bp = m_dequeue(queue);
892       bp = mbuf_Read(bp, &secs, sizeof secs);
893       bp = m_pullup(bp);
894       m_len = m_length(bp);
895       pip = (struct ip *)MBUF_CTOP(bp);
896       if (!FilterCheck(pip, &bundle->filter.alive, &alivesecs)) {
897         if (secs == 0)
898           secs = alivesecs;
899         bundle_StartIdleTimer(bundle, secs);
900       }
901       link_PushPacket(l, bp, bundle, 0, PROTO_IP);
902       ipcp_AddOutOctets(ipcp, m_len);
903       return 1;
904     }
905   } while (queue-- != ipcp->Queue);
906 
907   return 0;
908 }
909