fault_tolerant_router 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 2c69907fbd38de0ff105840c14d481fe9cacdca4
4
+ data.tar.gz: 17fb44fca49be4915537d43832aed800a35f8a99
5
+ SHA512:
6
+ metadata.gz: 919e67ecec171564be6b4006601a70fc272855a4b2f1c69303f1b1cab598bd4db13f43dbfc19620a32e69371a447bc54fa6d505afe03c18181cca3db2699c571
7
+ data.tar.gz: 5ade1292b33e980528caac4f81d91cd1f572a8cd358c98b795765dfbb97b6081bf995f843c27f2e15b7ab10eba73afae311bf252ecbef536698a14b93ec5c1d0
data/.gitignore ADDED
@@ -0,0 +1,23 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
18
+ *.bundle
19
+ *.so
20
+ *.o
21
+ *.a
22
+ mkmf.log
23
+ .idea/
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in fault_tolerant_router.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,340 @@
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 2, June 1991
3
+
4
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc., <http://fsf.org/>
5
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
+ Everyone is permitted to copy and distribute verbatim copies
7
+ of this license document, but changing it is not allowed.
8
+
9
+ Preamble
10
+
11
+ The licenses for most software are designed to take away your
12
+ freedom to share and change it. By contrast, the GNU General Public
13
+ License is intended to guarantee your freedom to share and change free
14
+ software--to make sure the software is free for all its users. This
15
+ General Public License applies to most of the Free Software
16
+ Foundation's software and to any other program whose authors commit to
17
+ using it. (Some other Free Software Foundation software is covered by
18
+ the GNU Lesser General Public License instead.) You can apply it to
19
+ your programs, too.
20
+
21
+ When we speak of free software, we are referring to freedom, not
22
+ price. Our General Public Licenses are designed to make sure that you
23
+ have the freedom to distribute copies of free software (and charge for
24
+ this service if you wish), that you receive source code or can get it
25
+ if you want it, that you can change the software or use pieces of it
26
+ in new free programs; and that you know you can do these things.
27
+
28
+ To protect your rights, we need to make restrictions that forbid
29
+ anyone to deny you these rights or to ask you to surrender the rights.
30
+ These restrictions translate to certain responsibilities for you if you
31
+ distribute copies of the software, or if you modify it.
32
+
33
+ For example, if you distribute copies of such a program, whether
34
+ gratis or for a fee, you must give the recipients all the rights that
35
+ you have. You must make sure that they, too, receive or can get the
36
+ source code. And you must show them these terms so they know their
37
+ rights.
38
+
39
+ We protect your rights with two steps: (1) copyright the software, and
40
+ (2) offer you this license which gives you legal permission to copy,
41
+ distribute and/or modify the software.
42
+
43
+ Also, for each author's protection and ours, we want to make certain
44
+ that everyone understands that there is no warranty for this free
45
+ software. If the software is modified by someone else and passed on, we
46
+ want its recipients to know that what they have is not the original, so
47
+ that any problems introduced by others will not reflect on the original
48
+ authors' reputations.
49
+
50
+ Finally, any free program is threatened constantly by software
51
+ patents. We wish to avoid the danger that redistributors of a free
52
+ program will individually obtain patent licenses, in effect making the
53
+ program proprietary. To prevent this, we have made it clear that any
54
+ patent must be licensed for everyone's free use or not licensed at all.
55
+
56
+ The precise terms and conditions for copying, distribution and
57
+ modification follow.
58
+
59
+ GNU GENERAL PUBLIC LICENSE
60
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
+
62
+ 0. This License applies to any program or other work which contains
63
+ a notice placed by the copyright holder saying it may be distributed
64
+ under the terms of this General Public License. The "Program", below,
65
+ refers to any such program or work, and a "work based on the Program"
66
+ means either the Program or any derivative work under copyright law:
67
+ that is to say, a work containing the Program or a portion of it,
68
+ either verbatim or with modifications and/or translated into another
69
+ language. (Hereinafter, translation is included without limitation in
70
+ the term "modification".) Each licensee is addressed as "you".
71
+
72
+ Activities other than copying, distribution and modification are not
73
+ covered by this License; they are outside its scope. The act of
74
+ running the Program is not restricted, and the output from the Program
75
+ is covered only if its contents constitute a work based on the
76
+ Program (independent of having been made by running the Program).
77
+ Whether that is true depends on what the Program does.
78
+
79
+ 1. You may copy and distribute verbatim copies of the Program's
80
+ source code as you receive it, in any medium, provided that you
81
+ conspicuously and appropriately publish on each copy an appropriate
82
+ copyright notice and disclaimer of warranty; keep intact all the
83
+ notices that refer to this License and to the absence of any warranty;
84
+ and give any other recipients of the Program a copy of this License
85
+ along with the Program.
86
+
87
+ You may charge a fee for the physical act of transferring a copy, and
88
+ you may at your option offer warranty protection in exchange for a fee.
89
+
90
+ 2. You may modify your copy or copies of the Program or any portion
91
+ of it, thus forming a work based on the Program, and copy and
92
+ distribute such modifications or work under the terms of Section 1
93
+ above, provided that you also meet all of these conditions:
94
+
95
+ a) You must cause the modified files to carry prominent notices
96
+ stating that you changed the files and the date of any change.
97
+
98
+ b) You must cause any work that you distribute or publish, that in
99
+ whole or in part contains or is derived from the Program or any
100
+ part thereof, to be licensed as a whole at no charge to all third
101
+ parties under the terms of this License.
102
+
103
+ c) If the modified program normally reads commands interactively
104
+ when run, you must cause it, when started running for such
105
+ interactive use in the most ordinary way, to print or display an
106
+ announcement including an appropriate copyright notice and a
107
+ notice that there is no warranty (or else, saying that you provide
108
+ a warranty) and that users may redistribute the program under
109
+ these conditions, and telling the user how to view a copy of this
110
+ License. (Exception: if the Program itself is interactive but
111
+ does not normally print such an announcement, your work based on
112
+ the Program is not required to print an announcement.)
113
+
114
+ These requirements apply to the modified work as a whole. If
115
+ identifiable sections of that work are not derived from the Program,
116
+ and can be reasonably considered independent and separate works in
117
+ themselves, then this License, and its terms, do not apply to those
118
+ sections when you distribute them as separate works. But when you
119
+ distribute the same sections as part of a whole which is a work based
120
+ on the Program, the distribution of the whole must be on the terms of
121
+ this License, whose permissions for other licensees extend to the
122
+ entire whole, and thus to each and every part regardless of who wrote it.
123
+
124
+ Thus, it is not the intent of this section to claim rights or contest
125
+ your rights to work written entirely by you; rather, the intent is to
126
+ exercise the right to control the distribution of derivative or
127
+ collective works based on the Program.
128
+
129
+ In addition, mere aggregation of another work not based on the Program
130
+ with the Program (or with a work based on the Program) on a volume of
131
+ a storage or distribution medium does not bring the other work under
132
+ the scope of this License.
133
+
134
+ 3. You may copy and distribute the Program (or a work based on it,
135
+ under Section 2) in object code or executable form under the terms of
136
+ Sections 1 and 2 above provided that you also do one of the following:
137
+
138
+ a) Accompany it with the complete corresponding machine-readable
139
+ source code, which must be distributed under the terms of Sections
140
+ 1 and 2 above on a medium customarily used for software interchange; or,
141
+
142
+ b) Accompany it with a written offer, valid for at least three
143
+ years, to give any third party, for a charge no more than your
144
+ cost of physically performing source distribution, a complete
145
+ machine-readable copy of the corresponding source code, to be
146
+ distributed under the terms of Sections 1 and 2 above on a medium
147
+ customarily used for software interchange; or,
148
+
149
+ c) Accompany it with the information you received as to the offer
150
+ to distribute corresponding source code. (This alternative is
151
+ allowed only for noncommercial distribution and only if you
152
+ received the program in object code or executable form with such
153
+ an offer, in accord with Subsection b above.)
154
+
155
+ The source code for a work means the preferred form of the work for
156
+ making modifications to it. For an executable work, complete source
157
+ code means all the source code for all modules it contains, plus any
158
+ associated interface definition files, plus the scripts used to
159
+ control compilation and installation of the executable. However, as a
160
+ special exception, the source code distributed need not include
161
+ anything that is normally distributed (in either source or binary
162
+ form) with the major components (compiler, kernel, and so on) of the
163
+ operating system on which the executable runs, unless that component
164
+ itself accompanies the executable.
165
+
166
+ If distribution of executable or object code is made by offering
167
+ access to copy from a designated place, then offering equivalent
168
+ access to copy the source code from the same place counts as
169
+ distribution of the source code, even though third parties are not
170
+ compelled to copy the source along with the object code.
171
+
172
+ 4. You may not copy, modify, sublicense, or distribute the Program
173
+ except as expressly provided under this License. Any attempt
174
+ otherwise to copy, modify, sublicense or distribute the Program is
175
+ void, and will automatically terminate your rights under this License.
176
+ However, parties who have received copies, or rights, from you under
177
+ this License will not have their licenses terminated so long as such
178
+ parties remain in full compliance.
179
+
180
+ 5. You are not required to accept this License, since you have not
181
+ signed it. However, nothing else grants you permission to modify or
182
+ distribute the Program or its derivative works. These actions are
183
+ prohibited by law if you do not accept this License. Therefore, by
184
+ modifying or distributing the Program (or any work based on the
185
+ Program), you indicate your acceptance of this License to do so, and
186
+ all its terms and conditions for copying, distributing or modifying
187
+ the Program or works based on it.
188
+
189
+ 6. Each time you redistribute the Program (or any work based on the
190
+ Program), the recipient automatically receives a license from the
191
+ original licensor to copy, distribute or modify the Program subject to
192
+ these terms and conditions. You may not impose any further
193
+ restrictions on the recipients' exercise of the rights granted herein.
194
+ You are not responsible for enforcing compliance by third parties to
195
+ this License.
196
+
197
+ 7. If, as a consequence of a court judgment or allegation of patent
198
+ infringement or for any other reason (not limited to patent issues),
199
+ conditions are imposed on you (whether by court order, agreement or
200
+ otherwise) that contradict the conditions of this License, they do not
201
+ excuse you from the conditions of this License. If you cannot
202
+ distribute so as to satisfy simultaneously your obligations under this
203
+ License and any other pertinent obligations, then as a consequence you
204
+ may not distribute the Program at all. For example, if a patent
205
+ license would not permit royalty-free redistribution of the Program by
206
+ all those who receive copies directly or indirectly through you, then
207
+ the only way you could satisfy both it and this License would be to
208
+ refrain entirely from distribution of the Program.
209
+
210
+ If any portion of this section is held invalid or unenforceable under
211
+ any particular circumstance, the balance of the section is intended to
212
+ apply and the section as a whole is intended to apply in other
213
+ circumstances.
214
+
215
+ It is not the purpose of this section to induce you to infringe any
216
+ patents or other property right claims or to contest validity of any
217
+ such claims; this section has the sole purpose of protecting the
218
+ integrity of the free software distribution system, which is
219
+ implemented by public license practices. Many people have made
220
+ generous contributions to the wide range of software distributed
221
+ through that system in reliance on consistent application of that
222
+ system; it is up to the author/donor to decide if he or she is willing
223
+ to distribute software through any other system and a licensee cannot
224
+ impose that choice.
225
+
226
+ This section is intended to make thoroughly clear what is believed to
227
+ be a consequence of the rest of this License.
228
+
229
+ 8. If the distribution and/or use of the Program is restricted in
230
+ certain countries either by patents or by copyrighted interfaces, the
231
+ original copyright holder who places the Program under this License
232
+ may add an explicit geographical distribution limitation excluding
233
+ those countries, so that distribution is permitted only in or among
234
+ countries not thus excluded. In such case, this License incorporates
235
+ the limitation as if written in the body of this License.
236
+
237
+ 9. The Free Software Foundation may publish revised and/or new versions
238
+ of the General Public License from time to time. Such new versions will
239
+ be similar in spirit to the present version, but may differ in detail to
240
+ address new problems or concerns.
241
+
242
+ Each version is given a distinguishing version number. If the Program
243
+ specifies a version number of this License which applies to it and "any
244
+ later version", you have the option of following the terms and conditions
245
+ either of that version or of any later version published by the Free
246
+ Software Foundation. If the Program does not specify a version number of
247
+ this License, you may choose any version ever published by the Free Software
248
+ Foundation.
249
+
250
+ 10. If you wish to incorporate parts of the Program into other free
251
+ programs whose distribution conditions are different, write to the author
252
+ to ask for permission. For software which is copyrighted by the Free
253
+ Software Foundation, write to the Free Software Foundation; we sometimes
254
+ make exceptions for this. Our decision will be guided by the two goals
255
+ of preserving the free status of all derivatives of our free software and
256
+ of promoting the sharing and reuse of software generally.
257
+
258
+ NO WARRANTY
259
+
260
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
+ FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
+ OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
+ PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
+ OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
+ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
+ TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
+ PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
+ REPAIR OR CORRECTION.
269
+
270
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
+ REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
+ INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
+ OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
+ TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
+ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
+ PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
+ POSSIBILITY OF SUCH DAMAGES.
279
+
280
+ END OF TERMS AND CONDITIONS
281
+
282
+ How to Apply These Terms to Your New Programs
283
+
284
+ If you develop a new program, and you want it to be of the greatest
285
+ possible use to the public, the best way to achieve this is to make it
286
+ free software which everyone can redistribute and change under these terms.
287
+
288
+ To do so, attach the following notices to the program. It is safest
289
+ to attach them to the start of each source file to most effectively
290
+ convey the exclusion of warranty; and each file should have at least
291
+ the "copyright" line and a pointer to where the full notice is found.
292
+
293
+ {description}
294
+ Copyright (C) {year} {fullname}
295
+
296
+ This program is free software; you can redistribute it and/or modify
297
+ it under the terms of the GNU General Public License as published by
298
+ the Free Software Foundation; either version 2 of the License, or
299
+ (at your option) any later version.
300
+
301
+ This program is distributed in the hope that it will be useful,
302
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
303
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
+ GNU General Public License for more details.
305
+
306
+ You should have received a copy of the GNU General Public License along
307
+ with this program; if not, write to the Free Software Foundation, Inc.,
308
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
+
310
+ Also add information on how to contact you by electronic and paper mail.
311
+
312
+ If the program is interactive, make it output a short notice like this
313
+ when it starts in an interactive mode:
314
+
315
+ Gnomovision version 69, Copyright (C) year name of author
316
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
+ This is free software, and you are welcome to redistribute it
318
+ under certain conditions; type `show c' for details.
319
+
320
+ The hypothetical commands `show w' and `show c' should show the appropriate
321
+ parts of the General Public License. Of course, the commands you use may
322
+ be called something other than `show w' and `show c'; they could even be
323
+ mouse-clicks or menu items--whatever suits your program.
324
+
325
+ You should also get your employer (if you work as a programmer) or your
326
+ school, if any, to sign a "copyright disclaimer" for the program, if
327
+ necessary. Here is a sample; alter the names:
328
+
329
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
+
332
+ {signature of Ty Coon}, 1 April 1989
333
+ Ty Coon, President of Vice
334
+
335
+ This General Public License does not permit incorporating your program into
336
+ proprietary programs. If your program is a subroutine library, you may
337
+ consider it more useful to permit linking proprietary applications with the
338
+ library. If this is what you want to do, use the GNU Lesser General
339
+ Public License instead of this License.
340
+
data/README.md ADDED
@@ -0,0 +1,251 @@
1
+ # Fault Tolerant Router
2
+
3
+ Fault Tolerant Router is a daemon, running in background on a Linux router or firewall, monitoring the state of multiple internet uplinks/providers 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. All of the routing changes are notified to the administrator by email.
4
+
5
+ Fault Tolerant Router is well tested and has been used in production for several years, in several sites.
6
+
7
+ ## Interaction between *multipath routing*, *iptables* and *ip policy routing*
8
+ 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:
9
+ * **Outgoing connections (from LAN/DMZ to WAN)**:
10
+ * **New connections**:
11
+ 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.
12
+ 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).
13
+ * **Established connections**:
14
+ 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.
15
+ * **Incoming connections (from WAN to LAN/DMZ)**:
16
+ 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 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.
17
+
18
+ ## The uplink monitor daemon
19
+
20
+ The daemon monitors the state of the uplinks by 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.
21
+
22
+ The IP addresses to ping and the number of required successful pings is configurable. In order not to get false positives or negatives here are some things to consider:
23
+ * Some ping packets can randomly get lost along the way, don't require 100% of the pings to be successful!
24
+ * Some of the hosts you are pinging (*tests/ips* configuration parameter) may be temporarily down.
25
+ * 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...), so your uplink would result as up while it's actually unusable.
26
+ * Sometimes an uplink can be not completely up or completely down, it's just "disturbed" and looses a lot of packets, being almost unusable: it's better to consider such uplink as down, so don't require too few successful pings, otherwise it may be considered up, because a few pings may pass through a "disturbed" link.
27
+
28
+ The order of IP addresses in *tests/ips* configuration parameter is not important, because the list is shuffled before every uplink check.
29
+
30
+ If no uplink is up, all of them are added to the default *multipath routing* table, to get some bandwidth as soon as one uplink comes back up.
31
+
32
+ ## Requirements
33
+ * [Ruby](https://www.ruby-lang.org)
34
+ * A Linux kernel with the following compiled in options (they are standard in mainstream Linux distributions):
35
+ * CONFIG_IP_ADVANCED_ROUTER
36
+ * CONFIG_IP_MULTIPLE_TABLES
37
+ * CONFIG_IP_ROUTE_MULTIPATH
38
+
39
+ ## Installation
40
+ `$ gem install fault_tolerant_router`
41
+
42
+ ## Usage
43
+ 1. Configure your router interfaces as usual but **don't** set any default route. An interface may have more than one IP address if needed.
44
+ 2. Save an example configuration file in /etc/fault_tolerant_router.conf (use the `--config` option to set another location):
45
+ `$ fault_tolerant_router generate_config`
46
+ 3. Edit /etc/fault_tolerant_router.conf
47
+ 4. _(Optional)_ Demo how Fault Tolerant Router works, to familiarize with it:
48
+ `$ fault_tolerant_router --demo monitor`
49
+ 5. Generate *iptables* rules and integrate them with your existing ones:
50
+ `$ fault_tolerant_router generate_iptables`
51
+ 6. _(Optional)_ Test email notification, to be sure SMTP parameters are correct and the administrator will get notifications:
52
+ `$ fault_tolerant_router email_test`
53
+ 7. Run the daemon:
54
+ `$ fault_tolerant_router monitor`
55
+ 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).
56
+ 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:
57
+ `$ fault_tolerant_router monitor &`
58
+
59
+ ## Configuration file
60
+ The fault_tolerant_router.conf configuration file is in [YAML](http://en.wikipedia.org/wiki/YAML) format. Here is the explanation of the options:
61
+ * **uplinks**: array of uplinks. The example configuration has 3 uplinks, but you can have from 2 to as many as you wish.
62
+ * **interface**: the network interface where the uplink is attached. Until today Fault Tolerant Router has always been used with each uplink on it's own physical interface, never tried with VLAN interfaces (it's in the to do list).
63
+ * **ip**: primary IP address of the network interface. You can have more than one IP address assigned to the interface, just specify the primary one.
64
+ * **gateway**: the gateway on this interface, usually the provider's router IP address.
65
+ * **description**: used in the alert emails.
66
+ * **weight**: optional parameter, it's the preference to assign to the 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
67
+ * **default_route**: optional parameter, default value is *true*. If set to *false* the uplink is excluded from the *multipath routing*, i.e. the uplink will never be used when choosing one for a new outgoing connection. Exception to this is if some kind of outgoing connection is forced to pass through this uplink, see [Iptables rules](#iptables-rules) section. Even if set to *false*, incoming connections are still possible. Use cases to set it to *false*:
68
+ * 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, etc. listening on this uplink.
69
+ * Temporarily force all of the outgoing LAN internet traffic to pass through the other uplinks, to stress test the other uplinks and determine their bandwidth
70
+ * Temporarily exclude the uplink to do some reconfiguration, for example changing one of the internet providers.
71
+ * **downlinks**
72
+ * **lan**: LAN interface
73
+ * **dmz**: DMZ interface, leave blank if you have no DMZ
74
+ * **tests**
75
+ * **ips**: an array of IPs 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 ips are shuffled, so listing order has no importance.
76
+ * **required_successful**: number of successfully pinged ips to consider an uplink to be functional
77
+ * **ping_retries**: number of ping retries before giving up on an ip
78
+ * **interval**: seconds between a check of the uplinks and the next one
79
+ * **log**
80
+ * **file**: log file path
81
+ * **max_size**: maximum log file size (in bytes). Once reached this size, the log file will be rotated.
82
+ * **old_files**: number of old rotated files to keep
83
+ * **email**
84
+ * **send**: set to *true* or *false* to enable or disable email notification
85
+ * **sender**: email sender
86
+ * **recipients**: an array of email recipients
87
+ * **smtp_parameters**: see http://ruby-doc.org/stdlib-2.2.0/libdoc/net/smtp/rdoc/Net/SMTP.html
88
+ * **base_table**: just need to change if you are already using [multiple routing tables](http://lartc.org/howto/lartc.rpdb.html), to avoid overlapping
89
+ * **base_priority**: just need to change if you are already using [ip rule](http://lartc.org/howto/lartc.rpdb.html), to avoid overlapping
90
+ * **base_fwmark**: just need to change if you are already using packet marking, to avoid overlapping
91
+
92
+ ## *Iptables* rules
93
+ *Iptables* rules are generated with the command:
94
+ `$ fault_tolerant_router generate_iptables`
95
+ Rules are in [iptables-save](http://manned.org/iptables-save.8) format, you should integrate them with your existing ones.
96
+ Documentation is included as comments in the output, here is a dump using the standard example configuration:
97
+ ```
98
+ #Integrate with your existing "iptables-save" configuration, or adapt to work
99
+ #with any other iptables configuration system
100
+
101
+ *mangle
102
+ :PREROUTING ACCEPT [0:0]
103
+ :POSTROUTING ACCEPT [0:0]
104
+ :OUTPUT ACCEPT [0:0]
105
+ :INPUT ACCEPT [0:0]
106
+
107
+ #New outbound connections: force a connection to use a specific uplink instead
108
+ #of participating in the multipath routing. This can be useful if you have an
109
+ #SMTP server that should always send emails originating from a specific IP
110
+ #address (because of PTR DNS records), or if you have some service that you want
111
+ #always to use a particular slow/fast uplink.
112
+ #
113
+ #Uncomment if needed.
114
+ #
115
+ #NB: these are just examples, you can add as many options as needed: -s, -d,
116
+ # --sport, etc.
117
+
118
+ #Example Provider 1
119
+ #[0:0] -A PREROUTING -i eth0 -m state --state NEW -p tcp --dport XXX -j CONNMARK --set-mark 1
120
+ #Example Provider 2
121
+ #[0:0] -A PREROUTING -i eth0 -m state --state NEW -p tcp --dport XXX -j CONNMARK --set-mark 2
122
+ #Example Provider 3
123
+ #[0:0] -A PREROUTING -i eth0 -m state --state NEW -p tcp --dport XXX -j CONNMARK --set-mark 3
124
+
125
+ #Mark packets with the outgoing interface:
126
+ #
127
+ #- Established outbound connections: mark non-first packets (first packet will
128
+ # be marked as 0, as a standard unmerked packet, because the connection has not
129
+ # yet been marked with CONNMARK --set-mark)
130
+ #
131
+ #- New outbound connections: mark first packet, only effective if marking has
132
+ # been done in the section above
133
+ #
134
+ #- Inbound connections: mark returning packets (from LAN/DMZ to WAN)
135
+
136
+ [0:0] -A PREROUTING -i eth0 -j CONNMARK --restore-mark
137
+
138
+ #New inbound connections: mark the connection with the incoming interface.
139
+
140
+ #Example Provider 1
141
+ [0:0] -A PREROUTING -i eth1 -m state --state NEW -j CONNMARK --set-mark 1
142
+ #Example Provider 2
143
+ [0:0] -A PREROUTING -i eth2 -m state --state NEW -j CONNMARK --set-mark 2
144
+ #Example Provider 3
145
+ [0:0] -A PREROUTING -i eth3 -m state --state NEW -j CONNMARK --set-mark 3
146
+
147
+ #New outbound connections: mark the connection with the outgoing interface
148
+ #(chosen by the multipath routing).
149
+
150
+ #Example Provider 1
151
+ [0:0] -A POSTROUTING -o eth1 -m state --state NEW -j CONNMARK --set-mark 1
152
+ #Example Provider 2
153
+ [0:0] -A POSTROUTING -o eth2 -m state --state NEW -j CONNMARK --set-mark 2
154
+ #Example Provider 3
155
+ [0:0] -A POSTROUTING -o eth3 -m state --state NEW -j CONNMARK --set-mark 3
156
+
157
+ COMMIT
158
+
159
+
160
+ *nat
161
+ :PREROUTING ACCEPT [0:0]
162
+ :POSTROUTING ACCEPT [0:0]
163
+ :OUTPUT ACCEPT [0:0]
164
+
165
+ #DNAT: WAN --> LAN/DMZ. The original destination IP (-d) can be any of the IP
166
+ #addresses assigned to the uplink interface. XXX.XXX.XXX.XXX can be any of your
167
+ #LAN/DMZ IPs.
168
+ #
169
+ #Uncomment if needed.
170
+ #
171
+ #NB: these are just examples, you can add as many options as you wish: -s,
172
+ # --sport, --dport, etc.
173
+
174
+ #Example Provider 1
175
+ #[0:0] -A PREROUTING -i eth1 -d 1.0.0.2 -j DNAT --to-destination XXX.XXX.XXX.XXX
176
+ #Example Provider 2
177
+ #[0:0] -A PREROUTING -i eth2 -d 2.0.0.2 -j DNAT --to-destination XXX.XXX.XXX.XXX
178
+ #Example Provider 3
179
+ #[0:0] -A PREROUTING -i eth3 -d 3.0.0.2 -j DNAT --to-destination XXX.XXX.XXX.XXX
180
+
181
+ #SNAT: LAN/DMZ --> WAN. Force an outgoing connection to use a specific source
182
+ #address instead of the default one of the outgoing interface. Of course this
183
+ #only makes sense if more than one IP address is assigned to the uplink
184
+ #interface.
185
+ #
186
+ #Uncomment if needed.
187
+ #
188
+ #NB: these are just examples, you can add as many options as needed: -d,
189
+ # --sport, --dport, etc.
190
+
191
+ #Example Provider 1
192
+ #[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o eth1 -j SNAT --to-source YYY.YYY.YYY.YYY
193
+ #Example Provider 2
194
+ #[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o eth2 -j SNAT --to-source YYY.YYY.YYY.YYY
195
+ #Example Provider 3
196
+ #[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o eth3 -j SNAT --to-source YYY.YYY.YYY.YYY
197
+
198
+ #SNAT: LAN --> WAN
199
+
200
+ #Example Provider 1
201
+ [0:0] -A POSTROUTING -o eth1 -j SNAT --to-source 1.0.0.2
202
+ #Example Provider 2
203
+ [0:0] -A POSTROUTING -o eth2 -j SNAT --to-source 2.0.0.2
204
+ #Example Provider 3
205
+ [0:0] -A POSTROUTING -o eth3 -j SNAT --to-source 3.0.0.2
206
+
207
+ COMMIT
208
+
209
+
210
+ *filter
211
+
212
+ :INPUT DROP [0:0]
213
+ :FORWARD DROP [0:0]
214
+ :OUTPUT ACCEPT [0:0]
215
+ :LAN_WAN - [0:0]
216
+ :WAN_LAN - [0:0]
217
+
218
+ #This is just a very basic example, add your own rules for the INPUT chain.
219
+
220
+ [0:0] -A INPUT -i lo -j ACCEPT
221
+ [0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
222
+
223
+ [0:0] -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
224
+
225
+ [0:0] -A FORWARD -i eth0 -o eth1 -j LAN_WAN
226
+ [0:0] -A FORWARD -i eth0 -o eth2 -j LAN_WAN
227
+ [0:0] -A FORWARD -i eth0 -o eth3 -j LAN_WAN
228
+ [0:0] -A FORWARD -i eth1 -o eth0 -j WAN_LAN
229
+ [0:0] -A FORWARD -i eth2 -o eth0 -j WAN_LAN
230
+ [0:0] -A FORWARD -i eth3 -o eth0 -j WAN_LAN
231
+
232
+ #This is just a very basic example, add your own rules for the FORWARD chain.
233
+
234
+ [0:0] -A LAN_WAN -j ACCEPT
235
+ [0:0] -A WAN_LAN -j REJECT
236
+
237
+ COMMIT
238
+ ```
239
+
240
+ ## To do
241
+ * Test using VLAN interfaces: Fault Tolerant Router has always been used with physical interfaces, each uplink on it's own physical interface.
242
+ * Implement routing through [realms](http://www.policyrouting.org/PolicyRoutingBook/ONLINE/CH07.web.html): this way we could connect all of the uplinks to a single Linux physical interface through a switch, without using VLANs.
243
+ * i18n
244
+ * If no uplinks are up, set tests/interval configuration option to 0, to get bandwidth as soon as an uplink comes back up
245
+
246
+ ## License
247
+ GNU General Public License v2.0, see LICENSE file
248
+
249
+ ## Author
250
+ Alessandro Zarrilli (Poggibonsi - Italy)
251
+ alessandro@zarrilli.net
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require 'bundler/gem_tasks'
@@ -0,0 +1,101 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'optparse'
4
+ require 'net/smtp'
5
+ require 'mail'
6
+ require 'logger'
7
+ require 'yaml'
8
+ require 'fault_tolerant_router/version'
9
+ require 'fault_tolerant_router/generate_config'
10
+ require 'fault_tolerant_router/generate_iptables'
11
+ require 'fault_tolerant_router/monitor'
12
+
13
+ options = {
14
+ configuration_file: '/etc/fault_tolerant_router.conf',
15
+ debug: false,
16
+ demo: false
17
+ }
18
+ parser = OptionParser.new do |opts|
19
+ opts.banner = "Usage: #{File.basename($0)} [OPTION]... ACTION"
20
+ opts.separator ''
21
+ opts.separator 'ACTION = generate_config|generate_iptables|email_test|monitor'
22
+ opts.separator ''
23
+ opts.separator ' generate_config: save an example configuration'
24
+ opts.separator ' generate_iptables: generate an "iptables-save" configuration'
25
+ opts.separator ' email_test: send a test email to verify the correctness of smtp parameters'
26
+ opts.separator ' monitor: monitor uplinks and change routing accordingly'
27
+ opts.separator ''
28
+ opts.on('--config=FILE', 'Configuration file (default /etc/fault_tolerant_router.conf)') do |configuration_file|
29
+ options[:configuration_file] = configuration_file
30
+ end
31
+ opts.separator ''
32
+ opts.separator '"monitor" specific options:'
33
+ opts.on('--debug', 'Print debug output') do |debug|
34
+ options[:debug] = debug
35
+ end
36
+ opts.on('--demo', 'Demo the program by faking random uplink failures') do |demo|
37
+ options[:demo] = demo
38
+ end
39
+ opts.separator ''
40
+ opts.separator "Version #{FaultTolerantRouter::VERSION}"
41
+ opts.separator 'Alessandro Zarrilli <alessandro@zarrilli.net>'
42
+ opts.separator 'https://github.com/drsound/fault_tolerant_router'
43
+ end
44
+ begin
45
+ parser.parse!
46
+ rescue OptionParser::ParseError
47
+ puts parser.help
48
+ exit 1
49
+ end
50
+
51
+ DEMO = options[:demo]
52
+ #activate debug if we are in demo mode
53
+ DEBUG = options[:debug] || DEMO
54
+
55
+ unless ARGV.size == 1 && %w(generate_config generate_iptables email_test monitor).include?(ARGV[0])
56
+ puts parser.help
57
+ exit 1
58
+ end
59
+
60
+ if ARGV[0] == 'generate_config'
61
+ generate_config(options[:configuration_file])
62
+ exit 0
63
+ end
64
+
65
+ unless File.exists?(options[:configuration_file])
66
+ puts "Configuration file #{options[:configuration_file]} does not exists!"
67
+ exit 1
68
+ end
69
+
70
+ config = YAML.load_file(options[:configuration_file])
71
+ UPLINKS = config['uplinks'].map { |uplink| Hash[uplink.map { |k, v| [k.to_sym, v] }] }
72
+ LAN_INTERFACE = config['downlinks']['lan']
73
+ DMZ_INTERFACE = config['downlinks']['dmz']
74
+ TEST_IPS = config['tests']['ips']
75
+ REQUIRED_SUCCESSFUL_TESTS = config['tests']['required_successful']
76
+ PING_RETRIES = config['tests']['ping_retries']
77
+ TEST_INTERVAL = config['tests']['interval']
78
+ LOG_FILE = config['log']['log_file']
79
+ LOG_MAX_SIZE = config['log']['max_size']
80
+ LOG_OLD_FILES = config['log']['old_files']
81
+ SEND_EMAIL = config['email']['send']
82
+ EMAIL_SENDER = config['email']['sender']
83
+ EMAIL_RECIPIENTS = config['email']['recipients']
84
+ SMTP_PARAMETERS = Hash[config['email']['smtp_parameters'].map { |k, v| [k.to_sym, v] }]
85
+ BASE_TABLE = config['base_table']
86
+ BASE_PRIORITY = config['base_priority']
87
+ BASE_FWMARK = config['base_fwmark']
88
+
89
+ case ARGV[0]
90
+ when 'generate_iptables'
91
+ generate_iptables
92
+ when 'email_test'
93
+ begin
94
+ send_email('fault_tolerant_router test')
95
+ puts "Test email sent to #{EMAIL_RECIPIENTS.join(', ')}"
96
+ rescue Exception => e
97
+ puts "Problem sending email: #{e}"
98
+ end
99
+ else
100
+ monitor
101
+ end
@@ -0,0 +1,24 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'fault_tolerant_router/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'fault_tolerant_router'
8
+ spec.version = FaultTolerantRouter::VERSION
9
+ spec.authors = ['Alessandro Zarrilli']
10
+ spec.email = ['alessandro@zarrilli.net']
11
+ spec.summary = %q{Multiple uplinks Linux routing supervising daemon}
12
+ spec.description = %q{Fault Tolerant Router is a daemon, running in background on a Linux router or firewall, monitoring the state of multiple internet uplinks/providers 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. 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.}
13
+ spec.homepage = 'https://github.com/drsound/fault_tolerant_router'
14
+ spec.license = 'GPL-2'
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.add_development_dependency 'bundler'
22
+ spec.add_development_dependency 'rake'
23
+ spec.add_runtime_dependency 'mail', '~> 2.6'
24
+ end
@@ -0,0 +1,98 @@
1
+ def generate_config(file_path)
2
+ if File.exists?(file_path)
3
+ puts "Configuration file #{file_path} already exists, will not overwrite!"
4
+ exit 1
5
+ end
6
+ begin
7
+ open(file_path, 'w') do |file|
8
+ file.puts <<END
9
+ #add as many uplinks as needed
10
+ uplinks:
11
+ - interface: eth1
12
+ ip: 1.0.0.2
13
+ gateway: 1.0.0.1
14
+ description: Example Provider 1
15
+ #optional parameter
16
+ weight: 1
17
+ #optional parameter, default is true
18
+ default_route: true
19
+ - interface: eth2
20
+ ip: 2.0.0.2
21
+ gateway: 2.0.0.1
22
+ description: Example Provider 2
23
+ #optional parameter
24
+ weight: 2
25
+ #optional parameter, default is true
26
+ default_route: true
27
+ - interface: eth3
28
+ ip: 3.0.0.2
29
+ gateway: 3.0.0.1
30
+ description: Example Provider 3
31
+ #optional parameter
32
+ weight: 1
33
+ #optional parameter, default is true
34
+ default_route: true
35
+
36
+ downlinks:
37
+ lan: eth0
38
+ #leave blank if you have no DMZ
39
+ dmz:
40
+
41
+ tests:
42
+ #add as many ips as needed, make sure they are reliable ones, these are Google DNS, OpenDNS DNS, public DNS server
43
+ #list order is not important, because the list is shuffled before every test
44
+ ips:
45
+ - 8.8.8.8
46
+ - 8.8.4.4
47
+ - 208.67.222.222
48
+ - 208.67.220.220
49
+ - 4.2.2.2
50
+ - 4.2.2.3
51
+ #number of successful pinged addresses to consider an uplink to be functional
52
+ required_successful: 4
53
+ #ping retries in case of ping error
54
+ ping_retries: 1
55
+ #seconds between a check of the uplinks and the next one
56
+ interval: 60
57
+
58
+ log:
59
+ #file: "/var/log/fault_tolerant_router.log"
60
+ file: "/tmp/fault_tolerant_router.log"
61
+ #max log file size (in bytes)
62
+ max_size: 1024000
63
+ #number of old log files to keep
64
+ old_files: 10
65
+
66
+ email:
67
+ send: false
68
+ sender: router@domain.com
69
+ recipients:
70
+ - user1@domain.com
71
+ - user2@domain.com
72
+ - user3@domain.com
73
+ #see http://ruby-doc.org/stdlib-2.2.0/libdoc/net/smtp/rdoc/Net/SMTP.html
74
+ smtp_parameters:
75
+ address: smtp.gmail.com
76
+ port: 587
77
+ #domain: domain.com
78
+ authentication: :login
79
+ enable_starttls_auto: true
80
+ user_name: user@gmail.com
81
+ password: secret-password
82
+
83
+ #base ip route table
84
+ base_table: 1
85
+
86
+ #base ip rule priority, must be higher than 32767 (default priority, see "ip rule")
87
+ base_priority: 40000
88
+
89
+ #base fwmark
90
+ base_fwmark: 1
91
+ END
92
+ end
93
+ puts "Example configuration saved to #{file_path}"
94
+ rescue
95
+ puts "Error while saving configuration file #{file_path}!"
96
+ exit 1
97
+ end
98
+ end
@@ -0,0 +1,172 @@
1
+ def generate_iptables
2
+ puts <<END
3
+ #Integrate with your existing "iptables-save" configuration, or adapt to work
4
+ #with any other iptables configuration system
5
+
6
+ *mangle
7
+ :PREROUTING ACCEPT [0:0]
8
+ :POSTROUTING ACCEPT [0:0]
9
+ :OUTPUT ACCEPT [0:0]
10
+ :INPUT ACCEPT [0:0]
11
+
12
+ #New outbound connections: force a connection to use a specific uplink instead
13
+ #of participating in the multipath routing. This can be useful if you have an
14
+ #SMTP server that should always send emails originating from a specific IP
15
+ #address (because of PTR DNS records), or if you have some service that you want
16
+ #always to use a particular slow/fast uplink.
17
+ #
18
+ #Uncomment if needed.
19
+ #
20
+ #NB: these are just examples, you can add as many options as needed: -s, -d,
21
+ # --sport, etc.
22
+
23
+ END
24
+ UPLINKS.each_with_index do |uplink, i|
25
+ puts "##{uplink[:description]}"
26
+ puts "#[0:0] -A PREROUTING -i #{LAN_INTERFACE} -m state --state NEW -p tcp --dport XXX -j CONNMARK --set-mark #{BASE_FWMARK + i}"
27
+ puts "#[0:0] -A PREROUTING -i #{DMZ_INTERFACE} -m state --state NEW -p tcp --dport XXX -j CONNMARK --set-mark #{BASE_FWMARK + i}" if DMZ_INTERFACE
28
+ end
29
+ puts <<END
30
+
31
+ #Mark packets with the outgoing interface:
32
+ #
33
+ #- Established outbound connections: mark non-first packets (first packet will
34
+ # be marked as 0, as a standard unmerked packet, because the connection has not
35
+ # yet been marked with CONNMARK --set-mark)
36
+ #
37
+ #- New outbound connections: mark first packet, only effective if marking has
38
+ # been done in the section above
39
+ #
40
+ #- Inbound connections: mark returning packets (from LAN/DMZ to WAN)
41
+
42
+ [0:0] -A PREROUTING -i #{LAN_INTERFACE} -j CONNMARK --restore-mark
43
+ END
44
+ puts "[0:0] -A PREROUTING -i #{DMZ_INTERFACE} -j CONNMARK --restore-mark" if DMZ_INTERFACE
45
+ puts <<END
46
+
47
+ #New inbound connections: mark the connection with the incoming interface.
48
+
49
+ END
50
+ UPLINKS.each_with_index do |uplink, i|
51
+ puts "##{uplink[:description]}"
52
+ puts "[0:0] -A PREROUTING -i #{uplink[:interface]} -m state --state NEW -j CONNMARK --set-mark #{BASE_FWMARK + i}"
53
+ end
54
+ puts <<END
55
+
56
+ #New outbound connections: mark the connection with the outgoing interface
57
+ #(chosen by the multipath routing).
58
+
59
+ END
60
+ UPLINKS.each_with_index do |uplink, i|
61
+ puts "##{uplink[:description]}"
62
+ puts "[0:0] -A POSTROUTING -o #{uplink[:interface]} -m state --state NEW -j CONNMARK --set-mark #{BASE_FWMARK + i}"
63
+ end
64
+ puts <<END
65
+
66
+ COMMIT
67
+
68
+
69
+ *nat
70
+ :PREROUTING ACCEPT [0:0]
71
+ :POSTROUTING ACCEPT [0:0]
72
+ :OUTPUT ACCEPT [0:0]
73
+
74
+ #DNAT: WAN --> LAN/DMZ. The original destination IP (-d) can be any of the IP
75
+ #addresses assigned to the uplink interface. XXX.XXX.XXX.XXX can be any of your
76
+ #LAN/DMZ IPs.
77
+ #
78
+ #Uncomment if needed.
79
+ #
80
+ #NB: these are just examples, you can add as many options as you wish: -s,
81
+ # --sport, --dport, etc.
82
+
83
+ END
84
+ UPLINKS.each do |uplink|
85
+ puts "##{uplink[:description]}"
86
+ puts "#[0:0] -A PREROUTING -i #{uplink[:interface]} -d #{uplink[:ip]} -j DNAT --to-destination XXX.XXX.XXX.XXX"
87
+ end
88
+ puts <<END
89
+
90
+ #SNAT: LAN/DMZ --> WAN. Force an outgoing connection to use a specific source
91
+ #address instead of the default one of the outgoing interface. Of course this
92
+ #only makes sense if more than one IP address is assigned to the uplink
93
+ #interface.
94
+ #
95
+ #Uncomment if needed.
96
+ #
97
+ #NB: these are just examples, you can add as many options as needed: -d,
98
+ # --sport, --dport, etc.
99
+
100
+ END
101
+ UPLINKS.each do |uplink|
102
+ puts "##{uplink[:description]}"
103
+ puts "#[0:0] -A POSTROUTING -s XXX.XXX.XXX.XXX -o #{uplink[:interface]} -j SNAT --to-source YYY.YYY.YYY.YYY"
104
+ end
105
+ puts <<END
106
+
107
+ #SNAT: LAN --> WAN
108
+
109
+ END
110
+ UPLINKS.each do |uplink|
111
+ puts "##{uplink[:description]}"
112
+ puts "[0:0] -A POSTROUTING -o #{uplink[:interface]} -j SNAT --to-source #{uplink[:ip]}"
113
+ end
114
+ puts <<END
115
+
116
+ COMMIT
117
+
118
+
119
+ *filter
120
+
121
+ :INPUT DROP [0:0]
122
+ :FORWARD DROP [0:0]
123
+ :OUTPUT ACCEPT [0:0]
124
+ :LAN_WAN - [0:0]
125
+ :WAN_LAN - [0:0]
126
+ END
127
+
128
+ if DMZ_INTERFACE
129
+ puts ':DMZ_WAN - [0:0]'
130
+ puts ':WAN_DMZ - [0:0]'
131
+ end
132
+
133
+ puts <<END
134
+
135
+ #This is just a very basic example, add your own rules for the INPUT chain.
136
+
137
+ [0:0] -A INPUT -i lo -j ACCEPT
138
+ [0:0] -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
139
+
140
+ [0:0] -A FORWARD -m state --state RELATED,ESTABLISHED -j ACCEPT
141
+
142
+ END
143
+ UPLINKS.each do |uplink|
144
+ puts "[0:0] -A FORWARD -i #{LAN_INTERFACE} -o #{uplink[:interface]} -j LAN_WAN"
145
+ end
146
+ UPLINKS.each do |uplink|
147
+ puts "[0:0] -A FORWARD -i #{uplink[:interface]} -o #{LAN_INTERFACE} -j WAN_LAN"
148
+ end
149
+ if DMZ_INTERFACE
150
+ UPLINKS.each do |uplink|
151
+ puts "[0:0] -A FORWARD -i #{DMZ_INTERFACE} -o #{uplink[:interface]} -j DMZ_WAN"
152
+ end
153
+ UPLINKS.each do |uplink|
154
+ puts "[0:0] -A FORWARD -i #{uplink[:interface]} -o #{DMZ_INTERFACE} -j WAN_DMZ"
155
+ end
156
+ end
157
+ puts <<END
158
+
159
+ #This is just a very basic example, add your own rules for the FORWARD chain.
160
+
161
+ [0:0] -A LAN_WAN -j ACCEPT
162
+ [0:0] -A WAN_LAN -j REJECT
163
+ END
164
+ if DMZ_INTERFACE
165
+ puts '[0:0] -A DMZ_WAN -j ACCEPT'
166
+ puts '[0:0] -A WAN_DMZ -j ACCEPT'
167
+ end
168
+ puts <<END
169
+
170
+ COMMIT
171
+ END
172
+ end
@@ -0,0 +1,182 @@
1
+ def command(c)
2
+ `#{c}` unless DEMO
3
+ puts "Command: #{c}" if DEBUG
4
+ end
5
+
6
+ def ping(ip, source)
7
+ if DEMO
8
+ sleep 0.1
9
+ rand(3) > 0
10
+ else
11
+ `ping -n -c 1 -W 2 -I #{source} #{ip}`
12
+ $?.to_i == 0
13
+ end
14
+ end
15
+
16
+ def set_default_route
17
+ #find the enabled uplinks
18
+ enabled_uplinks = UPLINKS.find_all { |uplink| uplink[:enabled] }
19
+ #do not use balancing if there is just one enabled uplink
20
+ if enabled_uplinks.size == 1
21
+ nexthops = "via #{enabled_uplinks.first[:gateway]}"
22
+ else
23
+ nexthops = enabled_uplinks.collect do |uplink|
24
+ #the "weight" parameter is optional
25
+ weight = uplink[:weight] ? " weight #{uplink[:weight]}" : ''
26
+ "nexthop via #{uplink[:gateway]}#{weight}"
27
+ end
28
+ nexthops = nexthops.join(' ')
29
+ end
30
+ #set the route for first packet of outbound connections
31
+ command "ip route replace table #{BASE_TABLE + UPLINKS.size} default #{nexthops}"
32
+ #apply the routing changes
33
+ command 'ip route flush cache'
34
+ end
35
+
36
+ def send_email(body)
37
+ mail = Mail.new
38
+ mail.from = EMAIL_SENDER
39
+ mail.to = EMAIL_RECIPIENTS
40
+ mail.subject = 'Uplinks status change'
41
+ mail.body = body
42
+ mail.delivery_method :smtp, SMTP_PARAMETERS
43
+ mail.deliver
44
+ end
45
+
46
+ def monitor
47
+ logger = Logger.new(LOG_FILE, LOG_OLD_FILES, LOG_MAX_SIZE)
48
+
49
+ #enable all the uplinks
50
+ UPLINKS.each do |uplink|
51
+ uplink[:working] = true
52
+ uplink[:default_route] ||= uplink[:default_route].nil?
53
+ uplink[:enabled] = uplink[:default_route]
54
+ end
55
+
56
+ #clean all previous configurations, try to clean more than needed (double) to avoid problems in case of changes in the
57
+ #number of uplinks between different executions
58
+ ((UPLINKS.size * 2 + 1) * 2).times do |i|
59
+ command "ip rule del priority #{BASE_PRIORITY + i} &> /dev/null"
60
+ end
61
+ ((UPLINKS.size + 1) * 2).times do |i|
62
+ command "ip route del table #{BASE_TABLE + i} &> /dev/null"
63
+ end
64
+
65
+ #disable "reverse path filtering" on the uplink interfaces
66
+ command 'echo 0 > /proc/sys/net/ipv4/conf/all/rp_filter'
67
+ UPLINKS.each do |uplink|
68
+ command "echo 2 > /proc/sys/net/ipv4/conf/#{uplink[:interface]}/rp_filter"
69
+ end
70
+
71
+ #- locally generated packets having as source ip the ethX ip
72
+ #- returning packets of inbound connections coming from ethX
73
+ #- non-first packets of outbound connections for which the first packet has been sent to ethX via multipath routing
74
+ UPLINKS.each_with_index do |uplink, i|
75
+ command "ip route add table #{BASE_TABLE + i} default via #{uplink[:gateway]} src #{uplink[:ip]}"
76
+ command "ip rule add priority #{BASE_PRIORITY + i} from #{uplink[:ip]} lookup #{BASE_TABLE + i}"
77
+ command "ip rule add priority #{BASE_PRIORITY + UPLINKS.size + i} fwmark #{BASE_FWMARK + i} lookup #{BASE_TABLE + i}"
78
+ end
79
+ #first packet of outbound connections
80
+ command "ip rule add priority #{BASE_PRIORITY + UPLINKS.size * 2} from all lookup #{BASE_TABLE + UPLINKS.size}"
81
+ set_default_route
82
+
83
+ loop do
84
+ #for each uplink...
85
+ UPLINKS.each do |uplink|
86
+ #set current "working" state as the previous one
87
+ uplink[:previously_working] = uplink[:working]
88
+ #set current "enabled" state as the previous one
89
+ uplink[:previously_enabled] = uplink[:enabled]
90
+ uplink[:successful_tests] = 0
91
+ uplink[:unsuccessful_tests] = 0
92
+ #for each test (in random order)...
93
+ TEST_IPS.shuffle.each_with_index do |test, i|
94
+ successful_test = false
95
+ #retry for several times...
96
+ PING_RETRIES.times do
97
+ if DEBUG
98
+ print "Uplink #{uplink[:description]}: ping #{test}... "
99
+ STDOUT.flush
100
+ end
101
+ if ping(test, uplink[:ip])
102
+ successful_test = true
103
+ puts 'ok' if DEBUG
104
+ #avoid more pings to the same ip after a successful one
105
+ break
106
+ else
107
+ puts 'error' if DEBUG
108
+ end
109
+ end
110
+ if successful_test
111
+ uplink[:successful_tests] += 1
112
+ else
113
+ uplink[:unsuccessful_tests] += 1
114
+ end
115
+ #if not currently doing the last test...
116
+ if i + 1 < TEST_IPS.size
117
+ if uplink[:successful_tests] >= REQUIRED_SUCCESSFUL_TESTS
118
+ puts "Uplink #{uplink[:description]}: avoiding more tests because there are enough positive ones" if DEBUG
119
+ break
120
+ elsif TEST_IPS.size - uplink[:unsuccessful_tests] < REQUIRED_SUCCESSFUL_TESTS
121
+ puts "Uplink #{uplink[:description]}: avoiding more tests because too many have been failed" if DEBUG
122
+ break
123
+ end
124
+ end
125
+ end
126
+ uplink[:working] = uplink[:successful_tests] >= REQUIRED_SUCCESSFUL_TESTS
127
+ uplink[:enabled] = uplink[:working] && uplink[:default_route]
128
+ end
129
+
130
+ #only consider uplinks flagged as default route
131
+ if UPLINKS.find_all { |uplink| uplink[:default_route] }.all? { |uplink| !uplink[:working] }
132
+ UPLINKS.find_all { |uplink| uplink[:default_route] }.each { |uplink| uplink[:enabled] = true }
133
+ puts 'No uplink seems to be working, enabling all of them' if DEBUG
134
+ end
135
+
136
+ UPLINKS.each do |uplink|
137
+ description = case
138
+ when uplink[:enabled] && !uplink[:previously_enabled] then
139
+ ', enabled'
140
+ when !uplink[:enabled] && uplink[:previously_enabled] then
141
+ ', disabled'
142
+ else
143
+ ''
144
+ end
145
+ puts "Uplink #{uplink[:description]}: #{uplink[:successful_tests]} successful tests, #{uplink[:unsuccessful_tests]} unsuccessful tests#{description}"
146
+ end if DEBUG
147
+
148
+ #set a new default route if there are changes between the previous and the current uplinks situation
149
+ set_default_route if UPLINKS.any? { |uplink| uplink[:enabled] != uplink[:previously_enabled] }
150
+
151
+ if UPLINKS.any? { |uplink| uplink[:working] != uplink[:previously_working] }
152
+ body = ''
153
+ UPLINKS.each do |uplink|
154
+ body += "Uplink #{uplink[:description]}: #{uplink[:previously_working] ? 'up' : 'down'}"
155
+ if uplink[:previously_working] == uplink[:working]
156
+ body += "\n"
157
+ else
158
+ body += " --> #{uplink[:working] ? 'up' : 'down'}\n"
159
+ end
160
+ end
161
+
162
+ logger.warn(body.gsub("\n", ';'))
163
+
164
+ if SEND_EMAIL
165
+ begin
166
+ send_email(body)
167
+ rescue Exception => e
168
+ puts "Problem sending email: #{e}" if DEBUG
169
+ logger.error("Problem sending email: #{e}")
170
+ end
171
+ end
172
+ end
173
+
174
+ if DEMO
175
+ puts "Waiting just 5 seconds because we are in demo mode, otherwise would wait #{TEST_INTERVAL} seconds..."
176
+ sleep 5
177
+ else
178
+ puts "Waiting #{TEST_INTERVAL} seconds..." if DEBUG
179
+ sleep TEST_INTERVAL
180
+ end
181
+ end
182
+ end
@@ -0,0 +1,3 @@
1
+ module FaultTolerantRouter
2
+ VERSION = '1.0.0'
3
+ end
metadata ADDED
@@ -0,0 +1,107 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: fault_tolerant_router
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Alessandro Zarrilli
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-02-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: mail
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '2.6'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '2.6'
55
+ description: 'Fault Tolerant Router is a daemon, running in background on a Linux
56
+ router or firewall, monitoring the state of multiple internet uplinks/providers
57
+ and changing the routing accordingly. LAN/DMZ internet traffic (outgoing connections)
58
+ is load balanced between the uplinks using Linux multipath routing. The daemon monitors
59
+ the state of the uplinks by routinely pinging well known IP addresses (Google public
60
+ DNS servers, etc.) through each outgoing interface: once an uplink goes down, it
61
+ is excluded from the multipath routing, when it comes back up, it is included again.
62
+ All of the routing changes are notified to the administrator by email. Fault Tolerant
63
+ Router is well tested and has been used in production for several years, in several
64
+ sites. See https://github.com/drsound/fault_tolerant_router for full documentation.'
65
+ email:
66
+ - alessandro@zarrilli.net
67
+ executables:
68
+ - fault_tolerant_router
69
+ extensions: []
70
+ extra_rdoc_files: []
71
+ files:
72
+ - ".gitignore"
73
+ - Gemfile
74
+ - LICENSE
75
+ - README.md
76
+ - Rakefile
77
+ - bin/fault_tolerant_router
78
+ - fault_tolerant_router.gemspec
79
+ - lib/fault_tolerant_router/generate_config.rb
80
+ - lib/fault_tolerant_router/generate_iptables.rb
81
+ - lib/fault_tolerant_router/monitor.rb
82
+ - lib/fault_tolerant_router/version.rb
83
+ homepage: https://github.com/drsound/fault_tolerant_router
84
+ licenses:
85
+ - GPL-2
86
+ metadata: {}
87
+ post_install_message:
88
+ rdoc_options: []
89
+ require_paths:
90
+ - lib
91
+ required_ruby_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ requirements: []
102
+ rubyforge_project:
103
+ rubygems_version: 2.4.5
104
+ signing_key:
105
+ specification_version: 4
106
+ summary: Multiple uplinks Linux routing supervising daemon
107
+ test_files: []