3 // (c) Copyrigth 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd)
10 #include <linux/if_tun.h>
13 #include <net/route.h>
16 #include <netinet/in.h>
22 #include <sys/ioctl.h>
23 #include <sys/socket.h>
26 #include <sys/resource.h>
27 #include <sys/types.h>
41 #include "constants.h"
45 ipt radiusserver
[MAXRADSERVER
]; // radius servers
46 u8 numradiusservers
= 0; // how many radius servers
49 char tapdevice
[10] = ""; // tap device name
50 int tapfd
= -1; // tap interface file handle
51 int udpfd
= -1; // UDP file handle
52 int controlfd
= -1; // Control signal handle
53 int snoopfd
= -1; // UDP file handle for sending out intercept data
54 int radfd
= -1; // RADIUS requests file handle
55 int ifrfd
= -1; // File descriptor for routing, etc
56 char debug
= 0; // debug leveL
57 time_t basetime
= 0; // base clock
58 char hostname
[1000] = ""; // us.
59 ipt myip
= 0; // MY IP
60 u16 tapmac
[3]; // MAC of tap interface
61 int tapidx
; // ifr_ifindex of tap device
62 char *radiussecret
= 0; // RADIUS secret
63 char *l2tpsecret
= 0; // L2TP secret
64 u32 sessionid
= 0; // session id for radius accounting
65 char *snoop_destination_host
= NULL
;
66 u16 snoop_destination_port
= 0;
67 char *log_filename
= NULL
;
68 char *config_file
= CONFIGFILE
;
69 FILE *log_stream
= NULL
;
70 unsigned long default_dns1
= 0, default_dns2
= 0;
71 struct sockaddr_in snoop_addr
= {0};
72 extern unsigned long rl_rate
;
73 extern int cluster_sockfd
;
74 unsigned long last_sid
= 0;
75 int config_save_state
= 0;
76 int radius_accounting
= 0;
77 char *accounting_dir
= NULL
;
78 uint32_t cluster_address
= 0;
79 uint32_t bind_address
= INADDR_ANY
;
80 int handle_interface
= 0;
84 sessionidt
*cli_session_kill
= NULL
;
85 tunnelidt
*cli_tunnel_kill
= NULL
;
87 static void *ip_hash
[256];
88 unsigned long udp_tx
= 0, udp_rx
= 0, udp_rx_pkt
= 0;
89 unsigned long eth_tx
= 0, eth_rx
= 0, eth_rx_pkt
= 0;
90 unsigned int ip_pool_index
= 0;
91 unsigned int ip_pool_size
= 0;
93 char time_now_string
[64] = {0};
97 char *_program_name
= NULL
;
98 linked_list
*loaded_plugins
;
99 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
101 char *plugin_functions
[] = {
109 "plugin_new_session",
110 "plugin_kill_session",
112 "plugin_radius_response",
114 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
116 tunnelt
*tunnel
= NULL
; // 1000 * 45 = 45000 = 45k
117 sessiont
*session
= NULL
; // 5000 * 213 = 1065000 = 1 Mb
118 radiust
*radius
= NULL
;
119 ippoolt
*ip_address_pool
= NULL
;
120 tunnelidt tunnelfree
; // free list link heads
121 sessionidt sessionfree
= 0;
123 controlt
*controlfree
= 0;
124 struct Tstats
*_statistics
= NULL
;
126 struct Tringbuffer
*ringbuffer
= NULL
;
128 tbft
*filter_buckets
= NULL
;
130 void sigalrm_handler(int);
131 void sighup_handler(int);
132 void sigterm_handler(int);
133 void sigquit_handler(int);
134 void sigchild_handler(int);
135 void sigsegv_handler(int);
136 void read_config_file();
140 // return internal time (10ths since run)
145 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
148 // work out a retry time based on try number
149 clockt
backoff(u8
try)
151 if (try > 5) try = 5; // max backoff
152 return now() + 10 * (1 << try);
155 void _log(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *format
, ...)
162 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
163 ringbuffer
->tail
= 0;
164 if (ringbuffer
->tail
== ringbuffer
->head
)
165 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
166 ringbuffer
->head
= 0;
168 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
169 ringbuffer
->buffer
[ringbuffer
->tail
].address
= address
;
170 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
171 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
172 va_start(ap
, format
);
173 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
178 if (debug
< level
) return;
180 if (!log_stream
&& log_filename
)
182 if ((log_stream
= fopen(log_filename
, "a")))
183 fseek(log_stream
, 0, SEEK_END
);
184 setbuf(log_stream
, NULL
);
189 setbuf(log_stream
, NULL
);
192 va_start(ap
, format
);
193 fprintf(log_stream
, "%s %02d/%02d ", time_now_string
, t
, s
);
194 vfprintf(log_stream
, format
, ap
);
198 void _log_hex(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *title
, const char *data
, int maxsize
)
201 unsigned const char *d
= (unsigned const char *)data
;
203 if (debug
< level
) return;
204 log(level
, address
, s
, t
, "%s (%d bytes):\n", title
, maxsize
);
205 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
206 for (i
= 0; i
< maxsize
; )
208 fprintf(log_stream
, "%4X: ", i
);
209 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
211 fprintf(log_stream
, "%02X ", d
[j
]);
213 fputs(": ", log_stream
);
216 for (; j
< i
+ 16; j
++)
218 fputs(" ", log_stream
);
220 fputs(": ", log_stream
);
223 fputs(" ", log_stream
);
224 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
226 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
227 fputc(d
[j
], log_stream
);
229 fputc('.', log_stream
);
232 fputs(" ", log_stream
);
236 fputs("\n", log_stream
);
239 setbuf(log_stream
, NULL
);
244 void routeset(ipt ip
, ipt mask
, ipt gw
, u8 add
)
247 memset(&r
, 0, sizeof(r
));
248 r
.rt_dev
= tapdevice
;
249 r
.rt_dst
.sa_family
= AF_INET
;
250 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
251 r
.rt_gateway
.sa_family
= AF_INET
;
252 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
253 r
.rt_genmask
.sa_family
= AF_INET
;
254 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
? : 0xFFFFFFF);
255 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
257 r
.rt_flags
|= RTF_GATEWAY
;
259 r
.rt_flags
|= RTF_HOST
;
260 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0) perror("routeset");
261 log(1, ip
, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n", add
? "Add" : "Del", ip
>> 24, ip
>> 16 & 255, ip
>> 8 & 255, ip
& 255, mask
>> 24, mask
>> 16 & 255, mask
>> 8 & 255, mask
& 255, gw
>> 24, gw
>> 16 & 255, gw
>> 8 & 255, gw
& 255);
264 // Set up TAP interface
268 struct sockaddr_in sin
= {0};
269 memset(&ifr
, 0, sizeof(ifr
));
270 ifr
.ifr_flags
= IFF_TUN
;
272 tapfd
= open(TAPDEVICE
, O_RDWR
);
275 log(0, 0, 0, 0, "Can't open %s: %s\n", TAPDEVICE
, strerror(errno
));
278 if (ioctl(tapfd
, TUNSETIFF
, (void *) &ifr
) < 0)
280 log(0, 0, 0, 0, "Can't set tap interface: %s\n", strerror(errno
));
283 assert(strlen(ifr
.ifr_name
) < sizeof(tapdevice
));
284 strcpy(tapdevice
, ifr
.ifr_name
);
285 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
287 sin
.sin_family
= AF_INET
;
288 sin
.sin_addr
.s_addr
= handle_interface
? bind_address
: 0x01010101; // 1.1.1.1
289 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
291 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
293 perror("set tap addr");
296 ifr
.ifr_flags
= IFF_UP
;
297 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
299 perror("set tap flags");
302 if (ioctl(ifrfd
, SIOCGIFHWADDR
, (void *) &ifr
) < 0)
304 perror("get tap hwaddr");
307 memcpy(&tapmac
, 2 + (u8
*) & ifr
.ifr_hwaddr
, 6);
308 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
310 perror("get tap ifindex");
313 tapidx
= ifr
.ifr_ifindex
;
320 struct sockaddr_in addr
;
323 memset(&addr
, 0, sizeof(addr
));
324 addr
.sin_family
= AF_INET
;
325 addr
.sin_port
= htons(L2TPPORT
);
326 addr
.sin_addr
.s_addr
= bind_address
;
327 udpfd
= socket(AF_INET
, SOCK_DGRAM
, UDP
);
328 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
329 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
334 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, UDP
);
337 memset(&addr
, 0, sizeof(addr
));
338 addr
.sin_family
= AF_INET
;
339 addr
.sin_port
= htons(1702);
340 controlfd
= socket(AF_INET
, SOCK_DGRAM
, 17);
341 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
342 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
349 // Find session by IP, 0 for not found
350 sessionidt
sessionbyip(ipt ip
)
352 unsigned char *a
= (char *)&ip
;
353 char **d
= (char **) ip_hash
;
356 STAT(call_sessionbyip
);
359 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
360 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
361 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
363 return (ipt
) d
[(size_t) *a
];
366 void cache_sessionid(ipt ip
, sessionidt s
)
368 unsigned char *a
= (char *) &ip
;
369 char **d
= (char **) ip_hash
;
372 for (i
= 0; i
< 3; i
++)
374 if (!d
[(size_t) a
[i
]])
376 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
380 d
= (char **) d
[(size_t) a
[i
]];
383 log(4, ip
, s
, session
[s
].tunnel
, "Caching session ID %d for ip address\n", s
);
384 d
[(size_t) a
[3]] = (char *)((int)s
);
387 void uncache_sessionid(ipt ip
)
389 unsigned char *a
= (char *) &ip
;
390 char **d
= (char **) ip_hash
;
393 for (i
= 0; i
< 3; i
++)
395 if (!d
[(size_t) a
[i
]]) return;
396 d
= (char **) d
[(size_t) a
[i
]];
398 d
[(size_t) a
[3]] = NULL
;
401 // Find session by username, 0 for not found
402 // walled garden'd users aren't authenticated, so the username is
403 // reasonably useless. Ignore them to avoid incorrect actions
404 sessionidt
sessionbyuser(char *username
)
408 STAT(call_sessionbyuser
);
410 for (s
= 1; s
< MAXSESSION
&& (session
[s
].walled_garden
|| strncmp(session
[s
].user
, username
, 128)); s
++);
416 void send_garp(ipt ip
)
420 unsigned char mac
[6];
422 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
428 memset(&ifr
, 0, sizeof(ifr
));
429 strcpy(ifr
.ifr_name
, "eth0");
430 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
432 perror("get eth0 hwaddr");
435 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
436 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
438 perror("get eth0 ifindex");
442 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
445 // Find session by username, 0 for not found
446 sessiont
*sessiontbysessionidt(sessionidt s
)
448 if (!s
|| s
> MAXSESSION
) return NULL
;
452 sessionidt
sessionidtbysessiont(sessiont
*s
)
454 sessionidt val
= s
-session
;
455 if (s
< session
|| val
> MAXSESSION
) return 0;
459 // send gratuitous ARP to set ARP table for newly allocated IP
460 void sessionsendarp(sessionidt s
)
462 unsigned char mac
[6];
466 *(u16
*) (mac
+ 0) = htons(tapmac
[0]); // set source address
467 *(u16
*) (mac
+ 2) = htons(tapmac
[1]);
468 *(u16
*) (mac
+ 4) = htons(tapmac
[2]);
469 sendarp(tapidx
, mac
, session
[s
].ip
);
473 // Handle ARP requests
474 void processarp(u8
* buf
, int len
)
480 STAT(call_processarp
);
485 log(0, 0, 0, 0, "Unexpected length ARP %d bytes\n", len
);
489 if (*(u16
*) (buf
+ 16) != htons(PKTARP
))
491 log(0, 0, 0, 0, "Unexpected ARP type %04X\n", ntohs(*(u16
*) (buf
+ 16)));
495 if (*(u16
*) (buf
+ 18) != htons(0x0001))
497 log(0, 0, 0, 0, "Unexpected ARP hard type %04X\n", ntohs(*(u16
*) (buf
+ 18)));
501 if (*(u16
*) (buf
+ 20) != htons(PKTIP
))
503 log(0, 0, 0, 0, "Unexpected ARP prot type %04X\n", ntohs(*(u16
*) (buf
+ 20)));
509 log(0, 0, 0, 0, "Unexpected ARP hard len %d\n", buf
[22]);
515 log(0, 0, 0, 0, "Unexpected ARP prot len %d\n", buf
[23]);
519 if (*(u16
*) (buf
+ 24) != htons(0x0001))
521 log(0, 0, 0, 0, "Unexpected ARP op %04X\n", ntohs(*(u16
*) (buf
+ 24)));
525 ip
= ntohl(*(u32
*) (buf
+ 42));
527 s
= sessionbyip(htonl(ip
));
530 log(3, ip
, s
, session
[s
].tunnel
, "ARP reply for %u.%u.%u.%u\n", ip
>> 24, ip
>> 16 & 255, ip
>> 8 & 255, ip
& 255, session
[s
].tunnel
, s
);
531 memcpy(buf
+ 4, buf
+ 10, 6); // set destination as source
532 *(u16
*) (buf
+ 10) = htons(tapmac
[0]); // set soucre address
533 *(u16
*) (buf
+ 12) = htons(tapmac
[1]);
534 *(u16
*) (buf
+ 14) = htons(tapmac
[2]);
535 *(u16
*) (buf
+ 24) = htons(0x0002); // ARP reply
536 memcpy(buf
+ 26, buf
+ 10, 6); // sender ethernet
537 memcpy(buf
+ 36, buf
+ 4, 6); // target ethernet
538 *(u32
*) (buf
+ 42) = *(u32
*) (buf
+ 32); // target IP
539 *(u32
*) (buf
+ 32) = htonl(ip
); // sender IP
540 write(tapfd
, buf
, len
);
545 log(3, ip
, 0, 0, "ARP request for unknown IP %u.%u.%u.%u\n", ip
>> 24, ip
>> 16 & 255, ip
>> 8 & 255, ip
& 255);
550 // actually send a control message for a specific tunnel
551 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
553 struct sockaddr_in addr
;
556 STAT(call_tunnelsend
);
560 log(1, 0, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
561 STAT(tunnel_tx_errors
);
564 memset(&addr
, 0, sizeof(addr
));
565 addr
.sin_family
= AF_INET
;
566 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
567 addr
.sin_port
= htons(tunnel
[t
].port
);
569 // sequence expected, if sequence in message
570 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
572 // If this is a control message, deal with retries
575 tunnel
[t
].last
= time_now
; // control message sent
576 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
577 if (tunnel
[t
].try > 1)
579 STAT(tunnel_retries
);
580 log(3, tunnel
[t
].ip
, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
584 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
586 log(0, tunnel
[t
].ip
, ntohs((*(u16
*) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
587 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
588 STAT(tunnel_tx_errors
);
592 log_hex(5, "Send Tunnel Data", buf
, l
);
593 STAT(tunnel_tx_packets
);
594 INC_STAT(tunnel_tx_bytes
, l
);
597 // process outgoing (to tunnel) IP
598 void processipout(u8
* buf
, int len
)
606 STAT(call_processipout
);
610 log(1, 0, 0, 0, "Short IP, %d bytes\n", len
);
611 STAT(tunnel_tx_errors
);
615 // Skip the tun header
619 // Got an IP header now
620 if (*(u8
*)(buf
) >> 4 != 4)
622 log(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
626 ip
= *(u32
*)(buf
+ 16);
627 if (!(s
= sessionbyip(ip
)))
629 // log(4, 0, 0, 0, "IP: Can't find session for IP %s\n", inet_toa(ip));
632 t
= session
[s
].tunnel
;
635 // Snooping this session, send it to ASIO
636 if (sp
->snoop
) snoop_send_packet(buf
, len
);
638 log(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
642 struct param_packet_rx packet
= { &tunnel
[t
], &session
[s
], buf
, len
};
643 run_plugins(PLUGIN_PACKET_RX
, &packet
);
646 // Add on L2TP header
648 u8
*p
= makeppp(b
, buf
, len
, t
, s
, PPPIP
);
649 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
650 sp
->cout
+= len
; // byte count
656 // add an AVP (16 bit)
657 void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
659 u16 l
= (m
? 0x8008 : 0x0008);
660 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
661 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
662 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
663 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
667 // add an AVP (32 bit)
668 void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
670 u16 l
= (m
? 0x800A : 0x000A);
671 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
672 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
673 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
674 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
678 // add an AVP (32 bit)
679 void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
681 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
682 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
683 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
684 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
685 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
686 c
->length
+= 6 + strlen(val
);
690 void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
692 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
693 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
694 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
695 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
696 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
697 c
->length
+= 6 + len
;
700 // new control connection
701 controlt
*controlnew(u16 mtype
)
705 c
= malloc(sizeof(controlt
));
709 controlfree
= c
->next
;
713 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
715 control16(c
, 0, mtype
, 1);
719 // send zero block if nothing is waiting
720 void controlnull(tunnelidt t
)
723 if (tunnel
[t
].controlc
)
725 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
726 *(u16
*) (buf
+ 2) = htons(12); // length
727 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
728 *(u16
*) (buf
+ 6) = htons(0); // session
729 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
730 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
731 tunnelsend(buf
, 12, t
);
734 // add a control message to a tunnel, and send if within window
735 void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
737 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
738 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
739 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
740 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
741 tunnel
[t
].ns
++; // advance sequence
742 // link in message in to queue
743 if (tunnel
[t
].controlc
)
744 tunnel
[t
].controle
->next
= c
;
746 tunnel
[t
].controls
= c
;
747 tunnel
[t
].controle
= c
;
748 tunnel
[t
].controlc
++;
749 // send now if space in window
750 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
752 tunnel
[t
].try = 0; // first send
753 tunnelsend(c
->buf
, c
->length
, t
);
757 // start tidy shutdown of session
758 void sessionshutdown(sessionidt s
, char *reason
)
760 int dead
= session
[s
].die
;
761 int walled_garden
= session
[s
].walled_garden
;
764 STAT(call_sessionshutdown
);
766 if (!session
[s
].tunnel
)
767 return; // not a live session
770 log(2, 0, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
772 session
[s
].die
= now() + 150; // Clean up in 15 seconds
775 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
776 run_plugins(PLUGIN_KILL_SESSION
, &data
);
779 // RADIUS Stop message
780 if (session
[s
].opened
&& !walled_garden
&& !dead
) {
781 u8 r
= session
[s
].radius
;
786 log(1, 0, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
787 STAT(radius_overflow
);
791 for (n
= 0; n
< 15; n
++)
792 radius
[r
].auth
[n
] = rand();
795 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
796 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
800 { // IP allocated, clear and unroute
802 if (session
[s
].route
[0].ip
)
804 routeset(session
[s
].ip
, 0, 0, 0);
805 for (r
= 0; r
< MAXROUTE
; r
++)
807 if (session
[s
].route
[r
].ip
)
809 routeset(session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, session
[s
].ip
, 0);
810 session
[s
].route
[r
].ip
= 0;
814 if (session
[s
].throttle
) throttle_session(s
, 0); session
[s
].throttle
= 0;
815 free_ip_address(session
[s
].ip
);
819 controlt
*c
= controlnew(14); // sending CDN
820 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
821 control16(c
, 14, s
, 1); // assigned session (our end)
822 controladd(c
, session
[s
].tunnel
, s
); // send the message
824 cluster_send_session(s
);
827 void sendipcp(tunnelidt t
, sessionidt s
)
830 u8 r
= session
[s
].radius
;
837 if (radius
[r
].state
!= RADIUSIPCP
)
839 radius
[r
].state
= RADIUSIPCP
;
842 radius
[r
].retry
= backoff(radius
[r
].try++);
843 if (radius
[r
].try > 10)
845 sessionshutdown(s
, "No reply on IPCP");
848 q
= makeppp(buf
, 0, 0, t
, s
, PPPIPCP
);
850 q
[1] = r
; // ID, dont care, we only send one type of request
851 *(u16
*) (q
+ 2) = htons(10);
854 *(u32
*) (q
+ 6) = htonl(myip
? : session
[s
].ip
); // send my IP (use theirs if I dont have one)
855 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
858 // kill a session now
859 void sessionkill(sessionidt s
, char *reason
)
862 STAT(call_sessionkill
);
864 sessionshutdown(s
, reason
); // close radius/routes, etc.
865 if (session
[s
].radius
)
866 radius
[session
[s
].radius
].session
= 0; // cant send clean accounting data, session is killed
867 memset(&session
[s
], 0, sizeof(session
[s
]));
868 session
[s
].next
= sessionfree
;
870 log(2, 0, s
, session
[s
].tunnel
, "Kill session %d: %s\n", s
, reason
);
871 cluster_send_session(s
);
875 void tunnelkill(tunnelidt t
, char *reason
)
880 STAT(call_tunnelkill
);
882 // free control messages
883 while ((c
= tunnel
[t
].controls
))
885 controlt
* n
= c
->next
;
886 tunnel
[t
].controls
= n
;
887 tunnel
[t
].controlc
--;
888 c
->next
= controlfree
;
892 for (s
= 0; s
< MAXSESSION
; s
++)
893 if (session
[s
].tunnel
== t
)
894 sessionkill(s
, reason
);
896 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
897 tunnel
[t
].next
= tunnelfree
;
898 cluster_send_tunnel(t
);
899 log(1, 0, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
903 // shut down a tunnel
904 void tunnelshutdown(tunnelidt t
, char *reason
)
908 STAT(call_tunnelshutdown
);
910 if (!tunnel
[t
].last
|| !tunnel
[t
].far
)
911 { // never set up, can immediately kill
912 tunnelkill(t
, reason
);
915 log(1, 0, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
917 for (s
= 0; s
< MAXSESSION
; s
++)
918 if (session
[s
].tunnel
== t
)
919 sessionkill(s
, reason
);
920 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
921 cluster_send_tunnel(t
);
922 // TBA - should we wait for sessions to stop?
924 controlt
*c
= controlnew(4); // sending StopCCN
925 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
926 control16(c
, 9, t
, 1); // assigned tunnel (our end)
927 controladd(c
, t
, 0); // send the message
931 // read and process packet on tunnel (UDP)
932 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
934 char *chapresponse
= NULL
;
935 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
939 STAT(call_processudp
);
943 log_hex(5, "UDP Data", buf
, len
);
944 STAT(tunnel_rx_packets
);
945 INC_STAT(tunnel_rx_bytes
, len
);
948 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Short UDP, %d bytes\n", len
);
949 STAT(tunnel_rx_errors
);
952 if ((buf
[1] & 0x0F) != 2)
954 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
955 STAT(tunnel_rx_errors
);
960 l
= ntohs(*(u16
*) p
);
963 t
= ntohs(*(u16
*) p
);
965 s
= ntohs(*(u16
*) p
);
969 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid session ID\n");
970 STAT(tunnel_rx_errors
);
975 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid tunnel ID\n");
976 STAT(tunnel_rx_errors
);
979 if (s
&& !session
[s
].tunnel
)
981 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "UDP packet contains session %d but no session[%d].tunnel exists (LAC said tunnel = %d). Dropping packet.\n", s
, s
, t
);
982 STAT(tunnel_rx_errors
);
987 ns
= ntohs(*(u16
*) p
);
989 nr
= ntohs(*(u16
*) p
);
994 u16 o
= ntohs(*(u16
*) p
);
999 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1000 STAT(tunnel_rx_errors
);
1004 if (t
) tunnel
[t
].last
= time_now
;
1007 u16 message
= 0xFFFF; // message type
1009 u8 mandatorymessage
= 0;
1010 u8 chap
= 0; // if CHAP being used
1011 u16 asession
= 0; // assigned session
1012 u32 amagic
= 0; // magic number
1013 u8 aflags
= 0; // flags from last LCF
1014 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1015 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1016 char called
[MAXTEL
] = ""; // called number
1017 char calling
[MAXTEL
] = ""; // calling number
1018 if ((*buf
& 0xCA) != 0xC8)
1020 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad control header %02X\n", *buf
);
1021 STAT(tunnel_rx_errors
);
1024 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Control message (%d bytes): %d ns %d nr %d ns %d nr %d\n",
1025 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1026 // if no tunnel specified, assign one
1030 ipt ip = ntohl(*(ipt *) & addr->sin_addr);
1031 portt port = ntohs(addr->sin_port);
1033 // find existing tunnel that was not fully set up
1034 for (t = 0; t < MAXTUNNEL; t++)
1036 if ((tunnel[t].ip == ip && tunnel[t].port == port) &&
1037 (!tunnel[t].die || !tunnel[t].hostname[0]))
1039 char buf[600] = {0};
1040 snprintf(buf, 600, "Duplicate tunnel with %d. ip=%u port=%d die=%d hostname=%s",
1041 t, tunnel[t].ip, tunnel[t].port, tunnel[t].die, tunnel[t].hostname);
1042 tunnelshutdown(t, buf);
1051 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "No more tunnels\n");
1052 STAT(tunnel_overflow
);
1055 tunnelfree
= tunnel
[t
].next
;
1056 memset(&tunnel
[t
], 0, sizeof(tunnelt
));
1057 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1058 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1059 tunnel
[t
].window
= 4; // default window
1060 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " New tunnel from %u.%u.%u.%u/%u ID %d\n", tunnel
[t
].ip
>> 24, tunnel
[t
].ip
>> 16 & 255, tunnel
[t
].ip
>> 8 & 255, tunnel
[t
].ip
& 255, tunnel
[t
].port
, t
);
1061 STAT(tunnel_created
);
1063 { // check sequence of this message
1064 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1065 if (tunnel
[t
].controlc
)
1066 { // some to clear maybe
1067 while (tunnel
[t
].controlc
&& (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1069 controlt
*c
= tunnel
[t
].controls
;
1070 tunnel
[t
].controls
= c
->next
;
1071 tunnel
[t
].controlc
--;
1072 c
->next
= controlfree
;
1075 tunnel
[t
].try = 0; // we have progress
1078 if (tunnel
[t
].nr
< ns
&& tunnel
[t
].nr
!= 0)
1080 // is this the sequence we were expecting?
1081 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " Out of sequence tunnel %d, (%d not %d)\n", t
, ns
, tunnel
[t
].nr
);
1082 STAT(tunnel_rx_errors
);
1087 tunnel
[t
].nr
++; // receiver advance (do here so quoted correctly in any sends below)
1090 if (skip
< tunnel
[t
].controlc
)
1091 { // some control packets can now be sent that were previous stuck out of window
1092 int tosend
= tunnel
[t
].window
- skip
;
1093 controlt
*c
= tunnel
[t
].controls
;
1101 tunnel
[t
].try = 0; // first send
1102 tunnelsend(c
->buf
, c
->length
, t
);
1107 if (!tunnel
[t
].controlc
)
1108 tunnel
[t
].retry
= 0; // caught up
1111 { // if not a null message
1113 while (l
&& !(fatal
& 0x80))
1115 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1122 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Invalid length in AVP\n");
1123 STAT(tunnel_rx_errors
);
1130 // handle hidden AVPs
1133 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1137 if (!session
[s
].random_vector_length
)
1139 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no random vector.\n");
1143 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP\n");
1147 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1154 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1159 mtype
= ntohs(*(u16
*) (b
));
1163 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1166 case 0: // message type
1167 message
= ntohs(*(u16
*) b
);
1168 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Message type = %d (%s)\n", *b
,
1169 l2tp_message_types
[message
]);
1170 mandatorymessage
= flags
;
1172 case 1: // result code
1174 u16 rescode
= ntohs(*(u16
*)(b
));
1175 const char* resdesc
= "(unknown)";
1176 if (message
== 4) { /* StopCCN */
1177 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1178 resdesc
= stopccn_result_codes
[rescode
];
1179 } else if (message
== 14) { /* CDN */
1180 if (rescode
<= MAX_CDN_RESULT_CODE
)
1181 resdesc
= cdn_result_codes
[rescode
];
1184 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Result Code %d: %s\n",
1187 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1188 const char* errdesc
= "(unknown)";
1189 if (errcode
<= MAX_ERROR_CODE
)
1190 errdesc
= error_codes
[errcode
];
1191 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error Code %d: %s\n",
1195 /* %*s doesn't work?? */
1197 memcpy(buf
, b
+4, n
-4);
1199 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error String: %s\n",
1205 case 2: // protocol version
1207 version
= ntohs(*(u16
*) (b
));
1208 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Protocol version = %d\n", version
);
1209 if (version
&& version
!= 0x0100)
1210 { // allow 0.0 and 1.0
1211 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Bad protocol version %04X\n",
1218 case 3: // framing capabilities
1219 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1221 case 4: // bearer capabilities
1222 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1224 case 5: // tie breaker
1225 // We never open tunnels, so we don't
1226 // care about tie breakers
1227 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1229 case 6: // firmware revision
1230 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1232 case 7: // host name
1233 memset(tunnel
[t
].hostname
, 0, 128);
1234 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1235 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1236 // TBA - to send to RADIUS
1238 case 8: // vendor name
1239 memset(tunnel
[t
].vendor
, 0, 128);
1240 memcpy(tunnel
[t
].vendor
, b
, (n
>= 127) ? 127 : n
);
1241 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1243 case 9: // assigned tunnel
1244 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1245 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1247 case 10: // rx window
1248 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1249 if (!tunnel
[t
].window
)
1250 tunnel
[t
].window
= 1; // window of 0 is silly
1251 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1253 case 11: // Challenge
1255 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " LAC requested CHAP authentication for tunnel\n");
1256 build_chap_response(b
, 2, n
, &chapresponse
);
1259 case 14: // assigned session
1260 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1261 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " assigned session = %d\n", asession
);
1263 case 15: // call serial number
1264 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1266 case 18: // bearer type
1267 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1270 case 19: // framing type
1271 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1274 case 21: // called number
1275 memset(called
, 0, MAXTEL
);
1276 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1277 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Called <%s>\n", called
);
1279 case 22: // calling number
1280 memset(calling
, 0, MAXTEL
);
1281 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1282 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Calling <%s>\n", calling
);
1284 case 24: // tx connect speed
1287 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1291 // AS5300s send connect speed as a string
1293 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1294 session
[s
].tx_connect_speed
= atol(tmp
);
1296 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " TX connect speed <%d>\n",
1297 session
[s
].tx_connect_speed
);
1299 case 38: // rx connect speed
1302 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1306 // AS5300s send connect speed as a string
1308 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1309 session
[s
].rx_connect_speed
= atol(tmp
);
1311 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " RX connect speed <%d>\n",
1312 session
[s
].rx_connect_speed
);
1314 case 25: // Physical Channel ID
1316 u32 tmp
= ntohl(*(u32
*)b
);
1317 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Physical Channel ID <%X>\n", tmp
);
1320 case 29: // Proxy Authentication Type
1322 u16 authtype
= ntohs(*(u16
*)b
);
1323 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Type %d (%s)\n",
1324 authtype
, authtypes
[authtype
]);
1325 requestchap
= (authtype
== 2);
1328 case 30: // Proxy Authentication Name
1330 char authname
[64] = {0};
1331 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1332 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Name (%s)\n",
1336 case 31: // Proxy Authentication Challenge
1338 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1339 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Challenge (%X)\n", radius
[session
[s
].radius
].auth
);
1342 case 32: // Proxy Authentication ID
1344 u16 authid
= ntohs(*(u16
*)(b
));
1345 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth ID (%d)\n",
1347 if (session
[s
].radius
)
1348 radius
[session
[s
].radius
].id
= authid
;
1351 case 33: // Proxy Authentication Response
1353 char authresp
[64] = {0};
1354 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1355 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Response\n");
1358 case 27: // last send lcp
1359 { // find magic number
1360 u8
*p
= b
, *e
= p
+ n
;
1361 while (p
< e
&& p
[1])
1363 if (*p
== 5 && p
[1] == 6)
1364 amagic
= ntohl(*(u32
*) (p
+ 2));
1365 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5)
1368 aflags
|= SESSIONPFC
;
1370 aflags
|= SESSIONACFC
;
1375 char tmp
[500] = {0};
1377 memcpy((tmp
+ 1), b
, n
);
1381 case 28: // last recv lcp confreq
1383 char tmp
[500] = {0};
1385 memcpy((tmp
+ 1), b
, n
);
1388 case 26: // Initial Received LCP CONFREQ
1390 char tmp
[500] = {0};
1392 memcpy((tmp
+ 1), b
, n
);
1395 case 39: // seq required - we control it as an LNS anyway...
1397 case 36: // Random Vector
1398 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1399 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1400 memcpy(session
[s
].random_vector
, b
, n
);
1401 session
[s
].random_vector_length
= n
;
1404 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Unknown AVP type %d\n", mtype
);
1411 tunnelshutdown(t
, "Unknown Mandatory AVP");
1415 case 1: // SCCRQ - Start Control Connection Request
1417 controlt
*c
= controlnew(2); // sending SCCRP
1418 control16(c
, 2, version
, 1); // protocol version
1419 control32(c
, 3, 3, 1); // framing
1420 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1421 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1422 control16(c
, 9, t
, 1); // assigned tunnel
1423 controladd(c
, t
, s
); // send the resply
1430 controlnull(t
); // ack
1433 controlnull(t
); // ack
1434 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1435 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1438 controlnull(t
); // simply ACK
1452 STAT(session_overflow
);
1453 tunnelshutdown(t
, "No free sessions");
1460 // make a RADIUS session
1463 STAT(radius_overflow
);
1464 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "No free RADIUS sessions for ICRQ\n");
1468 c
= controlnew(11); // sending ICRP
1470 sessionfree
= session
[s
].next
;
1471 memset(&session
[s
], 0, sizeof(session
[s
]));
1472 session
[s
].id
= sessionid
++;
1473 session
[s
].opened
= time(NULL
);
1474 session
[s
].tunnel
= t
;
1475 session
[s
].far
= asession
;
1476 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1477 control16(c
, 14, s
, 1); // assigned session
1478 controladd(c
, t
, s
); // send the reply
1480 radiusfree
= radius
[r
].next
;
1481 memset(&radius
[r
], 0, sizeof(radius
[r
]));
1482 session
[s
].radius
= r
;
1483 radius
[r
].session
= s
;
1485 // Generate a random challenge
1487 for (n
= 0; n
< 15; n
++)
1488 radius
[r
].auth
[n
] = rand();
1490 strcpy(radius
[r
].calling
, calling
);
1491 strcpy(session
[s
].called
, called
);
1492 strcpy(session
[s
].calling
, calling
);
1493 STAT(session_created
);
1500 session
[s
].magic
= amagic
; // set magic number
1501 session
[s
].flags
= aflags
; // set flags received
1502 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1503 controlnull(t
); // ack
1504 // In CHAP state, request PAP instead
1509 controlnull(t
); // ack
1510 sessionshutdown(s
, "Closed (Received CDN)");
1513 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Missing message type\n");
1516 STAT(tunnel_rx_errors
);
1517 if (mandatorymessage
& 0x80)
1518 tunnelshutdown(t
, "Unknown message");
1520 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown message type %d\n", message
);
1523 if (chapresponse
) free(chapresponse
);
1524 cluster_send_tunnel(t
);
1528 log(4, 0, s
, t
, " Got a ZLB ack\n");
1535 log_hex(5, "Receive Tunnel Data", p
, l
);
1538 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1539 return; // closing session, PPP not processed
1541 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1542 { // HDLC address header, discard
1548 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Short ppp length %d\n", l
);
1549 STAT(tunnel_rx_errors
);
1559 prot
= ntohs(*(u16
*) p
);
1565 session
[s
].last_packet
= time_now
;
1566 processpap(t
, s
, p
, l
);
1568 else if (prot
== PPPCHAP
)
1570 session
[s
].last_packet
= time_now
;
1571 processchap(t
, s
, p
, l
);
1573 else if (prot
== PPPLCP
)
1575 session
[s
].last_packet
= time_now
;
1576 processlcp(t
, s
, p
, l
);
1578 else if (prot
== PPPIPCP
)
1580 session
[s
].last_packet
= time_now
;
1581 processipcp(t
, s
, p
, l
);
1583 else if (prot
== PPPCCP
)
1585 session
[s
].last_packet
= time_now
;
1586 processccp(t
, s
, p
, l
);
1588 else if (prot
== PPPIP
)
1590 session
[s
].last_packet
= time_now
;
1591 processipin(t
, s
, p
, l
);
1595 STAT(tunnel_rx_errors
);
1596 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown PPP protocol %04X\n", prot
);
1601 // read and process packet on tap
1602 void processtap(u8
* buf
, int len
)
1604 log_hex(5, "Receive TAP Data", buf
, len
);
1605 STAT(tap_rx_packets
);
1606 INC_STAT(tap_rx_bytes
, len
);
1608 STAT(call_processtap
);
1614 log(1, 0, 0, 0, "Short tap packet %d bytes\n", len
);
1615 STAT(tap_rx_errors
);
1618 if (*(u16
*) (buf
+ 2) == htons(PKTARP
)) // ARP
1619 processarp(buf
, len
);
1620 else if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // ARP
1621 processipout(buf
, len
);
1624 log(1, 0, 0, 0, "Unexpected tap packet %04X, %d bytes\n", ntohs(*(u16
*) (buf
+ 2)), len
);
1628 // main loop - gets packets on tap or udp and processes them
1635 clockt slow
= now(); // occasional functions like session/tunnel expiry, tunnel hello, etc
1636 clockt next_acct
= slow
+ ACCT_TIME
;
1637 clockt next_cluster_ping
= slow
+ 50;
1640 log(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tapfd=%d, radfd=%d, cluster_sockfd=%d, controlfd=%d\n",
1641 udpfd
, tapfd
, radfd
, cluster_sockfd
, controlfd
);
1647 FD_SET(controlfd
, &cr
);
1651 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &cr
);
1653 if (cn
< radfd
) cn
= radfd
;
1654 if (cn
< tapfd
) cn
= tapfd
;
1655 if (cn
< controlfd
) cn
= controlfd
;
1657 if (cn
< clifd
) cn
= clifd
;
1659 if (cn
< cluster_sockfd
) cn
= cluster_sockfd
;
1665 memcpy(&r
, &cr
, sizeof(fd_set
));
1666 n
= select(n
+ 1, &r
, 0, 0, &to
);
1677 struct sockaddr_in addr
;
1678 int alen
= sizeof(addr
);
1679 if (FD_ISSET(udpfd
, &r
))
1680 processudp(buf
, recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
), &addr
);
1681 else if (FD_ISSET(tapfd
, &r
))
1682 processtap(buf
, read(tapfd
, buf
, sizeof(buf
)));
1683 else if (FD_ISSET(radfd
, &r
))
1684 processrad(buf
, recv(radfd
, buf
, sizeof(buf
), 0));
1685 else if (FD_ISSET(cluster_sockfd
, &r
))
1686 processcluster(buf
, recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
));
1687 else if (FD_ISSET(controlfd
, &r
))
1688 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
);
1690 else if (FD_ISSET(clifd
, &r
))
1692 struct sockaddr_in addr
;
1694 int len
= sizeof(addr
);
1696 if ((sockfd
= accept(clifd
, (struct sockaddr
*)&addr
, &len
)) <= 0)
1698 log(0, 0, 0, 0, "accept error: %s\n", strerror(errno
));
1710 log(1, 0, 0, 0, "Main select() loop returned %d, but no fds have data waiting\n", n
);
1714 else if (n
== 0) { // handle timeouts
1715 clockt when
= now();
1716 clockt best
= when
+ 100; // default timeout
1720 for (r
= 0; r
< MAXRADIUS
; r
++)
1721 if (radius
[r
].state
&& radius
[r
].retry
)
1723 if (radius
[r
].retry
<= when
)
1725 if (radius
[r
].retry
&& radius
[r
].retry
< best
)
1726 best
= radius
[r
].retry
;
1728 for (t
= 0; t
< MAXTUNNEL
; t
++)
1730 // check for expired tunnels
1731 if (tunnel
[t
].die
&& tunnel
[t
].die
<= when
)
1733 STAT(tunnel_timeout
);
1734 tunnelkill(t
, "Expired");
1737 // check for message resend
1738 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
1740 // resend pending messages as timeout on reply
1741 if (tunnel
[t
].retry
<= when
)
1743 controlt
*c
= tunnel
[t
].controls
;
1744 u8 w
= tunnel
[t
].window
;
1745 tunnel
[t
].try++; // another try
1746 if (tunnel
[t
].try > 5)
1747 tunnelkill(t
, "Timeout on control message"); // game over
1751 tunnelsend(c
->buf
, c
->length
, t
);
1755 if (tunnel
[t
].retry
&& tunnel
[t
].retry
< best
)
1756 best
= tunnel
[t
].retry
;
1759 if (tunnel
[t
].ip
&& !tunnel
[t
].die
&& tunnel
[t
].last
< when
+ 600 && !tunnel
[t
].controlc
)
1761 controlt
*c
= controlnew(6); // sending HELLO
1762 controladd(c
, t
, 0); // send the message
1763 log(3, tunnel
[t
].ip
, 0, t
, "Sending HELLO message\n");
1768 // Check for sessions that have been killed from the CLI
1769 if (cli_session_kill
[0])
1772 for (i
= 0; i
< MAXSESSION
&& cli_session_kill
[i
]; i
++)
1774 log(2, 0, cli_session_kill
[i
], 0, "Dropping session by CLI\n");
1775 sessionshutdown(cli_session_kill
[i
], "Requested by CLI");
1776 cli_session_kill
[i
] = 0;
1779 // Check for tunnels that have been killed from the CLI
1780 if (cli_tunnel_kill
[0])
1783 for (i
= 0; i
< MAXTUNNEL
&& cli_tunnel_kill
[i
]; i
++)
1785 log(2, 0, cli_tunnel_kill
[i
], 0, "Dropping tunnel by CLI\n");
1786 tunnelshutdown(cli_tunnel_kill
[i
], "Requested by CLI");
1787 cli_tunnel_kill
[i
] = 0;
1792 for (s
= 0; s
< MAXSESSION
; s
++)
1794 // check for expired sessions
1795 if (session
[s
].die
&& session
[s
].die
<= when
)
1797 STAT(session_timeout
);
1798 sessionkill(s
, "Expired");
1802 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
1803 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
1805 sessionkill(s
, "No response to LCP ECHO requests");
1809 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
1810 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
1812 u8 b
[MAXCONTROL
] = {0};
1813 u8
*q
= makeppp(b
, 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
1816 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
1817 *(u16
*)(q
+ 2) = htons(8); // Length
1818 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
1820 log(4, session
[s
].ip
, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
1821 time_now
- session
[s
].last_packet
);
1822 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
1826 if (accounting_dir
&& next_acct
<= when
)
1828 // Dump accounting data
1829 next_acct
= when
+ ACCT_TIME
;
1833 if (cluster_sockfd
&& next_cluster_ping
<= when
)
1835 // Dump accounting data
1836 next_cluster_ping
= when
+ 50;
1837 cluster_send_message(cluster_address
, bind_address
, C_PING
, hostname
, strlen(hostname
));
1841 best
= when
+ 1; // should not really happen
1842 to
.tv_sec
= (best
- when
) / 10;
1843 to
.tv_usec
= 100000 * ((best
- when
) % 10);
1844 log(5, 0, 0, 0, "Next time check in %d.%d seconds\n", (best
- when
) / 10, ((best
- when
) % 10));
1849 // Init data structures
1854 _statistics
= mmap(NULL
, sizeof(struct Tstats
), PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1855 if (_statistics
<= 0)
1857 log(0, 0, 0, 0, "Error doing mmap for _statistics: %s\n", strerror(errno
));
1860 tunnel
= mmap(NULL
, sizeof(tunnelt
) * MAXTUNNEL
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1863 log(0, 0, 0, 0, "Error doing mmap for tunnels: %s\n", strerror(errno
));
1866 session
= mmap(NULL
, sizeof(sessiont
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1869 log(0, 0, 0, 0, "Error doing mmap for sessions: %s\n", strerror(errno
));
1872 radius
= mmap(NULL
, sizeof(radiust
) * MAXRADIUS
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1875 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno
));
1878 ip_address_pool
= mmap(NULL
, sizeof(ippoolt
) * MAXIPPOOL
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1879 if (ip_address_pool
<= 0)
1881 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno
));
1885 ringbuffer
= mmap(NULL
, sizeof(struct Tringbuffer
), PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1886 if (ringbuffer
<= 0)
1888 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno
));
1891 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
1895 cli_session_kill
= mmap(NULL
, sizeof(sessionidt
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1896 if (cli_session_kill
<= 0)
1898 log(0, 0, 0, 0, "Error doing mmap for cli session kill: %s\n", strerror(errno
));
1901 memset(cli_session_kill
, 0, sizeof(sessionidt
) * MAXSESSION
);
1902 cli_tunnel_kill
= mmap(NULL
, sizeof(tunnelidt
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1903 if (cli_tunnel_kill
<= 0)
1905 log(0, 0, 0, 0, "Error doing mmap for cli tunnel kill: %s\n", strerror(errno
));
1908 memset(cli_tunnel_kill
, 0, sizeof(tunnelidt
) * MAXSESSION
);
1910 filter_buckets
= mmap(NULL
, sizeof(tbft
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1911 if (filter_buckets
<= 0)
1913 log(0, 0, 0, 0, "Error doing mmap for filter buckets: %s\n", strerror(errno
));
1916 memset(filter_buckets
, 0, sizeof(tbft
) * MAXSESSION
);
1920 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
1921 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
1922 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
1923 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
1924 for (i
= 1; i
< MAXTUNNEL
- 1; i
++)
1925 tunnel
[i
].next
= i
+ 1;
1926 tunnel
[MAXTUNNEL
- 1].next
= 0;
1928 for (i
= 1; i
< MAXSESSION
- 1; i
++)
1929 session
[i
].next
= i
+ 1;
1930 session
[MAXSESSION
- 1].next
= 0;
1932 for (i
= 1; i
< MAXRADIUS
- 1; i
++)
1933 radius
[i
].next
= i
+ 1;
1934 radius
[MAXRADIUS
- 1].next
= 0;
1938 // Grab my hostname unless it's been specified
1939 gethostname(hostname
, sizeof(hostname
));
1941 struct hostent
*h
= gethostbyname(hostname
);
1943 myip
= ntohl(*(u32
*) h
->h_addr
);
1946 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
1948 // Start the timer routine off
1950 strftime(time_now_string
, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
1953 void initiptables(void)
1955 /* Flush the tables here so that we have a clean slate */
1956 system("iptables -t nat -F l2tpns");
1957 system("iptables -t mangle -F l2tpns");
1960 ipt
assign_ip_address()
1964 STAT(call_assign_ip_address
);
1969 if (ip_pool_index
>= ip_pool_size
)
1975 if (!ip_address_pool
[ip_pool_index
].assigned
&& ip_address_pool
[ip_pool_index
].address
)
1977 ip_address_pool
[ip_pool_index
].assigned
= 1;
1978 log(4, ip_address_pool
[ip_pool_index
].address
, 0, 0, "assign_ip_address(): Allocating ip address %lu from pool\n", ip_pool_index
);
1980 return ntohl(ip_address_pool
[ip_pool_index
].address
);
1987 void free_ip_address(ipt address
)
1992 STAT(call_free_ip_address
);
1996 for (i
= 0; i
<= ip_pool_size
; i
++)
1998 if (ip_address_pool
[i
].address
== a
)
2001 ip_address_pool
[i
].assigned
= 0;
2004 uncache_sessionid(htonl(address
));
2007 // Initialize the IP address pool
2013 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2015 if (!(f
= fopen(IPPOOLFILE
, "r")))
2017 log(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2021 buf
= (char *)malloc(4096);
2023 while (pi
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2026 if (*buf
== '#' || *buf
== '\n')
2027 continue; // Skip comments / blank lines
2028 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2029 if ((p
= (char *)strchr(buf
, ':')))
2033 src
= inet_addr(buf
);
2034 if (src
== INADDR_NONE
)
2036 log(0, 0, 0, 0, "Invalid address pool IP %s", buf
);
2039 // This entry is for a specific IP only
2040 if (src
!= bind_address
)
2045 if ((p
= (char *)strchr(pool
, '/')))
2049 unsigned long start
= 0, end
= 0, mask
= 0, ip
;
2052 log(2, 0, 0, 0, "Adding IP address range %s\n", buf
);
2054 if (!*p
|| !(numbits
= atoi(p
)))
2056 log(0, 0, 0, 0, "Invalid pool range %s/\n", buf
, p
);
2059 start
= end
= ntohl(inet_addr(pool
));
2060 mask
= (unsigned long)(pow(2, numbits
) - 1) << (32 - numbits
);
2062 end
= start
+ (int)(pow(2, (32 - numbits
))) - 1;
2063 for (ip
= (start
+ 1); ip
< end
&& pi
< MAXIPPOOL
; ip
++)
2065 if ((ip
& 0xFF) == 0 || (ip
& 0xFF) == 255)
2067 ip_address_pool
[pi
++].address
= htonl(ip
);
2070 // Add a static route for this pool
2071 log(5, 0, 0, 0, "Adding route for address pool %s/%d\n", inet_toa(htonl(start
)), 32+mask
);
2072 memset(&r
, 0, sizeof(r
));
2073 r
.rt_dev
= tapdevice
;
2074 r
.rt_dst
.sa_family
= AF_INET
;
2075 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(start
);
2076 r
.rt_genmask
.sa_family
= AF_INET
;
2077 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
2078 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
2079 if (ioctl(ifrfd
, SIOCADDRT
, (void *) &r
) < 0)
2081 log(0, 0, 0, 0, "Error adding ip address pool route %s/%d: %s\n", inet_toa(start
), mask
, strerror(errno
));
2086 // It's a single ip address
2087 ip_address_pool
[pi
++].address
= inet_addr(pool
);
2093 log(1, 0, 0, 0, "IP address pool is %d addresses\n", pi
);
2097 void snoop_send_packet(char *packet
, u16 size
)
2099 if (!snoop_addr
.sin_port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2102 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2103 log(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2104 STAT(packets_snooped
);
2107 void dump_acct_info()
2109 char filename
[1024];
2111 time_t t
= time(NULL
);
2116 STAT(call_dump_acct_info
);
2118 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2119 snprintf(filename
, 1024, "%s/%s", accounting_dir
, timestr
);
2121 for (i
= 0; i
< MAXSESSION
; i
++)
2123 if (!session
[i
].opened
|| !session
[i
].cin
|| !session
[i
].cout
|| !*session
[i
].user
|| session
[i
].walled_garden
)
2127 time_t now
= time(NULL
);
2128 if (!(f
= fopen(filename
, "w")))
2130 log(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2133 log(3, 0, 0, 0, "Dumping accounting information to %s\n", filename
);
2134 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2138 "# format: username ip qos uptxoctets downrxoctets\n",
2144 log(4, 0, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
2145 fprintf(f
, "%s %s %d %lu %lu\n",
2146 session
[i
].user
, // username
2147 inet_toa(htonl(session
[i
].ip
)), // ip
2148 (session
[i
].throttle
) ? 2 : 1, // qos
2149 (unsigned long)session
[i
].cin
, // uptxoctets
2150 (unsigned long)session
[i
].cout
); // downrxoctets
2152 session
[i
].pin
= session
[i
].cin
= 0;
2153 session
[i
].pout
= session
[i
].cout
= 0;
2160 int main(int argc
, char *argv
[])
2164 _program_name
= strdup(argv
[0]);
2168 rlim
.rlim_cur
= RLIM_INFINITY
;
2169 rlim
.rlim_max
= RLIM_INFINITY
;
2170 // Remove the maximum core size
2171 setrlimit(RLIMIT_CORE
, &rlim
);
2172 // Make core dumps go to /tmp
2176 time(&basetime
); // start clock
2179 while ((o
= getopt(argc
, argv
, "vc:f:h:a:")) >= 0)
2187 config_file
= strdup(optarg
);
2190 log_filename
= strdup(optarg
);
2193 strncpy(hostname
, optarg
, 1000);
2196 myip
= inet_addr(optarg
);
2197 if (myip
== INADDR_NONE
) {
2198 log(0, 0, 0, 0, "Invalid ip %s\n", optarg
);
2201 bind_address
= myip
;
2202 handle_interface
= 1;
2206 printf("Args are:\n\t-c <file>\tConfig file\n\t-h <hostname>\tForce hostname\n\t-a <address>\tUse specific address\n\t-f <file>\tLog File\n\t-v\t\tDebug\n");
2216 log(0, 0, 0, 0, "$Id: l2tpns.c,v 1.1 2003-12-16 07:07:39 fred_nerk Exp $\n(c) Copyright 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2218 /* Start up the cluster first, so that we don't have two machines with
2219 * the same IP at once.
2220 * This is still racy, but the second GARP should fix that
2222 cluster_init(bind_address
, 0);
2223 cluster_send_message(cluster_address
, bind_address
, C_HELLO
, hostname
, strlen(hostname
));
2226 log(1, 0, 0, 0, "Set up on interface %s\n", tapdevice
);
2232 if (handle_interface
) {
2233 send_garp(bind_address
);
2241 signal(SIGALRM
, sigalrm_handler
);
2242 signal(SIGHUP
, sighup_handler
);
2243 signal(SIGTERM
, sigterm_handler
);
2244 signal(SIGINT
, sigterm_handler
);
2245 signal(SIGQUIT
, sigquit_handler
);
2246 signal(SIGCHLD
, sigchild_handler
);
2247 signal(SIGSEGV
, sigsegv_handler
);
2251 for (n
= 0; n
< numradiusservers
; n
++)
2252 log(1, 0, 0, 0, "RADIUS to %s\n", inet_toa(htonl(radiusserver
[n
])));
2257 // Drop privileges here
2258 if (target_uid
> 0 && geteuid() == 0)
2263 if (l2tpsecret
) free(l2tpsecret
);
2264 if (log_filename
) free(log_filename
);
2265 if (snoop_destination_host
) free(snoop_destination_host
);
2266 if (radiussecret
) free(radiussecret
);
2271 void sighup_handler(int junk
)
2273 if (log_stream
!= stderr
)
2280 void sigalrm_handler(int junk
)
2282 // Log current traffic stats
2285 printf("UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%lu OUT:%lu\n",
2286 (udp_rx
/ 1024.0 / 1024.0 * 8),
2287 (eth_tx
/ 1024.0 / 1024.0 * 8),
2288 (eth_rx
/ 1024.0 / 1024.0 * 8),
2289 (udp_tx
/ 1024.0 / 1024.0 * 8),
2290 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
2291 udp_rx_pkt
, eth_rx_pkt
);
2293 udp_tx
= udp_rx
= 0;
2294 udp_rx_pkt
= eth_rx_pkt
= 0;
2295 eth_tx
= eth_rx
= 0;
2298 // Update the internal time counter
2300 strftime(time_now_string
, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2305 struct param_timer p
= { time_now
};
2306 run_plugins(PLUGIN_TIMER
, &p
);
2311 void sigterm_handler(int junk
)
2313 log(1, 0, 0, 0, "Shutting down cleanly\n");
2314 if (config_save_state
)
2319 void sigquit_handler(int junk
)
2322 log(1, 0, 0, 0, "Shutting down without saving sessions\n");
2323 for (i
= 0; i
< MAXSESSION
; i
++)
2325 if (session
[i
].opened
)
2326 sessionkill(i
, "L2TPNS Closing");
2328 for (i
= 0; i
< MAXTUNNEL
; i
++)
2331 tunnelshutdown(i
, "L2TPNS Closing");
2336 void sigchild_handler(int signal
)
2341 pid
= wait(&status
);
2343 status
= (WIFEXITED(status
)) ? WEXITSTATUS(status
) : 0;
2347 log(3, 0, 0, 0, "CLI client closed connection\n");
2349 log(2, 0, 0, 0, "CLI child died with rc %d!\n", status
);
2354 void *backtrace_buffer
[30] = {0};
2356 void sigsegv_handler(int signal
)
2358 log(0, 0, 0, 0, "----------------------------------------------\n");
2359 log(0, 0, 0, 0, "- SEGFAULT! -\n");
2360 log(0, 0, 0, 0, "----------------------------------------------\n");
2369 if (!config_save_state
) return;
2371 if (stat(STATEFILE
, &sb
) < 0)
2374 if (sb
.st_mtime
< (time(NULL
) - 60))
2376 log(0, 0, 0, 0, "State file is too old to read\n");
2381 if (!(f
= fopen(STATEFILE
, "r")))
2383 log(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
2389 log(1, 0, 0, 0, "Reading state information\n");
2392 if (fread(&numtunnels
, sizeof(numtunnels
), 1, f
) <= 0)
2394 log(0, 0, 0, 0, "Error reading saved state (tunnel count): %s\n", strerror(errno
));
2399 log(2, 0, 0, 0, "Reading %lu tunnels\n", numtunnels
);
2400 fread(tunnel
, sizeof(tunnelt
), numtunnels
, f
);
2402 for (i
= 0; i
< numtunnels
; i
++)
2404 tunnel
[i
].controlc
= 0;
2405 tunnel
[i
].controls
= NULL
;
2406 tunnel
[i
].controle
= NULL
;
2407 if (*tunnel
[i
].hostname
)
2409 log(3, 0, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
2417 if (fread(&numsessions
, sizeof(numsessions
), 1, f
) <= 0)
2419 log(0, 0, 0, 0, "Error reading saved state (session count): %s\n", strerror(errno
));
2424 log(2, 0, 0, 0, "Reading %lu sessions\n", numsessions
);
2425 if (fread(session
, sizeof(sessiont
), numsessions
, f
) < numsessions
)
2427 log(0, 0, 0, 0, "Error reading saved state (%d sessions): %s\n", numsessions
, strerror(errno
));
2432 for (i
= 0; i
< numsessions
; i
++)
2435 session
[i
].throttle
= 0;
2436 if (session
[i
].opened
)
2438 log(2, 0, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
2439 if (session
[i
].ip
&& session
[i
].ip
!= 0xFFFFFFFE)
2442 sessionsetup(session
[i
].tunnel
, i
, 0);
2443 for (x
= 0; x
< MAXIPPOOL
&& ip_address_pool
[x
].address
; x
++)
2445 if (ip_address_pool
[x
].address
== session
[i
].ip
)
2447 ip_address_pool
[x
].assigned
= 1;
2454 log(2, 0, i
, 0, "No IP for session\n");
2458 for (i
= 0; i
< numsessions
&& session
[i
].opened
; i
++)
2459 sessionfree
= session
[i
].next
;
2462 log(0, 0, 0, 0, "Loaded saved state information\n");
2470 if (!config_save_state
) return;
2472 if ((f
= fopen(STATEFILE
, "w")))
2475 log(1, 0, 0, 0, "Dumping state information\n");
2478 fwrite(&i
, sizeof(i
), 1, f
); // Number of tunnels
2480 log(2, 0, 0, 0, "Dumping %lu tunnels\n", i
);
2481 fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
);
2484 fwrite(&i
, sizeof(i
), 1, f
); // Number of sessions
2485 log(2, 0, 0, 0, "Dumping %lu sessions\n", i
);
2486 fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
);
2492 log(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
2497 void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
2500 *challenge_response
= NULL
;
2502 if (!l2tpsecret
|| !*l2tpsecret
)
2504 log(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
2509 if (challenge_length != 16)
2511 log(0, 0, 0, 0, "Challenge length != 16.\n");
2516 log(4, 0, 0, 0, " Building challenge response for CHAP request\n");
2518 *challenge_response
= (char *)calloc(17, 1);
2521 MD5Update(&ctx
, &id
, 1);
2522 MD5Update(&ctx
, l2tpsecret
, strlen(l2tpsecret
));
2523 MD5Update(&ctx
, challenge
, challenge_length
);
2524 MD5Final(*challenge_response
, &ctx
);
2529 void read_config_file()
2534 if (!config_file
) return;
2535 if (!(f
= fopen(config_file
, "r"))) {
2536 fprintf(stderr
, "Can't open config file %s: %s\n", config_file
, strerror(errno
));
2543 radiussecret
= NULL
;
2555 log_filename
= NULL
;
2558 if (snoop_destination_host
)
2560 free(snoop_destination_host
);
2561 snoop_destination_host
= NULL
;
2564 if (numradiusservers
) {
2566 for (n
= 0; n
< numradiusservers
; n
++)
2567 radiusserver
[n
] = 0;
2568 numradiusservers
= 0;
2571 snoop_destination_port
= 0L;
2572 config_save_state
= 0;
2575 default_dns1
= default_dns2
= 0;
2576 radius_accounting
= 0;
2578 buf
= (char *)malloc(4096);
2580 while (fgets(buf
, 4096, f
)) {
2583 if (*buf
== '#') continue;
2584 if ((p
= strchr(buf
, '\n'))) *p
= 0;
2585 p
= t
= strchr(buf
, '=');
2589 while (*p
&& *p
== ' ') p
++;
2590 while (*t
&& *t
== ' ') *t
-- = 0;
2592 if (strcmp(buf
, "log file") == 0) {
2594 log_filename
= strdup(p
);
2595 } else if (strcmp(buf
, "l2tp secret") == 0) {
2597 l2tpsecret
= strdup(p
);
2598 log(0, 0, 0, 0, "L2TP Secret is \"%s\"\n", l2tpsecret
);
2599 } else if (strcmp(buf
, "radius secret") == 0) {
2601 radiussecret
= strdup(p
);
2602 log(4, 0, 0, 0, "Radius Secret is \"%s\"\n", radiussecret
);
2603 } else if (strcmp(buf
, "radius accounting") == 0) {
2604 radius_accounting
= atoi(p
);
2605 log(4, 0, 0, 0, "Radius Account is %s\n", radius_accounting
? "on" : "off");
2606 } else if (strcmp(buf
, "throttle rate") == 0) {
2610 log(1, 0, 0, 0, "Disabled throttling.\n");
2614 log(1, 0, 0, 0, "Enabled throttling (rate is %lu kbits/s)\n", rl_rate
);
2616 } else if (strcmp(buf
, "debug") == 0) {
2618 log(debug
, 0, 0, 0, "Set debugging level to %d\n", debug
);
2619 } else if (strcmp(buf
, "accounting dir") == 0) {
2620 accounting_dir
= strdup(p
);
2621 log(debug
, 0, 0, 0, "Will dump accounting information to %s\n", accounting_dir
);
2622 } else if (strcmp(buf
, "dns server") == 0) {
2623 unsigned long addr
= 0;
2624 if (inet_aton(p
, (struct in_addr
*)&addr
) < 0) {
2625 printf("Invalid DNS server %s\n", p
);
2628 if (default_dns1
== 0)
2629 default_dns1
= addr
;
2630 else if (default_dns2
== 0)
2631 default_dns2
= addr
;
2632 } else if (strcmp(buf
, "radius server") == 0) {
2633 struct hostent
*h
= gethostbyname(p
);
2636 while (*h
->h_addr_list
)
2638 ipt ip
= ntohl(*(u32
*) * h
->h_addr_list
);
2639 if (numradiusservers
< MAXRADSERVER
)
2640 radiusserver
[numradiusservers
++] = ip
;
2642 log(0, 0, 0, 0, "Too many RADIUS IPs\n");
2648 ipt ip
= ntohl(inet_addr(p
));
2649 if (ip
&& ip
!= 0xFFFFFFFF)
2651 if (numradiusservers
< MAXRADSERVER
)
2652 radiusserver
[numradiusservers
++] = ip
;
2654 log(0, 0, 0, 0, "Too many RADIUS IPs\n");
2657 log(0, 0, 0, 0, "Unknown server %s\n", p
);
2659 } else if (strcmp(buf
, "snoop host") == 0) {
2660 snoop_destination_host
= strdup(p
);
2661 } else if (strcmp(buf
, "snoop port") == 0) {
2662 snoop_destination_port
= atol(p
);
2663 } else if (strcmp(buf
, "bind address") == 0) {
2666 // Already overridden on the command line
2667 bind_address
= inet_addr(p
);
2668 handle_interface
= 1;
2670 } else if (strcmp(buf
, "dump speed") == 0) {
2671 dump_speed
= atoi(p
);
2672 } else if (strcmp(buf
, "setuid") == 0) {
2673 target_uid
= atoi(p
);
2674 } else if (strcmp(buf
, "cluster master") == 0) {
2675 struct hostent
*h
= gethostbyname(p
);
2678 if (*h
->h_addr_list
)
2680 cluster_address
= *(u32
*) *h
->h_addr_list
;
2685 cluster_address
= inet_addr(p
);
2687 } else if (strcmp(buf
, "save state") == 0) {
2688 if (strcasecmp(p
, "no") == 0) {
2689 config_save_state
= 0;
2691 config_save_state
= 1;
2693 } else if (strcmp(buf
, "plugin") == 0) {
2696 struct param_config cp
= { buf
, p
};
2697 int rc
= run_plugins(PLUGIN_CONFIG
, &cp
);
2698 if (rc
== 0) log(0, 0, 0, 0, "Unknown config directive \"%s\"\n", buf
);
2702 if (snoop_destination_host
)
2704 if (inet_aton(snoop_destination_host
, &snoop_addr
.sin_addr
))
2706 snoop_addr
.sin_port
= htons(snoop_destination_port
);
2707 snoop_addr
.sin_family
= AF_INET
;
2711 log(0, 0, 0, 0, "Can't find address for snoop host %s\n", snoop_destination_host
);
2717 log(2, 0, 0, 0, "Done reading config file\n");
2720 int sessionsetup(tunnelidt t
, sessionidt s
, u8 routes
)
2722 // A session now exists, set it up
2727 STAT(call_sessionsetup
);
2729 log(3, session
[s
].ip
, s
, t
, "Doing session setup for session\n");
2730 if (!session
[s
].ip
) {
2731 log(0, session
[s
].ip
, s
, t
, "VERY VERY BAD! sessionsetup() called with no session[s].ip\n");
2734 if (session
[s
].ip
== 0xFFFFFFFE)
2736 session
[s
].ip
= assign_ip_address(); // Assign one from the pool;
2738 log(2, session
[s
].ip
, s
, t
, "IP assigned is a magic token. Assign address from pool: %s\n",
2739 inet_toa(htonl(session
[s
].ip
)));
2742 // Make sure this is right
2743 session
[s
].tunnel
= t
;
2744 // zap old sessions with same IP and/or username
2745 // Don't kill walled_garden sessions - doing so leads to a DoS
2746 // from someone who doesn't need to know the password
2748 user
= session
[s
].user
;
2749 for (i
= 0; i
< MAXSESSION
; i
++)
2751 if (i
== s
) continue;
2752 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
2753 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
2754 sessionkill(i
, "Duplicate session for user");
2759 if (session
[s
].route
[routes
].ip
&& session
[s
].route
[routes
].mask
)
2761 log(2, session
[s
].ip
, s
, t
, "Routing session\n");
2762 routeset(session
[s
].ip
, 0, 0, 1);
2764 routeset(session
[s
].route
[routes
].ip
, session
[s
].route
[routes
].mask
,
2769 if (!session
[s
].sid
)
2772 // Force throttling on or off
2773 // This has the advantage of cleaning up after another throttled user who may have left
2774 // firewall rules lying around
2775 throttle_session(s
, session
[s
].throttle
);
2778 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
2779 run_plugins(PLUGIN_NEW_SESSION
, &data
);
2782 session
[s
].sid
= ++last_sid
;
2783 cache_sessionid(htonl(session
[s
].ip
), s
);
2785 cluster_send_session(s
);
2786 session
[s
].last_packet
= time_now
;
2788 char *sessionip
, *tunnelip
;
2789 sessionip
= strdup(inet_toa(ntohl(session
[s
].ip
)));
2790 tunnelip
= strdup(inet_toa(ntohl(tunnel
[t
].ip
)));
2791 log(2, session
[s
].ip
, s
, t
, "Login by %s at %s from %s (%s)\n",
2792 session
[s
].user
, sessionip
, tunnelip
, tunnel
[t
].hostname
);
2793 if (sessionip
) free(sessionip
);
2794 if (tunnelip
) free(tunnelip
);
2797 return 1; // RADIUS OK and IP allocated, done...
2801 void ringbuffer_dump(FILE *stream
)
2803 int i
= ringbuffer
->head
;
2805 while (i
!= ringbuffer
->tail
)
2807 if (*ringbuffer
->buffer
[i
].message
)
2808 fprintf(stream
, "%d-%s", ringbuffer
->buffer
[i
].level
, ringbuffer
->buffer
[i
].message
);
2809 if (++i
== ringbuffer
->tail
) break;
2810 if (i
== RINGBUFFER_SIZE
) i
= 0;
2819 loaded_plugins
= ll_init();
2820 // Initialize the plugins to nothing
2821 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
2822 plugins
[i
] = ll_init();
2825 void add_plugin(char *plugin_name
)
2828 int (*initfunc
)(struct pluginfuncs
*);
2829 char path
[256] = {0};
2831 struct pluginfuncs funcs
;
2834 funcs
._log_hex
= _log_hex
;
2835 funcs
.inet_toa
= inet_toa
;
2836 funcs
.get_session_by_username
= sessionbyuser
;
2837 funcs
.get_session_by_id
= sessiontbysessionidt
;
2838 funcs
.get_id_by_session
= sessionidtbysessiont
;
2839 funcs
.sessionkill
= sessionkill
;
2840 funcs
.radiusnew
= radiusnew
;
2841 funcs
.radiussend
= radiussend
;
2843 snprintf(path
, 256, "%s/%s.so", LIBDIR
, plugin_name
);
2845 log(2, 0, 0, 0, "Loading plugin from %s\n", path
);
2846 p
= dlopen(path
, RTLD_NOW
);
2849 log(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
2853 if (ll_contains(loaded_plugins
, p
))
2860 int *v
= dlsym(p
, "__plugin_api_version");
2861 if (!v
|| *v
!= PLUGIN_API_VERSION
)
2863 log(1, 0, 0, 0, " Plugin load failed: API version mismatch\n", dlerror());
2869 initfunc
= dlsym(p
, "plugin_init");
2872 log(1, 0, 0, 0, " Plugin load failed: function plugin_init() does not exist.\n", dlerror());
2877 if (!initfunc(&funcs
))
2879 log(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE.\n", dlerror());
2884 for (i
= 0; i
< max_plugin_functions
; i
++)
2887 if (!plugin_functions
[i
]) continue;
2888 if ((x
= dlsym(p
, plugin_functions
[i
])))
2890 log(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
2891 ll_push(plugins
[i
], x
);
2894 log(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name
);
2897 void remove_plugin(char *plugin_name
)
2901 char path
[256] = {0};
2904 snprintf(path
, 256, "%s/%s.so", LIBDIR
, plugin_name
);
2906 log(2, 0, 0, 0, "Removing plugin %s\n", plugin_name
);
2907 // Get the existing pointer
2908 p
= dlopen(path
, RTLD_LAZY
);
2911 for (i
= 0; i
< max_plugin_functions
; i
++)
2914 if (!plugin_functions
[i
]) continue;
2915 if ((x
= dlsym(p
, plugin_functions
[i
]))) ll_delete(plugins
[i
], x
);
2918 if (ll_contains(loaded_plugins
, p
))
2920 ll_delete(loaded_plugins
, p
);
2922 donefunc
= dlsym(p
, "plugin_done");
2923 if (donefunc
) donefunc();
2928 log(2, 0, 0, 0, "Removed plugin %s\n", plugin_name
);
2931 int run_plugins(int plugin_type
, void *data
)
2933 int (*func
)(void *data
);
2934 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
) return 1;
2936 ll_reset(plugins
[plugin_type
]);
2937 while ((func
= ll_next(plugins
[plugin_type
])))
2941 if (rc
== PLUGIN_RET_STOP
) return 1;
2942 if (rc
== PLUGIN_RET_ERROR
) return 0;
2947 void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
)
2951 struct param_control param
= { buf
, len
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), NULL
, 0, 0 };
2953 log(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Received ");
2954 dump_packet(buf
, log_stream
);
2956 resp
= calloc(1400, 1);
2957 l
= new_packet(PKT_RESP_ERROR
, resp
);
2958 *(int *)(resp
+ 6) = *(int *)(buf
+ 6);
2960 param
.type
= ntohs(*(short *)(buf
+ 2));
2961 param
.id
= ntohl(*(int *)(buf
+ 6));
2962 param
.data_length
= ntohs(*(short *)(buf
+ 4)) - 10;
2963 param
.data
= (param
.data_length
> 0) ? (char *)(buf
+ 10) : NULL
;
2964 param
.response
= resp
;
2965 param
.response_length
= l
;
2967 if (param
.type
== PKT_LOAD_PLUGIN
&& param
.data_length
)
2969 add_plugin(param
.data
);
2971 else if (param
.type
== PKT_UNLOAD_PLUGIN
&& param
.data_length
)
2973 remove_plugin(param
.data
);
2977 run_plugins(PLUGIN_CONTROL
, ¶m
);
2980 if (param
.send_response
)
2982 send_packet(controlfd
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), param
.response
, param
.response_length
);
2983 log(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Sent Control packet response\n");