From: Benjamin Cama Date: Thu, 7 Jul 2011 10:47:12 +0000 (+0200) Subject: Merge remote-tracking branch 'upstream-repo/master' into upstream X-Git-Tag: upstream/2.2.1 X-Git-Url: http://git.sameswireless.fr/l2tpns.git/commitdiff_plain/e57e8c3825df6800ace741a7798ca96c6e9a577e?hp=f2a3180cc0123acabfed9e48200be0a063f695c0 Merge remote-tracking branch 'upstream-repo/master' into upstream --- diff --git a/Changes b/Changes index abe7854..aad8483 100644 --- a/Changes +++ b/Changes @@ -1,16 +1,27 @@ -* Fri Dec 1 2006 Brendan O'Dea 2.1.21 -- Security: Rhys Kidd identified a vulnerability in the handling of - heartbeat packets. Drop oversize heartbeat packets. - -* Thu Aug 3 2006 Brendan O'Dea 2.1.20 -- Fix sign problem with reporting of unknown VSAs. -- Allow DNS servers to be specified either using the old or new - vendor-specific Ascend formats. - -* Fri Jun 23 2006 Brendan O'Dea 2.1.19 +* Thu Jan 20 2011 Brendan O'Dea 2.2.x +- Apply MLPPP patch from Muhammad Tayseer Alquoatli. +- Apply patch from Michael O to avoid sending multiple CDNs. +- Apply patch from Cyril Elkaim to fix an issue with MacOS. +- Apply patch from Geoffrey D. Bennett to fix retry of control packets. + +* Mon Dec 18 2006 Brendan O'Dea 2.2.0 +- Only poll clifd if successfully bound. +- Add "Practical VPNs" document from Liran Tal as Docs/vpn . +- Add Multilink support from Khaled Al Hamwi. +- Remove non-working setuid option. +- Convert manual.html to Docbook. - Kludge around problem with Netgear DM602 authentication. +- Add session/idle timeouts (Graham Maltby). - Use result code AVP to set Acct-Terminate-Cause is disconnect cause AVP is not present. +- Add radius_bind_{min,max} to simplify firewalling of RADIUS ports. +- Fix sign problem with reporting of unknown RADIUS VSAs. +- Allow DNS servers to be specified either using the old or new + vendor-specific Ascend formats. +- Security [CVE-2006-5873]: Rhys Kidd identified a vulnerability in the + handling of heartbeat packets. Drop oversize heartbeat packets. +- Don't send interim records before session start (Daryl Tester). +- Add "shutdown" and "reload" CLI commands (Daryl Tester). * Tue Apr 18 2006 Brendan O'Dea 2.1.18 - Don't shutdown on TerminateReq, wait for CDN. diff --git a/Docs/common/config.xml b/Docs/common/config.xml new file mode 100644 index 0000000..6207ae3 --- /dev/null +++ b/Docs/common/config.xml @@ -0,0 +1,4 @@ + + + + diff --git a/Docs/common/docbook.css b/Docs/common/docbook.css new file mode 100644 index 0000000..00e3974 --- /dev/null +++ b/Docs/common/docbook.css @@ -0,0 +1,69 @@ +div.article > div.titlepage { + text-align: center; +} + +.abstract { + text-align: justify; +} + +.title { + font-family: sans-serif; + font-weight: bolder; + margin-bottom: 0.5em; +} + +.sect2, .sect2, .sect3, .sect4 { + margin-left: 2%; + margin-right: 2%; +} + +.sect2 .title, .sect2 .title, .sect3 .title, .sect4 .title { + margin-left: 0; + margin-right: 0; +} + +.synopsis, .screen, .programlisting { + font-family: monospace; + font-size: 1em; + display: block; + padding: 10px; + border: 1px solid #bbb; + background-color: #eee; + color: #000; + overflow: auto; + border-radius: 2.5px; + -moz-border-radius: 2.5px; + margin: 0.5em 2em; +} + +.programlisting em { + color: red; +} + +.hanging-indent { + margin-left: 4em; + text-indent: -2em; +} + +table { + margin: 0.5em 2em; + border: 1px solid #bbb; + border-collapse: collapse; +} + +td { + vertical-align: baseline; +} + +thead { + background-color: #eee; +} + +td table { + margin: 0; + border: 0; +} + +td { + border: 1px solid #bbb; +} \ No newline at end of file diff --git a/Docs/manual/manual.xml b/Docs/manual/manual.xml new file mode 100644 index 0000000..38e7b81 --- /dev/null +++ b/Docs/manual/manual.xml @@ -0,0 +1,2163 @@ + + + +
+ + L2TPNS Manual + + + + Overview + + l2tpns is half of a complete L2TP + implementation. It supports only the LNS side of the + connection. + + + + L2TP (Layer 2 Tunneling Protocol) is designed to allow any layer + 2 protocol (e.g. Ethernet, PPP) to be tunneled over an IP + connection. l2tpns implements PPP over L2TP + only. + + + + There are a couple of other L2TP implementations, of which + l2tpd + is probably the most popular. l2tpd also will handle being + either end of a tunnel, and is a lot more configurable than + l2tpns. However, due to the way it works, it + is nowhere near as scalable. + + + + l2tpns uses the TUN/TAP interface provided by + the Linux kernel to receive and send packets. Using some packet + manipulation it doesn't require a single interface per + connection, as l2tpd does. + + + + This allows it to scale extremely well to very high loads and + very high numbers of connections. + + + + It also has a plugin architecture which allows custom code to be + run during processing. An example of this is in the walled + garden module included. + + + + + Installation + + Requirements + + + + Linux kernel version 2.4 or above, with the Tun/Tap + interface either compiled in, or as a module. + + + + + + libcli 1.8.5 or greater. You can get this from + + SourceForge + + + + + + + Compiling + + You can generally get away with just running + make from the source directory. This will + compile the daemon, associated tools and any modules shipped + with the distribution. + + + + + Installing + + After you have successfully compiled everything, run + make install to install it. By + default, the binaries are installed into + /usr/sbin, the configuration into + /etc/l2tpns, and the modules into + /usr/lib/l2tpns. + + + + You will definately need to edit the configuration files + before you start. See for + more information. + + + + + Running + + You only need to run /usr/sbin/l2tpns as + root to start it. It does not normally detach to a daemon + process (see the option), so you should + perhaps run it from init. + + + + By default there is no log destination set, so all log + messages will go to stdout. + + + + + + Configuration + + All configuration of the software is done from the files + installed into /etc/l2tpns. + + + + <filename>startup-config</filename> + + This is the main configuration file for + l2tpns. The format of the file is a list + of commands that can be run through the command-line + interface. This file can also be written directly by the + l2tpns process if a user runs the + write memory command, so any comments + will be lost. However if your policy is not to write the + config by the program, then feel free to comment the file with + a # or ! at the + beginning of the line. + + + + A list of the possible configuration directives follows. Each + of these should be set by a line like: + +set configstring "value" +set ipaddress 192.168.1.1 +set boolean true + + + + + + debug (int) + + + Sets the level of messages that will be written to the + log file. The value should be between 0 and 5, with 0 + being no debugging, and 5 being the highest. A rough + description of the levels is: + + + + 0: Critical Errors + + Things are probably broken + + + + + 1: Errors + + + Things might have gone wrong, but probably will + recover + + + + + + 2: Warnings + + + Just in case you care what is not quite perfect + + + + + + 3: Information + + Parameters of control packets + + + + + 4: Calls + + For tracing the execution of the code + + + + + 5: Packets + + + Everything, including a hex dump of all packets + processed... probably twice + + + + + + + + Note that the higher you set the debugging level, the + slower the program will run. Also, at level 5 a + lot of information will be logged. + This should only ever be used for working out why it + doesn't work at all. + + + + + + log_file (string) + + + This will be where all logging and debugging information + is written to. This may be either a filename, such as + /var/log/l2tpns, or the special + magic string + syslog:facility, + where facility is any one of + the syslog logging facilities, such as + local5. + + + + + + pid_file (string) + + + If set, the process id will be written to the specified + file. The value must be an absolute path. + + + + + + random_device (string) + + + Path to random data source (default + /dev/urandom). Use "" to use the + rand() library function. + + + + + + l2tp_secret (string) + + + The secret used by l2tpns for + authenticating tunnel request. Must be the same as the + LAC, or authentication will fail. Only actually be used + if the LAC requests authentication. + + + + + + l2tp_mtu (int) + + + MTU of interface for L2TP traffic (default: + 1500). Used to set link MRU and + adjust TCP MSS. + + + + + + ppp_restart_time (int) + ppp_max_configure (int) + ppp_max_failure (int) + + + PPP counter and timer values, as described in §4.1 + of + RFC1661. + + + + + + primary_dns (ip address) + econdary_dns (ip address) + + + Whenever a PPP connection is established, DNS servers + will be sent to the user, both a primary and a + secondary. If either is set to 0.0.0.0, then that one + will not be sent. + + + + + + primary_radius (ip address) + secondary_radius (ip address) + + + Sets the RADIUS servers used for both authentication and + accounting. If the primary server does not respond, + then the secondary RADIUS server will be tried. + + + + In addition to the source IP address and identifier, + the RADIUS server must include + the source port when detecting duplicates to supress + (in order to cope with a large number of sessions + comming on-line simultaneously + l2tpns uses a set of udp sockets, + each with a seperate identifier). + + + + + + + + primary_radius_port (short) + secondary_radius_port (short) + + + Sets the authentication ports for the primary and + secondary RADIUS servers. The accounting port is one + more than the authentication port. If no RADIUS ports + are given, the authentication port defaults to 1645, and + the accounting port to 1646. + + + + + + radius_accounting (boolean) + + + If set to true, then RADIUS accounting packets will be + sent. This means that a Start record will be sent when + the session is successfully authenticated, and a Stop + record will be sent when the session is closed. + + + + + + radius_interim (int) + + + If radius_accounting is on, defines + the interval between sending of RADIUS interim + accounting records (in seconds). + + + + + + radius_secret (string) + + + This secret will be used in all RADIUS queries. If this + is not set then RADIUS queries will fail. + + + + + + radius_authtypes (string) + + + A comma separated list of supported RADIUS + authentication methods (pap or + chap), in order of preference + (default pap). + + + + + + radius_bind_min (short) + radius_bind_max (short) + + + Define a port range in which to bind sockets used to + send and receive RADIUS packets. Must be at least + RADIUS_FDS (64) wide. Simplifies firewalling of RADIUS + ports (default: dynamically assigned). + + + + + + radius_dae_port (short) + + + Port for DAE RADIUS (Packet of Death/Disconnect, Change + of Authorization) requests (default: + 3799). + + + + + + allow_duplicate_users (boolean) + + + Allow multiple logins with the same username. If false + (the default), any prior session with the same username + will be dropped when a new session is established. + + + + + + guest_account (string) + + + Allow multiple logins matching this specific username. + + + + + + bind_address (ip address) + + + When the tun interface is created, it is assigned the + address specified here. If no address is given, 1.1.1.1 + is used. Packets containing user traffic should be + routed via this address if given, otherwise the primary + address of the machine. + + + + + + peer_address (ip address) + + Address to send to clients as the default gateway. + + + + + send_garp (boolean) + + + Determines whether or not to send a gratuitous ARP for + the bind_address when the server is ready to handle + traffic (default: true). This value + is ignored if BGP is configured. + + + + + + throttle_speed (int) + + + Sets the default speed (in kbits/s) which sessions will + be limited to. If this is set to 0, then throttling + will not be used at all. Note: You can set this by the + CLI, but changes will not affect currently connected + users. + + + + + + throttle_buckets (int) + + + Number of token buckets to allocate for throttling. + Each throttled session requires two buckets (in and + out). + + + + + + accounting_dir (string) + + + If set to a directory, then every 5 minutes the current + usage for every connected use will be dumped to a file + in this directory. Each file dumped begins with a + header, where each line is prefixed by #. + Following the header is a single line for every + connected user, fields separated by a space. + + + + The fields are username, ip, qos, uptxoctets, + downrxoctets. The qos field is 1 if a standard user, + and 2 if the user is throttled. + + + + + + dump_speed (boolean) + + + If set to true, then the current bandwidth utilization + will be logged every second. Even if this is disabled, + you can see this information by running the + uptime command on the CLI. + + + + + + multi_read_count (int) + + + Number of packets to read off each of the UDP and TUN + fds when returned as readable by select (default: 10). + Avoids incurring the unnecessary system call overhead of + select on busy servers. + + + + + + scheduler_fifo (boolean) + + + Sets the scheduling policy for the + l2tpns process to + SCHED_FIFO. This causes the kernel + to immediately preempt any currently running + SCHED_OTHER (normal) process in + favour of l2tpns when it becomes + runnable. Ignored on uniprocessor systems. + + + + + + lock_pages (boolean) + + + Keep all pages mapped by the l2tpns + process in memory. + + + + + + icmp_rate (int) + + + Maximum number of host unreachable ICMP packets to send + per second. + + + + + + packet_limit (int) + + + Maximum number of packets of downstream traffic to be + handled each tenth of a second per session. If zero, no + limit is applied (default: 0). Intended as a DoS + prevention mechanism and not a general throttling + control (packets are dropped, not queued). + + + + + + cluster_address (ip address) + + + Multicast cluster address (default: 239.192.13.13). + See for more information. + + + + + + cluster_interface (string) + + Interface for cluster packets (default: eth0) + + + + + cluster_mcast_ttl (int) + + TTL for multicast packets (default: 1). + + + + + cluster_hb_interval (int) + + + Interval in tenths of a second between cluster + heartbeat/pings. + + + + + + cluster_hb_timeout (int) + + + Cluster heartbeat timeout in tenths of a second. A new + master will be elected when this interval has been + passed without seeing a heartbeat from the master. + + + + + + cluster_master_min_adv (int) + + + Determines the minumum number of up to date slaves + required before the master will drop routes (default: 1). + + + + + + ipv6_prefix (ipv6 address) + + + Enable negotiation of IPv6. This forms the the first 64 + bits of the client allocated address. The remaining 64 + come from the allocated IPv4 address and 4 bytes of 0s. + + + + + + + BGP + + BGP routing configuration is entered by the command: + router bgp as + where as specifies the local AS + number. + + + + Subsequent lines prefixed with + neighbour peer + define the attributes of BGP neighhbours. Valid commands + are: + +neighbour peer remote-as as +neighbour peer timers keepalive hold + + + + + Where peer specifies the BGP + neighbour as either a hostname or IP address, + as is the remote AS number and + keepalive, + hold are the timer values in + seconds. + + + + + Access Lists + + Named access-lists are configured using one of the commands: + +ip access-list standard name +ip access-list extended name + + + + + Subsequent lines prefixed with permit or + deny define the body of the access-list. + Standard access-list syntax: + + + + {permit|deny} + {host|source + source-wildcard|any} + [{host|destination + destination-wildcard|any}] + + + Extended access-lists: + + {permit|deny} + ip + {host|source + source-wildcard|any} + {host|destination + destination-wildcard|any} + [fragments] + + + + {permit|deny} + udp + {host|source + source-wildcard|any} + [{eq|neq|gt|lt} + port|range + from + to] + {host|destination + destination-wildcard|any} + [{eq|neq|gt|lt} + port|range + from + to] + [fragments] + + + + {permit|deny} + tcp + {host|source + source-wildcard|any} + [{eq|neq|gt|lt} + port|range + from + to] + {host|destination + destination-wildcard|any} + [{eq|neq|gt|lt} + port|range + from + to] + [{established|{match-any|match-all} + {+|-}{fin|syn|rst|psh|ack|urg} + ...|fragments] + + + + + + <filename>users</filename> + + Usernames and passwords for the command-line interface are + stored in this file. The format is + +username:password + + where password may either by plain + text, an MD5 digest (prefixed by + $1salt$) + or a DES password, distinguished from plain text by the prefix + {crypt}. + + + + The username enable has a special meaning + and is used to set the enable password. + + + + + If this file doesn't exist, then anyone who can get to port + 23 will be allowed access without a username or password. + + + + + + <filename>ip_pool</filename> + + This file is used to configure the IP address pool which user + addresses are assigned from. This file should contain either + an IP address or a CIDR network per line. e.g.: + + +192.168.1.1 +192.168.1.2 +192.168.1.3 +192.168.4.0/24 +172.16.0.0/16 +10.0.0.0/8 + + + + + Keep in mind that l2tpns can only handle + 65535 connections per process, so don't put more than 65535 IP + addresses in the configuration file. They will be + wasted. + + + + + <filename>build-garden</filename> + + The garden plugin on startup creates a NAT table called + "garden" then sources the build-garden + script to populate that table. All packets from gardened + users will be sent through this table. Example: + + +iptables -t nat -A garden -p tcp -m tcp --dport 25 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p udp -m udp --dport 53 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p tcp -m tcp --dport 53 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p tcp -m tcp --dport 80 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p tcp -m tcp --dport 110 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p tcp -m tcp --dport 443 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p icmp -m icmp --icmp-type echo-request -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p icmp -j ACCEPT +iptables -t nat -A garden -j DROP + + + + + + + Operation + + A running l2tpns process can be controlled in a number of ways. + The primary method of control is by the Command-Line Interface + (CLI). + + + + You can also remotely send commands to modules via the + nsctl client provided. + + + + There are also a number of signals that l2tpns understands and + takes action when it receives them. + + + + Command-Line Interface + + You can access the command line interface by telneting to port + 23. There is no IP address restriction, so it's a good idea + to firewall this port off from anyone who doesn't need access + to it. See for information on + restricting access based on a username and password. + + + + The CLI gives you real-time control over almost everything in + the process. The interface is designed to look like a Cisco + device, and supports things like command history, line editing + and context sensitive help. This is provided by linking with + the + libcli library. Some general documentation of the + interface is + here. + + + + After you have connected to the telnet port (and perhaps + logged in), you will be presented with a + hostname> + prompt. + + + + Enter help to get a list of possible + commands, or press ? for + context-specific help. + + + + A brief overview of the more important commands + follows: + + + + + show session [ID] + + + + + + Detailed information for a specific session is + presented if you specify a session + ID argument. + + + + If no ID is given, a + summary of all connected sessions is produced. Note + that this summary list can be around 185 columns wide, + so you should probably use a wide + terminal. + + + + The columns listed in the summary are: + + + + + + + + + SID + Session ID + + + TID + Tunnel ID + + See also the CLI + command. + + + + Username + + The username given in the PPP authentication. + + + If this is *, then LCP authentication has + not completed. + + + + IP + The IP address given to the session. + + If this is 0.0.0.0, IPCP negotiation has not + completed + + + + I + Intercept + + Y or N: indicates whether the session is + being snooped. See also the + + CLI command. + + + + T + Throttled + + Y or N: indicates whether the session is + currently throttled. See also the + + CLI command. + + + + G + Walled Garden + + Y or N: indicates whether the user is + trapped in the walled garden. This field is + present even if the garden module is not + loaded. + + + + 6 + IPv6 + + Y or N: indicates whether the session has + IPv6 active (IPV6CP open) + + + + opened + + The number of seconds since the + session started + + + + downloaded + + Number of bytes downloaded by the user + + + + uploaded + + Number of bytes uploaded by the user + + + + idle + + The number of seconds since traffic was + detected on the session + + + + LAC + + The IP address of the LAC the session is + connected to. + + + + CLI + + The Calling-Line-Identification field + provided during the session setup. This + field is generated by the LAC. + + + + + + + + + + + + show users + + + show user username + + + + + + With no arguments, display a list of currently + connected users. If an argument is given, the session + details for the given + username are displayed. + + + + + + + show tunnel [ID] + + + + + Produce a summary list of all open tunnels, or detail + on a specific tunnel ID. + + + + The columns listed in the summary are: + + + + + + TID + Tunnel ID + + + Hostname + + The hostname for the tunnel as provided by + the LAC. This has no relation to DNS, it is + just a text field. + + + + IP + The IP address of the LAC + + + State + + Tunnel state: Free, Open, Dieing, Opening + + + + Sessions + The number of open sessions on the tunnel + + + + + + + + + + show pool + + + Displays the current IP address pool allocation. This + will only display addresses that are in use, or are + reserved for re-allocation to a disconnected user. + + + + If an address is not currently in use, but has been + used, then in the User column the username will be + shown in square brackets, followed by the time since + the address was used: + + +IP Address Used Session User +192.168.100.6 N [joe.user] 1548s + + + + + + + show radius + + + Show a summary of the in-use RADIUS sessions. This + list should not be very long, as RADIUS sessions + should be cleaned up as soon as they are used. The + columns listed are: + + + + + + Radius + + The ID of the RADIUS request. This is sent + in the packet to the RADIUS server for + identification + + + + State + + The state of the request: WAIT, CHAP, AUTH, + IPCP, START, STOP or NULL + + + + Session + + The session ID that this RADIUS request is + associated with + + + + Retry + + If a response does not appear to the + request, it will retry at this time. This + is a Unix timestamp + + + + Try + + Retry count. The RADIUS request is + discarded after 3 retries + + + + + + + + + + + show running-config + + + This will list the current running configuration. + This is in a format that can either be pasted into the + configuration file, or run directly at the command + line. + + + + + + show counters + + + Internally, counters are kept of key values, such as + bytes and packets transferred, as well as function + call counters. This function displays all these + counters, and is probably only useful for debugging. + + + + You can reset these counters by running + clear counters. + + + + + + show cluster + + + Show cluster status. Shows the cluster state for this + server (Master/Slave), information about known peers + and (for slaves) the master IP address, last packet + seen and up-to-date status. See + for more information. + + + + + + write memory + + + This will write the current running configuration to + the config file startup-config, + which will be run on a restart. + + + + + + + snoop user + IP + port + + + + You must specify a username, IP address and port. All + packets for the current session for that username will + be forwarded to the given host/port. Specify + no snoop + username to + disable interception for the session. + + + + If you want interception to be permanent, you will + have to modify the RADIUS response for the user. See + . + + + + + + + throttle user + [in|out] rate + + + + You must specify a username, which will be throttled + for the current session to + rate Kbps. Prefix + rate with + in or + out to set different upstream + and downstream rates. + + + + Specify no throttle + username to + disable throttling for the current session. + + + + If you want throttling to be permanent, you will have + to modify the RADIUS response for the user. See . + + + + + + + drop session + + + + This will cleanly disconnect the session specified by + session ID. + + + + + + + drop tunnel + + + + This will cleanly disconnect the tunnel specified by + tunnel ID, as well as all + sessions on that tunnel. + + + + + + uptime + + + This will show how long the l2tpns + process has been running, and the current bandwidth + utilization: + + +17:10:35 up 8 days, 2212 users, load average: 0.21, 0.17, 0.16 +Bandwidth: UDP-ETH:6/6 ETH-UDP:13/13 TOTAL:37.6 IN:3033 OUT:2569 + + + The bandwidth line contains 4 sets of values: + + + + + + UDP-ETH + + The current bandwidth going from the LAC to + the ethernet (user uploads), in mbits/sec. + + + + ETH-UDP + + The current bandwidth going from ethernet to + the LAC (user downloads). + + + + TOTAL + The total aggregate bandwidth in mbits/s. + + + IN and OUT + + Packets/per-second going between UDP-ETH and + ETH-UDP. + + + + + + + These counters are updated every second. + + + + + + configure terminal + + + Enter configuration mode. Use + exit or + ^Z to exit this mode. + + + + The following commands are valid in this mode: + + + + + load plugin + name + + + + Load a plugin. You must specify the plugin + name, and it will search in + /usr/lib/l2tpns for + name.so. + You can unload a loaded plugin with + remove plugin + name. + + + + + + set ... + + + Set a configuration variable. You must specify + the variable name, and the value. If the value + contains any spaces, you should quote the value + with double (") or single (') quotes. + + + + You can set any configuration value in this + way, although some may require a restart to + take effect. See . + + + + + + router bgp ... + + + Configure BGP. See . + + + + + + ip access-list ... + + + Configure a named access list. See . + + + + + + + + + + + + + nsctl + + nsctl sends messages to a running + l2tpns instance to be control plugins. + + + + Arguments are command and optional + args. See + nsctl(8). + + + + Built-in command are load_plugin, + unload_plugin and + help. Any other commands are passed to + plugins for processing by the + plugin_control function. + + + + + Signals + + While the process is running, you can send it a few different + signals, using the kill command. + + +killall -HUP l2tpns + + + The signals understood are: + + + + SIGHUP + + Reload the config from disk and re-open log file. + + + + + SIGTERM + SIGINT + + + Stop process. Tunnels and sessions are not + terminated. This signal should be used to stop + l2tpns on a cluster node where + there are other machines to continue handling traffic. + See + + + + + + SIGQUIT + + + Shut down tunnels and sessions, exit process when + complete. + + + + + + + + + + Throttling + + l2tpns contains support for slowing down user + sessions to whatever speed you desire. The global setting + throttle_speed defines the default throttle + rate. + + + + To throttle a sesion permanently, add a + Cisco-AVPair RADIUS attribute. The + autothrotle module interprets the following + attributes: + + + + + + throttle=yes + + Throttle upstream/downstream traffic to the configured + throttle_speed. + + + + + + throttle=rate + + + Throttle upstream/downstream traffic to the specified + rate Kbps. + + + + + + lcp:interface-config#1=service-policy input + rate + + + + Alternate (Cisco) format: throttle + upstream/downstream to specified + rate Kbps. + + + + + + lcp:interface-config#2=service-policy output + rate + + + + + + + + + You can also enable and disable throttling an active session + using the CLI command. + + + + + Interception + + You may have to deal with legal requirements to be able to + intercept a user's traffic at any time. + l2tpns allows you to begin and end + interception on the fly, as well as at authentication time. + + + + When a user is being intercepted, a copy of every packet they + send and receive will be sent wrapped in a UDP packet to a + specified host. + + + + The UDP packet contains just the raw IP frame, with no extra + headers. The script scripts/l2tpns-capture + may be used as the end-point for such intercepts, writing the + data in PCAP format (suitable for inspection with + tcpdump). + + + + To enable or disable interception of a connected user, use the + and no + snoop CLI commands. These will enable interception + immediately. + + + + If you wish the user to be intercepted whenever they reconnect, + you will need to modify the RADIUS response to include the + Vendor-Specific value + Cisco-AVPair="intercept=ip:port". + For this feature to be enabled, you need to have the + autosnoop module loaded. + + + + + Plugins + + So as to make l2tpns as flexible as possible, + a plugin API is include which you can use to hook into certain + events. + + + + There are a some standard modules included which may be used as + examples: autosnoop, + autothrottle, garden, + sessionctl, + setrxspeed, snoopctl, + stripdomain and + throttlectl. + + + + When an event occurs that has a hook, l2tpns + looks for a predefined function name in every loaded module, and + runs them in the order the modules were loaded. + + + + The function should return PLUGIN_RET_OK if it is + all OK. If it returns PLUGIN_RET_STOP, then it is + assumed to have worked, but that no further modules should be + run for this event. + + + + A return of PLUGIN_RET_ERROR means that this module + failed, and no further processing should be done for this event. + Use this with care. + + + + Most event functions take a specific structure named + param_event, which + varies in content with each event. The function name for each + event will be + plugin_event, so for the + event timer, the function declaration + should look like: + + +int plugin_timer(struct param_timer *data); + + + A list of the available events follows, with a list of all the + fields in the supplied structure: + + + + + + + + + + + Event + Description + Arguments + + + + + + plugin_init + + + Called when the plugin is loaded. A pointer to a + struct containing function pointers is passed as the + only argument, allowing the plugin to call back into + the main code. + + + Prior to loading the plugin, l2tpns + checks the API version the plugin was compiled + against. All plugins should contain: + +int plugin_api_version = PLUGIN_API_VERSION; + + + + struct pluginfuncs * + + + + See pluginfuncs structure in + plugin.h for available functions. + + + + + plugin_done + + Called when the plugin is unloaded or + l2tpns is shutdown. + + void + + + No arguments. + + + + plugin_pre_auth + + Called after a RADIUS response has been received, but + before it has been processed by the code. This will + allow you to modify the response in some way. + + + struct plugin param_pre_auth * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + char *username + User name. + + + char *password + Password. + + + int protocol + + Authentication protocol: 0xC023 for PAP, + 0xC223 for CHAP. + + + + int continue_auth + Set to 0 to stop processing authentication modules. + + + + plugin_post_auth + + Called after a RADIUS response has been received, and + the basic checks have been performed. This is what + the garden module uses to force + authentication to be accepted. + + + struct plugin param_post_auth * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + char *username + User name. + + + short auth_allowed + + Initially true or false depending on whether + authentication has been allowed so far. You can + set this to 1 or 0 to force authentication to be + accepted or rejected. + + + + int protocol + + Authentication protocol: 0xC023 for PAP, + 0xC223 for CHAP. + + + + + plugin_timer + + Run once per second. + + + struct plugin param_timer * + + + + time_t time_now + The current unix timestamp. + + + + plugin_new_session + + Called after a session is fully set up. The session + is now ready to handle traffic. + + + struct plugin param_new_session * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + + plugin_kill_session + + Called when a session is about to be shut down. This + may be called multiple times for the same session. + + + struct plugin param_kill_session * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + + plugin_control + + + Called in whenever a nsctl packet + is received. This should handle the packet and form a + response if required. + + + Plugin-specific help strings may be included in the + output of nsctl help by + defining a NULL terminated list of + strings as follows: + +char *plugin_control_help[] = { ..., NULL }; + + + + + struct plugin param_control * + + + + int iam_master + If true, this node is the cluster master. + + + int argc + nsctl arguments. + + + char **argc + + + int reponse + + Response from control message (if handled): should be + either NSCTL_RES_OK or + NSCTL_RES_ERR. + + + + char *additional + + Additional information, output by + nsctl on receiving the response. + + + + + plugin_radius_response + + Called whenever a RADIUS response includes a + Cisco-AVPair value. The value is + split into + key=value + pairs. Will be called once for each pair in the + response. + + + struct plugin param_radius_response * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + char *key + Key and value. + + + char *value + + + + plugin_radius_reset + + Called whenever a RADIUS CoA request is received to + reset any options to default values before the new + values are applied. + + + struct param_radius_reset * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + + plugin_radius_account + + Called when preparing a RADIUS accounting record to + allow additional data to be added to the packet. + + + struct param_radius_account * + + + + tunnelt *t + Tunnel. + + + sessiont *s + Session. + + + uint8_t **packet + + Pointer to the end of the currently assembled + packet buffer. The value should be incremented by the + length of any data added. + + + + + plugin_become_master + + Called when a node elects itself cluster master. + + void + + + No arguments. + + + + plugin_new_session_master + + Called once for each open session on becoming cluster + master. + + sessiont * + + + + Session. + + + + + + + + + + Walled Garden + + A "Walled Garden" is implemented so that you can provide perhaps + limited service to sessions that incorrectly authenticate. + + + + Whenever a session provides incorrect authentication, and the + RADIUS server responds with Auth-Reject, the walled garden + module (if loaded) will force authentication to succeed, but set + the walled_garden flag in the session + structure, and adds an iptables rule to the + garden_users chain to cause all packets for + the session to traverse the garden chain. + + + + This doesn't just work. To set this all + up, you will to setup the garden nat table + with the script with rules + to limit user's traffic. + + + + For example, to force all traffic except DNS to be forwarded to + 192.168.1.1, add these entries to your + build-garden script: + + +iptables -t nat -A garden -p tcp --dport ! 53 -j DNAT --to 192.168.1.1 +iptables -t nat -A garden -p udp --dport ! 53 -j DNAT --to 192.168.1.1 + + + + + l2tpns will add entries to the + garden_users chain as appropriate. + + + + You can check the amount of traffic being captured using the + following command: + + +iptables -t nat -L garden -nvx + + + + + + Filtering + + Sessions may be filtered by specifying + Filter-Id attributes in the RADIUS reply. + filter.in + specifies that the named access-list + filter should be applied to traffic + from the customer, + filter.out + specifies a list for traffic to the customer. + + + + + Clustering + + An l2tpns cluster consists of one* or more + servers configured with the same configuration, notably the + multicast cluster_address. + + + *A stand-alone server is simply a degraded cluster. + + + Initially servers come up as cluster slaves, and periodically + (every cluster_hb_interval/10 seconds) send + out ping packets containing the start time of the process to the + multicast cluster_address. + + + + A cluster master sends heartbeat rather than ping packets, which + contain those session and tunnel changes since the last + heartbeat. + + + + When a slave has not seen a heartbeat within + cluster_hb_timeout/10 seconds it "elects" a + new master by examining the list of peers it has seen pings from + and determines which of these and itself is the "best" candidate + to be master. "Best" in this context means the server with the + highest uptime (the highest IP address is used as a tie-breaker + in the case of equal uptimes). + + + + After discovering a master, and determining that it is + up-to-date (has seen an update for all in-use sessions and + tunnels from heartbeat packets) will raise a route (see ) for the bind_address and + for all addresses/networks in ip_pool. + + + + Any packets recieved by the slave which would alter the session + state, as well as packets for throttled or gardened sessions are + forwarded to the master for handling. In addition, byte + counters for session traffic are periodically forwarded. + + + + The master, when determining that it has at least one* up-to-date + slave will drop all routes (raising them again if all slaves + disappear) and subsequently handle only packets forwarded to it + by the slaves. + + + *Configurable with cluster_master_min_adv + + + + Routing + + If you are running a single instance, you may simply statically + route the IP pools to the bind_address + (l2tpns will send a gratuitous arp). + + + + For a cluster, configure the members as BGP neighbours on your + router and configure multi-path load-balancing. Cisco uses + maximum-paths ibgp for IBGP. If this is + not supported by your IOS revision, you can use + maximum-paths (which works for EBGP) and + set as_number to a private value such as + 64512. + + +
diff --git a/Docs/startup-config.5 b/Docs/startup-config.5 index a74c87f..6c2cf28 100644 --- a/Docs/startup-config.5 +++ b/Docs/startup-config.5 @@ -2,7 +2,7 @@ .de Id .ds Dt \\$4 \\$5 .. -.Id $Id: startup-config.5,v 1.15 2005/09/16 05:04:31 bodea Exp $ +.Id $Id: startup-config.5,v 1.18 2006/07/01 12:40:17 bodea Exp $ .TH STARTUP-CONFIG 5 "\*(Dt" L2TPNS "File Formats and Conventions" .SH NAME startup\-config \- configuration file for l2tpns @@ -77,17 +77,17 @@ Number of configure requests to send before giving up (default: 10). Number of Configure-Nak requests to send before sending a Configure-Reject (default: 5). .TP -.BR primary_dns , " secondary_dns" +.BR primary_dns ", " secondary_dns Whenever a PPP connection is established, DNS servers will be sent to the user, both a primary and a secondary. If either is set to 0.0.0.0, then that one will not be sent. .TP -.BR primary_radius , " secondary_radius" +.BR primary_radius ", " secondary_radius Sets the RADIUS servers used for both authentication and accounting. If the primary server does not respond, then the secondary RADIUS server will be tried. .TP -.BR primary_radius_port , " secondary_radius_port" +.BR primary_radius_port ", " secondary_radius_port Sets the authentication ports for the primary and secondary RADIUS servers. The accounting port is one more than the authentication port. If no ports are given, authentication defaults to 1645, and @@ -118,11 +118,19 @@ A comma separated list of supported RADIUS authentication methods Port for DAE RADIUS (Packet of Death/Disconnect, Change of Authorization) requests (default: 3799). .TP +.BR radius_bind_min ", " radius_bind_max +Define a port range in which to bind sockets used to send and receive +RADIUS packets. Must be at least RADIUS_FDS (64) wide. Simplifies +firewalling of RADIUS ports (default: dynamically assigned). +.TP .B allow_duplicate_users Allow multiple logins with the same username. If false (the default), any prior session with the same username will be dropped when a new session is established. .TP +.B guest_account +Allow multiple logins matching this specific username. +.TP .B bind_address When the tun interface is created, it is assigned the address specified here. If no address is given, 1.1.1.1 is used. Packets @@ -149,10 +157,6 @@ session requires two buckets (in and out). If set to a directory, then every 5 minutes the current usage for every connected use will be dumped to a file in this directory. .TP -.B setuid -After starting up and binding the interface, change UID to this. This -doesn't work properly. -.TP .B dump_speed If set to true, then the current bandwidth utilization will be logged every second. Even if this is disabled, you can see this information diff --git a/Docs/vpn/practical-vpns.xml b/Docs/vpn/practical-vpns.xml new file mode 100644 index 0000000..ccb92c7 --- /dev/null +++ b/Docs/vpn/practical-vpns.xml @@ -0,0 +1,1086 @@ + + + +
+ + Practical VPNs + Implementing Full-scale VPNs + + + Liran + Tal + +
+ liran@enginx.com +
+
+
+ + + Yakov + Shtutz + Special thanks + + + + Shahar + Fermon + Testing and feedback + + + + + This document was compiled from the administrator's point of + view, to explain what are VPNs, how they are deployed today + and to detail the necessary steps and tools to achieve and + create a fully working VPN solution, integrated with RADIUS + systems for AAA. + + + + I will not dwell in this document on how to compile source + packages or kernel patching, and with the same tone I'm + assuming the reader is an exprerienced Linux user. + + + + VPNs have their share amount of gossip for being a very + complex thing, and in some cases this may be true as they tend + to be more security intenssive which require adding more and + more layers to the scheme. With this said, we'll take a look + at how fairly straight-forward it is to setup VPNs and + maintain them with varius Open-Source tools. + + +
+ + + Overview of VPNs and IPsec + + Virtual Private Networks + + The purpose of a VPN is to create a secure channel ontop of an + un-secure medium, where a computer or a device are put in each + end-point in order to establish communication, each of these + end-points are often reffered to as Point of Presense, or POP. + This kind of a communication allows the capability of creating + a Virtual Private Network, which is accesable over a medium + such as the Internet and thus, extend the physical boundaries + of an existing local network. + + + + VPNs have three forms: + + + Site-To-Site VPNs + + + these setups exist in order to extend the local network + to create a much bigger LAN over the Internet. + + + + + + Network-To-Host or Remote access VPNs + + + where a central VPN server is able to achieve multiple + connections, often reffered to as RoadWarrior VPNs. + (This setup is very common among ISPs) + + + + + + Network-To-Network + + + extranet VPNs allow secure connections within branches + and business partners, they are an extension of a + Site-To-Site VPNs. + + + + + + + + shows a Site-To-Site VPN diagram. +
+ Site to Site VPN + + + + + +
+
+ + + IP/VPNs are connections which are based upon IP tunnels. A + tunnel is a way to encapsulate an IP packet inside another IP + packet or some other type of packet. Why do we need + tunneling? A Virtual Private Network is identified by IANA's + private IP assignments and so such packet can not go beyond + the uplink Internet interface. + + + + shows the tunneling process. +
+ Tunneling Process + + + + + +
+
+ + + Several tunneling protocols are available for manifesting + VPNs. + + + + L2F + + + Layer 2 Forwarding, an older implementation which + assume position at the link layer of the OSI. It has + no encryption capabilities and hence, deprecated. + + + + + + L2TP + + + Layer 2 Tunneling Protocol, still no encryption + capabilities. + + + + + + PPTP + + + Point-to-Point Tunneling Protocol, and yet again, no + encryption. + + + + + + + + As seen, the requirement of encryption enhancement is urgent + in order to assure authentication, data integrity and privacy. + IPsec solves this by providing a suite of security measures + implemented at layer 3. + +
+ + + IP Security Suite (IPsec) + + VPN Security is now appearing, this complex things. How so? + VPN tunnels by themselves are easily maintained by + single-standalone tools like pppd, l2tpns, stunnel and others. + Involving security with VPNs though requires more: + + + + authentication, data integrity and privacy + + + + keying management + + + + + + + Keys are secrets being shared by two end-points to provide a + secure mean of communication against a third-party + connection from sniffing the actual data. + + + + + Different ways to handle key management include RADIUS (Remote + Authentication Dial In User Service) systems which provide AAA + (Authentication, Authorization and Accounting). Another + solution is ISAKMP/Oackly - Internet Security Association and + Key Management Protocol. This solution requires you to posess + one of the following: + + + + something you have + + + + something you know + + + + something you are + + + + + + The more requirements you meet the more secure is the medium, + once established. Let's review, something we have is like a + certificate, it proves who we are. Something we know, is a + key, a secret password which we were told in a whisper, and + something we are is our-fingerprint which identifies ourselves + from other individuals. + + + + IPsec in Depth + + IPsec consists of two main protocols, an Authentication + Header and Encapsulation Security Payload, also known as AH + and ESP. Although it is not bound to these and can be + extended (and often is) to other standarts such as + + + + Data Encryption Standart (DES and 3DES) + + + + Diffie-Hellman (DH) + + + + Secure Hash Algorithm-1 (SHA1) + + + + Message Digest 5 (MD5) + + + + Internet Key Exchange (IKE) + + + + Certification Authorities (CA) + + + + + + We'll be deploying an IKE daemon to handle the key + management, which uses the Diffie- Hellman cryptography + protocol in order to allow two parties to establish a + connection based upon a shared secret key that both parties + posess. (Authentication within IKE is handled by MD5 + hashing) + + + + IKE is responsible for authentication of two IPsec parties, + negotiation of keys for encryption algorithms and security + associations. This process is commonly regarded as two + phases: + + + + Phase 1: IKE Security Association + + + The IKE daemon authenticates against the peers in + order to achieve a secure channel, according to the + Diffie-Hellman key agreement. + + + + + + Phase 2: IKE IPsec Negotiation + + + After achieving an authenticated channel, the + parties now negotiate a secure transform (the way to + encrypt and secure the medium) where the sender is + offering his/hers transform set after which the + receiver decides upon one. An IPsec session can now + safely begin. + + + + + + + + Just to be clear, a Security Association is an agreed + relation between two parties which describes how they will + use security services (from IPsec) to communicate. + + + + + IPsec Modes + + IPsec can operate in two different modes: + + + + Transport mode + + + takes place when two devices (like a station and a + gateway (now considered a host)) are establishing a + connection which upon they both support IPsec. + + + + + + Tunnel mode + + + we require tunnel mode when we proxy IPsec + connetions between two stations behind the IPsec + gateway. For example, in a Site-to-Site VPN a + tunnel mode lives, since it exists in order to + provide the stations behind these gateways runing + the VPN/IPsec to communicate securely. In this + situation, both end-points are runing an IPsec + software. + + + + + + + + In definition, a tunnel mode IPsec is better secured than + transport. Without going too deep into the ins-and-outs of + the technical side, transport mode doesn't encapsulate the + actual IP layer but only the tcp/udp (Transport layer of the + OSI) where-as a tunnel mode encapsulate both the Transport + layer and the IP layer into a new IP packet. + + + + To summarize, we need VPNs for data-exchange methods and a + set of IPsec tools for security reasons. + + + +
+ + + VPN Deployment + + I've assembled another diagram to view the actual VPN setup. + gives a general description of + how the network will be layed out in real-world scenario. + +
+ VPN Deployment + + + + + +
+
+ + + We notice that a single Linux box is acting as a Gateway and has + all the services included with it. This is a bad idea from a + security prespective but it's easy to just deploy the FreeRADIUS + and MySQL servers on another machine. Of course the L2TPns and + the rest of the IPsec tools suite would have to remain on the + Gateway box (not necessarily the Firewall). + + + + attempts to explain the actual + process that the VPN takes and to detail the place that each of + that application-in-charge takes place. + +
+ VPN Process + + + + + +
+
+ + + Requirements + + The Toolbox + + Following is a description of the requirements you will + have to meet: + + + + A Linux box + + preferably a 2.4.27 kernel or higher. + + Debian is the chosen distribution which means we'll + be using apt-get for installation, but I'll also + focus on basic source tarballs installation. + + + + Dependencies: + + + + ipsec configuration in the kernel + + + + + + + + L2TPns + + an L2TP PPP Termination tool. + + Dependencies: + + + + libcli 1.8.0 or greater + + + + + tun/tap interface compiled in the kernel or as + a module + + + + + + + + + FreeRADIUS + + For authentication, and accounting. + + + + + MySQL + + To act as a back-end database for the RADIUS. + + + + + OpenSwan + + Provides the ipsec suite package. + + + + + + + + Kernel Support + + Debian stock kernel 2.4.27 and up are ipsec compatible + although if you think otherwise check for the + kernel-patch-openswan package. + + + + + + Installation + + L2TPns + + Installation +
+ + L2TPns is a layer 2 tunneling protocol network server + (LNS). It supports up to 65535 concurrent sessions per + server/cluster plus ISP features such as rate limiting, + walled garden, usage accounting, and more. + +
+ + + In a personal note - L2TPns is highly configurable for + many cases, and extremely reliable for + production/commerical use. + + + + + + Step 1: + + + Make sure you have libcli-1.8 development package + installed: + +# apt-cache search libcli +libcli-dev - emulates a cisco style telnet command-line interface (dev files) +libcli1 - emulates a cisco style telnet command-line interface +# apt-get install libcli-dev + + + + + + + Step 2: + + + Download the source from + + SourceForge. + + + + + + Step 3: + + + Build and install: + make && make install + + + + + + + + + Alternately, you can skip these steps and simply + apt-get install l2tpns. + + + + + + On RPM-based distributions, you should be able to make + packages from the libcli and l2tpns source tarballs with + rpmbuild -ta. + + + + + Once compiliation is done you will have l2tpns in + /usr/sbin/l2tpns, and all + configuration files can be found in + /etc/l2tpns/. + +
+ + + Configuration + + The only configuration that L2TPns takes is centralized in + the configuration file + /etc/l2tpns/startup-config. + +set debug 2 # Debugging level +set log_file "/var/log/l2tpns" # Log file: comment out to use stderr, use + # "syslog:facility" for syslog +set pid_file "/var/run/l2tpns.pid" # Write pid to this file +set l2tp_secret "secret" # shared secret +set primary_dns 212.117.128.6 # Only 2 DNS server entries are allowed +set secondary_dns 212.117.129.3 +set primary_radius 192.168.0.1 # Can have multiple radius server entries, + # but ony one radius secret +set primary_radius_port 1812 +set radius_secret "radius_secret" +set radius_accounting yes +set radius_dae_port 3799 +set accounting_dir "/var/run/l2tpns/acct" # Write usage accounting files into specified + # directory +set peer_address 192.168.0.1 # Gateway address given to clients +load plugin "sessionctl" # Drop/kill sessions +load plugin "autothrottle" # Throttle/snoop based on RADIUS +load plugin "throttlectl" # Control throttle/snoop with nsctl +load plugin "snoopctl" + + + + + This is the trimmed down version of probably most of + the common configuration and even some extra options. + + + + Important configuration options are highlited and you + should adjust these to meet your network needs. We can + deploy all of the environment into one box which is of + course not a very good idea from a security point of view, + but will function just fine. Moreover, we will be using + aliased IP addresses so once you've decided to move the + FreeRADIUS daemon to another computer on the LAN it will + be fairly easy and won't take too much configuration into + it. + + + + Next, we need to setup the IP pool that L2TPns will + provide to each VPN client. The configuration file is + located at /etc/l2tpns/ip_pool and + should look like the following: + 172.16.21.0/24 + + + + + Of course you can change this pool to anything else + (IANA IPs assigned for private internets only) just make + sure it is not conflicting with your current LAN network + addresses. This means that if you've assigned addresses + of 192.168.0.1 and 192.168.0.2 to your LAN boxes you + can't have a pool of 192.168.0.1/24 defined since L2TPns + will try to route those addresses from the tun device, + which is needless to say a bad idea... + + + + Next up, creating the access-list for L2TPns. + + + Add a username and password into + /etc/l2tpns/users: + admin:12345 + + The password may either be plain-text as above, or + encrypted with MD5 or DES (to distinguish DES from + plain-text passwords, prefix the value with + {crypt}). + + + + L2TPns utilizes a terminal connection on port 23 which you + would feel very comfortable in if you have worked with + routers and switches devices before. The terminal + provides control over the ppp termination which is why + we've created an account to log on to. + + +
+ + + IPsec + + Installation + + User-space IPsec tools for various IPsec implementations + exist for linux, among them is the port of KAME's + libipsec, setkey, and racoon. Others are the OpenSWAN (a + successor to the FreeSWAN project). + + + + Getting IPsec installed is fairly easy with Debian: + # apt-get install openswan + + + + The OpenSWAN project provides packages for RPM-based + distributions. + + + + Alternately, you may download the + source + from the OpenSWAN project: + +# tar xvzf openswan-2.4.4.tar.gz +# cd openswan-2.4.4 +# ./configure && make && make install + + + + + + Configuration + + OpenSWAN acts as the IKE daemon (remember IKE? it's job + is to authenticate between the two peers and negotiate a + secure medium). We will be setting up the IKE daemon as a + RoadWarrior configuration, a term for remote access + VPNs. + + + + We desire this approach for compatibilty because after our + VPN solution will be complete any user from a Windows + machine will be easily ready to connect without any 3rd + party applications, same for Linux. + + + + Configuration files are placed in + /etc/ipsec.d/, + /etc/ipsec.conf and + /etc/ipsec.secrets. + + + + Let's start by choosing the remote client and it's PSK + (Private Shared Key) /etc/ipsec.secrets: + +hostname_or_ipaddress %any : PSK "mysecretkeyisverylong" + + + + + This is an IP/key pair. The IP or FQDN defines the local + peer (like a SOHO branch), then the remote host. Here we + defined %any for all hosts, though it's possible to define + only a specific IP. At last, we define the key associated + with it. + + + + A better way to create a key is to utilize /dev/random for + creating a unique key. + # dd if=/dev/random count=16 bs=1 2>/dev/null | xxd -ps + + + + Next, let's prepare the configuration file + /etc/ipsec.conf: + +version 2.0 +config setup + nat_traversal=yes + +conn l2tp + authby=secret + pfs=no + keyingtries=3 + left=real_ip_address + leftnexthop=%defaultroute + leftprotoport=17/%any + right=%any + rightprotoport=17/%any + auto=add + +include /etc/ipsec.d/examples/no_oe.conf + + + + + In this file we have first defined version 2 which is a + must, then enabled NAT Traversal. To understand the + importance of this feature think of the following + scenario: A remote user attempts to connect while he's + behind a router and therefore NATed. The router has to + de-encapsulate the packet, change things and then build it + up again and send it. IPsec doesn't like other people + messing with it's packet. That's why we solve this issue + with NAT Traversal. + + + + Next up we configure authentication type (certificates, + psk, rsa keys, etc) then the left and right peers. The + default mode OpenSWAN takes is tunnel unless told + otherwise. I won't go into in-depth explanation of every + method, you can take a quick look at + /etc/ipsec.d/examples for more + explanation and other variations of working with RSA keys, + Certificates, host-to-host, and more. + + + + In summary: + + + + We've configured an almost complete IPsec VPN setup. + + + + + + We've installed and configured a VPN server (L2TPns) + and our IPsec security suite. + + + + + + To control both of them we use: + /etc/init.d/l2tpns and + /etc/init.d/racoon (location + of start-up scripts may vary on non-Debian systems, + or if you've installed from + source). + + + + + + + + + FreeRADIUS + + The VPN setup needs to authenticate against something, that + is the users database which we chose to be a FreeRADIUS + server backed with a MySQL database. + + + + Installation +
+ + FreeRADIUS is the premiere open source RADIUS server. + While detailed statistics are not available, we believe + that FreeRADIUS is well within the top 5 RADIUS servers + world-wide, in terms of the number of people who use it + daily for authentication. It scales from embedded + systems with small amounts of memory, to systems with + millions of users. It is fast, flexible, configurable, + and supports more authentication protocols than many + commercial servers. + +
+ + + Installing on Debian: + # apt-get install freeradius freeradius-mysql + + + + From source: Download the latest freeradius package from + freeradius.org + + +# tar xvzf freeradius.tar.gz +# cd freeradius +# ./configure && make && make install + + +
+ + + Configuration + + This will appear a bit complex but it isn't, it's just a + lot of configuration. + + + + Following are the configurations you need to have in your + /etc/freeradius/ files. + + + + In this section I will not give you a dump of the + configuration since they are very long and mostly default. + I'll just post which changes to make. + + + + We haven't yet configured MySQL, but it'll come + afterwards, don't worry. + + + + Make the following changes to the file + /etc/freeradius/sql.conf: + +server = "192.168.0.1" +login = "radius" +password = "12345678" + + + + + Add the following to the file + /etc/freeradius/clients.conf: + +client 192.168.0.1 { + secret = my_secret + shortname = localhost + nastype = other +} + + + + + Don't confuse the secret directive there with IPsec. + RADIUS server are using secret keys also to identify their + allowed NAS (Network Access Servers), these are the + clients that talk to the RADIUS server. + + + + Also, change the client 127.0.0.1 {} + directive to hold the secret "my_secret" like we + configured for 192.168.0.1 to avoid conflicts. + + + + Uncomment the sql directive in the + authorize, accounting, and + session sections of + /etc/freeradius/radiusd.conf. + + + + Now for populating FreeRADIUS with MySQL. If you don't + know or haven't set root password for MySQL you can do it + now with: + # mysqladmin -u root password password_here + + Then add the following to + /root/.my.cnf: + + +[mysqladmin] +user = root +password = password_here + + + + + Create the radius database, using the + schema given in + /usr/share/doc/freeradius/examples/db_mysql.sql.gz + . + + + + + It may be necessary to modify the column definition of + id in the nas table, removing + DEFAULT '0' such that the definition reads: + + id int(10) NOT NULL auto_increment, + + + + +# mysqladmin create radius +# mysql radius +mysql> source db_mysql.sql +mysql> GRANT ALL ON * TO 'radius'@'localhost' IDENTIFIED BY 'radius_password'; + + + All the configuration is now done. Let's add a user to + our VPN database. + +# mysql radius +mysql> INSERT INTO radcheck values (0, "test", "User-Password", "==", "1234"); + + + + + We have now created a user in the database of username + test and password 1234. + + + + Testing the RADIUS setup is simple using the radtest + utility provided with it. + +# radtest +Usage: radtest user passwd radius-server[:port] nas-port-number secret [ppphint] [nasname] +# radtest test 1234 192.168.0.1 1812 my_secret + + + + + radtest sends an Access-Request to the RADIUS server and + expects an Access-Accept back from it. If you're not + getting an Access-Accept from the RADIUS you're advised to + check the configuration again and see what you might have + missed. + + +
+ + + Firewall Configuration + + We need to apply a few things to iptables configuration and + kernel networking. + + + + First off, we need to accept VPN-specific packets through + the firewall. Of course you will have to adjust the rules + to fits you needs, in this case, ppp0 is the Internet + interface. + +# iptables --append INPUT --in-interface ppp0 -p udp --dport 1701 -j ACCEPT +# iptables --append INPUT --in-interface ppp0 -p udp --dport 500 -j ACCEPT +# iptables --append INPUT --in-interface ppp0 -p udp --dport 4500 -j ACCEPT +# iptables --append INPUT --in-interface ppp0 -p 50 -j ACCEPT + + + + + If you haven't setup your Linux box as a gateway yet then + you have to allow forwarding/masqing for the boxes on + the LAN (and therefore for the VPN clients): + +# iptables --table nat --append POSTROUTING --out-interface ppp0 -j MASQUERADE +# iptables --append FORWARD --in-interface eth0 -j ACCEPT +# echo 1 > /proc/sys/net/ipv4/ip_forward + + + +
+
+ + + References + + + VPN Reference + + + + + + + + + L2TPns Project + + + + + + + OpenSWAN Project + + + + + + +
diff --git a/Docs/vpn/site-to-site-vpn.png b/Docs/vpn/site-to-site-vpn.png new file mode 100644 index 0000000..46908c9 Binary files /dev/null and b/Docs/vpn/site-to-site-vpn.png differ diff --git a/Docs/vpn/tunneling-process.png b/Docs/vpn/tunneling-process.png new file mode 100644 index 0000000..0b24062 Binary files /dev/null and b/Docs/vpn/tunneling-process.png differ diff --git a/Docs/vpn/vpn-deployment.png b/Docs/vpn/vpn-deployment.png new file mode 100644 index 0000000..b49505e Binary files /dev/null and b/Docs/vpn/vpn-deployment.png differ diff --git a/Docs/vpn/vpn-process.png b/Docs/vpn/vpn-process.png new file mode 100644 index 0000000..b83e344 Binary files /dev/null and b/Docs/vpn/vpn-process.png differ diff --git a/THANKS b/THANKS index c39a07d..ef0ca1f 100644 --- a/THANKS +++ b/THANKS @@ -12,7 +12,7 @@ Yuri Juergen Kammer Simon Talbot Jonathan McDowell -Bjørn Augestad +Bjørn Augestad Roberto Chostakovis Jordan Hrycaj Vladislav Bjelic @@ -26,4 +26,8 @@ Jon Morby Paul Martin Jonathan Yarden Patrick Cole +Khaled Al Hamwi +Graham Maltby Rhys Kidd +Muhammad Tayseer Alquoatli +Cyril Elkaim diff --git a/autothrottle.c b/autothrottle.c index cd42365..2bc4c99 100644 --- a/autothrottle.c +++ b/autothrottle.c @@ -9,11 +9,11 @@ * lcp:interface-config#2=service-policy output N * * throttle=N - * throttle=yes (use throttle_rate from config) + * throttle=yes (use throttle_speed from config) * throttle=no */ -char const *cvs_id = "$Id: autothrottle.c,v 1.16 2005/10/11 09:04:53 bodea Exp $"; +char const *cvs_id = "$Id: autothrottle.c,v 1.17 2006/05/18 14:40:31 bodea Exp $"; int plugin_api_version = PLUGIN_API_VERSION; static struct pluginfuncs *f = 0; diff --git a/cli.c b/cli.c index bff3bf8..7fbe3d1 100644 --- a/cli.c +++ b/cli.c @@ -1,8 +1,8 @@ // L2TPNS Command Line Interface // vim: sw=8 ts=8 -char const *cvs_name = "$Name: release_2_1_21 $"; -char const *cvs_id_cli = "$Id: cli.c,v 1.71 2005/12/06 09:43:42 bodea Exp $"; +char const *cvs_name = "$Name: $"; +char const *cvs_id_cli = "$Id: cli.c,v 1.76 2006/12/18 12:08:28 bodea Exp $"; #include #include @@ -36,6 +36,7 @@ char const *cvs_id_cli = "$Id: cli.c,v 1.71 2005/12/06 09:43:42 bodea Exp $"; #endif extern tunnelt *tunnel; +extern bundlet *bundle; extern sessiont *session; extern radiust *radius; extern ippoolt *ip_address_pool; @@ -99,6 +100,9 @@ static int cmd_set(struct cli_def *cli, char *command, char **argv, int argc); static int cmd_load_plugin(struct cli_def *cli, char *command, char **argv, int argc); static int cmd_remove_plugin(struct cli_def *cli, char *command, char **argv, int argc); static int cmd_uptime(struct cli_def *cli, char *command, char **argv, int argc); +static int cmd_shutdown(struct cli_def *cli, char *command, char **argv, int argc); +static int cmd_reload(struct cli_def *cli, char *command, char **argv, int argc); + static int regular_stuff(struct cli_def *cli); @@ -175,6 +179,8 @@ void init_cli(char *hostname) #endif cli_register_command(cli, NULL, "uptime", cmd_uptime, PRIVILEGE_UNPRIVILEGED, MODE_EXEC, "Show uptime and bandwidth utilisation"); + cli_register_command(cli, NULL, "shutdown", cmd_shutdown, PRIVILEGE_PRIVILEGED, MODE_EXEC, "Shutdown l2tpns daemon and exit"); + cli_register_command(cli, NULL, "reload", cmd_reload, PRIVILEGE_PRIVILEGED, MODE_EXEC, "Reload configuration"); c = cli_register_command(cli, NULL, "write", NULL, PRIVILEGE_UNPRIVILEGED, MODE_EXEC, NULL); cli_register_command(cli, c, "memory", cmd_write_memory, PRIVILEGE_PRIVILEGED, MODE_EXEC, "Save the running config to flash"); @@ -268,7 +274,7 @@ void init_cli(char *hostname) } memset(&addr, 0, sizeof(addr)); - clifd = socket(PF_INET, SOCK_STREAM, 6); + clifd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); setsockopt(clifd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); { int flags; @@ -425,6 +431,18 @@ static int cmd_show_session(struct cli_def *cli, char *command, char **argv, int cli_print(cli, "\tUnique SID:\t%u", session[s].unique_id); cli_print(cli, "\tOpened:\t\t%u seconds", session[s].opened ? abs(time_now - session[s].opened) : 0); cli_print(cli, "\tIdle time:\t%u seconds", session[s].last_packet ? abs(time_now - session[s].last_packet) : 0); + if (session[s].session_timeout) + { + clockt opened = session[s].opened; + if (session[s].bundle && bundle[session[s].bundle].num_of_links > 1) + opened = bundle[session[s].bundle].online_time; + + cli_print(cli, "\tSess Timeout:\t%u seconds", session[s].session_timeout - (opened ? abs(time_now - opened) : 0)); + } + + if (session[s].idle_timeout) + cli_print(cli, "\tIdle Timeout:\t%u seconds", session[s].idle_timeout - (session[s].last_data ? abs(time_now - session[s].last_data) : 0)); + cli_print(cli, "\tBytes In/Out:\t%u/%u", session[s].cout, session[s].cin); cli_print(cli, "\tPkts In/Out:\t%u/%u", session[s].pout, session[s].pin); cli_print(cli, "\tMRU:\t\t%d", session[s].mru); @@ -2016,7 +2034,7 @@ static int cmd_router_bgp_neighbour(struct cli_def *cli, char *command, char **a int keepalive; int hold; - if (CLI_HELP_REQUESTED) + if (CLI_HELP_REQUESTED) { switch (argc) { @@ -2126,14 +2144,14 @@ static int cmd_router_bgp_neighbour(struct cli_def *cli, char *command, char **a config->neighbour[i].keepalive = keepalive; config->neighbour[i].hold = hold; - return CLI_OK; + return CLI_OK; } static int cmd_router_bgp_no_neighbour(struct cli_def *cli, char *command, char **argv, int argc) { int i; - if (CLI_HELP_REQUESTED) + if (CLI_HELP_REQUESTED) return cli_arg_help(cli, argc > 0, "A.B.C.D", "BGP neighbour address", "NAME", "BGP neighbour name", @@ -2158,7 +2176,7 @@ static int cmd_router_bgp_no_neighbour(struct cli_def *cli, char *command, char } memset(&config->neighbour[i], 0, sizeof(config->neighbour[i])); - return CLI_OK; + return CLI_OK; } static int cmd_show_bgp(struct cli_def *cli, char *command, char **argv, int argc) @@ -3064,3 +3082,21 @@ static int cmd_show_access_list(struct cli_def *cli, char *command, char **argv, return CLI_OK; } + +static int cmd_shutdown(struct cli_def *cli, char *command, char **argv, int argc) +{ + if (CLI_HELP_REQUESTED) + return CLI_HELP_NO_ARGS; + + kill(getppid(), SIGQUIT); + return CLI_OK; +} + +static int cmd_reload(struct cli_def *cli, char *command, char **argv, int argc) +{ + if (CLI_HELP_REQUESTED) + return CLI_HELP_NO_ARGS; + + kill(getppid(), SIGHUP); + return CLI_OK; +} diff --git a/cluster.c b/cluster.c index 538da20..8ac56f4 100644 --- a/cluster.c +++ b/cluster.c @@ -1,6 +1,6 @@ // L2TPNS Clustering Stuff -char const *cvs_id_cluster = "$Id: cluster.c,v 1.50.2.1 2006/12/02 14:09:14 bodea Exp $"; +char const *cvs_id_cluster = "$Id: cluster.c,v 1.55 2009/12/08 14:49:28 bodea Exp $"; #include #include @@ -42,6 +42,7 @@ extern int cluster_sockfd; // The filedescriptor for the cluster communications in_addr_t my_address = 0; // The network address of my ethernet port. static int walk_session_number = 0; // The next session to send when doing the slow table walk. +static int walk_bundle_number = 0; // The next bundle to send when doing the slow table walk. static int walk_tunnel_number = 0; // The next tunnel to send when doing the slow table walk. int forked = 0; // Sanity check: CLI must not diddle with heartbeat table @@ -85,6 +86,7 @@ int cluster_init() int opt; config->cluster_undefined_sessions = MAXSESSION-1; + config->cluster_undefined_bundles = MAXBUNDLE-1; config->cluster_undefined_tunnels = MAXTUNNEL-1; if (!config->cluster_address) @@ -227,7 +229,7 @@ static void cluster_uptodate(void) if (config->cluster_iam_uptodate) return; - if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels) + if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels || config->cluster_undefined_bundles) return; config->cluster_iam_uptodate = 1; @@ -400,7 +402,7 @@ void cluster_send_ping(time_t basetime) x.ver = 1; x.addr = config->bind_address; - x.undef = config->cluster_undefined_sessions + config->cluster_undefined_tunnels; + x.undef = config->cluster_undefined_sessions + config->cluster_undefined_tunnels + config->cluster_undefined_bundles; x.basetime = basetime; add_type(&p, C_PING, basetime, (uint8_t *) &x, sizeof(x)); @@ -520,7 +522,7 @@ void cluster_check_slaves(void) // void cluster_check_master(void) { - int i, count, tcount, high_unique_id = 0; + int i, count, tcount, bcount, high_unique_id = 0; int last_free = 0; clockt t = TIME; static int probed = 0; @@ -614,6 +616,19 @@ void cluster_check_master(void) config->cluster_highest_tunnelid = i; } + // + // Go through and mark all the bundles as defined. + // Count the highest used bundle number as well. + // + config->cluster_highest_bundleid = 0; + for (i = 0, bcount = 0; i < MAXBUNDLE; ++i) { + if (bundle[i].state == BUNDLEUNDEF) + bundle[i].state = BUNDLEFREE; + + if (bundle[i].state != BUNDLEFREE && i > config->cluster_highest_bundleid) + config->cluster_highest_bundleid = i; + } + // // Go through and mark all the sessions as being defined. // reset the idle timeouts. @@ -639,7 +654,7 @@ void cluster_check_master(void) } // Reset idle timeouts.. - session[i].last_packet = time_now; + session[i].last_packet = session[i].last_data = time_now; // Reset die relative to our uptime rather than the old master's if (session[i].die) session[i].die = TIME; @@ -675,10 +690,11 @@ void cluster_check_master(void) rebuild_address_pool(); // If we're not the very first master, this is a big issue! - if(count>0) + if (count > 0) LOG(0, 0, 0, "Warning: Fixed %d uninitialized sessions in becoming master!\n", count); config->cluster_undefined_sessions = 0; + config->cluster_undefined_bundles = 0; config->cluster_undefined_tunnels = 0; config->cluster_iam_uptodate = 1; // assume all peers are up-to-date @@ -696,7 +712,7 @@ void cluster_check_master(void) // we fix it up here, and we ensure that the 'first free session' // pointer is valid. // -static void cluster_check_sessions(int highsession, int freesession_ptr, int hightunnel) +static void cluster_check_sessions(int highsession, int freesession_ptr, int highbundle, int hightunnel) { int i; @@ -705,7 +721,7 @@ static void cluster_check_sessions(int highsession, int freesession_ptr, int hig if (config->cluster_iam_uptodate) return; - if (highsession > config->cluster_undefined_sessions && hightunnel > config->cluster_undefined_tunnels) + if (highsession > config->cluster_undefined_sessions && highbundle > config->cluster_undefined_bundles && hightunnel > config->cluster_undefined_tunnels) return; // Clear out defined sessions, counting the number of @@ -721,6 +737,19 @@ static void cluster_check_sessions(int highsession, int freesession_ptr, int hig ++config->cluster_undefined_sessions; } + // Clear out defined bundles, counting the number of + // undefs remaining. + config->cluster_undefined_bundles = 0; + for (i = 1 ; i < MAXBUNDLE; ++i) { + if (i > highbundle) { + if (bundle[i].state == BUNDLEUNDEF) bundle[i].state = BUNDLEFREE; // Defined. + continue; + } + + if (bundle[i].state == BUNDLEUNDEF) + ++config->cluster_undefined_bundles; + } + // Clear out defined tunnels, counting the number of // undefs remaining. config->cluster_undefined_tunnels = 0; @@ -735,9 +764,9 @@ static void cluster_check_sessions(int highsession, int freesession_ptr, int hig } - if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels) { - LOG(2, 0, 0, "Cleared undefined sessions/tunnels. %d sess (high %d), %d tunn (high %d)\n", - config->cluster_undefined_sessions, highsession, config->cluster_undefined_tunnels, hightunnel); + if (config->cluster_undefined_sessions || config->cluster_undefined_tunnels || config->cluster_undefined_bundles) { + LOG(2, 0, 0, "Cleared undefined sessions/bundles/tunnels. %d sess (high %d), %d bund (high %d), %d tunn (high %d)\n", + config->cluster_undefined_sessions, highsession, config->cluster_undefined_bundles, highbundle, config->cluster_undefined_tunnels, hightunnel); return; } @@ -770,6 +799,27 @@ static int hb_add_type(uint8_t **p, int type, int id) add_type(p, C_SESSION, id, (uint8_t *) &session[id], sizeof(sessiont)); break; + case C_CBUNDLE: { // Compressed C_BUNDLE + uint8_t c[sizeof(bundlet) * 2]; // Bigger than worst case. + uint8_t *d = (uint8_t *) &bundle[id]; + uint8_t *orig = d; + int size; + + size = rle_compress( &d, sizeof(bundlet), c, sizeof(c) ); + + // Did we compress the full structure, and is the size actually + // reduced?? + if ( (d - orig) == sizeof(bundlet) && size < sizeof(bundlet) ) { + add_type(p, C_CBUNDLE, id, c, size); + break; + } + // Failed to compress : Fall through. + } + + case C_BUNDLE: + add_type(p, C_BUNDLE, id, (uint8_t *) &bundle[id], sizeof(bundlet)); + break; + case C_CTUNNEL: { // Compressed C_TUNNEL uint8_t c[sizeof(tunnelt) * 2]; // Bigger than worst case. uint8_t *d = (uint8_t *) &tunnel[id]; @@ -802,7 +852,7 @@ static int hb_add_type(uint8_t **p, int type, int id) // void cluster_heartbeat() { - int i, count = 0, tcount = 0; + int i, count = 0, tcount = 0, bcount = 0; uint8_t buff[MAX_HEART_SIZE + sizeof(heartt) + sizeof(int) ]; heartt h; uint8_t *p = buff; @@ -823,7 +873,9 @@ void cluster_heartbeat() h.highsession = config->cluster_highest_sessionid; h.freesession = sessionfree; h.hightunnel = config->cluster_highest_tunnelid; + h.highbundle = config->cluster_highest_bundleid; h.size_sess = sizeof(sessiont); // Just in case. + h.size_bund = sizeof(bundlet); h.size_tunn = sizeof(tunnelt); h.interval = config->cluster_hb_interval; h.timeout = config->cluster_hb_timeout; @@ -878,6 +930,21 @@ void cluster_heartbeat() ++tcount; } + // + // Fill out the packet with bundles from the bundle table... + while ( (p + sizeof(uint32_t) * 2 + sizeof(bundlet) ) < (buff + MAX_HEART_SIZE) ) { + + if (!walk_bundle_number) // bundle #0 isn't valid. + ++walk_bundle_number; + + if (bcount >= config->cluster_highest_bundleid) + break; + + hb_add_type(&p, C_CBUNDLE, walk_bundle_number); + walk_bundle_number = (1+walk_bundle_number)%(config->cluster_highest_bundleid+1); // +1 avoids divide by zero. + ++bcount; + } + // // Did we do something wrong? if (p > (buff + sizeof(buff))) { // Did we somehow manage to overun the buffer? @@ -887,9 +954,9 @@ void cluster_heartbeat() } LOG(3, 0, 0, "Sending v%d heartbeat #%d, change #%" PRIu64 " with %d changes " - "(%d x-sess, %d x-tunnels, %d highsess, %d hightun, size %d)\n", + "(%d x-sess, %d x-bundles, %d x-tunnels, %d highsess, %d highbund, %d hightun, size %d)\n", HB_VERSION, h.seq, h.table_version, config->cluster_num_changes, - count, tcount, config->cluster_highest_sessionid, + count, bcount, tcount, config->cluster_highest_sessionid, config->cluster_highest_bundleid, config->cluster_highest_tunnelid, (int) (p - buff)); config->cluster_num_changes = 0; @@ -938,6 +1005,17 @@ int cluster_send_session(int sid) return type_changed(C_CSESSION, sid); } +// A particular bundle has been changed! +int cluster_send_bundle(int bid) +{ + if (!config->cluster_iam_master) { + LOG(0, 0, bid, "I'm not a master, but I just tried to change a bundle!\n"); + return -1; + } + + return type_changed(C_CBUNDLE, bid); +} + // A particular tunnel has been changed! int cluster_send_tunnel(int tid) { @@ -1135,7 +1213,9 @@ static int cluster_handle_bytes(uint8_t *data, int size) session[b->sid].cout_delta += b->cout; if (b->cin) - session[b->sid].last_packet = time_now; // Reset idle timer! + session[b->sid].last_packet = session[b->sid].last_data = time_now; + else if (b->cout) + session[b->sid].last_data = time_now; size -= sizeof(*b); ++b; @@ -1175,6 +1255,31 @@ static int cluster_recv_session(int more, uint8_t *p) return 0; } +static int cluster_recv_bundle(int more, uint8_t *p) +{ + if (more >= MAXBUNDLE) { + LOG(0, 0, 0, "DANGER: Received a bundle id > MAXBUNDLE!\n"); + return -1; + } + + if (bundle[more].state == BUNDLEUNDEF) { + if (config->cluster_iam_uptodate) { // Sanity. + LOG(0, 0, 0, "I thought I was uptodate but I just found an undefined bundle!\n"); + } else { + --config->cluster_undefined_bundles; + } + } + + memcpy(&bundle[more], p, sizeof(bundle[more]) ); + + LOG(5, 0, more, "Received bundle update\n"); + + if (!config->cluster_iam_uptodate) + cluster_uptodate(); // Check to see if we're up to date. + + return 0; +} + static int cluster_recv_tunnel(int more, uint8_t *p) { if (more >= MAXTUNNEL) { @@ -1465,7 +1570,7 @@ static int cluster_process_heartbeat(uint8_t *data, int size, int more, uint8_t // Check that we don't have too many undefined sessions, and // that the free session pointer is correct. - cluster_check_sessions(h->highsession, h->freesession, h->hightunnel); + cluster_check_sessions(h->highsession, h->freesession, h->highbundle, h->hightunnel); if (h->interval != config->cluster_hb_interval) { @@ -1573,6 +1678,34 @@ static int cluster_process_heartbeat(uint8_t *data, int size, int more, uint8_t p += sizeof(tunnel[more]); s -= sizeof(tunnel[more]); break; + + case C_CBUNDLE: { // Compressed bundle structure. + uint8_t c[ sizeof(bundlet) + 2]; + int size; + uint8_t *orig_p = p; + + size = rle_decompress((uint8_t **) &p, s, c, sizeof(c)); + s -= (p - orig_p); + + if (size != sizeof(bundlet) ) { // Ouch! Very very bad! + LOG(0, 0, 0, "DANGER: Received a CBUNDLE that didn't decompress correctly!\n"); + // Now what? Should exit! No-longer up to date! + break; + } + + cluster_recv_bundle(more, c); + break; + + } + case C_BUNDLE: + if ( s < sizeof(bundle[more])) + goto shortpacket; + + cluster_recv_bundle(more, p); + + p += sizeof(bundle[more]); + s -= sizeof(bundle[more]); + break; default: LOG(0, 0, 0, "DANGER: I received a heartbeat element where I didn't understand the type! (%d)\n", type); return -1; // can't process any more of the packet!! @@ -1640,7 +1773,7 @@ int processcluster(uint8_t *data, int size, in_addr_t addr) case C_FORWARD_DAE: // Forwarded DAE packet. pass off to processdae. if (!config->cluster_iam_master) { - LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD_%s from %s?\n", + LOG(0, 0, 0, "I'm not the master, but I got a C_FORWARD%s from %s?\n", type == C_FORWARD_DAE ? "_DAE" : "", fmtaddr(addr, 0)); return -1; @@ -1758,11 +1891,13 @@ int cmd_show_cluster(struct cli_def *cli, char *command, char **argv, int argc) cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version); cli_print(cli, "Next sequence number expected: %d", config->cluster_seq_number); cli_print(cli, "%d sessions undefined of %d", config->cluster_undefined_sessions, config->cluster_highest_sessionid); + cli_print(cli, "%d bundles undefined of %d", config->cluster_undefined_bundles, config->cluster_highest_bundleid); cli_print(cli, "%d tunnels undefined of %d", config->cluster_undefined_tunnels, config->cluster_highest_tunnelid); } else { cli_print(cli, "Table version # : %" PRIu64, config->cluster_table_version); cli_print(cli, "Next heartbeat # : %d", config->cluster_seq_number); cli_print(cli, "Highest session : %d", config->cluster_highest_sessionid); + cli_print(cli, "Highest bundle : %d", config->cluster_highest_bundleid); cli_print(cli, "Highest tunnel : %d", config->cluster_highest_tunnelid); cli_print(cli, "%d changes queued for sending", config->cluster_num_changes); } diff --git a/cluster.h b/cluster.h index fe95218..4f0f6d6 100644 --- a/cluster.h +++ b/cluster.h @@ -1,5 +1,5 @@ // L2TPNS Clustering Stuff -// $Id: cluster.h,v 1.14 2005/07/31 10:04:10 bodea Exp $ +// $Id: cluster.h,v 1.16 2006/12/04 20:54:51 bodea Exp $ #ifndef __CLUSTER_H__ #define __CLUSTER_H__ @@ -21,6 +21,8 @@ #define C_GARDEN 14 // Gardened packet #define C_MASTER 15 // Tell a slave the address of the master. #define C_FORWARD_DAE 16 // A DAE packet for the master to handle +#define C_BUNDLE 17 // Bundle structure. +#define C_CBUNDLE 18 // Compressed bundle structure. #define HB_VERSION 5 // Protocol version number.. #define HB_MAX_SEQ (1<<30) // Maximum sequence number. (MUST BE A POWER OF 2!) @@ -43,16 +45,18 @@ typedef struct { uint32_t highsession; // Id of the highest in-use session. uint32_t freesession; // Id of the first free session. + uint32_t highbundle; // Id of the highest used bundle. uint32_t hightunnel; // Id of the highest used tunnel. uint32_t size_sess; // Size of the session structure. + uint32_t size_bund; // size of the bundle structure. uint32_t size_tunn; // size of the tunnel structure. uint32_t interval; // ping/heartbeat interval uint32_t timeout; // heartbeat timeout uint64_t table_version; // # state changes processed by cluster - char reserved[128 - 13*sizeof(uint32_t)]; // Pad out to 128 bytes. + char reserved[128 - 13*sizeof(uint32_t) - sizeof(uint64_t)]; // Pad out to 128 bytes. } heartt; typedef struct { /* Used to update byte counters on the */ @@ -74,6 +78,7 @@ typedef struct { int cluster_init(void); int processcluster(uint8_t *buf, int size, in_addr_t addr); int cluster_send_session(int sid); +int cluster_send_bundle(int bid); int cluster_send_tunnel(int tid); int master_forward_packet(uint8_t *data, int size, in_addr_t addr, int port); int master_forward_dae_packet(uint8_t *data, int size, in_addr_t addr, int port); diff --git a/constants.c b/constants.c index 4efe717..155f2d1 100644 --- a/constants.c +++ b/constants.c @@ -1,6 +1,6 @@ // L2TPNS: constants -char const *cvs_id_constants = "$Id: constants.c,v 1.7 2005/07/31 10:04:10 bodea Exp $"; +char const *cvs_id_constants = "$Id: constants.c,v 1.8 2009/12/08 14:49:28 bodea Exp $"; #include #include "constants.h" @@ -197,7 +197,8 @@ CONSTANT(radius_state, "RADIUSSTART", // 3 "RADIUSSTOP", // 4 "RADIUSINTERIM", // 5 - "RADIUSWAIT" // 6 + "RADIUSWAIT", // 6 + "RADIUSJUSTAUTH" // 7 ) CONSTANT(radius_code, diff --git a/etc/startup-config.default b/etc/startup-config.default index 0c5051c..77425c8 100644 --- a/etc/startup-config.default +++ b/etc/startup-config.default @@ -41,6 +41,12 @@ set radius_secret "secret" # Allow multiple logins for the same username #set allow_duplicate_users no +# Kill timedout sessions ? (default yes) +#set kill_timedout_sessions no + +# Allow multiple logins for specific username +#set guest_account "" + # Write usage accounting files into specified directory set accounting_dir "/var/run/l2tpns/acct" @@ -59,9 +65,6 @@ set accounting_dir "/var/run/l2tpns/acct" # Number of buckets to allocate for throttling #set throttle_buckets 3000 -# If set to anything other than 0, setuid when initialised. -#set setuid 0 - # If set to true, dump current speed to stderr every second #set dump_speed no @@ -96,6 +99,9 @@ set accounting_dir "/var/run/l2tpns/acct" # Minimum number of slaves before master withdraws routes #set cluster_master_min_adv 1 +# IPv6 address prefix +#set ipv6_prefix :: + # Drop/kill sessions #load plugin "sessionctl" diff --git a/fake_epoll.h b/fake_epoll.h index d89f86a..638757b 100644 --- a/fake_epoll.h +++ b/fake_epoll.h @@ -1,5 +1,5 @@ /* kludge up some limited epoll semantics using select for 2.4 kernels */ -/* $Id: fake_epoll.h,v 1.1 2005/06/04 15:42:35 bodea Exp $ */ +/* $Id: fake_epoll.h,v 1.2 2007/06/28 07:22:50 bodea Exp $ */ #ifndef __FAKE_EPOLL_H__ #define __FAKE_EPOLL_H__ @@ -150,6 +150,9 @@ static int epoll_wait(int epfd __attribute__ ((unused)), tp = 0; n = select(_epoll_fds, &r, &w, 0, tp); + if (n < 0) + return n; + if (n > maxevents) n = maxevents; diff --git a/icmp.c b/icmp.c index f98e401..41f165b 100644 --- a/icmp.c +++ b/icmp.c @@ -1,6 +1,6 @@ // L2TPNS: icmp -char const *cvs_id_icmp = "$Id: icmp.c,v 1.10 2005/08/10 11:25:56 bodea Exp $"; +char const *cvs_id_icmp = "$Id: icmp.c,v 1.11 2006/04/27 09:53:49 bodea Exp $"; #include #include @@ -114,7 +114,7 @@ void send_ipv6_ra(sessionidt s, tunnelidt t, struct in6_addr *ip) LOG(3, s, t, "Sending IPv6 RA\n"); memset(b, 0, sizeof(b)); - o = makeppp(b, sizeof(b), 0, 0, s, t, PPPIPV6); + o = makeppp(b, sizeof(b), 0, 0, s, t, PPPIPV6, 0, 0, 0); if (!o) { diff --git a/l2tpns.c b/l2tpns.c index b4eca2e..8fdcb53 100644 --- a/l2tpns.c +++ b/l2tpns.c @@ -1,10 +1,10 @@ // L2TP Network Server // Adrian Kennard 2002 -// Copyright (c) 2003, 2004, 2005 Optus Internet Engineering +// Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced // vim: sw=8 ts=8 -char const *cvs_id_l2tpns = "$Id: l2tpns.c,v 1.161.2.1 2006/06/22 15:30:50 bodea Exp $"; +char const *cvs_id_l2tpns = "$Id: l2tpns.c,v 1.176 2011/01/20 12:48:40 bodea Exp $"; #include #include @@ -74,6 +74,9 @@ static int tunidx; // ifr_ifindex of tun device static int syslog_log = 0; // are we logging to syslog static FILE *log_stream = 0; // file handle for direct logging (i.e. direct into file, not via syslog). uint32_t last_id = 0; // Unique ID for radius accounting +// Guest change +char guest_users[10][32]; // Array of guest users +int guest_accounts_num = 0; // Number of guest users // calculated from config->l2tp_mtu uint16_t MRU = 0; // PPP MRU @@ -82,9 +85,13 @@ uint16_t MSS = 0; // TCP MSS struct cli_session_actions *cli_session_actions = NULL; // Pending session changes requested by CLI struct cli_tunnel_actions *cli_tunnel_actions = NULL; // Pending tunnel changes required by CLI -static void *ip_hash[256]; // Mapping from IP address to session structures. +union iphash { + sessionidt sess; + union iphash *idx; +} ip_hash[256]; // Mapping from IP address to session structures. + struct ipv6radix { - int sess; + sessionidt sess; struct ipv6radix *branch; } ipv6_hash[256]; // Mapping from IPv6 address to session structures. @@ -126,14 +133,17 @@ config_descriptt config_values[] = { CONFIG("radius_secret", radiussecret, STRING), CONFIG("radius_authtypes", radius_authtypes_s, STRING), CONFIG("radius_dae_port", radius_dae_port, SHORT), + CONFIG("radius_bind_min", radius_bind_min, SHORT), + CONFIG("radius_bind_max", radius_bind_max, SHORT), CONFIG("allow_duplicate_users", allow_duplicate_users, BOOL), + CONFIG("kill_timedout_sessions", kill_timedout_sessions, BOOL), + CONFIG("guest_account", guest_user, STRING), CONFIG("bind_address", bind_address, IPv4), CONFIG("peer_address", peer_address, IPv4), CONFIG("send_garp", send_garp, BOOL), CONFIG("throttle_speed", rl_rate, UNSIGNED_LONG), CONFIG("throttle_buckets", num_tbfs, INT), CONFIG("accounting_dir", accounting_dir, STRING), - CONFIG("setuid", target_uid, INT), CONFIG("dump_speed", dump_speed, BOOL), CONFIG("multi_read_count", multi_read_count, INT), CONFIG("scheduler_fifo", scheduler_fifo, BOOL), @@ -174,6 +184,8 @@ static sessiont shut_acct[8192]; static sessionidt shut_acct_n = 0; tunnelt *tunnel = NULL; // Array of tunnel structures. +bundlet *bundle = NULL; // Array of bundle structures. +fragmentationt *frag = NULL; // Array of fragmentation structures. sessiont *session = NULL; // Array of session structures. sessionlocalt *sess_local = NULL; // Array of local per-session counters. radiust *radius = NULL; // Array of radius structures. @@ -185,9 +197,9 @@ struct Tstats *_statistics = NULL; struct Tringbuffer *ringbuffer = NULL; #endif -static void cache_ipmap(in_addr_t ip, int s); +static void cache_ipmap(in_addr_t ip, sessionidt s); static void uncache_ipmap(in_addr_t ip); -static void cache_ipv6map(struct in6_addr ip, int prefixlen, int s); +static void cache_ipv6map(struct in6_addr ip, int prefixlen, sessionidt s); static void free_ip_address(sessionidt s); static void dump_acct_info(int all); static void sighup_handler(int sig); @@ -203,6 +215,7 @@ static void plugins_done(void); static void processcontrol(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local); static tunnelidt new_tunnel(void); static void unhide_value(uint8_t *value, size_t len, uint16_t type, uint8_t *vector, size_t vec_len); +static void bundleclear(bundleidt b); // on slaves, alow BGP to withdraw cleanly before exiting #define QUIT_DELAY 5 @@ -622,7 +635,7 @@ static void initudp(void) int flags = fcntl(udpfd, F_GETFL, 0); fcntl(udpfd, F_SETFL, flags | O_NONBLOCK); } - if (bind(udpfd, (void *) &addr, sizeof(addr)) < 0) + if (bind(udpfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno)); exit(1); @@ -635,7 +648,7 @@ static void initudp(void) controlfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); setsockopt(controlfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); setsockopt(controlfd, SOL_IP, IP_PKTINFO, &on, sizeof(on)); // recvfromto - if (bind(controlfd, (void *) &addr, sizeof(addr)) < 0) + if (bind(controlfd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno)); exit(1); @@ -648,7 +661,7 @@ static void initudp(void) daefd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); setsockopt(daefd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)); setsockopt(daefd, SOL_IP, IP_PKTINFO, &on, sizeof(on)); // recvfromto - if (bind(daefd, (void *) &addr, sizeof(addr)) < 0) + if (bind(daefd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno)); exit(1); @@ -673,19 +686,19 @@ static void initudp(void) // IP address. // -static int lookup_ipmap(in_addr_t ip) +static sessionidt lookup_ipmap(in_addr_t ip) { uint8_t *a = (uint8_t *) &ip; - uint8_t **d = (uint8_t **) ip_hash; + union iphash *h = ip_hash; - if (!(d = (uint8_t **) d[(size_t) *a++])) return 0; - if (!(d = (uint8_t **) d[(size_t) *a++])) return 0; - if (!(d = (uint8_t **) d[(size_t) *a++])) return 0; + if (!(h = h[*a++].idx)) return 0; + if (!(h = h[*a++].idx)) return 0; + if (!(h = h[*a++].idx)) return 0; - return (int) (intptr_t) d[(size_t) *a]; + return h[*a].sess; } -static int lookup_ipv6map(struct in6_addr ip) +static sessionidt lookup_ipv6map(struct in6_addr ip) { struct ipv6radix *curnode; int i; @@ -713,18 +726,18 @@ static int lookup_ipv6map(struct in6_addr ip) sessionidt sessionbyip(in_addr_t ip) { - int s = lookup_ipmap(ip); + sessionidt s = lookup_ipmap(ip); CSTAT(sessionbyip); if (s > 0 && s < MAXSESSION && session[s].opened) - return (sessionidt) s; + return s; return 0; } sessionidt sessionbyipv6(struct in6_addr ip) { - int s; + sessionidt s; CSTAT(sessionbyipv6); if (!memcmp(&config->ipv6_prefix, &ip, 8) || @@ -750,25 +763,22 @@ sessionidt sessionbyipv6(struct in6_addr ip) // // (It's actually cached in network order) // -static void cache_ipmap(in_addr_t ip, int s) +static void cache_ipmap(in_addr_t ip, sessionidt s) { in_addr_t nip = htonl(ip); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0] uint8_t *a = (uint8_t *) &nip; - uint8_t **d = (uint8_t **) ip_hash; + union iphash *h = ip_hash; int i; for (i = 0; i < 3; i++) { - if (!d[(size_t) a[i]]) - { - if (!(d[(size_t) a[i]] = calloc(256, sizeof(void *)))) - return; - } + if (!(h[a[i]].idx || (h[a[i]].idx = calloc(256, sizeof(union iphash))))) + return; - d = (uint8_t **) d[(size_t) a[i]]; + h = h[a[i]].idx; } - d[(size_t) a[3]] = (uint8_t *) (intptr_t) s; + h[a[3]].sess = s; if (s > 0) LOG(4, s, session[s].tunnel, "Caching ip address %s\n", fmtaddr(nip, 0)); @@ -783,7 +793,7 @@ static void uncache_ipmap(in_addr_t ip) cache_ipmap(ip, 0); // Assign it to the NULL session. } -static void cache_ipv6map(struct in6_addr ip, int prefixlen, int s) +static void cache_ipv6map(struct in6_addr ip, int prefixlen, sessionidt s) { int i; int bytes; @@ -824,7 +834,7 @@ static void cache_ipv6map(struct in6_addr ip, int prefixlen, int s) // int cmd_show_ipcache(struct cli_def *cli, char *command, char **argv, int argc) { - char **d = (char **) ip_hash, **e, **f, **g; + union iphash *d = ip_hash, *e, *f, *g; int i, j, k, l; int count = 0; @@ -835,24 +845,28 @@ int cmd_show_ipcache(struct cli_def *cli, char *command, char **argv, int argc) for (i = 0; i < 256; ++i) { - if (!d[i]) + if (!d[i].idx) continue; - e = (char **) d[i]; + + e = d[i].idx; for (j = 0; j < 256; ++j) { - if (!e[j]) + if (!e[j].idx) continue; - f = (char **) e[j]; + + f = e[j].idx; for (k = 0; k < 256; ++k) { - if (!f[k]) + if (!f[k].idx) continue; - g = (char **)f[k]; + + g = f[k].idx; for (l = 0; l < 256; ++l) { - if (!g[l]) + if (!g[l].sess) continue; - cli_print(cli, "%7d %d.%d.%d.%d", (int) (intptr_t) g[l], i, j, k, l); + + cli_print(cli, "%7d %d.%d.%d.%d", g[l].sess, i, j, k, l); ++count; } } @@ -1051,6 +1065,74 @@ void adjust_tcp_mss(sessionidt s, tunnelidt t, uint8_t *buf, int len, uint8_t *t *(uint16_t *) (tcp + 16) = htons(sum + (sum >> 16)); } +void processmpframe(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint8_t extra) +{ + uint16_t proto; + if (extra) { + // Skip the four extra bytes + p += 4; + l -= 4; + } + + if (*p & 1) + { + proto = *p++; + l--; + } + else + { + proto = ntohs(*(uint16_t *) p); + p += 2; + l -= 2; + } + if (proto == PPPIP) + { + if (session[s].die) + { + LOG(4, s, t, "MPPP: Session %d is closing. Don't process PPP packets\n", s); + return; // closing session, PPP not processed + } + session[s].last_packet = session[s].last_data = time_now; + processipin(s, t, p, l); + } + else if (proto == PPPIPV6 && config->ipv6_prefix.s6_addr[0]) + { + if (session[s].die) + { + LOG(4, s, t, "MPPP: Session %d is closing. Don't process PPP packets\n", s); + return; // closing session, PPP not processed + } + + session[s].last_packet = session[s].last_data = time_now; + processipv6in(s, t, p, l); + } + else if (proto == PPPIPCP) + { + session[s].last_packet = session[s].last_data = time_now; + processipcp(s, t, p, l); + } + else if (proto == PPPCCP) + { + session[s].last_packet = session[s].last_data = time_now; + processccp(s, t, p, l); + } + else + { + LOG(2, s, t, "MPPP: Unsupported MP protocol 0x%04X received\n",proto); + } +} + +static void update_session_out_stat(sessionidt s, sessiont *sp, int len) +{ + increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count + sp->cout_delta += len; + sp->pout++; + sp->last_data = time_now; + + sess_local[s].cout += len; // To send to master.. + sess_local[s].pout++; +} + // process outgoing (to tunnel) IP // static void processipout(uint8_t *buf, int len) @@ -1063,7 +1145,7 @@ static void processipout(uint8_t *buf, int len) uint8_t *data = buf; // Keep a copy of the originals. int size = len; - uint8_t b[MAXETHER + 20]; + uint8_t fragbuf[MAXETHER + 20]; CSTAT(processipout); @@ -1112,7 +1194,14 @@ static void processipout(uint8_t *buf, int len) } return; } + t = session[s].tunnel; + if (len > session[s].mru || (session[s].mrru && len > session[s].mrru)) + { + LOG(3, s, t, "Packet size more than session MRU\n"); + return; + } + sp = &session[s]; // DoS prevention: enforce a maximum number of packets per 0.1s for a session @@ -1183,26 +1272,81 @@ static void processipout(uint8_t *buf, int len) return; } - LOG(5, s, t, "Ethernet -> Tunnel (%d bytes)\n", len); - // Add on L2TP header - { - uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIP); - if (!p) return; - tunnelsend(b, len + (p-b), t); // send it... - } + { + bundleidt bid = 0; + if(session[s].bundle != 0 && bundle[session[s].bundle].num_of_links > 1) + { + bid = session[s].bundle; + s = bundle[bid].members[bundle[bid].current_ses = ++bundle[bid].current_ses % bundle[bid].num_of_links]; + t = session[s].tunnel; + sp = &session[s]; + LOG(4, s, t, "MPPP: (1)Session number becomes: %d\n", s); + if(len > MINFRAGLEN) + { + // Partition the packet to "bundle[b].num_of_links" fragments + bundlet *b = &bundle[bid]; + uint32_t num_of_links = b->num_of_links; + uint32_t fraglen = len / num_of_links; + fraglen = (fraglen > session[s].mru ? session[s].mru : fraglen); + uint32_t last_fraglen = fraglen + len % num_of_links; + last_fraglen = (last_fraglen > session[s].mru ? len % num_of_links : last_fraglen); + uint32_t remain = len; + + // send the first packet + uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, fraglen, s, t, PPPIP, 0, bid, MP_BEGIN); + if (!p) return; + tunnelsend(fragbuf, fraglen + (p-fragbuf), t); // send it... + // statistics + update_session_out_stat(s, sp, fraglen); + remain -= fraglen; + while (remain > last_fraglen) + { + s = b->members[b->current_ses = ++b->current_ses % num_of_links]; + t = session[s].tunnel; + sp = &session[s]; + LOG(4, s, t, "MPPP: (2)Session number becomes: %d\n", s); + p = makeppp(fragbuf, sizeof(fragbuf), buf+(len - remain), fraglen, s, t, PPPIP, 0, bid, 0); + if (!p) return; + tunnelsend(fragbuf, fraglen + (p-fragbuf), t); // send it... + update_session_out_stat(s, sp, fraglen); + remain -= fraglen; + } + // send the last fragment + s = b->members[b->current_ses = ++b->current_ses % num_of_links]; + t = session[s].tunnel; + sp = &session[s]; + LOG(4, s, t, "MPPP: (2)Session number becomes: %d\n", s); + p = makeppp(fragbuf, sizeof(fragbuf), buf+(len - remain), remain, s, t, PPPIP, 0, bid, MP_END); + if (!p) return; + tunnelsend(fragbuf, remain + (p-fragbuf), t); // send it... + update_session_out_stat(s, sp, remain); + if (remain != last_fraglen) + LOG(3, s, t, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain, last_fraglen); + } + else { + // Send it as one frame + uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, len, s, t, PPPIP, 0, bid, MP_BOTH_BITS); + if (!p) return; + tunnelsend(fragbuf, len + (p-fragbuf), t); // send it... + LOG(4, s, t, "MPPP: packet sent as one frame\n"); + update_session_out_stat(s, sp, len); + } + } + else + { + uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, len, s, t, PPPIP, 0, 0, 0); + if (!p) return; + tunnelsend(fragbuf, len + (p-fragbuf), t); // send it... + update_session_out_stat(s, sp, len); + } + } // Snooping this session, send it to intercept box if (sp->snoop_ip && sp->snoop_port) snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port); - increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count - sp->cout_delta += len; - sp->pout++; udp_tx += len; - - sess_local[s].cout += len; // To send to master.. - sess_local[s].pout++; } // process outgoing (to tunnel) IPv6 @@ -1273,8 +1417,15 @@ static void processipv6out(uint8_t * buf, int len) } return; } + if (session[s].bundle && bundle[session[s].bundle].num_of_links > 1) + { + bundleidt bid = session[s].bundle; + s = bundle[bid].members[bundle[bid].current_ses = ++bundle[bid].current_ses % bundle[bid].num_of_links]; + LOG(3, s, session[s].tunnel, "MPPP: Session number becomes: %u\n", s); + } t = session[s].tunnel; sp = &session[s]; + sp->last_data = time_now; // FIXME: add DoS prevention/filters? @@ -1298,7 +1449,7 @@ static void processipv6out(uint8_t * buf, int len) // Add on L2TP header { - uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIPV6); + uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIPV6, 0, 0, 0); if (!p) return; tunnelsend(b, len + (p-b), t); // send it... } @@ -1350,7 +1501,7 @@ static void send_ipout(sessionidt s, uint8_t *buf, int len) // Add on L2TP header { - uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIP); + uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIP, 0, 0, 0); if (!p) return; tunnelsend(b, len + (p-b), t); // send it... } @@ -1562,7 +1713,9 @@ void filter_session(sessionidt s, int filter_in, int filter_out) void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_error, int term_cause) { int walled_garden = session[s].walled_garden; - + bundleidt b = session[s].bundle; + //delete routes only for last session in bundle (in case of MPPP) + int del_routes = !b || (bundle[b].num_of_links == 1); CSTAT(sessionshutdown); @@ -1575,8 +1728,9 @@ void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_e if (!session[s].die) { struct param_kill_session data = { &tunnel[session[s].tunnel], &session[s] }; - LOG(2, s, session[s].tunnel, "Shutting down session %d: %s\n", s, reason); + LOG(2, s, session[s].tunnel, "Shutting down session %u: %s\n", s, reason); run_plugins(PLUGIN_KILL_SESSION, &data); + session[s].die = TIME + 150; // Clean up in 15 seconds } if (session[s].ip && !walled_garden && !session[s].die) @@ -1611,21 +1765,52 @@ void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_e (session[s].route[r].ip & session[s].route[r].mask)) routed++; - routeset(s, session[s].route[r].ip, session[s].route[r].mask, 0, 0); + if (del_routes) routeset(s, session[s].route[r].ip, session[s].route[r].mask, 0, 0); session[s].route[r].ip = 0; } if (session[s].ip_pool_index == -1) // static ip { - if (!routed) routeset(s, session[s].ip, 0, 0, 0); + if (!routed && del_routes) routeset(s, session[s].ip, 0, 0, 0); session[s].ip = 0; } else free_ip_address(s); // unroute IPv6, if setup - if (session[s].ppp.ipv6cp == Opened && session[s].ipv6prefixlen) + if (session[s].ppp.ipv6cp == Opened && session[s].ipv6prefixlen && del_routes) route6set(s, session[s].ipv6route, session[s].ipv6prefixlen, 0); + + if (b) + { + // This session was part of a bundle + bundle[b].num_of_links--; + LOG(3, s, 0, "MPPP: Dropping member link: %d from bundle %d\n",s,b); + if(bundle[b].num_of_links == 0) + { + bundleclear(b); + LOG(3, s, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b); + } + else + { + // Adjust the members array to accomodate the new change + uint8_t mem_num = 0; + // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--") + if(bundle[b].members[bundle[b].num_of_links] != s) + { + uint8_t ml; + for(ml = 0; mlcluster_highest_sessionid ; ++s) @@ -1871,7 +2060,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) } if ((buf[1] & 0x0F) != 2) { - LOG(1, 0, 0, "Bad L2TP ver %d\n", (buf[1] & 0x0F) != 2); + LOG(1, 0, 0, "Bad L2TP ver %d\n", buf[1] & 0x0F); STAT(tunnel_rx_errors); return; } @@ -1968,7 +2157,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) } } - LOG(3, s, t, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n", + LOG(3, s, t, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n", l, tunnel[t].controlc, tunnel[t].ns, tunnel[t].nr, ns, nr); // if no tunnel specified, assign one @@ -1985,7 +2174,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) tunnel[t].port = ntohs(addr->sin_port); tunnel[t].window = 4; // default window STAT(tunnel_created); - LOG(1, 0, t, " New tunnel from %s:%u ID %d\n", + LOG(1, 0, t, " New tunnel from %s:%u ID %u\n", fmtaddr(htonl(tunnel[t].ip), 0), tunnel[t].port, t); } @@ -1999,7 +2188,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) { // is this the sequence we were expecting? STAT(tunnel_rx_errors); - LOG(1, 0, t, " Out of sequence tunnel %d, (%d is not the expected %d)\n", + LOG(1, 0, t, " Out of sequence tunnel %u, (%u is not the expected %u)\n", t, ns, tunnel[t].nr); if (l) // Is this not a ZLB? @@ -2087,7 +2276,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) b += 2; if (*(uint16_t *) (b)) { - LOG(2, s, t, "Unknown AVP vendor %d\n", ntohs(*(uint16_t *) (b))); + LOG(2, s, t, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b))); fatal = flags; result = 2; // general error error = 6; // generic vendor-specific error @@ -2152,7 +2341,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) n = orig_len; } - LOG(4, s, t, " AVP %d (%s) len %d%s%s\n", mtype, l2tp_avp_name(mtype), n, + LOG(4, s, t, " AVP %u (%s) len %d%s%s\n", mtype, l2tp_avp_name(mtype), n, flags & 0x40 ? ", hidden" : "", flags & 0x80 ? ", mandatory" : ""); switch (mtype) @@ -2160,7 +2349,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) case 0: // message type message = ntohs(*(uint16_t *) b); mandatory = flags & 0x80; - LOG(4, s, t, " Message type = %d (%s)\n", *b, l2tp_code(message)); + LOG(4, s, t, " Message type = %u (%s)\n", *b, l2tp_code(message)); break; case 1: // result code { @@ -2183,12 +2372,12 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) cause = TERM_ADMIN_RESET; } - LOG(4, s, t, " Result Code %d: %s\n", rescode, resdesc); + LOG(4, s, t, " Result Code %u: %s\n", rescode, resdesc); if (n >= 4) { uint16_t errcode = ntohs(*(uint16_t *)(b + 2)); errdesc = l2tp_error_code(errcode); - LOG(4, s, t, " Error Code %d: %s\n", errcode, errdesc); + LOG(4, s, t, " Error Code %u: %s\n", errcode, errdesc); } if (n > 4) LOG(4, s, t, " Error String: %.*s\n", n-4, b+4); @@ -2206,7 +2395,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) case 2: // protocol version { version = ntohs(*(uint16_t *) (b)); - LOG(4, s, t, " Protocol version = %d\n", version); + LOG(4, s, t, " Protocol version = %u\n", version); if (version && version != 0x0100) { // allow 0.0 and 1.0 LOG(1, s, t, " Bad protocol version %04X\n", version); @@ -2240,13 +2429,13 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) break; case 9: // assigned tunnel tunnel[t].far = ntohs(*(uint16_t *) (b)); - LOG(4, s, t, " Remote tunnel id = %d\n", tunnel[t].far); + LOG(4, s, t, " Remote tunnel id = %u\n", tunnel[t].far); break; case 10: // rx window tunnel[t].window = ntohs(*(uint16_t *) (b)); if (!tunnel[t].window) tunnel[t].window = 1; // window of 0 is silly - LOG(4, s, t, " rx window = %d\n", tunnel[t].window); + LOG(4, s, t, " rx window = %u\n", tunnel[t].window); break; case 11: // Challenge { @@ -2261,17 +2450,17 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) case 14: // assigned session asession = session[s].far = ntohs(*(uint16_t *) (b)); - LOG(4, s, t, " assigned session = %d\n", asession); + LOG(4, s, t, " assigned session = %u\n", asession); break; case 15: // call serial number - LOG(4, s, t, " call serial number = %d\n", ntohl(*(uint32_t *)b)); + LOG(4, s, t, " call serial number = %u\n", ntohl(*(uint32_t *)b)); break; case 18: // bearer type - LOG(4, s, t, " bearer type = %d\n", ntohl(*(uint32_t *)b)); + LOG(4, s, t, " bearer type = %u\n", ntohl(*(uint32_t *)b)); // TBA - for RADIUS break; case 19: // framing type - LOG(4, s, t, " framing type = %d\n", ntohl(*(uint32_t *)b)); + LOG(4, s, t, " framing type = %u\n", ntohl(*(uint32_t *)b)); // TBA break; case 21: // called number @@ -2325,7 +2514,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) case 29: // Proxy Authentication Type { uint16_t atype = ntohs(*(uint16_t *)b); - LOG(4, s, t, " Proxy Auth Type %d (%s)\n", atype, ppp_auth_type(atype)); + LOG(4, s, t, " Proxy Auth Type %u (%s)\n", atype, ppp_auth_type(atype)); break; } case 30: // Proxy Authentication Name @@ -2345,7 +2534,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) case 32: // Proxy Authentication ID { uint16_t authid = ntohs(*(uint16_t *)(b)); - LOG(4, s, t, " Proxy Auth ID (%d)\n", authid); + LOG(4, s, t, " Proxy Auth ID (%u)\n", authid); break; } case 33: // Proxy Authentication Response @@ -2463,7 +2652,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) default: { static char e[] = "unknown AVP 0xXXXX"; - LOG(2, s, t, " Unknown AVP type %d\n", mtype); + LOG(2, s, t, " Unknown AVP type %u\n", mtype); fatal = flags; result = 2; // general error error = 8; // unknown mandatory AVP @@ -2497,9 +2686,11 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) break; case 2: // SCCRP tunnel[t].state = TUNNELOPEN; + tunnel[t].lastrec = time_now; break; case 3: // SCCN tunnel[t].state = TUNNELOPEN; + tunnel[t].lastrec = time_now; controlnull(t); // ack break; case 4: // StopCCN @@ -2533,8 +2724,8 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) session[s].opened = time_now; session[s].tunnel = t; session[s].far = asession; - session[s].last_packet = time_now; - LOG(3, s, t, "New session (%d/%d)\n", tunnel[t].far, session[s].far); + session[s].last_packet = session[s].last_data = time_now; + LOG(3, s, t, "New session (%u/%u)\n", tunnel[t].far, session[s].far); control16(c, 14, s, 1); // assigned session controladd(c, asession, t); // send the reply @@ -2575,6 +2766,11 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) // start LCP sess_local[s].lcp_authtype = config->radius_authprefer; sess_local[s].ppp_mru = MRU; + + // Set multilink options before sending initial LCP packet + sess_local[s].mp_mrru = 1614; + sess_local[s].mp_epdis = config->bind_address ? config->bind_address : my_address; + sendlcp(s, t); change_state(s, lcp, RequestSent); break; @@ -2591,7 +2787,7 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) if (mandatory) tunnelshutdown(t, "Unknown message type", 2, 6, "unknown message type"); else - LOG(1, s, t, "Unknown message type %d\n", message); + LOG(1, s, t, "Unknown message type %u\n", message); break; } if (chapresponse) free(chapresponse); @@ -2685,11 +2881,11 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) { if (session[s].die) { - LOG(4, s, t, "Session %d is closing. Don't process PPP packets\n", s); + LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s); return; // closing session, PPP not processed } - session[s].last_packet = time_now; + session[s].last_packet = session[s].last_data = time_now; if (session[s].walled_garden && !config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); @@ -2698,15 +2894,32 @@ void processudp(uint8_t *buf, int len, struct sockaddr_in *addr) processipin(s, t, p, l); } + else if (proto == PPPMP) + { + if (session[s].die) + { + LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s); + return; // closing session, PPP not processed + } + + session[s].last_packet = session[s].last_data = time_now; + if (session[s].walled_garden && !config->cluster_iam_master) + { + master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); + return; + } + + processmpin(s, t, p, l); + } else if (proto == PPPIPV6 && config->ipv6_prefix.s6_addr[0]) { if (session[s].die) { - LOG(4, s, t, "Session %d is closing. Don't process PPP packets\n", s); + LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s); return; // closing session, PPP not processed } - session[s].last_packet = time_now; + session[s].last_packet = session[s].last_data = time_now; if (session[s].walled_garden && !config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); @@ -2820,7 +3033,7 @@ static void regular_cleanups(double period) if (tunnel[t].retry <= TIME) { controlt *c = tunnel[t].controls; - uint8_t w = tunnel[t].window; + uint16_t w = tunnel[t].window; tunnel[t].try++; // another try if (tunnel[t].try > 5) tunnelkill(t, "Timeout on control message"); // game over @@ -3018,7 +3231,7 @@ static void regular_cleanups(double period) { uint8_t b[MAXETHER]; - uint8_t *q = makeppp(b, sizeof(b), 0, 0, s, session[s].tunnel, PPPLCP); + uint8_t *q = makeppp(b, sizeof(b), 0, 0, s, session[s].tunnel, PPPLCP, 1, 0, 0); if (!q) continue; *q = EchoReq; @@ -3033,6 +3246,45 @@ static void regular_cleanups(double period) s_actions++; } + // Drop sessions who have reached session_timeout seconds + if (session[s].session_timeout) + { + bundleidt bid = session[s].bundle; + if (bid) + { + if (time_now - bundle[bid].last_check >= 1) + { + bundle[bid].online_time += (time_now - bundle[bid].last_check) * bundle[bid].num_of_links; + bundle[bid].last_check = time_now; + if (bundle[bid].online_time >= session[s].session_timeout) + { + int ses; + for (ses = bundle[bid].num_of_links - 1; ses >= 0; ses--) + { + sessionshutdown(bundle[bid].members[ses], "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT); + s_actions++; + continue; + } + } + } + } + else if (time_now - session[s].opened >= session[s].session_timeout) + { + sessionshutdown(s, "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT); + s_actions++; + continue; + } + } + + // Drop sessions who have reached idle_timeout seconds + if (session[s].last_data && session[s].idle_timeout && (time_now - session[s].last_data >= session[s].idle_timeout)) + { + sessionshutdown(s, "Idle Timeout Reached", CDN_ADMIN_DISC, TERM_IDLE_TIMEOUT); + STAT(session_timeout); + s_actions++; + continue; + } + // Check for actions requested from the CLI if ((a = cli_session_actions[s].action)) { @@ -3057,7 +3309,7 @@ static void regular_cleanups(double period) } else if (a & CLI_SESS_SNOOP) { - LOG(2, s, session[s].tunnel, "Snooping session by CLI (to %s:%d)\n", + LOG(2, s, session[s].tunnel, "Snooping session by CLI (to %s:%u)\n", fmtaddr(cli_session_actions[s].snoop_ip, 0), cli_session_actions[s].snoop_port); @@ -3111,7 +3363,8 @@ static void regular_cleanups(double period) if (config->radius_accounting && config->radius_interim > 0 && session[s].ip && !session[s].walled_garden && !sess_local[s].radius // RADIUS already in progress - && time_now - sess_local[s].last_interim >= config->radius_interim) + && time_now - sess_local[s].last_interim >= config->radius_interim + && session[s].flags & SESSION_STARTED) { int rad = radiusnew(s); if (!rad) @@ -3200,7 +3453,7 @@ static int still_busy(void) if (last_talked != TIME) { - LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i); + LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i); last_talked = TIME; } return 1; @@ -3222,7 +3475,7 @@ static int still_busy(void) if (last_talked != TIME) { - LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i, radius[i].session); + LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i, radius[i].session); last_talked = TIME; } return 1; @@ -3274,9 +3527,12 @@ static void mainloop(void) e.events = EPOLLIN; i = 0; - d[i].type = FD_TYPE_CLI; - e.data.ptr = &d[i++]; - epoll_ctl(epollfd, EPOLL_CTL_ADD, clifd, &e); + if (clifd >= 0) + { + d[i].type = FD_TYPE_CLI; + e.data.ptr = &d[i++]; + epoll_ctl(epollfd, EPOLL_CTL_ADD, clifd, &e); + } d[i].type = FD_TYPE_CLUSTER; e.data.ptr = &d[i++]; @@ -3707,6 +3963,7 @@ static void initdata(int optdebug, char *optconfig) config->ppp_restart_time = 3; config->ppp_max_configure = 10; config->ppp_max_failure = 5; + config->kill_timedout_sessions = 1; strcpy(config->random_device, RANDOMDEVICE); log_stream = stderr; @@ -3730,6 +3987,16 @@ static void initdata(int optdebug, char *optconfig) LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno)); exit(1); } + if (!(bundle = shared_malloc(sizeof(bundlet) * MAXBUNDLE))) + { + LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno)); + exit(1); + } + if (!(frag = shared_malloc(sizeof(fragmentationt) * MAXBUNDLE))) + { + LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno)); + exit(1); + } if (!(session = shared_malloc(sizeof(sessiont) * MAXSESSION))) { LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno)); @@ -3776,6 +4043,7 @@ static void initdata(int optdebug, char *optconfig) memset(cli_tunnel_actions, 0, sizeof(struct cli_tunnel_actions) * MAXSESSION); memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL); + memset(bundle, 0, sizeof(bundlet) * MAXBUNDLE); memset(session, 0, sizeof(sessiont) * MAXSESSION); memset(radius, 0, sizeof(radiust) * MAXRADIUS); memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL); @@ -3793,6 +4061,10 @@ static void initdata(int optdebug, char *optconfig) for (i = 1; i < MAXTUNNEL; i++) tunnel[i].state = TUNNELUNDEF; // mark it as not filled in. + for (i = 1; i < MAXBUNDLE; i++) { + bundle[i].state = BUNDLEUNDEF; + } + if (!*hostname) { // Grab my hostname unless it's been specified @@ -3927,7 +4199,7 @@ void rebuild_address_pool(void) if (ipid < 1) // Not found in the pool either? good. continue; - LOG(0, i, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n", + LOG(0, i, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n", i, fmtaddr(session[i].ip, 0), ipid); // Fall through and process it as part of the pool. @@ -3936,7 +4208,7 @@ void rebuild_address_pool(void) if (ipid > MAXIPPOOL || ipid < 0) { - LOG(0, i, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i, ipid); + LOG(0, i, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i, ipid); ipid = -1; session[i].ip_pool_index = ipid; continue; @@ -4084,7 +4356,7 @@ void snoop_send_packet(uint8_t *packet, uint16_t size, in_addr_t destination, ui snoop_addr.sin_addr.s_addr = destination; snoop_addr.sin_port = ntohs(port); - LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size, + LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size, fmtaddr(snoop_addr.sin_addr.s_addr, 0), htons(snoop_addr.sin_port)); @@ -4219,7 +4491,7 @@ int main(int argc, char *argv[]) init_tbf(config->num_tbfs); LOG(0, 0, 0, "L2TPNS version " VERSION "\n"); - LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005 Optus Internet Engineering\n"); + LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n"); LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n"); { struct rlimit rlim; @@ -4291,10 +4563,6 @@ int main(int argc, char *argv[]) LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno)); } - // Drop privileges here - if (config->target_uid > 0 && geteuid() == 0) - setuid(config->target_uid); - mainloop(); /* remove plugins (so cleanup code gets run) */ @@ -4522,6 +4790,40 @@ static void update_config() } } + // Guest change + guest_accounts_num = 0; + char *p2 = config->guest_user; + while (p2 && *p2) + { + char *s = strpbrk(p2, " \t,"); + if (s) + { + *s++ = 0; + while (*s == ' ' || *s == '\t') + s++; + + if (!*s) + s = 0; + } + + strcpy(guest_users[guest_accounts_num], p2); + LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num, guest_users[guest_accounts_num]); + guest_accounts_num++; + p2 = s; + } + // Rebuild the guest_user array + strcpy(config->guest_user, ""); + int ui = 0; + for (ui=0; uiguest_user, guest_users[ui]); + if (uiguest_user, ","); + } + } + + memcpy(config->old_plugins, config->plugins, sizeof(config->plugins)); if (!config->multi_read_count) config->multi_read_count = 10; if (!config->cluster_address) config->cluster_address = inet_addr(DEFAULT_MCAST_ADDR); @@ -4600,6 +4902,20 @@ int sessionsetup(sessionidt s, tunnelidt t) LOG(3, s, t, "Doing session setup for session\n"); + // Join a bundle if the MRRU option is accepted + if(session[s].mrru > 0 && session[s].bundle == 0) + { + LOG(3, s, t, "This session can be part of multilink bundle\n"); + if (join_bundle(s) > 0) + cluster_send_bundle(session[s].bundle); + else + { + LOG(0, s, t, "MPPP: Mismaching mssf option with other sessions in bundle\n"); + sessionshutdown(s, "Mismaching mssf option.", CDN_NONE, TERM_SERVICE_UNAVAILABLE); + return 0; + } + } + if (!session[s].ip) { assign_ip_address(s); @@ -4627,6 +4943,9 @@ int sessionsetup(sessionidt s, tunnelidt t) { if (i == s) continue; if (!session[s].opened) continue; + // Allow duplicate sessions for multilink ones of the same bundle. + if (session[s].bundle && session[i].bundle && session[s].bundle == session[i].bundle) + continue; if (ip == session[i].ip) { sessionkill(i, "Duplicate IP address"); @@ -4635,11 +4954,27 @@ int sessionsetup(sessionidt s, tunnelidt t) if (config->allow_duplicate_users) continue; if (session[s].walled_garden || session[i].walled_garden) continue; + // Guest change + int found = 0; + int gu; + for (gu = 0; gu < guest_accounts_num; gu++) + { + if (!strcasecmp(user, guest_users[gu])) + { + found = 1; + break; + } + } + if (found) continue; + + // Drop the new session in case of duplicate sessionss, not the old one. if (!strcasecmp(user, session[i].user)) sessionkill(i, "Duplicate session for users"); } } + // no need to set a route for the same IP address of the bundle + if (!session[s].bundle || (bundle[session[s].bundle].num_of_links == 1)) { int routed = 0; @@ -4679,7 +5014,7 @@ int sessionsetup(sessionidt s, tunnelidt t) if (session[s].throttle_in || session[s].throttle_out) throttle_session(s, session[s].throttle_in, session[s].throttle_out); - session[s].last_packet = time_now; + session[s].last_packet = session[s].last_data = time_now; LOG(2, s, t, "Login by %s at %s from %s (%s)\n", session[s].user, fmtaddr(htonl(session[s].ip), 0), @@ -4782,13 +5117,13 @@ int load_session(sessionidt s, sessiont *new) // check filters if (new->filter_in && (new->filter_in > MAXFILTER || !ip_filters[new->filter_in - 1].name[0])) { - LOG(2, s, session[s].tunnel, "Dropping invalid input filter %d\n", (int) new->filter_in); + LOG(2, s, session[s].tunnel, "Dropping invalid input filter %u\n", (int) new->filter_in); new->filter_in = 0; } if (new->filter_out && (new->filter_out > MAXFILTER || !ip_filters[new->filter_out - 1].name[0])) { - LOG(2, s, session[s].tunnel, "Dropping invalid output filter %d\n", (int) new->filter_out); + LOG(2, s, session[s].tunnel, "Dropping invalid output filter %u\n", (int) new->filter_out); new->filter_out = 0; } @@ -5172,7 +5507,7 @@ static tunnelidt new_tunnel() { if (tunnel[i].state == TUNNELFREE) { - LOG(4, 0, i, "Assigning tunnel ID %d\n", i); + LOG(4, 0, i, "Assigning tunnel ID %u\n", i); if (i > config->cluster_highest_tunnelid) config->cluster_highest_tunnelid = i; return i; @@ -5242,7 +5577,7 @@ int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc if (!session[s].opened) continue; - idle = time_now - session[s].last_packet; + idle = time_now - session[s].last_data; idle /= 5 ; // In multiples of 5 seconds. if (idle < 0) idle = 0; diff --git a/l2tpns.h b/l2tpns.h index 6c38bbf..6849be9 100644 --- a/l2tpns.h +++ b/l2tpns.h @@ -1,5 +1,5 @@ // L2TPNS Global Stuff -// $Id: l2tpns.h,v 1.113.2.3 2006/12/02 14:09:14 bodea Exp $ +// $Id: l2tpns.h,v 1.121 2009/12/08 14:49:28 bodea Exp $ #ifndef __L2TPNS_H__ #define __L2TPNS_H__ @@ -14,10 +14,13 @@ #include #include -#define VERSION "2.1.21" +#define VERSION "2.2.0" // Limits #define MAXTUNNEL 500 // could be up to 65535 +#define MAXBUNDLE 300 // could be up to 65535 +#define MAXBUNDLESES 12 // Maximum number of member links in bundle +#define MAXADDRESS 20 // Maximum length for the Endpoint Discrminiator address #define MAXSESSION 60000 // could be up to 65535 #define MAXTBFS 6000 // Maximum token bucket filters. Might need up to 2 * session. @@ -43,10 +46,20 @@ #define MAXIPPOOL 131072 // max number of ip addresses in pool #define RINGBUFFER_SIZE 10000 // Number of ringbuffer entries to allocate #define MAX_LOG_LENGTH 512 // Maximum size of log message -#define ECHO_TIMEOUT 60 // Time between last packet sent and LCP ECHO generation -#define IDLE_TIMEOUT 240 // Time between last packet sent and LCP ECHO generation +#define ECHO_TIMEOUT 10 // Time between last packet sent and LCP ECHO generation +#define IDLE_TIMEOUT 240 // Time between last packet seen and session shutdown #define BUSY_WAIT_TIME 3000 // 5 minutes in 1/10th seconds to wait for radius to cleanup on shutdown +#define MP_BEGIN 0x80 // This value is used when (b)egin bit is set in MP header +#define MP_END 0x40 // This value is used when (e)nd bit is set in MP header +#define MP_BOTH_BITS 0xC0 // This value is used when both bits (begin and end) are set in MP header + +#define MINFRAGLEN 64 // Minumum fragment length +#define MAXFRAGLEN 750 // Maximum length for Multilink fragment (MTU / 2 sessions) +#define MAXFRAGNUM 128 // Maximum number of Multilink fragment in a bundle (must be in the form of 2^X) + // it's not expected to have a space for more than 10 unassembled packets = 10 * MAXBUNDLESES +#define MAXFRAGNUM_MASK 127 // Must be equal to MAXFRAGNUM-1 + // Constants #ifndef ETCDIR #define ETCDIR "/etc/l2tpns" @@ -186,6 +199,7 @@ enum { // Types typedef uint16_t sessionidt; +typedef uint16_t bundleidt; typedef uint16_t tunnelidt; typedef uint32_t clockt; typedef uint8_t hasht[16]; @@ -231,6 +245,20 @@ typedef struct controls // control message } controlt; +typedef struct { + uint8_t length; // Endpoint Discriminator length + uint8_t addr_class; // Endpoint Discriminator class + uint8_t address[MAXADDRESS]; // Endpoint Discriminator address +} epdist; + +typedef struct { + sessionidt sid; // Fragment originating session + uint8_t flags; // MP frame flags + uint32_t seq; // fragment seq num + uint16_t length; // Fragment length + uint8_t data[MAXFRAGLEN]; // Fragment data +} fragmentt; + typedef struct { sessionidt next; // next session in linked list @@ -261,7 +289,10 @@ typedef struct uint16_t mru; // maximum receive unit clockt opened; // when started clockt die; // being closed, when to finally free + uint32_t session_timeout; // Maximum session time in seconds + uint32_t idle_timeout; // Maximum idle time in seconds time_t last_packet; // Last packet from the user (used for idle timeouts) + time_t last_data; // Last data packet to/from the user (used for idle timeouts) in_addr_t dns1, dns2; // DNS servers routet route[MAXROUTE]; // static routes uint16_t tbf_in; // filter bucket for throttling in from the user. @@ -273,6 +304,11 @@ typedef struct char calling[MAXTEL]; // calling number uint32_t tx_connect_speed; uint32_t rx_connect_speed; + clockt timeout; // Session timeout + uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit + uint8_t mssf; // Multilink Short Sequence Number Header Format + epdist epdis; // Multilink Endpoint Discriminator + bundleidt bundle; // Multilink Bundle Identifier in_addr_t snoop_ip; // Interception destination IP uint16_t snoop_port; // Interception destination port uint8_t walled_garden; // is this session gardened? @@ -282,6 +318,36 @@ typedef struct } sessiont; +typedef struct +{ + int state; // current state (bundlestate enum) + uint32_t seq_num_t; // Sequence Number (transmission) + uint32_t timeout; // Session-Timeout for bundle + uint32_t max_seq; // Max value of sequence number field + uint8_t num_of_links; // Number of links joint to this bundle + uint32_t online_time; // The time this bundle is online + clockt last_check; // Last time the timeout is checked + uint32_t mrru; // Multilink Max-Receive-Reconstructed-Unit + uint8_t mssf; // Multilink Short Sequence Number Header Format + epdist epdis; // Multilink Endpoint Discriminator + char user[MAXUSER]; // Needed for matching member links + sessionidt current_ses; // Current session to use for sending (used in RR load-balancing) + sessionidt members[MAXBUNDLESES]; // Array for member links sessions +} +bundlet; + +typedef struct +{ + fragmentt fragment[MAXFRAGNUM]; + uint8_t reassembled_frame[MAXETHER]; // The reassembled frame + uint16_t re_frame_len; // The reassembled frame length + uint16_t re_frame_begin_index, re_frame_end_index; // reassembled frame begin index, end index respectively + uint16_t start_index, end_index; // start and end sequence numbers available on the fragments array respectively + uint32_t M; // Minumum frame sequence number received over all bundle members + uint32_t start_seq; // Last received frame sequence number (bearing B bit) +} +fragmentationt; + #define AUTHPAP 1 // allow PAP #define AUTHCHAP 2 // allow CHAP @@ -311,6 +377,15 @@ typedef struct // our MRU uint16_t ppp_mru; + // our MRRU + uint16_t mp_mrru; + + // our mssf + uint16_t mp_mssf; + + // our Endpoint Discriminator + in_addr_t mp_epdis; + // DoS prevention clockt last_packet_out; uint32_t packets_out; @@ -324,6 +399,9 @@ typedef struct // last LCP Echo time_t last_echo; + + // Last Multilink frame sequence number received + uint32_t last_seq; } sessionlocalt; // session flags @@ -407,6 +485,23 @@ enum TUNNELUNDEF, // Undefined }; +enum +{ + BUNDLEFREE, // Not in use + BUNDLEOPEN, // Active bundle + BUNDLEUNDEF, // Undefined +}; + +enum +{ + NULLCLASS = 0, //End Point Discriminator classes + LOCALADDR, + IPADDR, + IEEEMACADDR, + PPPMAGIC, + PSNDN, +}; + enum { RADIUSNULL, // Not in use @@ -416,6 +511,7 @@ enum RADIUSSTOP, // sending stop accounting to RADIUS server RADIUSINTERIM, // sending interim accounting to RADIUS server RADIUSWAIT, // waiting timeout before available, in case delayed replies + RADIUSJUSTAUTH, // sending auth to RADIUS server, just authentication, no ip assigning }; struct Tstats @@ -554,13 +650,16 @@ typedef struct uint16_t radiusport[MAXRADSERVER]; // radius base ports uint8_t numradiusservers; // radius server count - uint16_t radius_dae_port; // local port for radius dae + uint16_t radius_dae_port; // port for radius DAE + uint16_t radius_bind_min; // port range for udp sockets used to send/recv radius packets + uint16_t radius_bind_max; char radius_authtypes_s[32]; // list of valid authentication types (chap, pap) in order of preference int radius_authtypes; int radius_authprefer; int allow_duplicate_users; // allow multiple logins with the same username + int kill_timedout_sessions; // kill authenticated sessions with "session_timeout == 0" in_addr_t default_dns1, default_dns2; @@ -572,7 +671,6 @@ typedef struct in_addr_t peer_address; int send_garp; // Set to true to garp for vip address on startup - int target_uid; int dump_speed; char plugins[64][MAXPLUGINS]; char old_plugins[64][MAXPLUGINS]; @@ -583,6 +681,7 @@ typedef struct int lock_pages; // Lock pages into memory. int icmp_rate; // Max number of ICMP unreachable per second to send int max_packets; // DoS prevention: per session limit of packets/0.1s + char epdis_addr[20]; // MP Endpoint Discriminator address in_addr_t cluster_address; // Multicast address of cluster. // Send to this address to have everyone hear. @@ -594,8 +693,10 @@ typedef struct int cluster_seq_number; // Sequence number of the next heartbeat we'll send out // (or the seq number we're next expecting if we're a slave). int cluster_undefined_sessions; // How many sessions we're yet to receive from the master. + int cluster_undefined_bundles; // How many bundles we're yet to receive from the master. int cluster_undefined_tunnels; // How many tunnels we're yet to receive from the master. int cluster_highest_sessionid; + int cluster_highest_bundleid; int cluster_highest_tunnelid; clockt cluster_last_hb; // Last time we saw a heartbeat from the master. int cluster_last_hb_ver; // Heartbeat version last seen from master @@ -611,6 +712,8 @@ typedef struct int cluster_master_min_adv; // Master advertises routes while the number of up to date // slaves is less than this value. + // Guest change + char guest_user[MAXUSER]; // Guest account username #ifdef BGP #define BGP_NUM_PEERS 2 @@ -727,14 +830,17 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); void processipcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); +void processmpin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); +void processmpframe(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint8_t extra); void processipv6in(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); void processccp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l); void sendchap(sessionidt s, tunnelidt t); -uint8_t *makeppp(uint8_t *b, int size, uint8_t *p, int l, sessionidt s, tunnelidt t, uint16_t mtype); +uint8_t *makeppp(uint8_t *b, int size, uint8_t *p, int l, sessionidt s, tunnelidt t, uint16_t mtype, uint8_t prio, bundleidt bid, uint8_t mp_bits); void sendlcp(sessionidt s, tunnelidt t); void send_ipin(sessionidt s, uint8_t *buf, int len); void sendccp(sessionidt s, tunnelidt t); void protoreject(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint16_t proto); +int join_bundle(sessionidt s); // radius.c @@ -802,6 +908,7 @@ void host_unreachable(in_addr_t destination, uint16_t id, in_addr_t source, uint extern tunnelt *tunnel; +extern bundlet *bundle; extern sessiont *session; extern sessionlocalt *sess_local; extern ippoolt *ip_address_pool; diff --git a/l2tpns.spec b/l2tpns.spec index 4cd9ca8..021a848 100644 --- a/l2tpns.spec +++ b/l2tpns.spec @@ -1,6 +1,6 @@ Summary: A high-speed clustered L2TP LNS Name: l2tpns -Version: 2.1.21 +Version: 2.2.0 Release: 1 License: GPL Group: System Environment/Daemons @@ -43,5 +43,5 @@ rm -rf %{buildroot} %attr(644,root,root) /usr/share/man/man[58]/* %changelog -* Fri Dec 1 2006 Brendan O'Dea 2.1.21-1 -- 2.1.21 release, see /usr/share/doc/l2tpns-2.1.21/Changes +* Mon Dec 18 2006 Brendan O'Dea 2.2.0-1 +- 2.2.0 release, see /usr/share/doc/l2tpns-2.2.0/Changes diff --git a/md5.c b/md5.c index 9abecfb..184a876 100644 --- a/md5.c +++ b/md5.c @@ -15,10 +15,7 @@ * and avoid compile-time configuration. */ -#ifndef HAVE_OPENSSL - #include - #include "md5.h" /* @@ -27,18 +24,18 @@ * F is optimized compared to its RFC 1321 definition just like in Colin * Plumb's implementation. */ -#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) -#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) -#define H(x, y, z) ((x) ^ (y) ^ (z)) -#define I(x, y, z) ((y) ^ ((x) | ~(z))) +#define F(x, y, z) ((z) ^ ((x) & ((y) ^ (z)))) +#define G(x, y, z) ((y) ^ ((z) & ((x) ^ (y)))) +#define H(x, y, z) ((x) ^ (y) ^ (z)) +#define I(x, y, z) ((y) ^ ((x) | ~(z))) /* * The MD5 transformation for all four rounds. */ #define STEP(f, a, b, c, d, x, t, s) \ - (a) += f((b), (c), (d)) + (x) + (t); \ - (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ - (a) += (b); + (a) += f((b), (c), (d)) + (x) + (t); \ + (a) = (((a) << (s)) | (((a) & 0xffffffff) >> (32 - (s)))); \ + (a) += (b); /* * SET reads 4 input bytes in little-endian byte order and stores them @@ -49,19 +46,17 @@ * doesn't work. */ #if defined(__i386__) || defined(__vax__) -#define SET(n) \ - (*(MD5_u32plus *)&ptr[(n) * 4]) -#define GET(n) \ - SET(n) +# define SET(n) (*(MD5_u32plus *)&ptr[(n) * 4]) +# define GET(n) SET(n) #else -#define SET(n) \ - (ctx->block[(n)] = \ - (MD5_u32plus)ptr[(n) * 4] | \ - ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ - ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ - ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) -#define GET(n) \ - (ctx->block[(n)]) +# define SET(n) \ + (ctx->block[(n)] = \ + (MD5_u32plus)ptr[(n) * 4] | \ + ((MD5_u32plus)ptr[(n) * 4 + 1] << 8) | \ + ((MD5_u32plus)ptr[(n) * 4 + 2] << 16) | \ + ((MD5_u32plus)ptr[(n) * 4 + 3] << 24)) +# define GET(n) \ + (ctx->block[(n)]) #endif /* @@ -70,205 +65,208 @@ */ static void *body(MD5_CTX *ctx, void *data, unsigned long size) { - unsigned char *ptr; - MD5_u32plus a, b, c, d; - MD5_u32plus saved_a, saved_b, saved_c, saved_d; - - ptr = data; - - a = ctx->a; - b = ctx->b; - c = ctx->c; - d = ctx->d; - - do { - saved_a = a; - saved_b = b; - saved_c = c; - saved_d = d; - -/* Round 1 */ - STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) - STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) - STEP(F, c, d, a, b, SET(2), 0x242070db, 17) - STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) - STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) - STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) - STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) - STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) - STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) - STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) - STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) - STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) - STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) - STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) - STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) - STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) - -/* Round 2 */ - STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) - STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) - STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) - STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) - STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) - STEP(G, d, a, b, c, GET(10), 0x02441453, 9) - STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) - STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) - STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) - STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) - STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) - STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) - STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) - STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) - STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) - STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) - -/* Round 3 */ - STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) - STEP(H, d, a, b, c, GET(8), 0x8771f681, 11) - STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) - STEP(H, b, c, d, a, GET(14), 0xfde5380c, 23) - STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) - STEP(H, d, a, b, c, GET(4), 0x4bdecfa9, 11) - STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) - STEP(H, b, c, d, a, GET(10), 0xbebfbc70, 23) - STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) - STEP(H, d, a, b, c, GET(0), 0xeaa127fa, 11) - STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) - STEP(H, b, c, d, a, GET(6), 0x04881d05, 23) - STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) - STEP(H, d, a, b, c, GET(12), 0xe6db99e5, 11) - STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) - STEP(H, b, c, d, a, GET(2), 0xc4ac5665, 23) - -/* Round 4 */ - STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) - STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) - STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) - STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) - STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) - STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) - STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) - STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) - STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) - STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) - STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) - STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) - STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) - STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) - STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) - STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) - - a += saved_a; - b += saved_b; - c += saved_c; - d += saved_d; - - ptr += 64; - } while (size -= 64); - - ctx->a = a; - ctx->b = b; - ctx->c = c; - ctx->d = d; - - return ptr; + unsigned char *ptr; + MD5_u32plus a, b, c, d; + MD5_u32plus saved_a, saved_b, saved_c, saved_d; + + ptr = data; + + a = ctx->a; + b = ctx->b; + c = ctx->c; + d = ctx->d; + + do { + saved_a = a; + saved_b = b; + saved_c = c; + saved_d = d; + + /* Round 1 */ + STEP(F, a, b, c, d, SET(0), 0xd76aa478, 7) + STEP(F, d, a, b, c, SET(1), 0xe8c7b756, 12) + STEP(F, c, d, a, b, SET(2), 0x242070db, 17) + STEP(F, b, c, d, a, SET(3), 0xc1bdceee, 22) + STEP(F, a, b, c, d, SET(4), 0xf57c0faf, 7) + STEP(F, d, a, b, c, SET(5), 0x4787c62a, 12) + STEP(F, c, d, a, b, SET(6), 0xa8304613, 17) + STEP(F, b, c, d, a, SET(7), 0xfd469501, 22) + STEP(F, a, b, c, d, SET(8), 0x698098d8, 7) + STEP(F, d, a, b, c, SET(9), 0x8b44f7af, 12) + STEP(F, c, d, a, b, SET(10), 0xffff5bb1, 17) + STEP(F, b, c, d, a, SET(11), 0x895cd7be, 22) + STEP(F, a, b, c, d, SET(12), 0x6b901122, 7) + STEP(F, d, a, b, c, SET(13), 0xfd987193, 12) + STEP(F, c, d, a, b, SET(14), 0xa679438e, 17) + STEP(F, b, c, d, a, SET(15), 0x49b40821, 22) + + /* Round 2 */ + STEP(G, a, b, c, d, GET(1), 0xf61e2562, 5) + STEP(G, d, a, b, c, GET(6), 0xc040b340, 9) + STEP(G, c, d, a, b, GET(11), 0x265e5a51, 14) + STEP(G, b, c, d, a, GET(0), 0xe9b6c7aa, 20) + STEP(G, a, b, c, d, GET(5), 0xd62f105d, 5) + STEP(G, d, a, b, c, GET(10), 0x02441453, 9) + STEP(G, c, d, a, b, GET(15), 0xd8a1e681, 14) + STEP(G, b, c, d, a, GET(4), 0xe7d3fbc8, 20) + STEP(G, a, b, c, d, GET(9), 0x21e1cde6, 5) + STEP(G, d, a, b, c, GET(14), 0xc33707d6, 9) + STEP(G, c, d, a, b, GET(3), 0xf4d50d87, 14) + STEP(G, b, c, d, a, GET(8), 0x455a14ed, 20) + STEP(G, a, b, c, d, GET(13), 0xa9e3e905, 5) + STEP(G, d, a, b, c, GET(2), 0xfcefa3f8, 9) + STEP(G, c, d, a, b, GET(7), 0x676f02d9, 14) + STEP(G, b, c, d, a, GET(12), 0x8d2a4c8a, 20) + + /* Round 3 */ + STEP(H, a, b, c, d, GET(5), 0xfffa3942, 4) + STEP(H, d, a, b, c, GET(8), 0x8771f681, 11) + STEP(H, c, d, a, b, GET(11), 0x6d9d6122, 16) + STEP(H, b, c, d, a, GET(14), 0xfde5380c, 23) + STEP(H, a, b, c, d, GET(1), 0xa4beea44, 4) + STEP(H, d, a, b, c, GET(4), 0x4bdecfa9, 11) + STEP(H, c, d, a, b, GET(7), 0xf6bb4b60, 16) + STEP(H, b, c, d, a, GET(10), 0xbebfbc70, 23) + STEP(H, a, b, c, d, GET(13), 0x289b7ec6, 4) + STEP(H, d, a, b, c, GET(0), 0xeaa127fa, 11) + STEP(H, c, d, a, b, GET(3), 0xd4ef3085, 16) + STEP(H, b, c, d, a, GET(6), 0x04881d05, 23) + STEP(H, a, b, c, d, GET(9), 0xd9d4d039, 4) + STEP(H, d, a, b, c, GET(12), 0xe6db99e5, 11) + STEP(H, c, d, a, b, GET(15), 0x1fa27cf8, 16) + STEP(H, b, c, d, a, GET(2), 0xc4ac5665, 23) + + /* Round 4 */ + STEP(I, a, b, c, d, GET(0), 0xf4292244, 6) + STEP(I, d, a, b, c, GET(7), 0x432aff97, 10) + STEP(I, c, d, a, b, GET(14), 0xab9423a7, 15) + STEP(I, b, c, d, a, GET(5), 0xfc93a039, 21) + STEP(I, a, b, c, d, GET(12), 0x655b59c3, 6) + STEP(I, d, a, b, c, GET(3), 0x8f0ccc92, 10) + STEP(I, c, d, a, b, GET(10), 0xffeff47d, 15) + STEP(I, b, c, d, a, GET(1), 0x85845dd1, 21) + STEP(I, a, b, c, d, GET(8), 0x6fa87e4f, 6) + STEP(I, d, a, b, c, GET(15), 0xfe2ce6e0, 10) + STEP(I, c, d, a, b, GET(6), 0xa3014314, 15) + STEP(I, b, c, d, a, GET(13), 0x4e0811a1, 21) + STEP(I, a, b, c, d, GET(4), 0xf7537e82, 6) + STEP(I, d, a, b, c, GET(11), 0xbd3af235, 10) + STEP(I, c, d, a, b, GET(2), 0x2ad7d2bb, 15) + STEP(I, b, c, d, a, GET(9), 0xeb86d391, 21) + + a += saved_a; + b += saved_b; + c += saved_c; + d += saved_d; + + ptr += MD5_BLOCK_SZ; + } while (size -= MD5_BLOCK_SZ); + + ctx->a = a; + ctx->b = b; + ctx->c = c; + ctx->d = d; + + return ptr; } void MD5_Init(MD5_CTX *ctx) { - ctx->a = 0x67452301; - ctx->b = 0xefcdab89; - ctx->c = 0x98badcfe; - ctx->d = 0x10325476; + ctx->a = 0x67452301; + ctx->b = 0xefcdab89; + ctx->c = 0x98badcfe; + ctx->d = 0x10325476; - ctx->lo = 0; - ctx->hi = 0; + ctx->lo = 0; + ctx->hi = 0; } void MD5_Update(MD5_CTX *ctx, void *data, unsigned long size) { - MD5_u32plus saved_lo; - unsigned long used, free; + MD5_u32plus saved_lo; + unsigned long used, free; - saved_lo = ctx->lo; - if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) - ctx->hi++; - ctx->hi += size >> 29; + saved_lo = ctx->lo; + if ((ctx->lo = (saved_lo + size) & 0x1fffffff) < saved_lo) + ctx->hi++; - used = saved_lo & 0x3f; + ctx->hi += size >> 29; - if (used) { - free = 64 - used; + used = saved_lo & 0x3f; - if (size < free) { - memcpy(&ctx->buffer[used], data, size); - return; - } + if (used) + { + free = MD5_BLOCK_SZ - used; - memcpy(&ctx->buffer[used], data, free); - data = (unsigned char *)data + free; - size -= free; - body(ctx, ctx->buffer, 64); + if (size < free) + { + memcpy(&ctx->buffer[used], data, size); + return; } - if (size >= 64) { - data = body(ctx, data, size & ~(unsigned long)0x3f); - size &= 0x3f; - } + memcpy(&ctx->buffer[used], data, free); + data = (unsigned char *)data + free; + size -= free; + body(ctx, ctx->buffer, MD5_BLOCK_SZ); + } - memcpy(ctx->buffer, data, size); + if (size >= MD5_BLOCK_SZ) + { + data = body(ctx, data, size & ~(unsigned long)0x3f); + size &= 0x3f; + } + + memcpy(ctx->buffer, data, size); } void MD5_Final(unsigned char *result, MD5_CTX *ctx) { - unsigned long used, free; - - used = ctx->lo & 0x3f; - - ctx->buffer[used++] = 0x80; - - free = 64 - used; - - if (free < 8) { - memset(&ctx->buffer[used], 0, free); - body(ctx, ctx->buffer, 64); - used = 0; - free = 64; - } - - memset(&ctx->buffer[used], 0, free - 8); - - ctx->lo <<= 3; - ctx->buffer[56] = ctx->lo; - ctx->buffer[57] = ctx->lo >> 8; - ctx->buffer[58] = ctx->lo >> 16; - ctx->buffer[59] = ctx->lo >> 24; - ctx->buffer[60] = ctx->hi; - ctx->buffer[61] = ctx->hi >> 8; - ctx->buffer[62] = ctx->hi >> 16; - ctx->buffer[63] = ctx->hi >> 24; - - body(ctx, ctx->buffer, 64); - - result[0] = ctx->a; - result[1] = ctx->a >> 8; - result[2] = ctx->a >> 16; - result[3] = ctx->a >> 24; - result[4] = ctx->b; - result[5] = ctx->b >> 8; - result[6] = ctx->b >> 16; - result[7] = ctx->b >> 24; - result[8] = ctx->c; - result[9] = ctx->c >> 8; - result[10] = ctx->c >> 16; - result[11] = ctx->c >> 24; - result[12] = ctx->d; - result[13] = ctx->d >> 8; - result[14] = ctx->d >> 16; - result[15] = ctx->d >> 24; - - memset(ctx, 0, sizeof(*ctx)); + unsigned long used, free; + + used = ctx->lo & 0x3f; + + ctx->buffer[used++] = 0x80; + + free = MD5_BLOCK_SZ - used; + + if (free < 8) + { + memset(&ctx->buffer[used], 0, free); + body(ctx, ctx->buffer, MD5_BLOCK_SZ); + used = 0; + free = MD5_BLOCK_SZ; + } + + memset(&ctx->buffer[used], 0, free - 8); + + ctx->lo <<= 3; + ctx->buffer[56] = ctx->lo; + ctx->buffer[57] = ctx->lo >> 8; + ctx->buffer[58] = ctx->lo >> 16; + ctx->buffer[59] = ctx->lo >> 24; + ctx->buffer[60] = ctx->hi; + ctx->buffer[61] = ctx->hi >> 8; + ctx->buffer[62] = ctx->hi >> 16; + ctx->buffer[63] = ctx->hi >> 24; + + body(ctx, ctx->buffer, MD5_BLOCK_SZ); + + result[0] = ctx->a; + result[1] = ctx->a >> 8; + result[2] = ctx->a >> 16; + result[3] = ctx->a >> 24; + result[4] = ctx->b; + result[5] = ctx->b >> 8; + result[6] = ctx->b >> 16; + result[7] = ctx->b >> 24; + result[8] = ctx->c; + result[9] = ctx->c >> 8; + result[10] = ctx->c >> 16; + result[11] = ctx->c >> 24; + result[12] = ctx->d; + result[13] = ctx->d >> 8; + result[14] = ctx->d >> 16; + result[15] = ctx->d >> 24; + + memset(ctx, 0, sizeof(*ctx)); } - -#endif diff --git a/md5.h b/md5.h index 1ff5045..25a59e0 100644 --- a/md5.h +++ b/md5.h @@ -6,23 +6,24 @@ * in the public domain. See md5.c for more information. */ -#ifdef HAVE_OPENSSL -#include -#elif !defined(_MD5_H) -#define _MD5_H +#ifndef __MD5_H__ +#define __MD5_H__ + +#define MD5_DIGEST_SZ 16 +#define MD5_BLOCK_SZ 64 /* Any 32-bit or wider unsigned integer data type will do */ typedef unsigned long MD5_u32plus; typedef struct { - MD5_u32plus lo, hi; - MD5_u32plus a, b, c, d; - unsigned char buffer[64]; - MD5_u32plus block[16]; + MD5_u32plus lo, hi; + MD5_u32plus a, b, c, d; + unsigned char buffer[MD5_BLOCK_SZ]; + MD5_u32plus block[MD5_DIGEST_SZ]; } MD5_CTX; extern void MD5_Init(MD5_CTX *ctx); extern void MD5_Update(MD5_CTX *ctx, void *data, unsigned long size); extern void MD5_Final(unsigned char *result, MD5_CTX *ctx); -#endif +#endif /* __MD5_H__ */ diff --git a/plugin.h b/plugin.h index 9a4b67e..d6cac99 100644 --- a/plugin.h +++ b/plugin.h @@ -8,8 +8,6 @@ enum { PLUGIN_PRE_AUTH = 1, PLUGIN_POST_AUTH, - PLUGIN_PACKET_RX, - PLUGIN_PACKET_TX, PLUGIN_TIMER, PLUGIN_NEW_SESSION, PLUGIN_KILL_SESSION, @@ -62,25 +60,21 @@ struct param_post_auth int protocol; }; -struct param_packet_rx +struct param_timer { - tunnelt *t; - sessiont *s; - char *buf; - int len; + time_t time_now; }; -struct param_packet_tx +struct param_new_session { tunnelt *t; sessiont *s; - char *buf; - int len; }; -struct param_timer +struct param_kill_session { - time_t time_now; + tunnelt *t; + sessiont *s; }; struct param_control @@ -93,18 +87,6 @@ struct param_control char *additional; }; -struct param_new_session -{ - tunnelt *t; - sessiont *s; -}; - -struct param_kill_session -{ - tunnelt *t; - sessiont *s; -}; - struct param_radius_response { tunnelt *t; diff --git a/ppp.c b/ppp.c index d903496..7942e6e 100644 --- a/ppp.c +++ b/ppp.c @@ -1,6 +1,6 @@ // L2TPNS PPP Stuff -char const *cvs_id_ppp = "$Id: ppp.c,v 1.99.2.1 2006/05/26 07:33:52 bodea Exp $"; +char const *cvs_id_ppp = "$Id: ppp.c,v 1.104 2009/12/08 14:49:28 bodea Exp $"; #include #include @@ -15,6 +15,8 @@ char const *cvs_id_ppp = "$Id: ppp.c,v 1.99.2.1 2006/05/26 07:33:52 bodea Exp $" #include "cluster.h" extern tunnelt *tunnel; +extern bundlet *bundle; +extern fragmentationt *frag; extern sessiont *session; extern radiust *radius; extern int tunfd; @@ -24,6 +26,20 @@ extern time_t time_now; extern configt *config; static int add_lcp_auth(uint8_t *b, int size, int authtype); +static bundleidt new_bundle(void); +static int epdiscmp(epdist, epdist); +static void setepdis(epdist *, epdist); +static void ipcp_open(sessionidt s, tunnelidt t); + +static int first_session_in_bundle(sessionidt s) +{ + bundleidt i; + for (i = 1; i < MAXBUNDLE; i++) + if (bundle[i].state != BUNDLEFREE) + if (epdiscmp(session[s].epdis,bundle[i].epdis) && !strcmp(session[s].user, bundle[i].user)) + return 0; + return 1; +} // Process PAP messages void processpap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) @@ -90,7 +106,7 @@ void processpap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) // respond now, either no RADIUS available or already authenticated uint8_t b[MAXETHER]; uint8_t id = p[1]; - uint8_t *p = makeppp(b, sizeof(b), 0, 0, s, t, PPPPAP); + uint8_t *p = makeppp(b, sizeof(b), 0, 0, s, t, PPPPAP, 0, 0, 0); if (!p) return; if (session[s].ip) @@ -134,7 +150,10 @@ void processpap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) radius[r].id = p[1]; LOG(3, s, t, "Sending login for %s/%s to RADIUS\n", user, pass); - radiussend(r, RADIUSAUTH); + if ((session[s].mrru) && (!first_session_in_bundle(s))) + radiussend(r, RADIUSJUSTAUTH); + else + radiussend(r, RADIUSAUTH); } } @@ -251,7 +270,10 @@ void processchap(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) radius[r].chap = 1; LOG(3, s, t, "CHAP login %s\n", session[s].user); - radiussend(r, RADIUSAUTH); + if ((session[s].mrru) && (!first_session_in_bundle(s))) + radiussend(r, RADIUSJUSTAUTH); + else + radiussend(r, RADIUSAUTH); } static void dumplcp(uint8_t *p, int l) @@ -360,16 +382,25 @@ void lcp_open(sessionidt s, tunnelidt t) } else { - // This-Layer-Up - sendipcp(s, t); - change_state(s, ipcp, RequestSent); - // move to passive state for IPv6 (if configured), CCP - if (config->ipv6_prefix.s6_addr[0]) - change_state(s, ipv6cp, Stopped); - else - change_state(s, ipv6cp, Closed); + if(session[s].bundle == 0 || bundle[session[s].bundle].num_of_links == 1) + { + // This-Layer-Up + sendipcp(s, t); + change_state(s, ipcp, RequestSent); + // move to passive state for IPv6 (if configured), CCP + if (config->ipv6_prefix.s6_addr[0]) + change_state(s, ipv6cp, Stopped); + else + change_state(s, ipv6cp, Closed); - change_state(s, ccp, Stopped); + change_state(s, ccp, Stopped); + } + else + { + sessionidt first_ses = bundle[session[s].bundle].members[0]; + LOG(3, s, t, "MPPP: Skipping IPCP negotiation for session:%d, first session of bundle is:%d\n",s,first_ses); + ipcp_open(s, t); + } } } @@ -387,7 +418,7 @@ static uint8_t *ppp_conf_rej(sessionidt s, uint8_t *buf, size_t blen, uint16_t m { if (!*response || **response != ConfigRej) { - queued = *response = makeppp(buf, blen, packet, 2, s, session[s].tunnel, mtype); + queued = *response = makeppp(buf, blen, packet, 2, s, session[s].tunnel, mtype, 0, 0, 0); if (!queued) return 0; @@ -431,7 +462,7 @@ static uint8_t *ppp_conf_nak(sessionidt s, uint8_t *buf, size_t blen, uint16_t m if (*nak_sent >= config->ppp_max_failure) return ppp_conf_rej(s, buf, blen, mtype, response, 0, packet, option); - queued = *response = makeppp(buf, blen, packet, 2, s, session[s].tunnel, mtype); + queued = *response = makeppp(buf, blen, packet, 2, s, session[s].tunnel, mtype, 0, 0, 0); if (!queued) return 0; @@ -463,7 +494,7 @@ static void ppp_code_rej(sessionidt s, tunnelidt t, uint16_t proto, l += 4; if (l > mru) l = mru; - q = makeppp(buf, size, 0, 0, s, t, proto); + q = makeppp(buf, size, 0, 0, s, t, proto, 0, 0, 0); if (!q) return; *q = CodeRej; @@ -575,6 +606,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) uint8_t *response = 0; static uint8_t asyncmap[4] = { 0, 0, 0, 0 }; // all zero static uint8_t authproto[5]; + int changed = 0; while (x > 2) { @@ -590,7 +622,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) if (mru >= MINMTU) { session[s].mru = mru; - cluster_send_session(s); + changed++; break; } @@ -663,6 +695,64 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) case 8: // Address-And-Control-Field-Compression break; + case 17: // Multilink Max-Receive-Reconstructed-Unit + { + uint16_t mrru = ntohs(*(uint16_t *)(o + 2)); + session[s].mrru = mrru; + changed++; + LOG(3, s, t, " Received PPP LCP option MRRU: %d\n",mrru); + } + break; + + case 18: // Multilink Short Sequence Number Header Format + { + session[s].mssf = 1; + changed++; + LOG(3, s, t, " Received PPP LCP option MSSN format\n"); + } + break; + + case 19: // Multilink Endpoint Discriminator + { + uint8_t epdis_class = o[2]; + int addr; + + session[s].epdis.addr_class = epdis_class; + session[s].epdis.length = length - 3; + if (session[s].epdis.length > 20) + { + LOG(1, s, t, "Error: received EndDis Address Length more than 20: %d\n", session[s].epdis.length); + session[s].epdis.length = 20; + } + + for (addr = 0; addr < session[s].epdis.length; addr++) + session[s].epdis.address[addr] = o[3+addr]; + + changed++; + + switch (epdis_class) + { + case LOCALADDR: + LOG(3, s, t, " Received PPP LCP option Multilink EndDis Local Address Class: %d\n",epdis_class); + break; + case IPADDR: + LOG(3, s, t, " Received PPP LCP option Multilink EndDis IP Address Class: %d\n",epdis_class); + break; + case IEEEMACADDR: + LOG(3, s, t, " Received PPP LCP option Multilink EndDis IEEE MAC Address Class: %d\n",epdis_class); + break; + case PPPMAGIC: + LOG(3, s, t, " Received PPP LCP option Multilink EndDis PPP Magic No Class: %d\n",epdis_class); + break; + case PSNDN: + LOG(3, s, t, " Received PPP LCP option Multilink EndDis PSND No Class: %d\n",epdis_class); + break; + default: + LOG(3, s, t, " Received PPP LCP option Multilink EndDis NULL Class %d\n",epdis_class); + } + } + break; + default: // Reject any unknown options LOG(3, s, t, " Rejecting unknown PPP LCP option %d\n", type); q = ppp_conf_rej(s, b, sizeof(b), PPPLCP, &response, q, p, o); @@ -671,6 +761,9 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) o += length; } + if (changed) + cluster_send_session(s); + if (response) { l = q - response; // LCP packet length @@ -679,7 +772,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) else { // Send packet back as ConfigAck - response = makeppp(b, sizeof(b), p, l, s, t, PPPLCP); + response = makeppp(b, sizeof(b), p, l, s, t, PPPLCP, 0, 0, 0); if (!response) return; *response = ConfigAck; } @@ -687,7 +780,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) switch (session[s].ppp.lcp) { case Closed: - response = makeppp(b, sizeof(b), p, 2, s, t, PPPLCP); + response = makeppp(b, sizeof(b), p, 2, s, t, PPPLCP, 0, 0, 0); if (!response) return; *response = TerminateAck; *((uint16_t *) (response + 2)) = htons(l = 4); @@ -820,6 +913,50 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) cluster_send_session(s); break; + case 17: // Multilink Max-Receive-Reconstructed-Unit + { + if (*p == ConfigNak) + { + sess_local[s].mp_mrru = ntohs(*(uint16_t *)(o + 2)); + LOG(3, s, t, " Remote requested MRRU of %u\n", sess_local[s].mp_mrru); + } + else + { + sess_local[s].mp_mrru = 0; + LOG(3, s, t, " Remote rejected MRRU negotiation\n"); + } + } + break; + + case 18: // Multilink Short Sequence Number Header Format + { + if (*p == ConfigNak) + { + sess_local[s].mp_mssf = 0; + LOG(3, s, t, " Remote requested Naked mssf\n"); + } + else + { + sess_local[s].mp_mssf = 0; + LOG(3, s, t, " Remote rejected mssf\n"); + } + } + break; + + case 19: // Multilink Endpoint Discriminator + { + if (*p == ConfigNak) + { + LOG(2, s, t, " Remote should not configNak Endpoint Dis!\n"); + } + else + { + sess_local[s].mp_epdis = 0; + LOG(3, s, t, " Remote rejected Endpoint Discriminator\n"); + } + } + break; + default: LOG(2, s, t, "LCP: remote sent %s for type %u?\n", ppp_code(*p), type); sessionshutdown(s, "Unable to negotiate LCP.", CDN_ADMIN_DISC, TERM_USER_ERROR); @@ -843,7 +980,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) case Closed: case Stopped: { - uint8_t *response = makeppp(b, sizeof(b), p, 2, s, t, PPPLCP); + uint8_t *response = makeppp(b, sizeof(b), p, 2, s, t, PPPLCP, 0, 0, 0); if (!response) return; *response = TerminateAck; *((uint16_t *) (response + 2)) = htons(l = 4); @@ -901,7 +1038,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) } *p = TerminateAck; // send ack - q = makeppp(b, sizeof(b), p, l, s, t, PPPLCP); + q = makeppp(b, sizeof(b), p, l, s, t, PPPLCP, 0, 0, 0); if (!q) return; LOG(3, s, t, "LCP: send %s\n", ppp_code(*q)); @@ -937,7 +1074,7 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) { *p = EchoReply; // reply *(uint32_t *) (p + 4) = htonl(session[s].magic); // our magic number - q = makeppp(b, sizeof(b), p, l, s, t, PPPLCP); + q = makeppp(b, sizeof(b), p, l, s, t, PPPLCP, 0, 0, 0); if (!q) return; LOG(4, s, t, "LCP: send %s\n", ppp_code(*q)); @@ -955,6 +1092,112 @@ void processlcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) } } +int join_bundle(sessionidt s) +{ + // Search for a bundle to join + bundleidt i; + bundleidt b; + for (i = 1; i < MAXBUNDLE; i++) + { + if (bundle[i].state != BUNDLEFREE) + { + if (epdiscmp(session[s].epdis,bundle[i].epdis) && !strcmp(session[s].user, bundle[i].user)) + { + sessionidt first_ses = bundle[i].members[0]; + if (bundle[i].mssf != session[s].mssf) + { + // uniformity of sequence number format must be insured + LOG(3, s, session[s].tunnel, "MPPP: unable to bundle session %d in bundle %d cause of different mssf\n", s, i); + return -1; + } + session[s].bundle = i; + session[s].ip = session[first_ses].ip; + session[s].dns1 = session[first_ses].dns1; + session[s].dns2 = session[first_ses].dns2; + session[s].timeout = session[first_ses].timeout; + + if(session[s].epdis.length > 0) + setepdis(&bundle[i].epdis, session[s].epdis); + + strcpy(bundle[i].user, session[s].user); + bundle[i].members[bundle[i].num_of_links] = s; + bundle[i].num_of_links++; + LOG(3, s, session[s].tunnel, "MPPP: Bundling additional line in bundle (%d), lines:%d\n",i,bundle[i].num_of_links); + return i; + } + } + } + + // No previously created bundle was found for this session, so create a new one + if (!(b = new_bundle())) return 0; + + session[s].bundle = b; + bundle[b].mrru = session[s].mrru; + bundle[b].mssf = session[s].mssf; + // FIXME !!! to enable l2tpns reading mssf frames receiver_max_seq, sender_max_seq must be introduce + // now session[s].mssf flag indecates that the receiver wish to receive frames in mssf, so max_seq (i.e. recv_max_seq) = 1<<24 + /* + if (bundle[b].mssf) + bundle[b].max_seq = 1 << 12; + else */ + bundle[b].max_seq = 1 << 24; + if(session[s].epdis.length > 0) + setepdis(&bundle[b].epdis, session[s].epdis); + + strcpy(bundle[b].user, session[s].user); + bundle[b].members[0] = s; + bundle[b].timeout = session[s].timeout; + LOG(3, s, session[s].tunnel, "MPPP: Created a new bundle (%d)\n", b); + return b; +} + +static int epdiscmp(epdist ep1, epdist ep2) +{ + int ad; + if (ep1.length != ep2.length) + return 0; + + if (ep1.addr_class != ep2.addr_class) + return 0; + + for (ad = 0; ad < ep1.length; ad++) + if (ep1.address[ad] != ep2.address[ad]) + return 0; + + return 1; +} + +static void setepdis(epdist *ep1, epdist ep2) +{ + int ad; + ep1->length = ep2.length; + ep1->addr_class = ep2.addr_class; + for (ad = 0; ad < ep2.length; ad++) + ep1->address[ad] = ep2.address[ad]; +} + +static bundleidt new_bundle() +{ + bundleidt i; + for (i = 1; i < MAXBUNDLE; i++) + { + if (bundle[i].state == BUNDLEFREE) + { + LOG(4, 0, 0, "MPPP: Assigning bundle ID %d\n", i); + bundle[i].num_of_links = 1; + bundle[i].last_check = time_now; // Initialize last_check value + bundle[i].state = BUNDLEOPEN; + bundle[i].current_ses = -1; // This is to enforce the first session 0 to be used at first + memset(&frag[i], 0, sizeof(fragmentationt)); + if (i > config->cluster_highest_bundleid) + config->cluster_highest_bundleid = i; + return i; + } + } + LOG(0, 0, 0, "MPPP: Can't find a free bundle! There shouldn't be this many in use!\n"); + return 0; +} + static void ipcp_open(sessionidt s, tunnelidt t) { LOG(3, s, t, "IPCP: Opened, session is now active\n"); @@ -1113,7 +1356,7 @@ void processipcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) else if (gotip) { // Send packet back as ConfigAck - response = makeppp(b, sizeof(b), p, l, s, t, PPPIPCP); + response = makeppp(b, sizeof(b), p, l, s, t, PPPIPCP, 0, 0, 0); if (!response) return; *response = ConfigAck; } @@ -1127,7 +1370,7 @@ void processipcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) switch (session[s].ppp.ipcp) { case Closed: - response = makeppp(b, sizeof(b), p, 2, s, t, PPPIPCP); + response = makeppp(b, sizeof(b), p, 2, s, t, PPPIPCP, 0, 0, 0); if (!response) return; *response = TerminateAck; *((uint16_t *) (response + 2)) = htons(l = 4); @@ -1200,7 +1443,7 @@ void processipcp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) } *p = TerminateAck; // send ack - q = makeppp(b, sizeof(b), p, l, s, t, PPPIPCP); + q = makeppp(b, sizeof(b), p, l, s, t, PPPIPCP, 0, 0, 0); if (!q) return; LOG(3, s, t, "IPCP: send %s\n", ppp_code(*q)); @@ -1334,7 +1577,7 @@ void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) else if (gotip) { // Send packet back as ConfigAck - response = makeppp(b, sizeof(b), p, l, s, t, PPPIPV6CP); + response = makeppp(b, sizeof(b), p, l, s, t, PPPIPV6CP, 0, 0, 0); if (!response) return; *response = ConfigAck; } @@ -1348,7 +1591,7 @@ void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) switch (session[s].ppp.ipv6cp) { case Closed: - response = makeppp(b, sizeof(b), p, 2, s, t, PPPIPV6CP); + response = makeppp(b, sizeof(b), p, 2, s, t, PPPIPV6CP, 0, 0, 0); if (!response) return; *response = TerminateAck; *((uint16_t *) (response + 2)) = htons(l = 4); @@ -1421,7 +1664,7 @@ void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) } *p = TerminateAck; // send ack - q = makeppp(b, sizeof(b), p, l, s, t, PPPIPV6CP); + q = makeppp(b, sizeof(b), p, l, s, t, PPPIPV6CP, 0, 0, 0); if (!q) return; LOG(3, s, t, "IPV6CP: send %s\n", ppp_code(*q)); @@ -1433,6 +1676,39 @@ void processipv6cp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) } } +static void update_sessions_in_stat(sessionidt s, uint16_t l) +{ + bundleidt b = session[s].bundle; + if (!b) + { + increment_counter(&session[s].cin, &session[s].cin_wrap, l); + session[s].cin_delta += l; + session[s].pin++; + + sess_local[s].cin += l; + sess_local[s].pin++; + } + else + { + int i = frag[b].re_frame_begin_index; + int end = frag[b].re_frame_end_index; + for (;;) + { + l = frag[b].fragment[i].length; + s = frag[b].fragment[i].sid; + increment_counter(&session[s].cin, &session[s].cin_wrap, l); + session[s].cin_delta += l; + session[s].pin++; + + sess_local[s].cin += l; + sess_local[s].pin++; + if (i == end) + return; + i = (i + 1) & MAXFRAGNUM_MASK; + } + } +} + // process IP packet received // // This MUST be called with at least 4 byte behind 'p'. @@ -1464,11 +1740,14 @@ void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) if (session[s].ppp.phase != Network || session[s].ppp.ipcp != Opened) return; - // no spoof (do sessionbyip to handled statically routed subnets) - if (ip != session[s].ip && sessionbyip(htonl(ip)) != s) + if (!session[s].bundle || bundle[session[s].bundle].num_of_links < 2) // FIXME: { - LOG(5, s, t, "Dropping packet with spoofed IP %s\n", fmtaddr(htonl(ip), 0)); - return; + // no spoof (do sessionbyip to handled statically routed subnets) + if (ip != session[s].ip && sessionbyip(htonl(ip)) != s) + { + LOG(4, s, t, "Dropping packet with spoofed IP %s\n", fmtaddr(htonl(ip), 0)); + return; + } } // run access-list if any @@ -1488,17 +1767,13 @@ void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) *(uint32_t *) p = htonl(PKTIP); l += 4; - // Are we throttled and a slave? - if (session[s].tbf_in && !config->cluster_iam_master) { - // Pass it to the master for handling. - master_throttle_packet(session[s].tbf_in, p, l); - return; - } - - // Are we throttled and a master?? - if (session[s].tbf_in && config->cluster_iam_master) { - // Actually handle the throttled packets. - tbf_queue_packet(session[s].tbf_in, p, l); + if (session[s].tbf_in) + { + // Are we throttling this session? + if (config->cluster_iam_master) + tbf_queue_packet(session[s].tbf_in, p, l); + else + master_throttle_packet(session[s].tbf_in, p, l); return; } @@ -1521,12 +1796,7 @@ void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) snoop_send_packet(p, l, session[s].snoop_ip, session[s].snoop_port); } - increment_counter(&session[s].cin, &session[s].cin_wrap, l); - session[s].cin_delta += l; - session[s].pin++; - - sess_local[s].cin += l; - sess_local[s].pin++; + update_sessions_in_stat(s, l); eth_tx += l; @@ -1534,6 +1804,195 @@ void processipin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) INC_STAT(tun_tx_bytes, l); } +// process Multilink PPP packet received +void processmpin(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) +{ + bundleidt b = session[s].bundle; + bundlet * this_bundle = &bundle[b]; + uint32_t frag_offset, M_offset; + uint16_t frag_index, M_index; + fragmentationt *this_fragmentation = &frag[b]; + uint8_t begin_frame = (*p & MP_BEGIN); + uint8_t end_frame = (*p & MP_END); + uint32_t seq_num; + uint8_t flags = *p; + uint16_t begin_index, end_index; + + // Perform length checking + if(l > MAXFRAGLEN) + { + LOG(2, s, t, "MPPP: discarding fragment larger than MAXFRAGLEN\n"); + return; + } + + if(!b) + { + LOG(2, s, t, "MPPP: Invalid bundle id: 0\n"); + return; + } + // FIXME !! session[s].mssf means that the receiver wants to receive frames in mssf not means the receiver will send frames in mssf + /* if(session[s].mssf) + { + // Get 12 bit for seq number + seq_num = ntohs((*(uint16_t *) p) & 0xFF0F); + p += 2; + l -= 2; + // After this point the pointer should be advanced 2 bytes + LOG(3, s, t, "MPPP: 12 bits, sequence number: %d\n",seq_num); + } + else */ + { + // Get 24 bit for seq number + seq_num = ntohl((*(uint32_t *) p) & 0xFFFFFF00); + p += 4; + l -= 4; + // After this point the pointer should be advanced 4 bytes + LOG(4, s, t, "MPPP: 24 bits sequence number:%d\n",seq_num); + } + + // calculate this fragment's offset from the begin seq in the bundle + frag_offset = (seq_num + this_bundle->max_seq - this_fragmentation->start_seq) & (this_bundle->max_seq-1); + + // discard this fragment if frag_offset is bigger that the fragmentation buffer size + if (frag_offset >= MAXFRAGNUM) + { + LOG(3, s, t, "MPPP: Index out of range, received more than MAXFRAGNUM fragment (lost frag) seq:%d, begin_seq:%d, bundle:%d, max:%d\n",seq_num, this_fragmentation->start_seq, b, this_bundle->max_seq); + return; + } + + // update M + sess_local[s].last_seq = seq_num; + if (seq_num < this_fragmentation->M) + this_fragmentation->M = seq_num; + else + { + uint32_t i, min = sess_local[(this_bundle->members[0])].last_seq;; + for (i = 1; i < this_bundle->num_of_links; i++) + { + uint32_t s_seq = sess_local[(this_bundle->members[i])].last_seq; + if (s_seq < min) + min = s_seq; + } + this_fragmentation->M = min; + } + + LOG(4, s, t, "MPPP: Setting M to %d\n", this_fragmentation->M); + //calculate M's offset from the begin seq in the bundle + M_offset = (this_fragmentation->M + this_bundle->max_seq - this_fragmentation->start_seq) & (this_bundle->max_seq-1); + + //caculate M's index in the fragment array + M_index = (M_offset + this_fragmentation->start_index) & MAXFRAGNUM_MASK; + + //caculate received fragment's index in the fragment array + frag_index = (frag_offset + this_fragmentation->start_index) & MAXFRAGNUM_MASK; + + //frame with a single fragment + if (begin_frame && end_frame) + { + // process and reset fragmentation + LOG(4, s, t, "MPPP: Both bits are set (Begin and End).\n"); + this_fragmentation->fragment[frag_index].length = l; + this_fragmentation->fragment[frag_index].sid = s; + this_fragmentation->fragment[frag_index].flags = flags; + this_fragmentation->fragment[frag_index].seq = seq_num; + this_fragmentation->re_frame_begin_index = frag_index; + this_fragmentation->re_frame_end_index = frag_index; + processmpframe(s, t, p, l, 0); + this_fragmentation->fragment[frag_index].length = 0; + this_fragmentation->fragment[frag_index].flags = 0; + end_index = frag_index; + } + else + { + // insert the frame in it's place + fragmentt *this_frag = &this_fragmentation->fragment[frag_index]; + this_frag->length = l; + this_frag->sid = s; + this_frag->flags = flags; + this_frag->seq = seq_num; + memcpy(this_frag->data, p, l); + + // try to assemble the frame that has the received fragment as a member + // get the beginning of this frame + begin_index = end_index = frag_index; + while (this_fragmentation->fragment[begin_index].length) + { + if (this_fragmentation->fragment[begin_index].flags & MP_BEGIN) + break; + begin_index = (begin_index ? (begin_index -1) : (MAXFRAGNUM -1)); + } + + // return if a lost fragment is found + if (!(this_fragmentation->fragment[begin_index].length)) + return; // assembling frame failed + // get the end of his frame + while (this_fragmentation->fragment[end_index].length) + { + if (this_fragmentation->fragment[end_index].flags & MP_END) + break; + end_index = (end_index +1) & MAXFRAGNUM_MASK; + } + + // return if a lost fragment is found + if (!(this_fragmentation->fragment[end_index].length)) + return; // assembling frame failed + + // assemble the packet + //assemble frame, process it, reset fragmentation + uint16_t cur_len = 4; // This is set to 4 to leave 4 bytes for function processipin + uint32_t i; + + LOG(4, s, t, "MPPP: processing fragments from %d to %d\n", begin_index, end_index); + // Push to the receive buffer + + for (i = begin_index;; i = (i + 1) & MAXFRAGNUM_MASK) + { + this_frag = &this_fragmentation->fragment[i]; + if(cur_len + this_frag->length > MAXETHER) + { + LOG(2, s, t, "MPPP: discarding reassembled frames larger than MAXETHER\n"); + break; + } + memcpy(this_fragmentation->reassembled_frame+cur_len, this_frag->data, this_frag->length); + LOG(5, s, t, "MPPP: processing frame at %d, with len %d\n", i, this_frag->length); + cur_len += this_frag->length; + if (i == end_index) + { + this_fragmentation->re_frame_len = cur_len; + this_fragmentation->re_frame_begin_index = begin_index; + this_fragmentation->re_frame_end_index = end_index; + // Process the resassembled frame + LOG(5, s, t, "MPPP: Process the reassembled frame, len=%d\n",cur_len); + processmpframe(s, t, this_fragmentation->reassembled_frame, this_fragmentation->re_frame_len, 1); + break; + } + } + // Set reassembled frame length to zero after processing it + this_fragmentation->re_frame_len = 0; + for (i = begin_index;; i = (i + 1) & MAXFRAGNUM_MASK) + { + this_fragmentation->fragment[i].length = 0; // Indicates that this fragment has been consumed + this_fragmentation->fragment[i].flags = 0; + if (i == end_index) + break; + } + } + //discard fragments received before the recently assembled frame + begin_index = this_fragmentation->start_index; + this_fragmentation->start_index = (end_index + 1) & MAXFRAGNUM_MASK; + this_fragmentation->start_seq = (this_fragmentation->fragment[end_index].seq + 1) & (this_bundle->max_seq-1); + //clear length and flags of the discarded fragments + while (begin_index != this_fragmentation->start_index) + { + this_fragmentation->fragment[begin_index].flags = 0; + this_fragmentation->fragment[begin_index].length = 0; + begin_index = (begin_index + 1) & MAXFRAGNUM_MASK; + } + + LOG(4, s, t, "MPPP after assembling: M index is =%d, start index is = %d, start seq=%d\n",M_index, this_fragmentation->start_index, this_fragmentation->start_seq); + return; +} + // process IPv6 packet received // // This MUST be called with at least 4 byte behind 'p'. @@ -1617,12 +2076,7 @@ void processipv6in(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) snoop_send_packet(p, l, session[s].snoop_ip, session[s].snoop_port); } - increment_counter(&session[s].cin, &session[s].cin_wrap, l); - session[s].cin_delta += l; - session[s].pin++; - - sess_local[s].cin += l; - sess_local[s].pin++; + update_sessions_in_stat(s, l); eth_tx += l; @@ -1693,7 +2147,7 @@ void processccp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) STAT(tunnel_rx_errors); } - LOG(3, s, t, "CCP: recv %s\n", ppp_code(*p)); + LOG(4, s, t, "CCP: recv %s\n", ppp_code(*p)); if (*p == ConfigAck) { switch (session[s].ppp.ccp) @@ -1726,13 +2180,13 @@ void processccp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) else // compression requested--reject *p = ConfigRej; - q = makeppp(b, sizeof(b), p, l, s, t, PPPCCP); + q = makeppp(b, sizeof(b), p, l, s, t, PPPCCP, 0, 0, 0); if (!q) return; switch (session[s].ppp.ccp) { case Closed: - q = makeppp(b, sizeof(b), p, 2, s, t, PPPCCP); + q = makeppp(b, sizeof(b), p, 2, s, t, PPPCCP, 0, 0, 0); if (!q) return; *q = TerminateAck; *((uint16_t *) (q + 2)) = htons(l = 4); @@ -1778,13 +2232,13 @@ void processccp(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l) return; } - LOG(3, s, t, "CCP: send %s\n", ppp_code(*q)); + LOG(4, s, t, "CCP: send %s\n", ppp_code(*q)); tunnelsend(b, l + (q - b), t); } else if (*p == TerminateReq) { *p = TerminateAck; - q = makeppp(b, sizeof(b), p, l, s, t, PPPCCP); + q = makeppp(b, sizeof(b), p, l, s, t, PPPCCP, 0, 0, 0); if (!q) return; LOG(3, s, t, "CCP: send %s\n", ppp_code(*q)); tunnelsend(b, l + (q - b), t); @@ -1828,7 +2282,7 @@ void sendchap(sessionidt s, tunnelidt t) STAT(tunnel_tx_errors); return ; } - q = makeppp(b, sizeof(b), 0, 0, s, t, PPPCHAP); + q = makeppp(b, sizeof(b), 0, 0, s, t, PPPCHAP, 0, 0, 0); if (!q) return; *q = 1; // challenge @@ -1842,37 +2296,86 @@ void sendchap(sessionidt s, tunnelidt t) // fill in a L2TP message with a PPP frame, // returns start of PPP frame -uint8_t *makeppp(uint8_t *b, int size, uint8_t *p, int l, sessionidt s, tunnelidt t, uint16_t mtype) +uint8_t *makeppp(uint8_t *b, int size, uint8_t *p, int l, sessionidt s, tunnelidt t, uint16_t mtype, uint8_t prio, bundleidt bid, uint8_t mp_bits) { - if (size < 12) // Need more space than this!! + uint16_t hdr = 0x0002; // L2TP with no options + uint16_t type = mtype; + uint8_t *start = b; + + if (size < 16) // Need more space than this!! { LOG(0, s, t, "makeppp buffer too small for L2TP header (size=%d)\n", size); return NULL; } - *(uint16_t *) (b + 0) = htons(0x0002); // L2TP with no options + if (prio) hdr |= 0x0100; // set priority bit + + *(uint16_t *) (b + 0) = htons(hdr); *(uint16_t *) (b + 2) = htons(tunnel[t].far); // tunnel *(uint16_t *) (b + 4) = htons(session[s].far); // session b += 6; - if (mtype == PPPLCP || !(session[s].flags & SESSION_ACFC)) + + // Check whether this session is part of multilink + if (bid) + { + if (bundle[bid].num_of_links > 1) + type = PPPMP; // Change PPP message type to the PPPMP + else + bid = 0; + } + + if (type == PPPLCP || !(session[s].flags & SESSION_ACFC)) { *(uint16_t *) b = htons(0xFF03); // HDLC header b += 2; } - if (mtype < 0x100 && session[s].flags & SESSION_PFC) - *b++ = mtype; + + if (type < 0x100 && session[s].flags & SESSION_PFC) + { + *b++ = type; + } else { - *(uint16_t *) b = htons(mtype); + *(uint16_t *) b = htons(type); b += 2; } - if (l + 12 > size) + if (bid) { - LOG(2, s, t, "makeppp would overflow buffer (size=%d, header+payload=%d)\n", size, l + 12); + // Set the sequence number and (B)egin (E)nd flags + if (session[s].mssf) + { + // Set the multilink bits + uint16_t bits_send = mp_bits; + *(uint16_t *) b = htons((bundle[bid].seq_num_t & 0x0FFF)|bits_send); + b += 2; + } + else + { + *(uint32_t *) b = htonl(bundle[bid].seq_num_t); + // Set the multilink bits + *b = mp_bits; + b += 4; + } + + bundle[bid].seq_num_t++; + + // Add the message type if this fragment has the begin bit set + if (mp_bits & MP_BEGIN) + { + //*b++ = mtype; // The next two lines are instead of this + *(uint16_t *) b = htons(mtype); // Message type + b += 2; + } + } + + if ((b - start) + l > size) + { + LOG(2, s, t, "makeppp would overflow buffer (size=%d, header+payload=%d)\n", size, (b - start) + l); return NULL; } + // Copy the payload if (p && l) memcpy(b, p, l); @@ -1911,10 +2414,10 @@ void sendlcp(sessionidt s, tunnelidt t) uint8_t b[500], *q, *l; int authtype = sess_local[s].lcp_authtype; - if (!(q = makeppp(b, sizeof(b), NULL, 0, s, t, PPPLCP))) + if (!(q = makeppp(b, sizeof(b), NULL, 0, s, t, PPPLCP, 0, 0, 0))) return; - LOG(3, s, t, "LCP: send ConfigReq%s%s%s\n", + LOG(3, s, t, "LCP: send ConfigReq%s%s%s including MP options\n", authtype ? " (" : "", authtype ? (authtype == AUTHCHAP ? "CHAP" : "PAP") : "", authtype ? ")" : ""); @@ -1941,6 +2444,20 @@ void sendlcp(sessionidt s, tunnelidt t) l += 4; } + if (sess_local[s].mp_mrru) + { + *l++ = 17; *l++ = 4; // Multilink Max-Receive-Reconstructed-Unit (length 4) + *(uint16_t *) l = htons(sess_local[s].mp_mrru); l += 2; + } + + if (sess_local[s].mp_epdis) + { + *l++ = 19; *l++ = 7; // Multilink Endpoint Discriminator (length 7) + *l++ = IPADDR; // Endpoint Discriminator class + *(uint32_t *) l = htonl(sess_local[s].mp_epdis); + l += 4; + } + *(uint16_t *)(q + 2) = htons(l - q); // Length LOG_HEX(5, "PPPLCP", q, l - q); @@ -1955,7 +2472,7 @@ void sendccp(sessionidt s, tunnelidt t) { uint8_t b[500], *q; - if (!(q = makeppp(b, sizeof(b), NULL, 0, s, t, PPPCCP))) + if (!(q = makeppp(b, sizeof(b), NULL, 0, s, t, PPPCCP, 0, 0, 0))) return; LOG(3, s, t, "CCP: send ConfigReq (no compression)\n"); @@ -1982,7 +2499,7 @@ void protoreject(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint16_t pro l += 6; if (l > mru) l = mru; - q = makeppp(buf, sizeof(buf), 0, 0, s, t, PPPLCP); + q = makeppp(buf, sizeof(buf), 0, 0, s, t, PPPLCP, 0, 0, 0); if (!q) return; *q = ProtocolRej; diff --git a/radius.c b/radius.c index 8a39894..93a1cde 100644 --- a/radius.c +++ b/radius.c @@ -1,6 +1,6 @@ // L2TPNS Radius Stuff -char const *cvs_id_radius = "$Id: radius.c,v 1.49.2.2 2006/08/02 14:17:20 bodea Exp $"; +char const *cvs_id_radius = "$Id: radius.c,v 1.56 2009/12/08 14:49:28 bodea Exp $"; #include #include @@ -45,6 +45,25 @@ static void calc_auth(const void *buf, size_t len, const uint8_t *in, uint8_t *o void initrad(void) { int i; + uint16_t port = 0; + uint16_t min = config->radius_bind_min; + uint16_t max = config->radius_bind_max; + int inc = 1; + struct sockaddr_in addr; + + if (min) + { + port = min; + if (!max) + max = ~0 - 1; + } + else if (max) /* no minimum specified, bind from max down */ + { + port = max; + min = 1; + inc = -1; + } + LOG(3, 0, 0, "Creating %d sockets for RADIUS queries\n", RADIUS_FDS); radfds = calloc(sizeof(int), RADIUS_FDS); for (i = 0; i < RADIUS_FDS; i++) @@ -53,6 +72,27 @@ void initrad(void) radfds[i] = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); flags = fcntl(radfds[i], F_GETFL, 0); fcntl(radfds[i], F_SETFL, flags | O_NONBLOCK); + + if (port) + { + int b; + + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = INADDR_ANY; + + do { + addr.sin_port = htons(port); + if ((b = bind(radfds[i], (struct sockaddr *) &addr, sizeof(addr))) < 0) + { + if ((port += inc) < min || port > max) + { + LOG(0, 0, 0, "Can't bind RADIUS socket in range %u-%u\n", min, max); + exit(1); + } + } + } while (b < 0); + } } } @@ -137,7 +177,7 @@ void radiussend(uint16_t r, uint8_t state) return; } - if (state != RADIUSAUTH && !config->radius_accounting) + if (state != RADIUSAUTH && state != RADIUSJUSTAUTH && !config->radius_accounting) { // Radius accounting is turned off radiusclear(r, s); @@ -157,7 +197,7 @@ void radiussend(uint16_t r, uint8_t state) { if (s) { - if (state == RADIUSAUTH) + if (state == RADIUSAUTH || state == RADIUSJUSTAUTH) sessionshutdown(s, "RADIUS timeout.", CDN_ADMIN_DISC, TERM_REAUTHENTICATION_FAILURE); else { @@ -179,6 +219,7 @@ void radiussend(uint16_t r, uint8_t state) switch (state) { case RADIUSAUTH: + case RADIUSJUSTAUTH: b[0] = AccessRequest; // access request break; case RADIUSSTART: @@ -199,7 +240,7 @@ void radiussend(uint16_t r, uint8_t state) strcpy((char *) p + 2, session[s].user); p += p[1]; } - if (state == RADIUSAUTH) + if (state == RADIUSAUTH || state == RADIUSJUSTAUTH) { if (radius[r].chap) { @@ -330,6 +371,7 @@ void radiussend(uint16_t r, uint8_t state) } } } + if (s) { *p = 5; // NAS-Port @@ -339,59 +381,80 @@ void radiussend(uint16_t r, uint8_t state) *p = 6; // Service-Type p[1] = 6; - *(uint32_t *) (p + 2) = htonl(2); // Framed-User + *(uint32_t *) (p + 2) = htonl((state == RADIUSJUSTAUTH ? 8 : 2)); // Authenticate only or Framed-User respectevily p += p[1]; *p = 7; // Framed-Protocol - p[1] = 6; - *(uint32_t *) (p + 2) = htonl(1); // PPP - p += p[1]; - } - if (s && session[s].ip) - { - *p = 8; // Framed-IP-Address - p[1] = 6; - *(uint32_t *) (p + 2) = htonl(session[s].ip); + p[1] = htonl((state == RADIUSJUSTAUTH ? 0 : 6)); + *(uint32_t *) (p + 2) = htonl((state == RADIUSJUSTAUTH ? 0 : 1)); // PPP p += p[1]; - } - if (s && session[s].route[0].ip) - { - int r; - for (r = 0; s && r < MAXROUTE && session[s].route[r].ip; r++) + + if (session[s].ip) { - int width = 32; - if (session[s].route[r].mask) + *p = 8; // Framed-IP-Address + p[1] = 6; + *(uint32_t *) (p + 2) = htonl(session[s].ip); + p += p[1]; + } + + if (session[s].route[0].ip) + { + int r; + for (r = 0; s && r < MAXROUTE && session[s].route[r].ip; r++) { - int mask = session[s].route[r].mask; - while (!(mask & 1)) - { - width--; - mask >>= 1; - } + int width = 32; + if (session[s].route[r].mask) + { + int mask = session[s].route[r].mask; + while (!(mask & 1)) + { + width--; + mask >>= 1; + } + } + + *p = 22; // Framed-Route + p[1] = sprintf((char *) p + 2, "%s/%d %s 1", + fmtaddr(htonl(session[s].route[r].ip), 0), + width, fmtaddr(htonl(session[s].ip), 1)) + 2; + + p += p[1]; } + } - *p = 22; // Framed-Route - p[1] = sprintf((char *) p + 2, "%s/%d %s 1", - fmtaddr(htonl(session[s].route[r].ip), 0), - width, fmtaddr(htonl(session[s].ip), 1)) + 2; + if (session[s].session_timeout) + { + *p = 27; // Session-Timeout + p[1] = 6; + *(uint32_t *) (p + 2) = htonl(session[s].session_timeout); + p += p[1]; + } + if (session[s].idle_timeout) + { + *p = 28; // Idle-Timeout + p[1] = 6; + *(uint32_t *) (p + 2) = htonl(session[s].idle_timeout); + p += p[1]; + } + + if (*session[s].called) + { + *p = 30; // called + p[1] = strlen(session[s].called) + 2; + strcpy((char *) p + 2, session[s].called); + p += p[1]; + } + + if (*session[s].calling) + { + *p = 31; // calling + p[1] = strlen(session[s].calling) + 2; + strcpy((char *) p + 2, session[s].calling); p += p[1]; } } - if (*session[s].called) - { - *p = 30; // called - p[1] = strlen(session[s].called) + 2; - strcpy((char *) p + 2, session[s].called); - p += p[1]; - } - if (*session[s].calling) - { - *p = 31; // calling - p[1] = strlen(session[s].calling) + 2; - strcpy((char *) p + 2, session[s].calling); - p += p[1]; - } + // NAS-IP-Address *p = 4; p[1] = 6; @@ -400,7 +463,7 @@ void radiussend(uint16_t r, uint8_t state) // All AVpairs added *(uint16_t *) (b + 2) = htons(p - b); - if (state != RADIUSAUTH) + if (state != RADIUSAUTH && state != RADIUSJUSTAUTH) { // Build auth for accounting packet calc_auth(b, p - b, zero, b + 4); @@ -413,7 +476,7 @@ void radiussend(uint16_t r, uint8_t state) // get radius port uint16_t port = config->radiusport[(radius[r].try - 1) % config->numradiusservers]; // assume RADIUS accounting port is the authentication port +1 - addr.sin_port = htons((state == RADIUSAUTH) ? port : port+1); + addr.sin_port = htons((state == RADIUSAUTH || state == RADIUSJUSTAUTH) ? port : port+1); } LOG_HEX(5, "RADIUS Send", b, (p - b)); @@ -496,7 +559,7 @@ void processrad(uint8_t *buf, int len, char socket_index) LOG(1, s, session[s].tunnel, " Unexpected RADIUS response\n"); return; } - if (radius[r].state != RADIUSAUTH && radius[r].state != RADIUSSTART + if (radius[r].state != RADIUSAUTH && radius[r].state != RADIUSJUSTAUTH && radius[r].state != RADIUSSTART && radius[r].state != RADIUSSTOP && radius[r].state != RADIUSINTERIM) { LOG(1, s, session[s].tunnel, " Unexpected RADIUS response\n"); @@ -511,7 +574,7 @@ void processrad(uint8_t *buf, int len, char socket_index) return; // Do nothing. On timeout, it will try the next radius server. } - if ((radius[r].state == RADIUSAUTH && r_code != AccessAccept && r_code != AccessReject) || + if (((radius[r].state == RADIUSAUTH ||radius[r].state == RADIUSJUSTAUTH) && r_code != AccessAccept && r_code != AccessReject) || ((radius[r].state == RADIUSSTART || radius[r].state == RADIUSSTOP || radius[r].state == RADIUSINTERIM) && r_code != AccountingResponse)) { LOG(1, s, session[s].tunnel, " Unexpected RADIUS response %s\n", radius_code(r_code)); @@ -519,7 +582,7 @@ void processrad(uint8_t *buf, int len, char socket_index) // care off finishing the radius session if that's really correct. } - if (radius[r].state == RADIUSAUTH) + if (radius[r].state == RADIUSAUTH || radius[r].state == RADIUSJUSTAUTH) { // run post-auth plugin struct param_post_auth packet = { @@ -537,7 +600,7 @@ void processrad(uint8_t *buf, int len, char socket_index) if (radius[r].chap) { // CHAP - uint8_t *p = makeppp(b, sizeof(b), 0, 0, s, t, PPPCHAP); + uint8_t *p = makeppp(b, sizeof(b), 0, 0, s, t, PPPCHAP, 0, 0, 0); if (!p) return; // Abort! *p = (r_code == AccessAccept) ? 3 : 4; // ack/nak @@ -551,7 +614,7 @@ void processrad(uint8_t *buf, int len, char socket_index) else { // PAP - uint8_t *p = makeppp(b, sizeof(b), 0, 0, s, t, PPPPAP); + uint8_t *p = makeppp(b, sizeof(b), 0, 0, s, t, PPPPAP, 0, 0, 0); if (!p) return; // Abort! // ack/nak @@ -715,6 +778,22 @@ void processrad(uint8_t *buf, int len, char socket_index) ip_filters[f].used++; } } + else if (*p == 27) + { + // Session-Timeout + if (p[1] < 6) continue; + session[s].session_timeout = ntohl(*(uint32_t *)(p + 2)); + LOG(3, s, session[s].tunnel, " Radius reply contains Session-Timeout = %u\n", session[s].session_timeout); + if(!session[s].session_timeout && config->kill_timedout_sessions) + sessionshutdown(s, "Session timeout is zero", CDN_ADMIN_DISC, 0); + } + else if (*p == 28) + { + // Idle-Timeout + if (p[1] < 6) continue; + session[s].idle_timeout = ntohl(*(uint32_t *)(p + 2)); + LOG(3, s, session[s].tunnel, " Radius reply contains Idle-Timeout = %u\n", session[s].idle_timeout); + } else if (*p == 99) { // Framed-IPv6-Route @@ -793,6 +872,7 @@ void radiusretry(uint16_t r) sendchap(s, t); break; case RADIUSAUTH: // sending auth to RADIUS server + case RADIUSJUSTAUTH: // sending auth to RADIUS server case RADIUSSTART: // sending start accounting to RADIUS server case RADIUSSTOP: // sending stop accounting to RADIUS server case RADIUSINTERIM: // sending interim accounting to RADIUS server diff --git a/test/Makefile b/test/Makefile new file mode 100644 index 0000000..ae9b79f --- /dev/null +++ b/test/Makefile @@ -0,0 +1,11 @@ +CFLAGS = -g -Wall -W -std=c99 -pedantic +TARGETS = bounce generateload radius + +all: $(TARGETS) +clean: + rm -f $(TARGETS) + +../md5.o: ../md5.c ../md5.h + $(MAKE) -C .. md5.o + +radius: radius.c ../md5.o diff --git a/test/bounce.c b/test/bounce.c index 5443b67..269d6c9 100644 --- a/test/bounce.c +++ b/test/bounce.c @@ -68,7 +68,8 @@ int main(int argc, char *argv[]) while (1) { struct sockaddr_in addr; - int alen = sizeof(addr), l; + socklen_t alen = sizeof(addr); + int l; unsigned int iseq; l = recvfrom(s, packet, 65535, 0, (void *) &addr, &alen); @@ -87,7 +88,7 @@ int main(int argc, char *argv[]) free(packet); } -void sigalarm(int junk) +void sigalarm(int unusedg __attribute__ ((unused))) { printf("Recv: %10llu %0.1fMbits/s (%lu pps) (%5ld dropped)\n", recv_count, (bytes / 1024.0 / 1024.0 * 8), pps, dropped); pps = bytes = 0; diff --git a/test/generateload.c b/test/generateload.c index 0b32199..b671b4f 100644 --- a/test/generateload.c +++ b/test/generateload.c @@ -1,3 +1,9 @@ +#define _POSIX_C_SOURCE 200112L +#include +#include +#include +#define __USE_XOPEN_EXTENDED +#define __USE_MISC #include #include #include @@ -6,11 +12,8 @@ #include #include #include -#include -#include #include #include -#include #include #include #include @@ -179,10 +182,10 @@ typedef struct } control_message; typedef struct { -unsigned long long send_count , recv_count ; -unsigned long long spkt , rpkt ; -unsigned int dropped; -unsigned long sbytes , rbytes ; +long long send_count, recv_count; +long long spkt, rpkt ; +int dropped; +long sbytes, rbytes ; int quitit; struct sessiont { @@ -210,7 +213,7 @@ void dump_control_message(control_message *c); u32 avp_get_32(control_message *c, int id); u16 avp_get_16(control_message *c, int id); char *avp_get_s(control_message *c, int id); -void reader_thread(int udpfd); +void reader_thread(void); void skip_zlb(); void cm_free(control_message *m); controlt *ppp_new(u16 session, int protocol); @@ -234,7 +237,7 @@ void print_report(); int ns = 0, nr = 0; int udpfd; int t = 0; -struct sockaddr_in gatewayaddr = {0}; +struct sockaddr_in gatewayaddr; int numsessions = NUM_SESSIONS; int packet_length = PACKET_LENGTH; int target_pps = TARGET_PPS; @@ -251,7 +254,7 @@ char *suffix = "@optusnet.com.au"; int main(int argc, char *argv[]) { int s; - char *packet; + unsigned char *packet; ss = (sharedt*) mmap(NULL, sizeof(*ss), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); @@ -377,6 +380,7 @@ int main(int argc, char *argv[]) printf("Bound to port %d\n", htons(addr.sin_port)); }/*}}}*/ + memset(&gatewayaddr, 0, sizeof(gatewayaddr)); gatewayaddr.sin_family = AF_INET; gatewayaddr.sin_port = htons(1701); inet_aton(gwaddr, &gatewayaddr.sin_addr); @@ -400,7 +404,8 @@ int main(int argc, char *argv[]) // Receive reply/*{{{*/ { struct sockaddr_in addr; - int alen = sizeof(addr), l; + int l; + socklen_t alen = sizeof(addr); l = recvfrom(udpfd, packet, 4096, 0, (void *) &addr, &alen); if (l < 0) @@ -409,7 +414,7 @@ int main(int argc, char *argv[]) return -1; } printf("Received "); - r = parsecontrol(packet, l); + r = parsecontrol((char *) packet, l); if (!r->first) { printf("Invalid packet.. no first avp\n"); @@ -446,7 +451,7 @@ int main(int argc, char *argv[]) printf("All session create requests sent...\n");/*}}}*/ if ( fork() == 0) { - reader_thread(udpfd); + reader_thread(); exit(0); } @@ -529,7 +534,7 @@ int main(int argc, char *argv[]) *(u16 *)(c->buf + 4) = htons(ss->sessions[i].remote_session); // Session ID iph->saddr = ss->sessions[i].addr; iph->check = 0; - iph->check = ntohs(checksum((char *)iph, sizeof(struct iphdr))); + iph->check = ntohs(checksum((unsigned char *)iph, sizeof(struct iphdr))); *((unsigned int *) data) = seq++; ppp_send(c); @@ -546,7 +551,8 @@ int main(int argc, char *argv[]) nanosleep(&req, NULL); } - if (max_packets && ss->send_count >= max_packets) ss->quitit++; + if (max_packets && ss->send_count >= max_packets) + ss->quitit++; } } @@ -602,22 +608,24 @@ void clean_shutdown()/*{{{*/ } }/*}}}*/ -void sigint(int signal) +void sigint(int unused __attribute__ ((unused))) { ss->quitit++; } -void sigalarm(int junk) +void sigalarm(int unused __attribute__ ((unused))) { static unsigned long long last_rpkts[AVG_SIZE], last_spkts[AVG_SIZE]; static int last = 0, avg_count = 0; - register unsigned int avg_s = 0, avg_r = 0, i; + unsigned int avg_s = 0, avg_r = 0; + int i; float loss; last_rpkts[last] = ss->rpkt; last_spkts[last] = ss->spkt; last = (last + 1) % AVG_SIZE; - if (avg_count < AVG_SIZE) avg_count++; + if (avg_count < AVG_SIZE) + avg_count++; for (i = 0; i < avg_count; i++) { @@ -867,7 +875,7 @@ void cm_free(control_message *m) // }}} -void reader_thread(int updfd)/*{{{*/ +void reader_thread()/*{{{*/ { unsigned char *packet; unsigned int seq = 0; @@ -877,7 +885,7 @@ void reader_thread(int updfd)/*{{{*/ while (!ss->quitit) { struct sockaddr_in addr; - int alen = sizeof(addr); + socklen_t alen = sizeof(addr); control_message *m; int l; int s; @@ -906,7 +914,7 @@ void reader_thread(int updfd)/*{{{*/ { // Control Packet printf("Reader Received "); - m = parsecontrol(packet, l); + m = parsecontrol((char *) packet, l); printf("\n"); s = m->session; @@ -975,7 +983,7 @@ void reader_thread(int updfd)/*{{{*/ if (protocol != PPPIP) { printf("Received "); - dump_ppp_packet(packet + 6, l - 6); + dump_ppp_packet((char *) (packet + 6), l - 6); } if (protocol == PPPLCP) @@ -1073,13 +1081,13 @@ void reader_thread(int updfd)/*{{{*/ if (iph->protocol == 17) { - int iseq; + unsigned int iseq; ss->recv_count++; ss->rpkt++; iseq = *((unsigned int *) data); - if (seq != iseq) { + if (seq != iseq) ss->dropped += (iseq - seq) ; - } + seq = iseq + 1; // Next sequence number to expect. } } @@ -1095,7 +1103,7 @@ void reader_thread(int updfd)/*{{{*/ void skip_zlb() /*{{{*/ { struct sockaddr_in addr; - int alen = sizeof(addr); + socklen_t alen = sizeof(addr); char buf[1024]; int l; l = recvfrom(udpfd, buf, 1024, MSG_PEEK, (void *) &addr, &alen);