diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..71281b3 --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,72 @@ + +Version 1.10.1 +-------------- + +[20051008] jonz: Fixed IP Whitelisting in Apache 1.3 Version + +[20051008] jonz: Corrected initialization to prevent dumping IP database + +[20051008] jonz: Documentation and code cleaned up, renamed mod_evasive + +Version 1.10.0 +-------------- + +[20050117] jonz: Security fix: Tempdir configuration directive (race condition) + +Version 1.9.0 +------------- + +[20031030] jonz: Added NSAPI/SunONE Support + +[20031030] jonz: Added TEMP_HOME definition to change temporary file locations + +Version 1.8.0 +------------- + +[20030901] jonz: Added support for IP Whitelisting + +Version 1.7.1 +------------- + +[20030826] jonz: Minor bugfixes to Apache 2.0 module + +[20030826] jonz: Corrections to object creation and cleanup + +Version 1.7.0 +------------- + +[20030822] jonz: Support for Apache 2.0 + +Version 1.6.1 +------------- + +[20030811] jonz: Bugfix: free() of another static variable + +Version 1.6.0 +------------- + +[20030806] jonz: Added syslog support + +Version 1.5.1 +------------- + +[20030516] jonz: Bugfix: free() of a static variable + +Version 1.5.0 +------------- + +[20030425] jonz: Added automated email notification + +[20030425] jonz: Added configurable system command + +Version 1.4.0 +------------- + +[20021031] jonz: Added support fror httpd.conf directives + +[20021031] jonz: Added --add-module support + +Version 1.0.0 +------------- + +[20021015] jonz: Initial Release diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..5f5c6a7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,146 @@ +GNU GENERAL PUBLIC LICENSE +Version 2, June 1991 + +Copyright (C) 1989, 1991 Free Software Foundation, Inc. +59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 Library 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. + +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. + +one line to give the program's name and an idea of what it does. +Copyright (C) yyyy name of author + +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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 Library General Public License instead of this License. + + +-------------------------------------------------------------------------------- +Return to GNU's home page. +FSF & GNU inquiries & questions to gnu@gnu.org. Other ways to contact the FSF. + +Comments on these web pages to webmasters@www.gnu.org, send other questions to gnu@gnu.org. + +Copyright notice above. +Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA + +Updated: Last modified: Sun Jul 15 13:13:30 CEST 2001 + diff --git a/Makefile.tmpl b/Makefile.tmpl new file mode 100644 index 0000000..5a64d12 --- /dev/null +++ b/Makefile.tmpl @@ -0,0 +1,15 @@ + +#Dependencies + +$(OBJS) $(OBJS_PIC): Makefile + +# DO NOT REMOVE +mod_evasive.o: mod_evasive.c $(INCDIR)/httpd.h \ + $(INCDIR)/ap_config.h $(INCDIR)/ap_mmn.h \ + $(INCDIR)/ap_config_auto.h $(OSDIR)/os.h \ + $(INCDIR)/ap_ctype.h $(INCDIR)/hsregex.h \ + $(INCDIR)/ap_alloc.h $(INCDIR)/buff.h $(INCDIR)/ap.h \ + $(INCDIR)/util_uri.h $(INCDIR)/http_config.h \ + $(INCDIR)/http_core.h $(INCDIR)/http_log.h \ + $(INCDIR)/http_main.h $(INCDIR)/http_protocol.h \ + $(INCDIR)/util_script.h diff --git a/README b/README new file mode 100644 index 0000000..2d09b62 --- /dev/null +++ b/README @@ -0,0 +1,378 @@ +Apache Evasive Maneuvers Module +For Apache 1.3 and 2.0 +Copyright (c) Deep Logic, Inc. +Version 1.10 [2005.0117] + +LICENSE + +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; version 2 +of the License. + +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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +WHAT IS MOD_EVASIVE ? + +mod_evasive is an evasive maneuvers module for Apache to provide evasive +action in the event of an HTTP DoS or DDoS attack or brute force attack. It +is also designed to be a detection tool, and can be easily configured to talk +to ipchains, firewalls, routers, and etcetera. + +Detection is performed by creating an internal dynamic hash table of IP +Addresses and URIs, and denying any single IP address from any of the following: + +- Requesting the same page more than a few times per second +- Making more than 50 concurrent requests on the same child per second +- Making any requests while temporarily blacklisted (on a blocking list) + +This method has worked well in both single-server script attacks as well +as distributed attacks, but just like other evasive tools, is only as +useful to the point of bandwidth and processor consumption (e.g. the +amount of bandwidth and processor required to receive/process/respond +to invalid requests), which is why it's a good idea to integrate this +with your firewalls and routers. + +This module instantiates for each listener individually, and therefore has +a built-in cleanup mechanism and scaling capabilities. Because of this, +legitimate requests are rarely ever compromised, only legitimate attacks. Even +a user repeatedly clicking on 'reload' should not be affected unless they do +it maliciously. + +Three different module sources have been provided: + +Apache v1.3 API: mod_evasive.c +Apache v2.0 API: mod_evasive20.c +NSAPI (iPlanet): mod_evasiveNSAPI.c * + +NOTE: mod_evasiveNSAPI is a port submitted by Reine Persson + and is not officially supported as part of the mod_evasive project. + +HOW IT WORKS + +A web hit request comes in. The following steps take place: + +- The IP address of the requestor is looked up on the temporary blacklist +- The IP address of the requestor and the URI are both hashed into a "key". + A lookup is performed in the listener's internal hash table to determine + if the same host has requested this page more than once within the past + 1 second. +- The IP address of the requestor is hashed into a "key". + A lookup is performed in the listerner's internal hash table to determine + if the same host has requested more than 50 objects within the past + second (from the same child). + +If any of the above are true, a 403 response is sent. This conserves +bandwidth and system resources in the event of a DoS attack. Additionally, +a system command and/or an email notification can also be triggered to block +all the originating addresses of a DDoS attack. + +Once a single 403 incident occurs, mod_evasive now blocks the entire IP +address for a period of 10 seconds (configurable). If the host requests a +page within this period, it is forced to wait even longer. Since this is +triggered from requesting the same URL multiple times per second, this +again does not affect legitimate users. + +The blacklist can/should be configured to talk to your network's firewalls +and/or routers to push the attack out to the front lines, but this is not +required. + +mod_evasive also performs syslog reporting using daemon.alert. Messages +will look like this: + +Aug 6 17:41:49 elijah mod_evasive[23184]: [ID 801097 daemon.alert] Blacklisting address x.x.x.x: possible attack. + +WHAT IS THIS TOOL USEFUL FOR? + +This tool is *excellent* at fending off request-based DoS attacks or scripted +attacks, and brute force attacks. When integrated with firewalls or IP filters, +mod_evasive can stand up to even large attacks. Its features will prevent you +from wasting bandwidth or having a few thousand CGI scripts running as a +result of an attack. + +If you do not have an infrastructure capable of fending off any other types +of DoS attacks, chances are this tool will only help you to the point of +your total bandwidth or server capacity for sending 403's. Without a solid +infrastructure and address filtering tool in place, a heavy distributed DoS +will most likely still take you offline. + +HOW TO INSTALL + +APACHE v1.3 +----------- + +Without DSO Support: + +1. Extract this archive into src/modules in the Apache source tree + +2. Run ./configure --add-module=src/modules/evasive/mod_evasive.c + +3. make, install + +4. Restart Apache + +With DSO Support, Ensim, or CPanel: + +1. $APACHE_ROOT/bin/apxs -iac mod_evasive.c + +2. Restart Apache + +APACHE v2.0 +----------- + +1. Extract this archive + +2. Run $APACHE_ROOT/bin/apxs -i -a -c mod_evasive20.c + +3. The module will be built and installed into $APACHE_ROOT/modules, and loaded into your httpd.conf + +4. Restart Apache + +NSAPI +SunONE (iPlanet,netscape) Installation +-------------------------------------- + +Tested on: +iPlanet 4.1sp12 +iPlanet 6.0sp5 + +Edit compile script for your environment and compile mod_evasiveNSAPI.c +to a shared library. + +CONFIGURATION + +mod_evasive has default options configured, but you may also add the +following block to your httpd.conf: + +APACHE v1.3 +----------- + + + DOSHashTableSize 3097 + DOSPageCount 2 + DOSSiteCount 50 + DOSPageInterval 1 + DOSSiteInterval 1 + DOSBlockingPeriod 10 + + +APACHE v2.0 +----------- + + DOSHashTableSize 3097 + DOSPageCount 2 + DOSSiteCount 50 + DOSPageInterval 1 + DOSSiteInterval 1 + DOSBlockingPeriod 10 + + +Optionally you can also add the following directives: + + DOSEmailNotify you@yourdomain.com + DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" + DOSLogDir "/var/lock/mod_evasive" + +You will also need to add this line if you are building with dynamic support: + +APACHE v1.3 +----------- + +AddModule mod_evasive.c + +APACHE v2.0 +----------- + +LoadModule evasive20_module modules/mod_evasive20.so + +(This line is already added to your configuration by apxs) + +NSAPI +SunONE (iPlanet,Netscape) Configuration +-------------------------------------- + +Configure iPlanet 4.1 +--------------------- + +Edit obj.conf: + +Init fn="load-modules" funcs="mod_evasive_init,mod_evasive_check" shlib="/opt/ns-4.1/plugins/lib/mod_evasive.sl" + +Init fn="mod_evasive_init" DOSPageCount=2 DOSSiteCount=50 DOSPageInterval=1 DOSSiteInterval=1 DOSBlockingPeriod=10 DOSWhitelist="10.60.0.7,10.65.0.10" + +In the default object: +PathCheck fn=mod_evasive_check + +Or an own object + +NameTrans fn=mod_evasive_check + + + +Configure iPlanet 6.0 +--------------------- + +Edit magnus.conf: + +Init fn="load-modules" funcs="mod_evasive_init,mod_evasive_check" shlib="/opt/iplanet-6.0/plugins/lib/mod_evasive.sl" + +Init fn="mod_evasive_init" DOSWhitelist="10.60.0.7,10.65.0.10" + +Edit obj.conf: +In the default object: +PathCheck fn=mod_evasive_check + +Or an own object + +NameTrans fn=mod_evasive_check + + +DOSHashTableSize +---------------- + +The hash table size defines the number of top-level nodes for each child's +hash table. Increasing this number will provide faster performance by +decreasing the number of iterations required to get to the record, but +consume more memory for table space. You should increase this if you have +a busy web server. The value you specify will automatically be tiered up to +the next prime number in the primes list (see mod_evasive.c for a list +of primes used). + +DOSPageCount +------------ + +This is the threshhold for the number of requests for the same page (or URI) +per page interval. Once the threshhold for that interval has been exceeded, +the IP address of the client will be added to the blocking list. + +DOSSiteCount +------------ + +This is the threshhold for the total number of requests for any object by +the same client on the same listener per site interval. Once the threshhold +for that interval has been exceeded, the IP address of the client will be added +to the blocking list. + +DOSPageInterval +--------------- + +The interval for the page count threshhold; defaults to 1 second intervals. + +DOSSiteInterval +--------------- + +The interval for the site count threshhold; defaults to 1 second intervals. + +DOSBlockingPeriod +----------------- + +The blocking period is the amount of time (in seconds) that a client will be +blocked for if they are added to the blocking list. During this time, all +subsequent requests from the client will result in a 403 (Forbidden) and +the timer being reset (e.g. another 10 seconds). Since the timer is reset +for every subsequent request, it is not necessary to have a long blocking +period; in the event of a DoS attack, this timer will keep getting reset. + +DOSEmailNotify +-------------- + +If this value is set, an email will be sent to the address specified +whenever an IP address becomes blacklisted. A locking mechanism using /tmp +prevents continuous emails from being sent. + +NOTE: Be sure MAILER is set correctly in mod_evasive.c + (or mod_evasive20.c). The default is "/bin/mail -t %s" where %s is + used to denote the destination email address set in the configuration. + If you are running on linux or some other operating system with a + different type of mailer, you'll need to change this. + +DOSSystemCommand +---------------- + +If this value is set, the system command specified will be executed +whenever an IP address becomes blacklisted. This is designed to enable +system calls to ip filter or other tools. A locking mechanism using /tmp +prevents continuous system calls. Use %s to denote the IP address of the +blacklisted IP. + +DOSLogDir +--------- + +Choose an alternative temp directory + +By default "/tmp" will be used for locking mechanism, which opens some +security issues if your system is open to shell users. + + http://security.lss.hr/index.php?page=details&ID=LSS-2005-01-01 + +In the event you have nonprivileged shell users, you'll want to create a +directory writable only to the user Apache is running as (usually root), +then set this in your httpd.conf. + +WHITELISTING IP ADDRESSES + +IP addresses of trusted clients can be whitelisted to insure they are never +denied. The purpose of whitelisting is to protect software, scripts, local +searchbots, or other automated tools from being denied for requesting large +amounts of data from the server. Whitelisting should *not* be used to add +customer lists or anything of the sort, as this will open the server to abuse. +This module is very difficult to trigger without performing some type of +malicious attack, and for that reason it is more appropriate to allow the +module to decide on its own whether or not an individual customer should be +blocked. + +To whitelist an address (or range) add an entry to the Apache configuration +in the following fashion: + +DOSWhitelist 127.0.0.1 +DOSWhitelist 127.0.0.* + +Wildcards can be used on up to the last 3 octets if necessary. Multiple +DOSWhitelist commands may be used in the configuration. + +TWEAKING APACHE + +The keep-alive settings for your children should be reasonable enough to +keep each child up long enough to resist a DOS attack (or at least part of +one). Remember, it is the child processes that maintain their own internal +IP address tables, and so when one exits, so does all of the IP information it +had. For every child that exits, another 5-10 copies of the page may get +through before putting the attacker back into '403 Land'. With this said, +you should have a very high MaxRequestsPerChild, but not unlimited as this +will prevent cleanup. + +You'll want to have a MaxRequestsPerChild set to a non-zero value, as +DosEvasive cleans up its internal hashes only on exit. The default +MaxRequestsPerChild is usually 10000. This should suffice in only allowing +a few requests per 10000 per child through in the event of an attack (although +if you use DOSSystemCommand to firewall the IP address, a hole will no +longer be open in between child cycles). + +TESTING + +Want to make sure it's working? Run test.pl, and view the response codes. +It's best to run it several times on the same machine as the web server until +you get 403 Forbidden messages. Some larger servers with high child counts +may require more of a beating than smaller servers before blacklisting +addresses. + +Please don't use this script to DoS others without their permission. + +KNOWN BUGS + +- This module appears to conflict with the Microsoft Frontpage Extensions. + Frontpage sucks anyway, so if you're using Frontpage I assume you're asking + for problems, and not really interested in conserving server resources anyway. + +FEEDBACK + +Please email me with questions, constructive comments, or feedback: + jonathan@nuclearelephant.com + diff --git a/mod_evasive.c b/mod_evasive.c new file mode 100644 index 0000000..1df066b --- /dev/null +++ b/mod_evasive.c @@ -0,0 +1,709 @@ +/* $Id: mod_evasive.c,v 1.3 2005/10/08 19:17:14 jonz Exp $ */ + +/* +mod_evasive for Apache 1.3 +Copyright (c) by Jonathan A. Zdziarski + +LICENSE + +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; version 2 +of the License. + +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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "httpd.h" +#include "http_core.h" +#include "http_config.h" +#include "http_log.h" +#include "http_request.h" + +module MODULE_VAR_EXPORT evasive_module; + +/* BEGIN DoS Evasive Maneuvers Definitions */ + +#define MAILER "/bin/mail -t %s" +#define LOG( A, ... ) { openlog("mod_evasive", LOG_PID, LOG_DAEMON); syslog( A, __VA_ARGS__ ); closelog(); } + +#define DEFAULT_HASH_TBL_SIZE 3079ul // Default hash table size +#define DEFAULT_PAGE_COUNT 2 // Default max page hit count/interval +#define DEFAULT_SITE_COUNT 50 // Default max site hit count/interval +#define DEFAULT_PAGE_INTERVAL 1 // Default 1 second page interval +#define DEFAULT_SITE_INTERVAL 1 // Default 1 second site interval +#define DEFAULT_BLOCKING_PERIOD 10 // Default block time (Seconds) +#define DEFAULT_LOG_DIR "/tmp" + +/* END DoS Evasive Maneuvers Definitions */ + +/* BEGIN NTT (Named Timestamp Tree) Headers */ + +enum { ntt_num_primes = 28 }; + +/* ntt root tree */ +struct ntt { + long size; + long items; + struct ntt_node **tbl; +}; + +/* ntt node (entry in the ntt root tree) */ +struct ntt_node { + char *key; + time_t timestamp; + long count; + struct ntt_node *next; +}; + +/* ntt cursor */ +struct ntt_c { + long iter_index; + struct ntt_node *iter_next; +}; + +struct ntt *ntt_create(long size); +struct ntt_node *ntt_find(struct ntt *ntt, const char *key); +struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); +struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); +struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); +int ntt_destroy(struct ntt *ntt); +int ntt_delete(struct ntt *ntt, const char *key); +long ntt_hashcode(struct ntt *ntt, const char *key); + +/* END NTT (Named Timestamp Tree) Headers */ + + +/* BEGIN DoS Evasive Maneuvers Globals */ + +struct ntt *hit_list; // Our dynamic hash table +struct ntt *white_list = NULL; // White list table + +static unsigned long hash_table_size = DEFAULT_HASH_TBL_SIZE; +static int page_count = DEFAULT_PAGE_COUNT; +static int page_interval = DEFAULT_PAGE_INTERVAL; +static int site_count = DEFAULT_SITE_COUNT; +static int site_interval = DEFAULT_SITE_INTERVAL; +static int blocking_period = DEFAULT_BLOCKING_PERIOD; +static char *log_dir = NULL; +static char *email_notify = NULL; +static char *sys_command = NULL; +int is_whitelisted(const char *ip); +static const char *whitelist(cmd_parms *cmd, void *mconfig, char *ip); + +/* END DoS Evasive Maneuvers Globals */ + +static void evasive_child_init(server_rec *s, pool *p) +{ + hit_list = ntt_create(hash_table_size); +} + +static int check_access(request_rec *r) +{ + int ret = OK; + + /* BEGIN Evasive Maneuvers Code */ + + if (r->prev == NULL && r->main == NULL && hit_list != NULL) { + unsigned long address = r->connection->remote_addr.sin_addr.s_addr; + char *text_add = inet_ntoa(r->connection->remote_addr.sin_addr); + char hash_key[2048]; + struct ntt_node *n; + time_t t = time(NULL); + + /* Check whitelist */ + + if (is_whitelisted(text_add)) + return OK; + + /* First see if the IP itself is on "hold" */ + snprintf(hash_key, 2048, "%ld", address); + n = ntt_find(hit_list, hash_key); + + if (n != NULL && t-n->timestamptimestamp = time(NULL); + + /* Not on hold, check hit stats */ + } else { + + /* Has URI been hit too much? */ + snprintf(hash_key, 2048, "%ld_%s", address, r->uri); + n = ntt_find(hit_list, hash_key); + if (n != NULL) { + + /* If URI is being hit too much, add to "hold" list and 403 */ + if (t-n->timestampcount>=page_count) { + ret = FORBIDDEN; + snprintf(hash_key, 2048, "%ld", address); + ntt_insert(hit_list, hash_key, time(NULL)); + } else { + + /* Reset our hit count list as necessary */ + if (t-n->timestamp>=page_interval) { + n->count=0; + } + } + n->timestamp = t; + n->count++; + } else { + ntt_insert(hit_list, hash_key, t); + } + + /* Has site been hit too much? */ + snprintf(hash_key, 2048, "%ld_SITE", address); + n = ntt_find(hit_list, hash_key); + if (n != NULL) { + + /* If site is being hit too much, add to "hold" list and 403 */ + if (t-n->timestampcount>=site_count) { + ret = FORBIDDEN; + snprintf(hash_key, 2048, "%ld", address); + ntt_insert(hit_list, hash_key, time(NULL)); + } else { + + /* Reset our hit count list as necessary */ + if (t-n->timestamp>=site_interval) { + n->count=0; + } + } + n->timestamp = t; + n->count++; + } else { + ntt_insert(hit_list, hash_key, t); + } + } + + /* Perform email notification and system functions */ + if (ret == FORBIDDEN) { + char filename[1024]; + struct stat s; + FILE *file; + + snprintf(filename, sizeof(filename), "%s/dos-%s", log_dir != NULL ? log_dir : DEFAULT_LOG_DIR, text_add); + if (stat(filename, &s)) { + file = fopen(filename, "w"); + if (file != NULL) { + fprintf(file, "%ld\n", getpid()); + fclose(file); + + LOG(LOG_ALERT, "Blacklisting address %s: possible attack.", text_add) + if (email_notify != NULL) { + snprintf(filename, sizeof(filename), MAILER, email_notify); + file = popen(filename, "w"); + if (file != NULL) { + fprintf(file, "To: %s\n", email_notify); + fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", text_add); + fprintf(file, "mod_evasive HTTP Blacklisted %s\n", text_add); + pclose(file); + } + } + + if (sys_command != NULL) { + snprintf(filename, sizeof(filename), sys_command, text_add); + system(filename); + } + + } else { + LOG(LOG_ALERT, "Couldn't open logfile %s: %s",filename, strerror(errno)); + } + + } /* if (temp file does not exist) */ + + } /* if (ret == FORBIDDEN) */ + + } /* if (r->prev == NULL && r->main == NULL && hit_list != NULL) */ + + /* END Evasive Maneuvers Code */ + + if (ret == FORBIDDEN + && (ap_satisfies(r) != SATISFY_ANY || !ap_some_auth_required(r))) { + ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r, + "client denied by server configuration: %s", + r->filename); + } + + return ret; +} + +static void evasive_child_exit(server_rec *s, pool *p) +{ + ntt_destroy(hit_list); + free(email_notify); + free(sys_command); +} + + +/* BEGIN NTT (Named Timestamp Tree) Functions */ + +static unsigned long ntt_prime_list[ntt_num_primes] = +{ + 53ul, 97ul, 193ul, 389ul, 769ul, + 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, + 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, + 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, + 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, + 1610612741ul, 3221225473ul, 4294967291ul +}; + + +/* Find the numeric position in the hash table based on key and modulus */ + +long ntt_hashcode(struct ntt *ntt, const char *key) { + unsigned long val = 0; + for (; *key; ++key) val = 5 * val + *key; + return(val % ntt->size); +} + +/* Creates a single node in the tree */ + +struct ntt_node *ntt_node_create(const char *key) { + char *node_key; + struct ntt_node* node; + + node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); + if (node == NULL) { + return NULL; + } + if ((node_key = strdup(key)) == NULL) { + free(node); + return NULL; + } + node->key = node_key; + node->timestamp = time(NULL); + node->next = NULL; + return(node); +} + +/* Tree initializer */ + +struct ntt *ntt_create(long size) { + long i = 0; + struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); + + if (ntt == NULL) + return NULL; + while (ntt_prime_list[i] < size) { i++; } + ntt->size = ntt_prime_list[i]; + ntt->items = 0; + ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); + if (ntt->tbl == NULL) { + free(ntt); + return NULL; + } + return(ntt); +} + +/* Find an object in the tree */ + +struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { + long hash_code; + struct ntt_node *node; + + if (ntt == NULL) return NULL; + + hash_code = ntt_hashcode(ntt, key); + node = ntt->tbl[hash_code]; + + while (node) { + if (!strcmp(key, node->key)) { + return(node); + } + node = node->next; + } + return((struct ntt_node *)NULL); +} + +/* Insert a node into the tree */ + +struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { + long hash_code; + struct ntt_node *parent; + struct ntt_node *node; + struct ntt_node *new_node = NULL; + + if (ntt == NULL) return NULL; + + hash_code = ntt_hashcode(ntt, key); + parent = NULL; + node = ntt->tbl[hash_code]; + + while (node != NULL) { + if (strcmp(key, node->key) == 0) { + new_node = node; + node = NULL; + } + + if (new_node == NULL) { + parent = node; + node = node->next; + } + } + + if (new_node != NULL) { + new_node->timestamp = timestamp; + new_node->count = 0; + return new_node; + } + + /* Create a new node */ + new_node = ntt_node_create(key); + new_node->timestamp = timestamp; + new_node->timestamp = 0; + + ntt->items++; + + /* Insert */ + if (parent) { /* Existing parent */ + parent->next = new_node; + return new_node; /* Return the locked node */ + } + + /* No existing parent; add directly to hash table */ + ntt->tbl[hash_code] = new_node; + return new_node; +} + +/* Tree destructor */ + +int ntt_destroy(struct ntt *ntt) { + struct ntt_node *node, *next; + struct ntt_c c; + + if (ntt == NULL) return -1; + + node = c_ntt_first(ntt, &c); + while(node != NULL) { + next = c_ntt_next(ntt, &c); + ntt_delete(ntt, node->key); + node = next; + } + + free(ntt->tbl); + free(ntt); + ntt = (struct ntt *) NULL; + + return 0; +} + +/* Delete a single node in the tree */ + +int ntt_delete(struct ntt *ntt, const char *key) { + long hash_code; + struct ntt_node *parent = NULL; + struct ntt_node *node; + struct ntt_node *del_node = NULL; + + if (ntt == NULL) return -1; + + hash_code = ntt_hashcode(ntt, key); + node = ntt->tbl[hash_code]; + + while (node != NULL) { + if (strcmp(key, node->key) == 0) { + del_node = node; + node = NULL; + } + + if (del_node == NULL) { + parent = node; + node = node->next; + } + } + + if (del_node != NULL) { + + if (parent) { + parent->next = del_node->next; + } else { + ntt->tbl[hash_code] = del_node->next; + } + + free(del_node->key); + free(del_node); + ntt->items--; + + return 0; + } + + return -5; +} + +/* Point cursor to first item in tree */ + +struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { + + c->iter_index = 0; + c->iter_next = (struct ntt_node *)NULL; + return(c_ntt_next(ntt, c)); +} + +/* Point cursor to next iteration in tree */ + +struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { + long index; + struct ntt_node *node = c->iter_next; + + if (ntt == NULL) return NULL; + + if (node) { + if (node != NULL) { + c->iter_next = node->next; + return (node); + } + } + + if (! node) { + while (c->iter_index < ntt->size) { + index = c->iter_index++; + + if (ntt->tbl[index]) { + c->iter_next = ntt->tbl[index]->next; + return(ntt->tbl[index]); + } + } + } + return((struct ntt_node *)NULL); +} + +/* END NTT (Named Pointer Tree) Functions */ + +/* BEGIN Configuration Functions */ + +static const char * +get_hash_tbl_size(cmd_parms *cmd, void *dconfig, char *value) { + long n = strtol(value, NULL, 0); + + if (n<=0) + hash_table_size = DEFAULT_HASH_TBL_SIZE; + else + hash_table_size = n; + + return NULL; +} + +static const char * +get_page_count(cmd_parms *cmd, void *dconfig, char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) + page_count = DEFAULT_PAGE_COUNT; + else + page_count = n; + + return NULL; +} + +static const char * +get_site_count(cmd_parms *cmd, void *dconfig, char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) + site_count = DEFAULT_SITE_COUNT; + else + site_count = n; + + return NULL; +} + +static const char * +get_page_interval(cmd_parms *cmd, void *dconfig, char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) + page_interval = DEFAULT_PAGE_INTERVAL; + else + page_interval = n; + + return NULL; +} + +static const char * +get_site_interval(cmd_parms *cmd, void *dconfig, char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) + site_interval = DEFAULT_SITE_INTERVAL; + else + site_interval = n; + + return NULL; +} + +static const char * +get_blocking_period(cmd_parms *cmd, void *dconfig, char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) + blocking_period = DEFAULT_BLOCKING_PERIOD; + else + blocking_period = n; + + return NULL; +} + +static const char * +get_log_dir(cmd_parms *cmd, void *dconfig, char *value) { + if (value != NULL && value[0] != 0) { + if (log_dir != NULL) + free(log_dir); + log_dir = strdup(value); + } + + return NULL; +} + +static const char * +get_email_notify(cmd_parms *cmd, void *dconfig, char *value) { + if (value != NULL && value[0] != 0) { + if (email_notify != NULL) + free(email_notify); + email_notify = strdup(value); + } + + return NULL; +} + +static const char * +get_sys_command(cmd_parms *cmd, void *dconfig, char *value) { + if (value != NULL && value[0] != 0) { + if (sys_command != NULL) + free(sys_command); + sys_command = strdup(value); + } + + return NULL; +} + +static const char *whitelist(cmd_parms *cmd, void *mconfig, char *ip) { + char entry[128]; + + if (white_list == NULL) + white_list = ntt_create(53ul); + snprintf(entry, sizeof(entry), "%s", ip); + ntt_insert(white_list, entry, time(NULL)); + + return NULL; +} + +/* END Configuration Functions */ + +int is_whitelisted(const char *ip) { + char hashkey[128]; + char octet[4][4]; + char *dip; + char *oct; + int i = 0; + + memset(octet, 0, 16); + dip = strdup(ip); + if (dip == NULL) + return 0; + + oct = strtok(dip, "."); + while(oct != NULL && i<4) { + if (strlen(oct)<=3) + strcpy(octet[i], oct); + i++; + oct = strtok(NULL, "."); + } + free(dip); + + /* Exact Match */ + snprintf(hashkey, sizeof(hashkey), "%s", ip); + if (ntt_find(white_list, hashkey)!=NULL) + return 1; + + /* IPv4 Wildcards */ + snprintf(hashkey, sizeof(hashkey), "%s.*.*.*", octet[0]); + if (ntt_find(white_list, hashkey)!=NULL) + return 1; + + snprintf(hashkey, sizeof(hashkey), "%s.%s.*.*", + octet[0], octet[1]); + if (ntt_find(white_list, hashkey)!=NULL) + return 1; + + snprintf(hashkey, sizeof(hashkey), "%s.%s.%s.*", + octet[0], octet[1], octet[2]); + if (ntt_find(white_list, hashkey)!=NULL) + return 1; + + /* No match */ + return 0; +} + +static command_rec command_table[] = { + + { "DOSWhitelist", whitelist, NULL, RSRC_CONF, ITERATE, + "Whitelist an IP or Wildcard. "}, + + { "DOSHashTableSize", get_hash_tbl_size, NULL, RSRC_CONF, TAKE1, + "Set size of hash table. " }, + + { "DOSPageCount", get_page_count, NULL, RSRC_CONF, TAKE1, + "Set maximum page hit count per interval. " }, + + { "DOSSiteCount", get_site_count, NULL, RSRC_CONF, TAKE1, + "Set maximum site hit count per interval. " }, + + { "DOSPageInterval", get_page_interval, NULL, RSRC_CONF, TAKE1, + "Set page interval. " }, + + { "DOSSiteInterval", get_site_interval, NULL, RSRC_CONF, TAKE1, + "Set site interval. " }, + + { "DOSLogDir", get_log_dir, NULL, RSRC_CONF, TAKE1, + "Set log dir. "}, + + { "DOSEmailNotify", get_email_notify, NULL, RSRC_CONF, TAKE1, + "Set email notification. "}, + + { "DOSSystemCommand", get_sys_command, NULL, RSRC_CONF, TAKE1, + "Set system command. "}, + + { "DOSBlockingPeriod", get_blocking_period, NULL, RSRC_CONF, TAKE1, + "Set blocking period for detected DoS IPs. "}, + + { NULL } +}; + +module MODULE_VAR_EXPORT evasive_module = { + STANDARD_MODULE_STUFF, + NULL, /* initializer */ + NULL, /* dir config creator */ + NULL, /* dir config merger */ + NULL, /* server config creator */ + NULL, /* server config merger */ + command_table, /* command table */ + NULL, /* handlers */ + NULL, /* filename translation */ + NULL, /* check_user_id */ + NULL, /* check auth */ + check_access, /* check access */ + NULL, /* type_checker */ + NULL, /* fixups */ + NULL, /* logger */ + NULL, /* header parser */ + evasive_child_init, /* child_init */ + evasive_child_exit, /* child_exit */ + NULL /* post read-request */ +}; + diff --git a/mod_evasive20.c b/mod_evasive20.c new file mode 100644 index 0000000..4fa228c --- /dev/null +++ b/mod_evasive20.c @@ -0,0 +1,699 @@ +/* +mod_evasive for Apache 2 +Copyright (c) by Jonathan A. Zdziarski + +LICENSE + +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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "httpd.h" +#include "http_core.h" +#include "http_config.h" +#include "http_log.h" +#include "http_request.h" + +module AP_MODULE_DECLARE_DATA evasive20_module; + +/* BEGIN DoS Evasive Maneuvers Definitions */ + +#define MAILER "/bin/mail %s" +#define LOG( A, ... ) { openlog("mod_evasive", LOG_PID, LOG_DAEMON); syslog( A, __VA_ARGS__ ); closelog(); } + +#define DEFAULT_HASH_TBL_SIZE 3097ul // Default hash table size +#define DEFAULT_PAGE_COUNT 2 // Default maximum page hit count per interval +#define DEFAULT_SITE_COUNT 50 // Default maximum site hit count per interval +#define DEFAULT_PAGE_INTERVAL 1 // Default 1 Second page interval +#define DEFAULT_SITE_INTERVAL 1 // Default 1 Second site interval +#define DEFAULT_BLOCKING_PERIOD 10 // Default for Detected IPs; blocked for 10 seconds +#define DEFAULT_LOG_DIR "/tmp" // Default temp directory + +/* END DoS Evasive Maneuvers Definitions */ + +/* BEGIN NTT (Named Timestamp Tree) Headers */ + +enum { ntt_num_primes = 28 }; + +/* ntt root tree */ +struct ntt { + long size; + long items; + struct ntt_node **tbl; +}; + +/* ntt node (entry in the ntt root tree) */ +struct ntt_node { + char *key; + time_t timestamp; + long count; + struct ntt_node *next; +}; + +/* ntt cursor */ +struct ntt_c { + long iter_index; + struct ntt_node *iter_next; +}; + +struct ntt *ntt_create(long size); +int ntt_destroy(struct ntt *ntt); +struct ntt_node *ntt_find(struct ntt *ntt, const char *key); +struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); +int ntt_delete(struct ntt *ntt, const char *key); +long ntt_hashcode(struct ntt *ntt, const char *key); +struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); +struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); + +/* END NTT (Named Timestamp Tree) Headers */ + + +/* BEGIN DoS Evasive Maneuvers Globals */ + +struct ntt *hit_list; // Our dynamic hash table + +static unsigned long hash_table_size = DEFAULT_HASH_TBL_SIZE; +static int page_count = DEFAULT_PAGE_COUNT; +static int page_interval = DEFAULT_PAGE_INTERVAL; +static int site_count = DEFAULT_SITE_COUNT; +static int site_interval = DEFAULT_SITE_INTERVAL; +static int blocking_period = DEFAULT_BLOCKING_PERIOD; +static char *email_notify = NULL; +static char *log_dir = NULL; +static char *system_command = NULL; +static const char *whitelist(cmd_parms *cmd, void *dconfig, const char *ip); +int is_whitelisted(const char *ip); + +/* END DoS Evasive Maneuvers Globals */ + +static void * create_hit_list(apr_pool_t *p, server_rec *s) +{ + /* Create a new hit list for this listener */ + + hit_list = ntt_create(hash_table_size); +} + +static const char *whitelist(cmd_parms *cmd, void *dconfig, const char *ip) +{ + char entry[128]; + snprintf(entry, sizeof(entry), "WHITELIST_%s", ip); + ntt_insert(hit_list, entry, time(NULL)); + + return NULL; +} + + +static int access_checker(request_rec *r) +{ + int ret = OK; + + /* BEGIN DoS Evasive Maneuvers Code */ + + if (r->prev == NULL && r->main == NULL && hit_list != NULL) { + char hash_key[2048]; + struct ntt_node *n; + time_t t = time(NULL); + + /* Check whitelist */ + if (is_whitelisted(r->connection->remote_ip)) + return OK; + + /* First see if the IP itself is on "hold" */ + n = ntt_find(hit_list, r->connection->remote_ip); + + if (n != NULL && t-n->timestamptimestamp = time(NULL); + + /* Not on hold, check hit stats */ + } else { + + /* Has URI been hit too much? */ + snprintf(hash_key, 2048, "%s_%s", r->connection->remote_ip, r->uri); + n = ntt_find(hit_list, hash_key); + if (n != NULL) { + + /* If URI is being hit too much, add to "hold" list and 403 */ + if (t-n->timestampcount>=page_count) { + ret = HTTP_FORBIDDEN; + ntt_insert(hit_list, r->connection->remote_ip, time(NULL)); + } else { + + /* Reset our hit count list as necessary */ + if (t-n->timestamp>=page_interval) { + n->count=0; + } + } + n->timestamp = t; + n->count++; + } else { + ntt_insert(hit_list, hash_key, t); + } + + /* Has site been hit too much? */ + snprintf(hash_key, 2048, "%s_SITE", r->connection->remote_ip); + n = ntt_find(hit_list, hash_key); + if (n != NULL) { + + /* If site is being hit too much, add to "hold" list and 403 */ + if (t-n->timestampcount>=site_count) { + ret = HTTP_FORBIDDEN; + ntt_insert(hit_list, r->connection->remote_ip, time(NULL)); + } else { + + /* Reset our hit count list as necessary */ + if (t-n->timestamp>=site_interval) { + n->count=0; + } + } + n->timestamp = t; + n->count++; + } else { + ntt_insert(hit_list, hash_key, t); + } + } + + /* Perform email notification and system functions */ + if (ret == HTTP_FORBIDDEN) { + char filename[1024]; + struct stat s; + FILE *file; + + snprintf(filename, sizeof(filename), "%s/dos-%s", log_dir != NULL ? log_dir : DEFAULT_LOG_DIR, r->connection->remote_ip); + if (stat(filename, &s)) { + file = fopen(filename, "w"); + if (file != NULL) { + fprintf(file, "%ld\n", getpid()); + fclose(file); + + LOG(LOG_ALERT, "Blacklisting address %s: possible DoS attack.", r->connection->remote_ip); + if (email_notify != NULL) { + snprintf(filename, sizeof(filename), MAILER, email_notify); + file = popen(filename, "w"); + if (file != NULL) { + fprintf(file, "To: %s\n", email_notify); + fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", r->connection->remote_ip); + fprintf(file, "mod_evasive HTTP Blacklisted %s\n", r->connection->remote_ip); + pclose(file); + } + } + + if (system_command != NULL) { + snprintf(filename, sizeof(filename), system_command, r->connection->remote_ip); + system(filename); + } + + } else { + LOG(LOG_ALERT, "Couldn't open logfile %s: %s",filename, strerror(errno)); + } + + } /* if (temp file does not exist) */ + + } /* if (ret == HTTP_FORBIDDEN) */ + + } /* if (r->prev == NULL && r->main == NULL && hit_list != NULL) */ + + /* END DoS Evasive Maneuvers Code */ + + if (ret == HTTP_FORBIDDEN + && (ap_satisfies(r) != SATISFY_ANY || !ap_some_auth_required(r))) { + ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, + "client denied by server configuration: %s", + r->filename); + } + + return ret; +} + +int is_whitelisted(const char *ip) { + char hashkey[128]; + char octet[4][4]; + char *dip; + char *oct; + int i = 0; + + memset(octet, 0, 16); + dip = strdup(ip); + if (dip == NULL) + return 0; + + oct = strtok(dip, "."); + while(oct != NULL && i<4) { + if (strlen(oct)<=3) + strcpy(octet[i], oct); + i++; + oct = strtok(NULL, "."); + } + free(dip); + + /* Exact Match */ + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s", ip); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + /* IPv4 Wildcards */ + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.*.*.*", octet[0]); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.*.*", octet[0], octet[1]); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.%s.*", octet[0], octet[1], octet[2]); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + /* No match */ + return 0; +} + +static apr_status_t destroy_hit_list(void *not_used) { + ntt_destroy(hit_list); + free(email_notify); + free(system_command); +} + + +/* BEGIN NTT (Named Timestamp Tree) Functions */ + +static unsigned long ntt_prime_list[ntt_num_primes] = +{ + 53ul, 97ul, 193ul, 389ul, 769ul, + 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, + 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, + 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, + 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, + 1610612741ul, 3221225473ul, 4294967291ul +}; + + +/* Find the numeric position in the hash table based on key and modulus */ + +long ntt_hashcode(struct ntt *ntt, const char *key) { + unsigned long val = 0; + for (; *key; ++key) val = 5 * val + *key; + return(val % ntt->size); +} + +/* Creates a single node in the tree */ + +struct ntt_node *ntt_node_create(const char *key) { + char *node_key; + struct ntt_node* node; + + node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); + if (node == NULL) { + return NULL; + } + if ((node_key = strdup(key)) == NULL) { + free(node); + return NULL; + } + node->key = node_key; + node->timestamp = time(NULL); + node->next = NULL; + return(node); +} + +/* Tree initializer */ + +struct ntt *ntt_create(long size) { + long i = 0; + struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); + + if (ntt == NULL) + return NULL; + while (ntt_prime_list[i] < size) { i++; } + ntt->size = ntt_prime_list[i]; + ntt->items = 0; + ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); + if (ntt->tbl == NULL) { + free(ntt); + return NULL; + } + return(ntt); +} + +/* Find an object in the tree */ + +struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { + long hash_code; + struct ntt_node *node; + + if (ntt == NULL) return NULL; + + hash_code = ntt_hashcode(ntt, key); + node = ntt->tbl[hash_code]; + + while (node) { + if (!strcmp(key, node->key)) { + return(node); + } + node = node->next; + } + return((struct ntt_node *)NULL); +} + +/* Insert a node into the tree */ + +struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { + long hash_code; + struct ntt_node *parent; + struct ntt_node *node; + struct ntt_node *new_node = NULL; + + if (ntt == NULL) return NULL; + + hash_code = ntt_hashcode(ntt, key); + parent = NULL; + node = ntt->tbl[hash_code]; + + while (node != NULL) { + if (strcmp(key, node->key) == 0) { + new_node = node; + node = NULL; + } + + if (new_node == NULL) { + parent = node; + node = node->next; + } + } + + if (new_node != NULL) { + new_node->timestamp = timestamp; + new_node->count = 0; + return new_node; + } + + /* Create a new node */ + new_node = ntt_node_create(key); + new_node->timestamp = timestamp; + new_node->timestamp = 0; + + ntt->items++; + + /* Insert */ + if (parent) { /* Existing parent */ + parent->next = new_node; + return new_node; /* Return the locked node */ + } + + /* No existing parent; add directly to hash table */ + ntt->tbl[hash_code] = new_node; + return new_node; +} + +/* Tree destructor */ + +int ntt_destroy(struct ntt *ntt) { + struct ntt_node *node, *next; + struct ntt_c c; + + if (ntt == NULL) return -1; + + node = c_ntt_first(ntt, &c); + while(node != NULL) { + next = c_ntt_next(ntt, &c); + ntt_delete(ntt, node->key); + node = next; + } + + free(ntt->tbl); + free(ntt); + ntt = (struct ntt *) NULL; + + return 0; +} + +/* Delete a single node in the tree */ + +int ntt_delete(struct ntt *ntt, const char *key) { + long hash_code; + struct ntt_node *parent = NULL; + struct ntt_node *node; + struct ntt_node *del_node = NULL; + + if (ntt == NULL) return -1; + + hash_code = ntt_hashcode(ntt, key); + node = ntt->tbl[hash_code]; + + while (node != NULL) { + if (strcmp(key, node->key) == 0) { + del_node = node; + node = NULL; + } + + if (del_node == NULL) { + parent = node; + node = node->next; + } + } + + if (del_node != NULL) { + + if (parent) { + parent->next = del_node->next; + } else { + ntt->tbl[hash_code] = del_node->next; + } + + free(del_node->key); + free(del_node); + ntt->items--; + + return 0; + } + + return -5; +} + +/* Point cursor to first item in tree */ + +struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { + + c->iter_index = 0; + c->iter_next = (struct ntt_node *)NULL; + return(c_ntt_next(ntt, c)); +} + +/* Point cursor to next iteration in tree */ + +struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { + long index; + struct ntt_node *node = c->iter_next; + + if (ntt == NULL) return NULL; + + if (node) { + if (node != NULL) { + c->iter_next = node->next; + return (node); + } + } + + if (! node) { + while (c->iter_index < ntt->size) { + index = c->iter_index++; + + if (ntt->tbl[index]) { + c->iter_next = ntt->tbl[index]->next; + return(ntt->tbl[index]); + } + } + } + return((struct ntt_node *)NULL); +} + +/* END NTT (Named Pointer Tree) Functions */ + + +/* BEGIN Configuration Functions */ + +static const char * +get_hash_tbl_size(cmd_parms *cmd, void *dconfig, const char *value) { + long n = strtol(value, NULL, 0); + + if (n<=0) { + hash_table_size = DEFAULT_HASH_TBL_SIZE; + } else { + hash_table_size = n; + } + + return NULL; +} + +static const char * +get_page_count(cmd_parms *cmd, void *dconfig, const char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) { + page_count = DEFAULT_PAGE_COUNT; + } else { + page_count = n; + } + + return NULL; +} + +static const char * +get_site_count(cmd_parms *cmd, void *dconfig, const char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) { + site_count = DEFAULT_SITE_COUNT; + } else { + site_count = n; + } + + return NULL; +} + +static const char * +get_page_interval(cmd_parms *cmd, void *dconfig, const char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) { + page_interval = DEFAULT_PAGE_INTERVAL; + } else { + page_interval = n; + } + + return NULL; +} + +static const char * +get_site_interval(cmd_parms *cmd, void *dconfig, const char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) { + site_interval = DEFAULT_SITE_INTERVAL; + } else { + site_interval = n; + } + + return NULL; +} + +static const char * +get_blocking_period(cmd_parms *cmd, void *dconfig, const char *value) { + long n = strtol(value, NULL, 0); + if (n<=0) { + blocking_period = DEFAULT_BLOCKING_PERIOD; + } else { + blocking_period = n; + } + + return NULL; +} + +static const char * +get_log_dir(cmd_parms *cmd, void *dconfig, const char *value) { + if (value != NULL && value[0] != 0) { + if (log_dir != NULL) + free(log_dir); + log_dir = strdup(value); + } + + return NULL; +} + +static const char * +get_email_notify(cmd_parms *cmd, void *dconfig, const char *value) { + if (value != NULL && value[0] != 0) { + if (email_notify != NULL) + free(email_notify); + email_notify = strdup(value); + } + + return NULL; +} + +static const char * +get_system_command(cmd_parms *cmd, void *dconfig, const char *value) { + if (value != NULL && value[0] != 0) { + if (system_command != NULL) + free(system_command); + system_command = strdup(value); + } + + return NULL; +} + +/* END Configuration Functions */ + +static const command_rec access_cmds[] = +{ + AP_INIT_TAKE1("DOSHashTableSize", get_hash_tbl_size, NULL, RSRC_CONF, + "Set size of hash table"), + + AP_INIT_TAKE1("DOSPageCount", get_page_count, NULL, RSRC_CONF, + "Set maximum page hit count per interval"), + + AP_INIT_TAKE1("DOSSiteCount", get_site_count, NULL, RSRC_CONF, + "Set maximum site hit count per interval"), + + AP_INIT_TAKE1("DOSPageInterval", get_page_interval, NULL, RSRC_CONF, + "Set page interval"), + + AP_INIT_TAKE1("DOSSiteInterval", get_site_interval, NULL, RSRC_CONF, + "Set site interval"), + + AP_INIT_TAKE1("DOSBlockingPeriod", get_blocking_period, NULL, RSRC_CONF, + "Set blocking period for detected DoS IPs"), + + AP_INIT_TAKE1("DOSEmailNotify", get_email_notify, NULL, RSRC_CONF, + "Set email notification"), + + AP_INIT_TAKE1("DOSLogDir", get_log_dir, NULL, RSRC_CONF, + "Set log dir"), + + AP_INIT_TAKE1("DOSSystemCommand", get_system_command, NULL, RSRC_CONF, + "Set system command on DoS"), + + AP_INIT_ITERATE("DOSWhitelist", whitelist, NULL, RSRC_CONF, + "IP-addresses wildcards to whitelist"), + + { NULL } +}; + +static void register_hooks(apr_pool_t *p) { + ap_hook_access_checker(access_checker, NULL, NULL, APR_HOOK_MIDDLE); + apr_pool_cleanup_register(p, NULL, apr_pool_cleanup_null, destroy_hit_list); +}; + +module AP_MODULE_DECLARE_DATA evasive20_module = +{ + STANDARD20_MODULE_STUFF, + NULL, + NULL, + create_hit_list, + NULL, + access_cmds, + register_hooks +}; + diff --git a/mod_evasiveNSAPI.c b/mod_evasiveNSAPI.c new file mode 100644 index 0000000..8712383 --- /dev/null +++ b/mod_evasiveNSAPI.c @@ -0,0 +1,608 @@ +/* +mod_dosevasive/1.8 for NSAPI + +Copyright 2002 by Jonathan A. Zdziarski. All rights reserved. + +LICENSE +------- + +This distribution may be freely distributed in its original form. +License is granted to make modifications to the source for internal, +private use only, provided you retain this notice, disclaimers, author's +copyright, and credits. + + +DISCLAIMER +---------- + +THIS SOFTWARE IS PROVIDE "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, +INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO WAY SHALL THE +AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +/* This is a port to NSAPI from mod_dosevasive/1.8 for Apache 2.0 + 2003-10-29 Reine Persson +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + + +/* BEGIN DoS Evasive Maneuvers Definitions */ + +#define DEFAULT_LOG_DIR "/tmp" +#define MAILER "/bin/mail %s" +#define LOG( A, ... ) { openlog("mod_dosevasive", LOG_PID, LOG_DAEMON); syslog( A, __VA_ARGS__ ); closelog(); } + +#define DEFAULT_HASH_TBL_SIZE 3097ul // Default hash table size +#define DEFAULT_PAGE_COUNT 2 // Default maximum page hit count per interval +#define DEFAULT_SITE_COUNT 50 // Default maximum site hit count per interval +#define DEFAULT_PAGE_INTERVAL 1 // Default 1 Second page interval +#define DEFAULT_SITE_INTERVAL 1 // Default 1 Second site interval +#define DEFAULT_BLOCKING_PERIOD 10 // Default for Detected IPs; blocked for 10 seconds + +/* END DoS Evasive Maneuvers Definitions */ + +static CRITICAL mod_dosevasive_crit; + +/* BEGIN NTT (Named Timestamp Tree) Headers */ + +enum { ntt_num_primes = 28 }; + +/* ntt root tree */ +struct ntt { + long size; + long items; + struct ntt_node **tbl; +}; + +/* ntt node (entry in the ntt root tree) */ +struct ntt_node { + char *key; + time_t timestamp; + long count; + struct ntt_node *next; +}; + +/* ntt cursor */ +struct ntt_c { + long iter_index; + struct ntt_node *iter_next; +}; + +struct ntt *ntt_create(long size); +int ntt_destroy(struct ntt *ntt); +struct ntt_node *ntt_find(struct ntt *ntt, const char *key); +struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); +int ntt_delete(struct ntt *ntt, const char *key); +long ntt_hashcode(struct ntt *ntt, const char *key); +struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); +struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); + +/* END NTT (Named Timestamp Tree) Headers */ + + +/* BEGIN DoS Evasive Maneuvers Globals */ + +struct ntt *hit_list; // Our dynamic hash table + +static unsigned long hash_table_size = DEFAULT_HASH_TBL_SIZE; +static int page_count = DEFAULT_PAGE_COUNT; +static int page_interval = DEFAULT_PAGE_INTERVAL; +static int site_count = DEFAULT_SITE_COUNT; +static int site_interval = DEFAULT_SITE_INTERVAL; +static int blocking_period = DEFAULT_BLOCKING_PERIOD; +static char *log_dir = NULL; +static char *email_notify = NULL; +static char *system_command = NULL; + +static const char * whitelist(const char *ip); +int is_whitelisted(const char *ip); +static int destroy_hit_list(void *not_used); + +/* END DoS Evasive Maneuvers Globals */ + +static char * +itemize(char *str,char delim) +{ + static char *nextitem = NULL; + char *result; + + if(str) + nextitem=str; + if(!nextitem) + return(NULL); + result=nextitem; + while(*nextitem && *nextitem!=delim) + ++nextitem; + if(*nextitem) + *nextitem++='\0'; + else + nextitem=NULL; + return(result); +} + + +NSAPI_PUBLIC int +mod_dosevasive_init(pblock *pb, Session *sn, Request *rq) +{ + char *ip,*stmp,*white_list=NULL; + int itmp; + + mod_dosevasive_crit = crit_init(); + if ((itmp=atoi(pblock_findval("DOSHashTableSize", pb))) != 0 ) + hash_table_size=itmp; + if ((itmp=atoi(pblock_findval("DOSPageCount", pb))) != 0 ) + page_count=itmp; + if ((itmp=atoi(pblock_findval("DOSSiteCount", pb))) != 0 ) + site_count=itmp; + if ((itmp=atoi(pblock_findval("DOSPageInterval", pb))) != 0 ) + page_interval=itmp; + if ((itmp=atoi(pblock_findval("DOSSiteInterval", pb))) != 0 ) + site_interval=itmp; + if ((itmp=atoi(pblock_findval("DOSBlockingPeriod", pb))) != 0 ) + blocking_period=itmp; + if ((stmp=pblock_findval("DOSLogDir", pb)) != NULL ) + log_dir=stmp; + if ((stmp=pblock_findval("DOSEmailNotify", pb)) != NULL ) + email_notify=stmp; + if ((stmp=pblock_findval("DOSSystemCommand", pb)) != NULL ) + system_command=stmp; + + white_list=pblock_findval("DOSWhitelist", pb); + + hit_list = ntt_create(hash_table_size); + + if ( white_list != NULL ) { + ip=itemize(white_list,','); + while( ip != NULL ) { + whitelist(ip); + ip=itemize(NULL,','); + } + } + return REQ_PROCEED; +} + +NSAPI_PUBLIC int +mod_dosevasive_check(pblock *pb, Session *sn, Request *rq) +{ + int ret = REQ_PROCEED; + + /* BEGIN DoS Evasive Maneuvers Code */ + + if (pblock_findval("NS_original_uri",rq->vars) == NULL && pblock_findval("referer",rq->headers) == NULL && hit_list != NULL) { + char hash_key[2048]; + struct ntt_node *n; + time_t t = time(NULL); + + /* Check whitelist */ + if (is_whitelisted(pblock_findval("ip",sn->client))) + return REQ_PROCEED; + + /* First see if the IP itself is on "hold" */ + n = ntt_find(hit_list, pblock_findval("ip",sn->client)); + + if (n != NULL && t-n->timestamptimestamp = time(NULL); + + /* Not on hold, check hit stats */ + } else { + + /* Has URI been hit too much? */ + snprintf(hash_key, 2048, "%s_%s", pblock_findval("ip",sn->client), pblock_findval("uri",rq->reqpb)); + n = ntt_find(hit_list, hash_key); + if (n != NULL) { + + /* If URI is being hit too much, add to "hold" list and 403 */ + if (t-n->timestampcount>=page_count) { + ret = REQ_ABORTED; + ntt_insert(hit_list, pblock_findval("ip",sn->client), time(NULL)); + } else { + + /* Reset our hit count list as necessary */ + if (t-n->timestamp>=page_interval) { + n->count=0; + } + } + n->timestamp = t; + n->count++; + } else { + + ntt_insert(hit_list, hash_key, t); + } + + /* Has site been hit too much? */ + snprintf(hash_key, 2048, "%s_SITE", pblock_findval("ip",sn->client)); + n = ntt_find(hit_list, hash_key); + if (n != NULL) { + + /* If site is being hit too much, add to "hold" list and 403 */ + if (t-n->timestampcount>=site_count) { + ret = REQ_ABORTED; + ntt_insert(hit_list, pblock_findval("ip",sn->client), time(NULL)); + } else { + + /* Reset our hit count list as necessary */ + if (t-n->timestamp>=site_interval) { + n->count=0; + } + } + n->timestamp = t; + n->count++; + } else { + ntt_insert(hit_list, hash_key, t); + } + } + + /* Perform email notification and system functions */ + if (ret == REQ_ABORTED) { + char filename[1024]; + struct stat s; + FILE *file; + + snprintf(filename, sizeof(filename), "%s/dos-%s", log_dir != NULL ? log_dir : DEFAULT_LOG_DIR, pblock_findval("ip",sn->client)); + if (stat(filename, &s)) { + file = fopen(filename, "w"); + if (file != NULL) { + fprintf(file, "%ld\n", getpid()); + fclose(file); + + LOG(LOG_ALERT, "Blacklisting address %s: possible DoS attack.",pblock_findval("ip",sn->client)); + if (email_notify != NULL) { + snprintf(filename, sizeof(filename), MAILER, email_notify); + file = popen(filename, "w"); + if (file != NULL) { + fprintf(file, "To: %s\n", email_notify); + fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", pblock_findval("ip",sn->client)); + fprintf(file, "mod_dosevasive HTTP Blacklisted %s\n", pblock_findval("ip",sn->client)); + pclose(file); + } else { + LOG(LOG_ALERT, "Couldn't open logfile %s: %s",filename, strerror(errno)); + } + } + + if (system_command != NULL) { + snprintf(filename, sizeof(filename), system_command, pblock_findval("ip",sn->client)); + system(filename); + } + + } + + } /* if (temp file does not exist) */ + + } /* if (ret == REQ_ABORTED) */ + + } /* if (vars->NS_Original_uri == NULL && headers->referer == NULL && hit_list != NULL) */ + + /* END DoS Evasive Maneuvers Code */ + + if (ret == REQ_ABORTED ) { + log_error(LOG_SECURITY,"mod_dosevasive_check",sn,rq,"client denied by server configuration: %s",pblock_findval("uri",rq->reqpb)); + protocol_status(sn, rq, PROTOCOL_FORBIDDEN, NULL); + } + return ret; +} + + +static const char *whitelist(const char *ip) +{ + char entry[128]; + snprintf(entry, sizeof(entry), "WHITELIST_%s", ip); + ntt_insert(hit_list, entry, time(NULL)); + + return NULL; +} + + +int is_whitelisted(const char *ip) { + char hashkey[128]; + char octet[4][4]; + char *dip; + char *oct; + int i = 0; + + memset(octet, 0, 16); + dip = strdup(ip); + if (dip == NULL) + return 0; + + oct = strtok(dip, "."); + while(oct != NULL && i<4) { + if (strlen(oct)<=3) + strcpy(octet[i], oct); + i++; + oct = strtok(NULL, "."); + } + free(dip); + + /* Exact Match */ + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s", ip); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + /* IPv4 Wildcards */ + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.*.*.*", octet[0]); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.*.*", octet[0], octet[1]); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.%s.*", octet[0], octet[1], octet[2]); + if (ntt_find(hit_list, hashkey)!=NULL) + return 1; + + /* No match */ + return 0; +} + +static int destroy_hit_list(void *not_used) { + ntt_destroy(hit_list); + free(log_dir); + free(email_notify); + free(system_command); + return 0; +} + + +/* BEGIN NTT (Named Timestamp Tree) Functions */ + +static unsigned long ntt_prime_list[ntt_num_primes] = +{ + 53ul, 97ul, 193ul, 389ul, 769ul, + 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, + 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, + 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, + 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, + 1610612741ul, 3221225473ul, 4294967291ul +}; + + +/* Find the numeric position in the hash table based on key and modulus */ + +long ntt_hashcode(struct ntt *ntt, const char *key) { + unsigned long val = 0; + for (; *key; ++key) val = 5 * val + *key; + return(val % ntt->size); +} + +/* Creates a single node in the tree */ + +struct ntt_node *ntt_node_create(const char *key) { + char *node_key; + struct ntt_node* node; + + node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); + if (node == NULL) { + return NULL; + } + if ((node_key = strdup(key)) == NULL) { + free(node); + return NULL; + } + node->key = node_key; + node->timestamp = time(NULL); + node->next = NULL; + return(node); +} + +/* Tree initializer */ + +struct ntt *ntt_create(long size) { + long i = 0; + struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); + + if (ntt == NULL) + return NULL; + while (ntt_prime_list[i] < size) { i++; } + ntt->size = ntt_prime_list[i]; + ntt->items = 0; + ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); + if (ntt->tbl == NULL) { + free(ntt); + return NULL; + } + return(ntt); +} + +/* Find an object in the tree */ + +struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { + long hash_code; + struct ntt_node *node; + + if (ntt == NULL) return NULL; + + hash_code = ntt_hashcode(ntt, key); + node = ntt->tbl[hash_code]; + + while (node) { + if (!strcmp(key, node->key)) { + return(node); + } + node = node->next; + } + return((struct ntt_node *)NULL); +} + +/* Insert a node into the tree */ + +struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { + long hash_code; + struct ntt_node *parent; + struct ntt_node *node; + struct ntt_node *new_node = NULL; + + if (ntt == NULL) return NULL; + + hash_code = ntt_hashcode(ntt, key); + parent = NULL; + node = ntt->tbl[hash_code]; + + crit_enter(mod_dosevasive_crit); /*Lock*/ + + while (node != NULL) { + if (strcmp(key, node->key) == 0) { + new_node = node; + node = NULL; + } + + if (new_node == NULL) { + parent = node; + node = node->next; + } + } + + if (new_node != NULL) { + new_node->timestamp = timestamp; + new_node->count = 0; + crit_exit(mod_dosevasive_crit); /*Unlock*/ + return new_node; + } + + /* Create a new node */ + new_node = ntt_node_create(key); + new_node->timestamp = timestamp; + new_node->timestamp = 0; + + ntt->items++; + + /* Insert */ + if (parent) { /* Existing parent */ + parent->next = new_node; + crit_exit(mod_dosevasive_crit); /*Unlock*/ + return new_node; /* Return the locked node */ + } + + /* No existing parent; add directly to hash table */ + ntt->tbl[hash_code] = new_node; + crit_exit(mod_dosevasive_crit); /*Unlock*/ + return new_node; +} + +/* Tree destructor */ + +int ntt_destroy(struct ntt *ntt) { + struct ntt_node *node, *next; + struct ntt_c c; + + if (ntt == NULL) return -1; + + node = c_ntt_first(ntt, &c); + while(node != NULL) { + next = c_ntt_next(ntt, &c); + ntt_delete(ntt, node->key); + node = next; + } + + free(ntt->tbl); + free(ntt); + ntt = (struct ntt *) NULL; + + return 0; +} + +/* Delete a single node in the tree */ + +int ntt_delete(struct ntt *ntt, const char *key) { + long hash_code; + struct ntt_node *parent = NULL; + struct ntt_node *node; + struct ntt_node *del_node = NULL; + + if (ntt == NULL) return -1; + + hash_code = ntt_hashcode(ntt, key); + node = ntt->tbl[hash_code]; + + while (node != NULL) { + if (strcmp(key, node->key) == 0) { + del_node = node; + node = NULL; + } + + if (del_node == NULL) { + parent = node; + node = node->next; + } + } + + if (del_node != NULL) { + + if (parent) { + parent->next = del_node->next; + } else { + ntt->tbl[hash_code] = del_node->next; + } + + free(del_node->key); + free(del_node); + ntt->items--; + + return 0; + } + + return -5; +} + +/* Point cursor to first item in tree */ + +struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { + + c->iter_index = 0; + c->iter_next = (struct ntt_node *)NULL; + return(c_ntt_next(ntt, c)); +} + +/* Point cursor to next iteration in tree */ + +struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { + long index; + struct ntt_node *node = c->iter_next; + + if (ntt == NULL) return NULL; + + if (node) { + if (node != NULL) { + c->iter_next = node->next; + return (node); + } + } + + if (! node) { + while (c->iter_index < ntt->size) { + index = c->iter_index++; + + if (ntt->tbl[index]) { + c->iter_next = ntt->tbl[index]->next; + return(ntt->tbl[index]); + } + } + } + return((struct ntt_node *)NULL); +} + +/* END NTT (Named Pointer Tree) Functions */ diff --git a/test.pl b/test.pl new file mode 100644 index 0000000..dc8ca76 --- /dev/null +++ b/test.pl @@ -0,0 +1,18 @@ +#!/usr/bin/perl + +# test.pl: small script to test mod_dosevasive's effectiveness + +use IO::Socket; +use strict; + +for(0..100) { + my($response); + my($SOCKET) = new IO::Socket::INET( Proto => "tcp", + PeerAddr=> "127.0.0.1:80"); + if (! defined $SOCKET) { die $!; } + print $SOCKET "GET /?$_ HTTP/1.0\n\n"; + $response = <$SOCKET>; + print $response; + close($SOCKET); +} +