Repository: drsound/fault_tolerant_router Branch: master Commit: 1ce8016c3104 Files: 13 Total size: 60.7 KB Directory structure: gitextract_e5h0vc58/ ├── .gitignore ├── Gemfile ├── LICENSE ├── README.md ├── Rakefile ├── bin/ │ └── fault_tolerant_router ├── fault_tolerant_router.gemspec └── lib/ └── fault_tolerant_router/ ├── generate_config.rb ├── generate_iptables.rb ├── monitor.rb ├── uplink.rb ├── uplinks.rb └── version.rb ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.gem *.rbc .bundle .config .yardoc Gemfile.lock InstalledFiles _yardoc coverage doc/ lib/bundler/man pkg rdoc spec/reports test/tmp test/version_tmp tmp *.bundle *.so *.o *.a mkmf.log .idea/ ================================================ FILE: Gemfile ================================================ source 'https://rubygems.org' # Specify your gem's dependencies in fault_tolerant_router.gemspec gemspec ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. {description} Copyright (C) {year} {fullname} This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. {signature of Ty Coon}, 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ # Fault Tolerant Router [![Gem Version](https://badge.fury.io/rb/fault_tolerant_router.svg)](http://badge.fury.io/rb/fault_tolerant_router) [![PayPayl donate button](https://img.shields.io/badge/paypal-donate-yellow.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=96LFVQRFGRPFW&lc=GB&item_name=Alessandro%20Zarrilli&item_number=fault_tolerant_router¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donate_SM%2egif%3aNonHosted "Donate once-off to this project using Paypal") ## In brief Do you have multiple internet connections (uplinks) with several providers? Do you want to transparently use all of the available bandwidth? Do you want to remain online even if some uplinks go down? This tool may help you! ## A more formal description Fault Tolerant Router is a daemon, running in background on a Linux router or firewall, monitoring the state of multiple internet uplinks and changing the routing accordingly. LAN/DMZ internet traffic (outgoing connections) is load balanced between the uplinks using Linux *multipath routing*. The daemon monitors the state of the uplinks by routinely pinging well known IP addresses (Google public DNS servers, etc.) through each outgoing interface: once an uplink goes down, it is excluded from the *multipath routing*, when it comes back up, it is included again. An uplink may be assigned to a priority group: lower priority uplinks will only be used if all higher priority ones are down. That's useful to only use pay-per-traffic uplinks if no regular uplink is working. All of the routing changes are notified to the administrator by email. Fault Tolerant Router is well tested and has been used in production for several years, in several sites. ## Alternatives Fault Tolerant Router has been featured on Slashdot, see [article](http://linux.slashdot.org/story/15/03/03/1910206/linux-and-multiple-internet-uplinks-a-new-tool) comments for interesting hints and alternatives. ## Interaction between *multipath routing*, *iptables* and *ip policy routing* The system is based on the interaction between Linux *multipath routing*, *iptables* and *ip policy routing*. Outgoing (from LAN/DMZ to WAN) and incoming (from WAN to LAN/DMZ) connections have a different behaviour: * **Outgoing connections (from LAN/DMZ to WAN)**: * **New connections**: The outgoing interface (uplink) is decided by the Linux *multipath routing*, in a round-robin fashion. Then, just before the packet leaves the router (in the *iptables* POSTROUTING chain), *iptables* marks the connection with the outgoing interface id, so that all subsequent connection packets will be sent through the same interface. NB: all the packets of the same connection should be originating from the same IP address, otherwise the server you are connecting to would refuse them, unless you are using specific protocols. * **Established connections**: Before the packet is routed (in the *iptables* PREROUTING chain), *iptables* marks it with the outgoing interface id that was previously assigned to the connection. This way, thanks to *ip policy routing*, the packet will pass through a specific routing table directing it to the connection outgoing interface. * **Incoming connections (from WAN to LAN/DMZ)**: The incoming interface is obviously decided by the connecting host, connecting to one of the IP addresses assigned to an uplink interface. Just after the packet enters the router (in the *iptables* PREROUTING chain), *iptables* marks the connection with the incoming interface id. Then, when the packet reaches the LAN or DMZ, a return packet is generated by the receiving host and sent back to the connecting host. Once this return packet hits the router, before it is actually routed (in the *iptables* PREROUTING chain), *iptables* marks it with the outgoing interface id that was previously assigned to that connection. This way, thanks to *ip policy routing*, the return packet will pass through a specific routing table directing it to the connection outgoing interface. ## The uplink monitor daemon The daemon monitors the state of the uplinks by routinely pinging well known IP addresses through each uplink: if enough pings are successful the uplink is considered up, if not it's considered down. If an uplink state change is detected, the default *multipath routing* table (used for LAN/DMZ to WAN new connections) is changed accordingly and the administrator is notified by email. The IP addresses to ping and the number of required successful pings are configurable. Here are some things to consider in order not to get false positives or negatives: * Some ping packets can randomly get lost along the way: do not require 100% of the pings to be successful! * Some of the hosts you are pinging (see *tests/ips* configuration parameter) may be temporarily down. * It's better not to ping too near hosts (for example your provider routers), because your provider could be temporarily disconnected from the rest of the internet (it happened to me), so the uplink would look as up while it's actually unusable. * Sometimes an uplink can be not completely up or down, it can be just "disturbed", losing a high percentage of packets and being almost unusable: it's better to consider such uplink as down, so do not require too few successful pings, otherwise it may be considered up, because a few pings may pass through a "disturbed" link. The order of IP addresses listed in *tests/ips* configuration parameter is not important, because the list is shuffled before every uplink check. ## Requirements * [Ruby](https://www.ruby-lang.org) * A Linux kernel with the following compiled in options (they are standard in mainstream Linux distributions): * CONFIG_IP_ADVANCED_ROUTER * CONFIG_IP_MULTIPLE_TABLES * CONFIG_IP_ROUTE_MULTIPATH ## Installation `$ gem install fault_tolerant_router` ## Usage Fault Tolerant Router should be run **as root**, or as an high privileges user, able to modify routing, etc. 1. Configure your router interfaces as usual, with every uplink connected to it's own physical interface. An interface may have more than one IP address if needed (from the same uplink of course). **Don't** set any default route. 2. Save an example configuration file in /etc/fault_tolerant_router.conf (use the `--config` option to set another location): `$ fault_tolerant_router generate_config` 3. Edit /etc/fault_tolerant_router.conf 4. _(Optional)_ Demo how Fault Tolerant Router works, to familiarize with it: `$ fault_tolerant_router --demo monitor` 5. Generate *iptables* rules and integrate them with your existing ones: `$ fault_tolerant_router generate_iptables` 6. _(Optional)_ Test email notification, to be sure SMTP parameters are correct and the administrator will get notifications: `$ fault_tolerant_router email_test` 7. Run the daemon: `$ fault_tolerant_router monitor` Previous command will actually run Fault Tolerant Router in foreground. To run it in background you should use your Linux distribution specific method to start it as a system service. See for example [start-stop-daemon](http://manned.org/start-stop-daemon). If you want a quick and dirty way to run the program in background, just add an ampersand at the end of the command line: `$ fault_tolerant_router monitor &` ## Configuration file The fault_tolerant_router.conf configuration file is in [YAML](http://en.wikipedia.org/wiki/YAML) format. Here is the explanation of the parameters: * **uplinks**: Array of uplinks. The example configuration has 3 uplinks, but you can have from 2 to as many as you wish. * **interface**: The network interface where the uplink is connected. Until today Fault Tolerant Router has always been used with each uplink on it's own physical interface, never tried it with VLAN interfaces (it's in the to do list). * **type**: Specify *static* for any kind of static IP interface or *ppp* for a PPP dynamic IP interface. * **ip**: Primary IP address of the network interface. You can have more than one IP address assigned to the interface, just specify here the primary one that will be used as standard SNAT source. Omit this parameter in case of a PPP dynamic IP interface. * **gateway**: The uplink gateway, usually the provider's router IP address. Omit this parameter in case of a PPP dynamic IP interface. * **description**: Uplink name, used in notifications. * **priority_group**: An integer value, representing the priority group the uplink is assigned to. Priority groups with lower values have higher priority. A priority group is considered available when at least one of its members is up. When choosing a default route, available priority groups are selected, then the highest priority of these is choosen and it's members are load balanced: lower priority group members are not used. That's useful for example to only use pay-per-traffic uplinks if no regular uplink is working: just set the pay-per-traffic uplinks to a lower priority then the regular. If no value is specified, the uplink is excluded from the *multipath routing*, i.e. the uplink will never be selected when choosing one for a new outgoing connection. There's an exception to this if some kind of outgoing connection is forced to pass through this uplink, see [Iptables rules](#iptables-rules) section. Note this parameter only affects outgoing connections: even if no value is specified incoming connections are still possible. Use cases to left this parameter empty: * Want to reserve an uplink for incoming connections only, excluding it from outgoing LAN internet traffic. Tipically you may want this because you have a mail server, web server, VPN server, etc. listening on an uplink. * Temporarily force all of the outgoing LAN internet traffic to pass through the other uplinks, to stress test them and determine their bandwidth. * Temporarily exclude an uplink to reconfigure it, for example because of and internet provider change. * **weight**: Optional parameter, it's the preference to assign to this uplink when choosing one for a new outgoing connection. Use when you have uplinks with different bandwidths. See http://www.policyrouting.org/PolicyRoutingBook/ONLINE/CH05.web.html * **downlinks** * **lan**: LAN interface * **dmz**: DMZ interface, leave blank if you have no DMZ * **tests** * **ips**: An array of IP addresses to ping to verify the uplinks state. You can add as many as you wish. Predefined ones are Google DNS, OpenDNS DNS, other public DNS. Every time an uplink is tested the IP addresses are shuffled, so listing order is not important. * **required_successful**: Number of successfully pinged IP addresses to consider an uplink to be functional * **ping_retries**: Number of ping retries before giving up on an IP * **interval**: Seconds between a check of the uplinks and the next one * **log** * **file**: Log file path * **max_size**: Maximum log file size (in bytes). Once reached this size, the log file will be rotated. * **old_files**: Number of old rotated files to keep * **email** * **send**: Set to *true* or *false* to enable or disable email notification * **sender**: Email sender * **recipients**: An array of email recipients * **smtp_parameters**: See http://ruby-doc.org/stdlib-2.3.1/libdoc/net/smtp/rdoc/Net/SMTP.html * **base_table**: Base IP route table number, just need to change if you are already using [multiple routing tables](http://lartc.org/howto/lartc.rpdb.html), to avoid overlapping. * **base_priority**: Just need to change if you are already using [ip policy routing](http://lartc.org/howto/lartc.rpdb.html), to avoid overlapping. Must be higher than 32767 (the default routing table priority, see `ip rule` command output). * **base_fwmark**: Just need to change if you are already using packet marking, to avoid overlapping. ## *Iptables* rules *Iptables* rules are generated with the command: `$ fault_tolerant_router generate_iptables` Rules are in [iptables-save](http://manned.org/iptables-save.8) format, you should integrate them with your existing ones. Documentation is included as comments in the output, here is a dump using the standard example configuration: ``` #Integrate with your existing "iptables-save" configuration, or adapt to work #with any other iptables configuration system *mangle :PREROUTING ACCEPT [0:0] :POSTROUTING ACCEPT [0:0] :OUTPUT ACCEPT [0:0] :INPUT ACCEPT [0:0] #New outbound connections: force a connection to use a specific uplink instead #of participating in the multipath routing. This can be useful if you have an #SMTP server that should always send emails originating from a specific IP #address (because of PTR DNS records), or if you have some service that you want #always to use a particular slow/fast uplink. # #Uncomment if needed. # #NB: these are just examples, you can add as many options as needed: -s, -d, # --sport, etc. #Example Provider 1 #[0:0] -A PREROUTING -i eth0 -m conntrack --ctstate NEW -p tcp --dport XXX -j CONNMARK --set-mark 1 #Example Provider 2 #[0:0] -A PREROUTING -i eth0 -m conntrack --ctstate NEW -p tcp --dport XXX -j CONNMARK --set-mark 2 #Example Provider 3 #[0:0] -A PREROUTING -i eth0 -m conntrack --ctstate NEW -p tcp --dport XXX -j CONNMARK --set-mark 3 #Mark packets with the outgoing interface: # #- Established outbound connections: mark non-first packets (first packet will # be marked as 0, as a standard unmerked packet, because the connection has not # yet been marked with CONNMARK --set-mark) # #- New outbound connections: mark first packet, only effective if marking has # been done in the section above # #- Inbound connections: mark returning packets (from LAN/DMZ to WAN) [0:0] -A PREROUTING -i eth0 -j CONNMARK --restore-mark #New inbound connections: mark the connection with the incoming interface. #Example Provider 1 [0:0] -A PREROUTING -i eth1 -m conntrack --ctstate NEW -j CONNMARK --set-mark 1 #Example Provider 2 [0:0] -A PREROUTING -i eth2 -m conntrack --ctstate NEW -j CONNMARK --set-mark 2 #Example Provider 3 [0:0] -A PREROUTING -i ppp0 -m conntrack --ctstate NEW -j CONNMARK --set-mark 3 #New outbound connections: mark the connection with the outgoing interface #(chosen by the multipath routing). #Example Provider 1 [0:0] -A POSTROUTING -o eth1 -m conntrack --ctstate NEW -j CONNMARK --set-mark 1 #Example Provider 2 [0:0] -A POSTROUTING -o eth2 -m conntrack --ctstate NEW -j CONNMARK --set-mark 2 #Example Provider 3 [0:0] -A POSTROUTING -o ppp0 -m conntrack --ctstate NEW -j CONNMARK --set-mark 3 COMMIT *nat :PREROUTING ACCEPT [0:0] :POSTROUTING ACCEPT [0:0] :OUTPUT ACCEPT [0:0] #DNAT: WAN --> LAN/DMZ. The original destination IP (-d) can be any of the IP #addresses assigned to the uplink interface. XXX.XXX.XXX.XXX can be any of your #LAN/DMZ IPs. # #Uncomment if needed. # #NB: these are just examples, you can add as many options as you wish: -s, # --sport, --dport, etc. #Example Provider 1 #[0:0] -A PREROUTING -i eth1 -d 1.0.0.2 -j DNAT --to-destination XXX.XXX.XXX.XXX #Example Provider 2 #[0:0] -A PREROUTING -i eth2 -d 2.0.0.2 -j DNAT --to-destination XXX.XXX.XXX.XXX #Example Provider 3 #[0:0] -A PREROUTING -i ppp0 -j DNAT --to-destination XXX.XXX.XXX.XXX #SNAT: LAN/DMZ --> WAN. Force an outgoing connection to use a specific source #address instead of the default one of the outgoing interface. Of course this #only makes sense if more than one IP address is assigned to the uplink #interface. # #Uncomment if needed. # #NB: these are just examples, you can add as many options as needed: -d, # --sport, --dport, etc. #Example Provider 1 #[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o eth1 -j SNAT --to-source YYY.YYY.YYY.YYY #Example Provider 2 #[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o eth2 -j SNAT --to-source YYY.YYY.YYY.YYY #Example Provider 3 #[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o ppp0 -j SNAT --to-source YYY.YYY.YYY.YYY #SNAT: LAN --> WAN #Example Provider 1 [0:0] -A POSTROUTING -o eth1 -j SNAT --to-source 1.0.0.2 #Example Provider 2 [0:0] -A POSTROUTING -o eth2 -j SNAT --to-source 2.0.0.2 #Example Provider 3 [0:0] -A POSTROUTING -o ppp0 -j MASQUERADE COMMIT *filter :INPUT DROP [0:0] :FORWARD DROP [0:0] :OUTPUT ACCEPT [0:0] :LAN_WAN - [0:0] :WAN_LAN - [0:0] #This is just a very basic example, add your own rules for the FORWARD chain. [0:0] -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT [0:0] -A FORWARD -i eth0 -o eth1 -j LAN_WAN [0:0] -A FORWARD -i eth0 -o eth2 -j LAN_WAN [0:0] -A FORWARD -i eth0 -o ppp0 -j LAN_WAN [0:0] -A FORWARD -i eth1 -o eth0 -j WAN_LAN [0:0] -A FORWARD -i eth2 -o eth0 -j WAN_LAN [0:0] -A FORWARD -i ppp0 -o eth0 -j WAN_LAN [0:0] -A LAN_WAN -j ACCEPT [0:0] -A WAN_LAN -j REJECT COMMIT ``` ## Changelog * v1.0.0: First release * v1.1.0: Dynamic IP PPP interfaces support * v1.2.0: Uplink priority groups ## To do See [issues](https://github.com/drsound/fault_tolerant_router/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement) tagged as *enhancement* on GitHub. ## License GNU General Public License v2.0, see LICENSE file ## Author Alessandro Zarrilli (Firenze - Italy) alessandro@zarrilli.net ================================================ FILE: Rakefile ================================================ require 'bundler/gem_tasks' ================================================ FILE: bin/fault_tolerant_router ================================================ #!/usr/bin/env ruby require 'optparse' require 'net/smtp' require 'mail' require 'logger' require 'socket' require 'yaml' require 'fault_tolerant_router/version' require 'fault_tolerant_router/generate_config' require 'fault_tolerant_router/generate_iptables' require 'fault_tolerant_router/monitor' require 'fault_tolerant_router/uplink' require 'fault_tolerant_router/uplinks' CONFIG_TEMPLATE = { 'uplinks' => { 'interface' => {}, 'type' => {}, 'ip' => {}, 'gateway' => {}, 'description' => {}, 'weight' => {}, 'priority_group' => {} }, 'downlinks' => { 'lan' => {}, 'dmz' => {} }, 'tests' => { 'ips' => {}, 'required_successful' => {}, 'ping_retries' => {}, 'interval' => {} }, 'log' => { 'file' => {}, 'max_size' => {}, 'old_files' => {} }, 'email' => { 'send' => {}, 'sender' => {}, 'recipients' => {}, 'smtp_parameters' => { 'address' => {}, 'port' => {}, 'authentication' => {}, 'enable_starttls_auto' => {}, 'user_name' => {}, 'password' => {} } }, 'base_table' => {}, 'base_priority' => {}, 'base_fwmark' => {} } def check_config(config, template, path = []) config.each do |k, v| unless template.keys.include?(k) puts "Error: unknown configuration parameter '#{(path + [k]).join('/')}'" exit 1 end case v when Hash check_config(v, template[k], path + [k]) when Array v.each { |v2| check_config(v2, template[k], path + [k]) if v2.is_a?(Hash) } end end end options = { configuration_file: '/etc/fault_tolerant_router.conf', debug: false, demo: false } parser = OptionParser.new do |opts| opts.banner = "Usage: #{File.basename($0)} [OPTION]... ACTION" opts.separator '' opts.separator 'ACTION = generate_config|generate_iptables|email_test|monitor' opts.separator '' opts.separator ' generate_config: save an example configuration' opts.separator ' generate_iptables: generate an "iptables-save" configuration' opts.separator ' email_test: send a test email to verify the correctness of SMTP parameters' opts.separator ' monitor: monitor uplinks and change routing accordingly' opts.separator '' opts.separator 'OPTIONS:' opts.on('--config=FILE', 'Configuration file (default /etc/fault_tolerant_router.conf)') do |configuration_file| options[:configuration_file] = configuration_file end opts.separator ' "monitor" specific options:' opts.on('--debug', 'Print debug output') do |debug| options[:debug] = debug end opts.on('--demo', 'Demo the program by faking random uplink failures') do |demo| options[:demo] = demo end opts.separator '' opts.separator "Version #{FaultTolerantRouter::VERSION}" opts.separator 'Alessandro Zarrilli ' opts.separator 'https://github.com/drsound/fault_tolerant_router' end begin parser.parse! rescue OptionParser::ParseError puts parser.help exit 1 end DEMO = options[:demo] #activate debug if in demo mode DEBUG = options[:debug] || DEMO unless ARGV.size == 1 && %w(generate_config generate_iptables email_test monitor).include?(ARGV[0]) puts parser.help exit 1 end if ARGV[0] == 'generate_config' generate_config(options[:configuration_file]) exit 0 end unless File.exists?(options[:configuration_file]) puts "Configuration file #{options[:configuration_file]} does not exists!" exit 1 end config = YAML.load_file(options[:configuration_file]) check_config(config, CONFIG_TEMPLATE) LAN_INTERFACE = config['downlinks']['lan'] DMZ_INTERFACE = config['downlinks']['dmz'] TEST_IPS = config['tests']['ips'] REQUIRED_SUCCESSFUL_TESTS = config['tests']['required_successful'] PING_RETRIES = config['tests']['ping_retries'] TEST_INTERVAL = config['tests']['interval'] LOG_FILE = config['log']['file'] LOG_MAX_SIZE = config['log']['max_size'] LOG_OLD_FILES = config['log']['old_files'] SEND_EMAIL = config['email']['send'] EMAIL_SENDER = config['email']['sender'] EMAIL_RECIPIENTS = config['email']['recipients'] SMTP_PARAMETERS = Hash[config['email']['smtp_parameters'].map { |k, v| [k.to_sym, v] }] BASE_TABLE = config['base_table'] BASE_PRIORITY = config['base_priority'] BASE_FWMARK = config['base_fwmark'] UPLINKS = Uplinks.new(config['uplinks']) case ARGV[0] when 'generate_iptables' generate_iptables when 'email_test' begin send_email('fault_tolerant_router test') puts "Test email sent to #{EMAIL_RECIPIENTS.join(', ')}" rescue Exception => e puts "Error sending email: #{e}" end else monitor end ================================================ FILE: fault_tolerant_router.gemspec ================================================ # coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'fault_tolerant_router/version' Gem::Specification.new do |spec| spec.name = 'fault_tolerant_router' spec.version = FaultTolerantRouter::VERSION spec.authors = ['Alessandro Zarrilli'] spec.email = ['alessandro@zarrilli.net'] spec.summary = %q{Multiple uplinks Linux routing supervising daemon} spec.description = %q{A daemon, running in background on a Linux router or firewall, monitoring the state of multiple internet uplinks and changing the routing accordingly. LAN/DMZ internet traffic (outgoing connections) is load balanced between the uplinks using Linux multipath routing. The daemon monitors the state of the uplinks by routinely pinging well known IP addresses (Google public DNS servers, etc.) through each outgoing interface: once an uplink goes down, it is excluded from the multipath routing, when it comes back up, it is included again. An uplink may be assigned to a priority group: lower priority uplinks will only be used if all higher priority ones are down. That's useful to only use pay-per-traffic uplinks if no regular uplink is working. All of the routing changes are notified to the administrator by email. Fault Tolerant Router is well tested and has been used in production for several years, in several sites. See https://github.com/drsound/fault_tolerant_router for full documentation.} spec.homepage = 'https://github.com/drsound/fault_tolerant_router' spec.license = 'GPL-2' spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ['lib'] spec.add_development_dependency 'bundler' spec.add_development_dependency 'rake' spec.add_runtime_dependency 'mail', '~> 2.6' end ================================================ FILE: lib/fault_tolerant_router/generate_config.rb ================================================ def generate_config(file_path) if File.exist?(file_path) puts "Configuration file #{file_path} already exists, will not overwrite!" exit 1 end begin open(file_path, 'w') do |file| file.puts < LAN/DMZ. The original destination IP (-d) can be any of the IP #addresses assigned to the uplink interface. XXX.XXX.XXX.XXX can be any of your #LAN/DMZ IPs. # #Uncomment if needed. # #NB: these are just examples, you can add as many options as you wish: -s, # --sport, --dport, etc. END UPLINKS.each do |uplink| puts "##{uplink.description}" if uplink.type == :ppp puts "#[0:0] -A PREROUTING -i #{uplink.interface} -j DNAT --to-destination XXX.XXX.XXX.XXX" else puts "#[0:0] -A PREROUTING -i #{uplink.interface} -d #{uplink.ip} -j DNAT --to-destination XXX.XXX.XXX.XXX" end end puts < WAN. Force an outgoing connection to use a specific source #address instead of the default one of the outgoing interface. Of course this #only makes sense if more than one IP address is assigned to the uplink #interface. # #Uncomment if needed. # #NB: these are just examples, you can add as many options as needed: -d, # --sport, --dport, etc. END UPLINKS.each do |uplink| puts "##{uplink.description}" puts "#[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o #{uplink.interface} -j SNAT --to-source YYY.YYY.YYY.YYY" end puts < WAN END UPLINKS.each do |uplink| puts "##{uplink.description}" if uplink.type == :ppp puts "[0:0] -A POSTROUTING -o #{uplink.interface} -j MASQUERADE" else puts "[0:0] -A POSTROUTING -o #{uplink.interface} -j SNAT --to-source #{uplink.ip}" end end puts < e puts "Problem sending email: #{e}" if DEBUG logger.error("Problem sending email: #{e}") end end if UPLINKS.all_priority_group_members_down? puts 'No waiting, because all of the priority group members are down' if DEBUG elsif DEMO puts "Waiting just 5 seconds because in demo mode, otherwise would be #{TEST_INTERVAL} seconds..." if DEBUG sleep 5 else puts "Waiting #{TEST_INTERVAL} seconds..." if DEBUG sleep TEST_INTERVAL end end end ================================================ FILE: lib/fault_tolerant_router/uplink.rb ================================================ class Uplink attr_reader :description, :fwmark, :gateway, :id, :interface, :ip, :previous_gateway, :previous_ip, :previously_up, :priority_group, :rule_priority_1, :table, :type, :up, :weight attr_accessor :default_route, :previously_default_route, :rule_priority_2 def initialize(config, id) @id = id @rule_priority_1 = BASE_PRIORITY + @id @table = BASE_TABLE + @id @fwmark = BASE_FWMARK + @id @interface = config['interface'] unless @interface puts 'Error: uplink interface not specified' exit 1 end @type = case config['type'] when 'static' :static when 'ppp' :ppp else puts "Error: '#{config['type']}' is not a valid uplink type" exit 1 end @description = config['description'] unless @description puts 'Error: uplink description not specified' exit 1 end @weight = config['weight'] @priority_group = config['priority_group'] @default_route = false if @type == :static @ip = config['ip'] unless @ip puts 'Error: uplink IP not specified' exit 1 end @gateway = config['gateway'] unless @gateway puts 'Error: uplink gateway not specified' exit 1 end else detect_ppp_ips! end @previous_ip = @ip @previous_gateway = @gateway #a new uplink is supposed to be up @up = true @previously_up = true end def detect_ppp_ips! @previous_ip = @ip @previous_gateway = @gateway if DEMO @ip = ['3.0.0.101', '3.0.0.102', nil].sample @gateway = ['3.0.0.1', '3.0.0.2', nil].sample else ifaddr = Socket.getifaddrs.find { |i| i.name == @interface && i.addr && i.addr.ipv4? } if ifaddr @ip = ifaddr.addr.ip_address @gateway = ifaddr.dstaddr.ip_address else @ip = nil @gateway = nil end end puts "Uplink #{@description}: detected ip #{@ip || 'none'}, gateway #{@gateway || 'none'}" if DEBUG end def ping(ip_address) if DEMO sleep 0.1 rand(3) > 0 else `ping -n -c 1 -W 2 -I #{@ip} #{ip_address}` $?.to_i == 0 end end def test! #save current state @previously_up = @up successful_tests = 0 unsuccessful_tests = 0 commands = [] if @type == :ppp detect_ppp_ips! if (@previous_ip != @ip) || (@previous_gateway != @gateway) #only apply routing commands if there are an ip and gateway, else they will be applied on next checks, whenever new ip and gateway will be available if @ip && @gateway commands << "ip rule del priority #{@rule_priority_1}" commands << "ip rule del priority #{@rule_priority_2}" commands += route_add_commands end end end #do not ping if there is no ip or gateway (for example in case of a PPP interface down) if @ip && @gateway #for each test (in random order)... TEST_IPS.shuffle.each_with_index do |test, i| successful_test = false #retry for several times... PING_RETRIES.times do if DEBUG print "Uplink #{@description}: ping #{test}... " STDOUT.flush end if ping(test) successful_test = true puts 'ok' if DEBUG #avoid more pings to the same ip after a successful one break else puts 'error' if DEBUG end end if successful_test successful_tests += 1 else unsuccessful_tests += 1 end #if not currently doing the last test... if i + 1 < TEST_IPS.size if successful_tests >= REQUIRED_SUCCESSFUL_TESTS puts "Uplink #{@description}: avoiding more tests because there are enough positive ones" if DEBUG break elsif TEST_IPS.size - unsuccessful_tests < REQUIRED_SUCCESSFUL_TESTS puts "Uplink #{@description}: avoiding more tests because too many have been failed" if DEBUG break end end end end @up = successful_tests >= REQUIRED_SUCCESSFUL_TESTS if DEBUG state = @previously_up ? 'up' : 'down' state += " --> #{@up ? 'up' : 'down'}" if @up != @previously_up puts "Uplink #{@description}: #{successful_tests} successful tests, #{unsuccessful_tests} unsuccessful tests, state #{state}" end commands end def route_add_commands #- locally generated packets having as source ip the ethX ip #- returning packets of inbound connections coming from ethX #- non-first packets of outbound connections for which the first packet has been sent to ethX via multipath routing [ "ip route replace table #{@table} default via #{@gateway} src #{@ip}", "ip rule add priority #{@rule_priority_1} from #{@ip} lookup #{@table}", "ip rule add priority #{@rule_priority_2} fwmark #{@fwmark} lookup #{@table}" ] end end ================================================ FILE: lib/fault_tolerant_router/uplinks.rb ================================================ class Uplinks include Enumerable def initialize(config) @uplinks = config.each_with_index.map { |uplink, i| Uplink.new(uplink, i) } @uplinks.each { |uplink| uplink.rule_priority_2 = BASE_PRIORITY + @uplinks.size + uplink.id } @default_route_table = @uplinks.map { |uplink| uplink.table }.max + 1 end def each @uplinks.each { |uplink| yield uplink } end def initialize_routing! commands = [] rule_priorities = @uplinks.map { |uplink| [uplink.rule_priority_1, uplink.rule_priority_2] }.flatten.minmax tables = @uplinks.map { |uplink| uplink.table }.minmax #enable IP forwarding commands << 'echo 1 > /proc/sys/net/ipv4/ip_forward' #clean all previous configurations, try to clean more than needed (double) to avoid problems in case of changes in the #number of uplinks between different executions ((rule_priorities.max - rule_priorities.min + 2) * 2).times { |i| commands << "ip rule del priority #{rule_priorities.min + i} &> /dev/null" } ((tables.max - tables.min + 2) * 2).times { |i| commands << "ip route del table #{tables.min + i} &> /dev/null" } #disable "reverse path filtering" on the uplink interfaces commands << 'echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter' commands += @uplinks.map { |uplink| "echo 2 > /proc/sys/net/ipv4/conf/#{uplink.interface}/rp_filter" } #set uplinks routes commands += @uplinks.map { |uplink| uplink.route_add_commands } #rule for first packet of outbound connections commands << "ip rule add priority #{rule_priorities.max + 1} from all lookup #{tables.max + 1}" #set default route commands += update_default_route! #apply the routing changes commands << 'ip route flush cache' commands.flatten end def update_default_route! #select uplinks that are up and with a specified priority group value selected = @uplinks.find_all { |uplink| uplink.up && uplink.priority_group } puts "Choosing default route: available uplinks: #{selected.map { |uplink| uplink.description }.join(', ')}" if DEBUG #restrict the selection to the members of highest priority group highest_available_priority = selected.map { |uplink| uplink.priority_group }.min selected = selected.find_all { |uplink| uplink.priority_group == highest_available_priority } puts "Choosing default route: highest priority group uplinks: #{selected.map { |uplink| uplink.description }.join(', ')}" if DEBUG changes = false #assign default route status to the uplinks and detect changes from previous configuration @uplinks.each do |uplink| uplink.previously_default_route = uplink.default_route uplink.default_route = selected.include?(uplink) changes ||= uplink.default_route != uplink.previously_default_route end #check if any default route uplink changed its gateway (for example due to a ppp update) if @uplinks.any? { |uplink| uplink.default_route && uplink.gateway != uplink.previous_gateway } changes ||= true puts "Choosing default route: detected gateway change in a default route uplink" if DEBUG end commands = [] if selected.size == 0 puts 'Choosing default route: no available uplinks, no need for an update' if DEBUG elsif !changes puts 'Choosing default route: no changes, no need for an update' if DEBUG else puts 'Choosing default route: changes detected, update needed' if DEBUG #do not use balancing if there is just one routing uplink if selected.size == 1 nexthops = "via #{selected.first.gateway}" else nexthops = selected.map do |uplink| #the "weight" parameter is optional tail = uplink.weight ? " weight #{uplink.weight}" : '' "nexthop via #{uplink.gateway}#{tail}" end nexthops = nexthops.join(' ') end #set the route for first packet of outbound connections commands << "ip route replace table #{@default_route_table} default #{nexthops}" end commands end def test! commands = [] messages = [] @uplinks.each do |uplink| c = uplink.test! commands += c end commands += update_default_route! #apply the routing changes, in any commands << 'ip route flush cache' if commands.any? changes = false @uplinks.each do |uplink| current = uplink.ip || 'none' previous = uplink.previous_ip || 'none' changes ||= current != previous ip = current == previous ? current : "#{previous} --> #{current}" current = uplink.gateway || 'none' previous = uplink.previous_gateway || 'none' changes ||= current != previous gateway = current == previous ? current : "#{previous} --> #{current}" current = uplink.up ? 'up' : 'down' previous = uplink.previously_up ? 'up' : 'down' changes ||= current != previous up = current == previous ? current : "#{previous} --> #{current}" current = uplink.default_route ? 'routing' : 'standby' previous = uplink.previously_default_route ? 'routing' : 'standby' changes ||= current != previous default_route = current == previous ? current : "#{previous} --> #{current}" messages << "Uplink #{uplink.description}: ip #{ip}, gateway #{gateway}, #{up}, #{default_route}" end messages = [] unless changes [commands, messages] end def all_priority_group_members_down? @uplinks.all? { |uplink| !uplink.priority_group || !uplink.up } end end ================================================ FILE: lib/fault_tolerant_router/version.rb ================================================ module FaultTolerantRouter VERSION = '1.2.0' end