├── CHANGELOG ├── Dockerfile ├── LICENSE ├── Makefile.tmpl ├── README.md ├── debian-build.sh ├── dist ├── libapache2-mod-evasive.deb └── libapache2-mod-evasive │ ├── DEBIAN │ ├── control │ └── postinst │ ├── etc │ └── apache2 │ │ └── mods-available │ │ └── evasive.load │ └── usr │ └── lib │ └── apache2 │ └── modules │ └── mod_evasive.so ├── docker-build.sh ├── mod_evasive.conf ├── mod_evasive13.c ├── mod_evasive20.c ├── mod_evasive24.c ├── mod_evasive24win.c ├── mod_evasiveNSAPI.c └── test ├── 00_regular_config ├── etc │ ├── mod_evasive.conf │ └── sites.conf ├── test.pl ├── test.sh └── www │ ├── j_spring_security_check │ └── whitelisted-uri ├── 01_no_config ├── etc │ ├── mod_evasive.conf │ └── sites.conf ├── test.pl ├── test.sh └── www │ ├── j_spring_security_check │ └── whitelisted-uri └── 02_reproduce_segfault ├── etc ├── mod_evasive.conf └── sites.conf ├── test.pl ├── test.sh └── www ├── j_spring_security_check └── whitelisted-uri /CHANGELOG: -------------------------------------------------------------------------------- 1 | Version 2.3.0 2 | ----------- 3 | 4 | [20240728] WebReusAbuse + jvdmr: Bugfix: segfault on empty config 5 | 6 | [20240728] jvdmr: Bugfix: count initialisation in apache 2.0 and windows apache 2.4 7 | 8 | [20240728] jvdmr: Add DOSWhitelistUri config option for Windows [EXPERIMENTAL/UNTESTED] 9 | 10 | Version 2.2.0 11 | ----------- 12 | 13 | [20200208] jvdmr: Add DOSWhitelistUri config option 14 | 15 | Version 2.1.1 16 | ----------- 17 | 18 | [20171011] jvdmr: Set Debian package version 19 | 20 | Version 2.0 21 | ----------- 22 | 23 | [20171010] jvdmr: Added Windows support (based off Greg Smith's port) 24 | 25 | [20171010] jvdmr: Renamed mod_evasive14 to mode_evasive13 to match Apache 1.3 version number 26 | 27 | [20171010] jvdmr: Backported new features to Apache 2.0 28 | 29 | [20171010] jvdmr: Debian package for Apache 2.4 30 | 31 | [20171010] jvdmr: Support for per-vhost configuration instead of only global 32 | 33 | [20171009] jvdmr: evasive20_module is now simply called evasive_module 34 | 35 | [20171009] jvdmr: Added DOSHTTPStatus directive 36 | 37 | [20171009] jvdmr: Added support for Apache 2.4 38 | 39 | Version 1.10.1 40 | -------------- 41 | 42 | [20051008] jonz: Fixed IP Whitelisting in Apache 1.3 Version 43 | 44 | [20051008] jonz: Corrected initialization to prevent dumping IP database 45 | 46 | [20051008] jonz: Documentation and code cleaned up, renamed mod_evasive 47 | 48 | Version 1.10.0 49 | -------------- 50 | 51 | [20050117] jonz: Security fix: Tempdir configuration directive (race condition) 52 | 53 | Version 1.9.0 54 | ------------- 55 | 56 | [20031030] jonz: Added NSAPI/SunONE Support 57 | 58 | [20031030] jonz: Added TEMP_HOME definition to change temporary file locations 59 | 60 | Version 1.8.0 61 | ------------- 62 | 63 | [20030901] jonz: Added support for IP Whitelisting 64 | 65 | Version 1.7.1 66 | ------------- 67 | 68 | [20030826] jonz: Minor bugfixes to Apache 2.0 module 69 | 70 | [20030826] jonz: Corrections to object creation and cleanup 71 | 72 | Version 1.7.0 73 | ------------- 74 | 75 | [20030822] jonz: Support for Apache 2.0 76 | 77 | Version 1.6.1 78 | ------------- 79 | 80 | [20030811] jonz: Bugfix: free() of another static variable 81 | 82 | Version 1.6.0 83 | ------------- 84 | 85 | [20030806] jonz: Added syslog support 86 | 87 | Version 1.5.1 88 | ------------- 89 | 90 | [20030516] jonz: Bugfix: free() of a static variable 91 | 92 | Version 1.5.0 93 | ------------- 94 | 95 | [20030425] jonz: Added automated email notification 96 | 97 | [20030425] jonz: Added configurable system command 98 | 99 | Version 1.4.0 100 | ------------- 101 | 102 | [20021031] jonz: Added support fror httpd.conf directives 103 | 104 | [20021031] jonz: Added --add-module support 105 | 106 | Version 1.0.0 107 | ------------- 108 | 109 | [20021015] jonz: Initial Release 110 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM jvdmr/apache-dev:latest AS build 2 | MAINTAINER @jvdmr 3 | 4 | ADD . /opt/jvdmr/apache2/mod_evasive 5 | WORKDIR /opt/jvdmr/apache2/mod_evasive 6 | 7 | RUN mv mod_evasive24.c mod_evasive.c && \ 8 | /usr/bin/apxs -i -a -c -l pcre2-8 mod_evasive.c && \ 9 | apache2ctl configtest 10 | 11 | CMD bash 12 | 13 | 14 | FROM debian:stable AS test 15 | 16 | EXPOSE 80 17 | 18 | WORKDIR /opt/jvdmr/apache2/mod_evasive 19 | 20 | ARG test_path test/00_regular_config 21 | 22 | RUN apt-get update 23 | RUN apt-get -y install apache2 24 | 25 | COPY --from=build /usr/lib/apache2/modules/mod_evasive.so /usr/lib/apache2/modules/mod_evasive.so 26 | COPY --from=build /etc/apache2/mods-available/evasive.load /etc/apache2/mods-available/evasive.load 27 | 28 | RUN mkdir -p /opt/jvdmr/apache2/mod_evasive 29 | COPY ${test_path}/www /opt/jvdmr/apache2/mod_evasive/www 30 | COPY ${test_path}/etc/mod_evasive.conf /etc/apache2/conf-enabled/mod_evasive.conf 31 | COPY ${test_path}/etc/sites.conf /etc/apache2/sites-enabled/sites.conf 32 | 33 | RUN a2enmod evasive 34 | CMD service apache2 start && bash 35 | 36 | 37 | FROM jvdmr/apache-dev:latest AS package 38 | 39 | WORKDIR /opt/jvdmr/apache2/mod_evasive 40 | 41 | COPY --from=build /usr/lib/apache2/modules/mod_evasive.so /usr/lib/apache2/modules/mod_evasive.so 42 | COPY mod_evasive.conf /etc/apache2/conf-enabled/mod_evasive.conf 43 | COPY debian-build.sh debian-build.sh 44 | 45 | CMD bash 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA 6 | 7 | Everyone is permitted to copy and distribute verbatim copies 8 | of this license document, but changing it is not allowed. 9 | 10 | Preamble 11 | 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. 12 | 13 | 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. 14 | 15 | 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. 16 | 17 | 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. 18 | 19 | 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. 20 | 21 | 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. 22 | 23 | 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. 24 | 25 | The precise terms and conditions for copying, distribution and modification follow. 26 | 27 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 28 | 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". 29 | 30 | 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. 31 | 32 | 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. 33 | 34 | 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. 35 | 36 | 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: 37 | 38 | 39 | a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. 40 | 41 | 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. 42 | 43 | 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.) 44 | 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. 45 | 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. 46 | 47 | 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. 48 | 49 | 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: 50 | 51 | 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, 52 | 53 | 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, 54 | 55 | 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.) 56 | 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. 57 | 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. 58 | 59 | 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. 60 | 61 | 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. 62 | 63 | 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. 64 | 65 | 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. 66 | 67 | 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. 68 | 69 | 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. 70 | 71 | This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 72 | 73 | 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. 74 | 75 | 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. 76 | 77 | 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. 78 | 79 | 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. 80 | 81 | NO WARRANTY 82 | 83 | 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. 84 | 85 | 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. 86 | 87 | 88 | END OF TERMS AND CONDITIONS 89 | How to Apply These Terms to Your New Programs 90 | 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. 91 | 92 | 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. 93 | 94 | one line to give the program's name and an idea of what it does. 95 | Copyright (C) yyyy name of author 96 | 97 | This program is free software; you can redistribute it and/or 98 | modify it under the terms of the GNU General Public License 99 | as published by the Free Software Foundation; either version 2 100 | of the License, or (at your option) any later version. 101 | 102 | This program is distributed in the hope that it will be useful, 103 | but WITHOUT ANY WARRANTY; without even the implied warranty of 104 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 105 | GNU General Public License for more details. 106 | 107 | You should have received a copy of the GNU General Public License 108 | along with this program; if not, write to the Free Software 109 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 110 | 111 | Also add information on how to contact you by electronic and paper mail. 112 | 113 | If the program is interactive, make it output a short notice like this when it starts in an interactive mode: 114 | 115 | Gnomovision version 69, Copyright (C) year name of author 116 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details 117 | type `show w'. This is free software, and you are welcome 118 | to redistribute it under certain conditions; type `show c' 119 | for details. 120 | 121 | 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. 122 | 123 | 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: 124 | 125 | Yoyodyne, Inc., hereby disclaims all copyright 126 | interest in the program `Gnomovision' 127 | (which makes passes at compilers) written 128 | by James Hacker. 129 | 130 | signature of Ty Coon, 1 April 1989 131 | Ty Coon, President of Vice 132 | 133 | 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. 134 | 135 | 136 | -------------------------------------------------------------------------------- 137 | Return to GNU's home page. 138 | FSF & GNU inquiries & questions to gnu@gnu.org. Other ways to contact the FSF. 139 | 140 | Comments on these web pages to webmasters@www.gnu.org, send other questions to gnu@gnu.org. 141 | 142 | Copyright notice above. 143 | Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA 144 | 145 | Updated: Last modified: Sun Jul 15 13:13:30 CEST 2001 146 | 147 | -------------------------------------------------------------------------------- /Makefile.tmpl: -------------------------------------------------------------------------------- 1 | 2 | #Dependencies 3 | 4 | $(OBJS) $(OBJS_PIC): Makefile 5 | 6 | # DO NOT REMOVE 7 | mod_evasive.o: mod_evasive.c $(INCDIR)/httpd.h \ 8 | $(INCDIR)/ap_config.h $(INCDIR)/ap_mmn.h \ 9 | $(INCDIR)/ap_config_auto.h $(OSDIR)/os.h \ 10 | $(INCDIR)/ap_ctype.h $(INCDIR)/hsregex.h \ 11 | $(INCDIR)/ap_alloc.h $(INCDIR)/buff.h $(INCDIR)/ap.h \ 12 | $(INCDIR)/util_uri.h $(INCDIR)/http_config.h \ 13 | $(INCDIR)/http_core.h $(INCDIR)/http_log.h \ 14 | $(INCDIR)/http_main.h $(INCDIR)/http_protocol.h \ 15 | $(INCDIR)/util_script.h 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | * Apache Evasive Maneuvers Module 2 | * For Apache 1.3, 2.0 and 2.4 3 | * Joris Vandermeersch 4 | * Based on mod_evasive by Jonathan Zdziarski (https://github.com/jzdziarski/mod_evasive) 5 | * Version 2.0 6 | 7 | # License 8 | ``` 9 | This program is free software; you can redistribute it and/or 10 | modify it under the terms of the GNU General Public License 11 | as published by the Free Software Foundation; version 2 12 | of the License. 13 | 14 | This program is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with this program; if not, write to the Free Software 21 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 22 | ``` 23 | 24 | # What is mod_evasive? 25 | 26 | mod_evasive is an evasive maneuvers module for Apache to provide evasive 27 | action in the event of an HTTP DoS or DDoS attack or brute force attack. It 28 | is also designed to be a detection tool, and can be easily configured to talk 29 | to ipchains, firewalls, routers, and etcetera. 30 | 31 | Detection is performed by creating an internal dynamic hash table of IP 32 | Addresses and URIs, and denying any single IP address from any of the following: 33 | 34 | - Requesting the same page more than a few times per second 35 | - Making more than 50 concurrent requests on the same child per second 36 | - Making any requests while temporarily blacklisted (on a blocking list) 37 | 38 | This method has worked well in both single-server script attacks as well 39 | as distributed attacks, but just like other evasive tools, is only as 40 | useful to the point of bandwidth and processor consumption (e.g. the 41 | amount of bandwidth and processor required to receive/process/respond 42 | to invalid requests), which is why it's a good idea to integrate this 43 | with your firewalls and routers. 44 | 45 | This module instantiates for each listener individually, and therefore has 46 | a built-in cleanup mechanism and scaling capabilities. Because of this, 47 | legitimate requests are rarely ever compromised, only legitimate attacks. Even 48 | a user repeatedly clicking on 'reload' should not be affected unless they do 49 | it maliciously. 50 | 51 | Five different module sources have been provided: 52 | 53 | * Apache v2.4 API: mod_evasive24.c 54 | * Apache v2.4 API (windows): mod_evasive24win.c 55 | * Apache v2.0 API: mod_evasive20.c 56 | * Apache v1.3 API: mod_evasive13.c (outdated) 57 | * NSAPI (iPlanet): mod_evasiveNSAPI.c 58 | 59 | NOTE: mod_evasiveNSAPI is a port submitted by Reine Persson 60 | and is not officially supported as part of the mod_evasive project. 61 | 62 | # How it works 63 | 64 | A web hit request comes in. The following steps take place: 65 | 66 | - The IP address of the requestor is looked up on the temporary blacklist 67 | - The IP address of the requestor and the URI are both hashed into a "key". 68 | A lookup is performed in the listener's internal hash table to determine 69 | if the same host has requested this page more than once within the past 70 | 1 second. 71 | - The IP address of the requestor is hashed into a "key". 72 | A lookup is performed in the listener's internal hash table to determine 73 | if the same host has requested more than 50 objects within the past 74 | second (from the same child). 75 | 76 | If any of the above are true, a 403 response is sent. This conserves 77 | bandwidth and system resources in the event of a DoS attack. Additionally, 78 | a system command and/or an email notification can also be triggered to block 79 | all the originating addresses of a DDoS attack. 80 | 81 | Once a single 403 incident occurs, mod_evasive now blocks the entire IP 82 | address for a period of 10 seconds (configurable). If the host requests a 83 | page within this period, it is forced to wait even longer. Since this is 84 | triggered from requesting the same URL multiple times per second, this 85 | again does not affect legitimate users. 86 | 87 | The blacklist can/should be configured to talk to your network's firewalls 88 | and/or routers to push the attack out to the front lines, but this is not 89 | required. 90 | 91 | mod_evasive also performs syslog reporting using daemon.alert. Messages 92 | will look like this: 93 | 94 | Aug 6 17:41:49 elijah mod_evasive[23184]: [ID 801097 daemon.alert] Blacklisting address x.x.x.x: possible attack. 95 | 96 | # What is this tool useful for? 97 | 98 | This tool is *excellent* at fending off request-based DoS attacks or scripted 99 | attacks, and brute force attacks. When integrated with firewalls or IP filters, 100 | mod_evasive can stand up to even large attacks. Its features will prevent you 101 | from wasting bandwidth or having a few thousand CGI scripts running as a 102 | result of an attack. 103 | 104 | If you do not have an infrastructure capable of fending off any other types 105 | of DoS attacks, chances are this tool will only help you to the point of 106 | your total bandwidth or server capacity for sending 403's. Without a solid 107 | infrastructure and address filtering tool in place, a heavy distributed DoS 108 | will most likely still take you offline. 109 | 110 | # How to install 111 | 112 | ## APACHE v2.0/v2.4 113 | 114 | ### On Debian 115 | 116 | 1. Download libapache2-mod-evasive.deb (found in the dist folder) 117 | 2. `dpkg -i libapache2-mod-evasive.deb` 118 | 3. Restart Apache 119 | 120 | ### On Windows 121 | 122 | There is a `mod_evasive24win.c` that includes all the features from the Linux 123 | version except DOSEmailNotify. It should work fine. Unfortunately I do not have 124 | a Windows development or testing environment. This means I can't test it, and I 125 | don't know how to install it. If you know how to do these things, please let me 126 | know and I'll update the instructions here. 127 | 128 | As always, any bugs may also be filed through Github and I'll see what I can do. 129 | 130 | ### Compile from source 131 | 132 | 1. Extract this archive 133 | 2. `mv mod_evasive24.c mod_evasive.c` 134 | 3. Run `$APACHE_ROOT/bin/apxs -i -a -c mod_evasive.c` 135 | 4. The module will be built and installed into $APACHE_ROOT/modules, and loaded into your httpd.conf 136 | 5. Restart Apache 137 | 138 | ## APACHE v1.3 (outdated) 139 | 140 | Note: This version is missing some features. 141 | 142 | Without DSO Support: 143 | 144 | 1. Extract this archive into src/modules in the Apache source tree 145 | 2. `mv mod_evasive13.c mod_evasive.c` 146 | 3. Run `./configure --add-module=src/modules/evasive/mod_evasive.c` 147 | 4. `make && make install` 148 | 5. Restart Apache 149 | 150 | With DSO Support, Ensim, or CPanel: 151 | 152 | 1. `$APACHE_ROOT/bin/apxs -iac mod_evasive.c` 153 | 2. Restart Apache 154 | 155 | ## NSAPI 156 | SunONE (iPlanet,netscape) Installation 157 | 158 | Tested on: 159 | iPlanet 4.1sp12 160 | iPlanet 6.0sp5 161 | 162 | Edit compile script for your environment and compile mod_evasiveNSAPI.c 163 | to a shared library. 164 | 165 | # Configuration 166 | 167 | mod_evasive has default options configured, but you may also add the 168 | following block to your httpd.conf: 169 | 170 | ## Apache (1.3/2.0/2.4) 171 | ``` 172 | 173 | DOSEnabled true 174 | DOSHashTableSize 3079 175 | DOSPageCount 2 176 | DOSSiteCount 50 177 | DOSPageInterval 1 178 | DOSSiteInterval 1 179 | DOSBlockingPeriod 10 180 | 181 | ``` 182 | 183 | Optionally you can also add the following directives: 184 | 185 | ``` 186 | DOSEmailNotify you@yourdomain.com 187 | DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" 188 | DOSLogDir "/var/lock/mod_evasive" 189 | DOSWhitelist 127.0.0.1 190 | DOSWhitelistUri whitelist.*regex 191 | DOSTargetlistUri targetlist.*regex 192 | DOSHTTPStatus 429 193 | ``` 194 | 195 | You will also need to add this line if you are building with dynamic support: 196 | 197 | ### APACHE v1.3 198 | 199 | ``` 200 | AddModule mod_evasive.c 201 | ``` 202 | 203 | ### APACHE v2.0 204 | 205 | ``` 206 | LoadModule evasive_module modules/mod_evasive.so 207 | ``` 208 | 209 | (This line is already added to your configuration by apxs) 210 | 211 | ## NSAPI 212 | SunONE (iPlanet,Netscape) Configuration 213 | 214 | ### Configure iPlanet 4.1 215 | 216 | Edit obj.conf: 217 | ``` 218 | Init fn="load-modules" funcs="mod_evasive_init,mod_evasive_check" shlib="/opt/ns-4.1/plugins/lib/mod_evasive.sl" 219 | 220 | Init fn="mod_evasive_init" DOSPageCount=2 DOSSiteCount=50 DOSPageInterval=1 DOSSiteInterval=1 DOSBlockingPeriod=10 DOSWhitelist="10.60.0.7,10.65.0.10" 221 | ``` 222 | 223 | In the default object: 224 | ``` 225 | PathCheck fn=mod_evasive_check 226 | ``` 227 | 228 | Or an own object 229 | ``` 230 | 231 | NameTrans fn=mod_evasive_check 232 | 233 | ``` 234 | 235 | ### Configure iPlanet 6.0 236 | 237 | Edit magnus.conf: 238 | ```                                                                                 239 | Init fn="load-modules" funcs="mod_evasive_init,mod_evasive_check" shlib="/opt/iplanet-6.0/plugins/lib/mod_evasive.sl" 240 | 241 | Init fn="mod_evasive_init" DOSWhitelist="10.60.0.7,10.65.0.10" 242 | ``` 243 | 244 | Edit obj.conf: 245 | In the default object: 246 | ``` 247 | PathCheck fn=mod_evasive_check 248 | ```                                                                                 249 | Or an own object 250 | ``` 251 | 252 | NameTrans fn=mod_evasive_check 253 | 254 | ``` 255 | 256 | # Features 257 | ## DOSEnabled 258 | 259 | Set to `true` to enable mod_evasive. Set globally to enable everywhere, or only 260 | in specific VirtualHosts otherwise. 261 | 262 | ## DOSHashTableSize 263 | 264 | The hash table size defines the number of top-level nodes for each child's 265 | hash table. Increasing this number will provide faster performance by 266 | decreasing the number of iterations required to get to the record, but 267 | consume more memory for table space. You should increase this if you have 268 | a busy web server. The value you specify will automatically be tiered up to 269 | the next prime number in the primes list (see mod_evasive.c for a list 270 | of primes used). 271 | 272 | ## DOSPageCount 273 | 274 | This is the threshold for the number of requests for the same page (or URI) 275 | per page interval. Once the threshold for that interval has been exceeded, 276 | the IP address of the client will be added to the blocking list. 277 | 278 | ## DOSSiteCount 279 | 280 | This is the threshold for the total number of requests for any object by 281 | the same client on the same listener per site interval. Once the threshold 282 | for that interval has been exceeded, the IP address of the client will be added 283 | to the blocking list. 284 | 285 | ## DOSPageInterval 286 | 287 | The interval for the page count threshold; defaults to 1 second intervals. 288 | 289 | ## DOSSiteInterval 290 | 291 | The interval for the site count threshold; defaults to 1 second intervals. 292 | 293 | ## DOSBlockingPeriod 294 | 295 | The blocking period is the amount of time (in seconds) that a client will be 296 | blocked for if they are added to the blocking list. During this time, all 297 | subsequent requests from the client will result in a 403 (Forbidden) and 298 | the timer being reset (e.g. another 10 seconds). Since the timer is reset 299 | for every subsequent request, it is not necessary to have a long blocking 300 | period; in the event of a DoS attack, this timer will keep getting reset. 301 | 302 | ## DOSEmailNotify 303 | 304 | If this value is set, an email will be sent to the address specified 305 | whenever an IP address becomes blacklisted. A locking mechanism using /tmp 306 | prevents continuous emails from being sent. 307 | 308 | NOTE: Be sure MAILER is set correctly in mod_evasive.c. The default is 309 | "/bin/mail -t %s" where %s is used to denote the destination email 310 | address set in the configuration. If you are running on linux or some 311 | other operating system with a different type of mailer, you'll need to 312 | change this. 313 | 314 | ## DOSSystemCommand 315 | 316 | If this value is set, the system command specified will be executed 317 | whenever an IP address becomes blacklisted. This is designed to enable 318 | system calls to ip filter or other tools. A locking mechanism using /tmp 319 | prevents continuous system calls. Use %s to denote the IP address of the 320 | blacklisted IP. 321 | 322 | ## DOSLogDir 323 | 324 | Choose an alternative temp directory 325 | 326 | By default "/tmp" will be used for locking mechanism, which opens some 327 | security issues if your system is open to shell users. 328 | 329 | http://security.lss.hr/index.php?page=details&ID=LSS-2005-01-01 330 | 331 | In the event you have nonprivileged shell users, you'll want to create a 332 | directory writable only to the user Apache is running as (usually root), 333 | then set this in your httpd.conf. 334 | 335 | ## DOSHTTPStatus 336 | 337 | Choose an alternative HTTP status code for the reply to blocked clients. 338 | 339 | By default mod_evasive returns 403 Forbidden to blocked clients. This 340 | directive allows any other HTTP code known to Apache to be used instead. 341 | 342 | ## Whitelisting IP Addresses 343 | 344 | IP addresses of trusted clients can be whitelisted to insure they are never 345 | denied. The purpose of whitelisting is to protect software, scripts, local 346 | searchbots, or other automated tools from being denied for requesting large 347 | amounts of data from the server. Whitelisting should *not* be used to add 348 | customer lists or anything of the sort, as this will open the server to abuse. 349 | This module is very difficult to trigger without performing some type of 350 | malicious attack, and for that reason it is more appropriate to allow the 351 | module to decide on its own whether or not an individual customer should be 352 | blocked. 353 | 354 | To whitelist an address (or range) add an entry to the Apache configuration 355 | in the following fashion: 356 | 357 | DOSWhitelist 127.0.0.1 358 | DOSWhitelist 127.0.0.* 359 | 360 | Wildcards can be used on up to the last 3 octets if necessary. Multiple 361 | DOSWhitelist commands may be used in the configuration. 362 | 363 | You can add several entries. 364 | 365 | ## Whitelisting URI's 366 | 367 | Specific URI's can be whitelisted to insure they are never denied. Some 368 | clients may repeatedly request the same URI (due to bugs, or for other 369 | reasons), and subsequently be blocked from making other (valid) requests. If 370 | you want, you may whitelist these URI's so these clients won't be blocked. 371 | Use with caution. 372 | 373 | To whitelist a URI add an entry to the Apache configuration 374 | in the following fashion: 375 | 376 | DOSWhitelistUri /path/to/whitelisted/resource 377 | DOSWhitelistUri .*whitelisted.* 378 | 379 | `DOSWhitelistUri` supports perl-style regex and matches the whole request URI 380 | (everything between the domain name and the ?) against this regex. 381 | 382 | You can add several entries. 383 | 384 | > [!CAUTION] 385 | > This is currently UNTESTED on Windows, I'm not sure it will even compile. Let 386 | > me know about any issues, or even if it does work as expected! :pray: 387 | 388 | ## Targeting URI's 389 | 390 | It may be desirable to apply DoS detection only to specific paths, such as '/login'. 391 | If a target list of URI's is defined, then URI's that do not match one of the targets are excluded from DoS detection. 392 | For example, if only '/login' is targeted, then excessive requests to '/home' will not trigger evasive responses. 393 | 394 | To target a URI add an entry to the Apache configuration 395 | in the following fashion: 396 | 397 | DOSTargetlistUri /path/to/targeted/resource 398 | DOSTargetlistUri .*targeted.* 399 | 400 | Like `DOSWhitelistUri`, `DOSTargetlistUri` supports perl-style regex and matches the whole request URI 401 | (everything between the domain name and the ?) against this regex. 402 | 403 | > [!CAUTION] 404 | > This is only available in mod_evasive24.c 405 | 406 | # Tweaking Apache 407 | 408 | The keep-alive settings for your children should be reasonable enough to 409 | keep each child up long enough to resist a DOS attack (or at least part of 410 | one). Remember, it is the child processes that maintain their own internal 411 | IP address tables, and so when one exits, so does all of the IP information it 412 | had. For every child that exits, another 5-10 copies of the page may get 413 | through before putting the attacker back into '403 Land'. With this said, 414 | you should have a very high MaxRequestsPerChild, but not unlimited as this 415 | will prevent cleanup. 416 | 417 | You'll want to have a MaxRequestsPerChild set to a non-zero value, as 418 | DosEvasive cleans up its internal hashes only on exit. The default 419 | MaxRequestsPerChild is usually 10000. This should suffice in only allowing 420 | a few requests per 10000 per child through in the event of an attack (although 421 | if you use DOSSystemCommand to firewall the IP address, a hole will no 422 | longer be open in between child cycles). 423 | 424 | # Testing 425 | 426 | Want to make sure it's working? Run test.pl, and view the response codes. 427 | It's best to run it several times on the same machine as the web server until 428 | you get 403 Forbidden messages. Some larger servers with high child counts 429 | may require more of a beating than smaller servers before blacklisting 430 | addresses. 431 | 432 | Please don't use this script to DoS others without their permission. 433 | 434 | # Known bugs and Issues 435 | 436 | - This module appears to conflict with the Microsoft Frontpage Extensions. 437 | Frontpage sucks anyway, so if you're using Frontpage I assume you're asking 438 | for problems, and not really interested in conserving server resources anyway. 439 | 440 | - When used together with mod_rewrite, mod_rewrite seems to take priority over 441 | this. This means that Apache will always rewrite the url even during an 442 | attack, and mod_evasive will be ineffective on the original url (but not on 443 | the rewritten url). For example, if you use mod_rewrite to redirect http to 444 | https, the redirect to https will always happen. In this case you should 445 | enable mod_evasive on the https virtualhost only, as it will not have any 446 | effect on the http virtualhost. 447 | 448 | - Using mpm_itk instead of the default mpm_event will cause mod_evasive to never 449 | get triggered. 450 | 451 | # Feedback 452 | 453 | Please use the Github issues feature to tell me about any bugs, missing features, ... 454 | -------------------------------------------------------------------------------- /debian-build.sh: -------------------------------------------------------------------------------- 1 | cd dist 2 | cp /usr/lib/apache2/modules/mod_evasive.so libapache2-mod-evasive/usr/lib/apache2/modules/mod_evasive.so 3 | dpkg-deb --build libapache2-mod-evasive 4 | -------------------------------------------------------------------------------- /dist/libapache2-mod-evasive.deb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jvdmr/mod_evasive/c2a6b8cd7610cb1d9995a5d40285b82b48a7407e/dist/libapache2-mod-evasive.deb -------------------------------------------------------------------------------- /dist/libapache2-mod-evasive/DEBIAN/control: -------------------------------------------------------------------------------- 1 | Package: libapache2-mod-evasive 2 | Version: 2.1.1 3 | Maintainer: Joris Vandermeersch 4 | Architecture: all 5 | Description: evasive module to minimize HTTP DoS or brute force attacks 6 | Depends: apache2 (>= 2.4) 7 | -------------------------------------------------------------------------------- /dist/libapache2-mod-evasive/DEBIAN/postinst: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | a2enmod evasive 4 | /usr/sbin/apache2ctl configtest 5 | -------------------------------------------------------------------------------- /dist/libapache2-mod-evasive/etc/apache2/mods-available/evasive.load: -------------------------------------------------------------------------------- 1 | LoadModule evasive_module /usr/lib/apache2/modules/mod_evasive.so 2 | -------------------------------------------------------------------------------- /dist/libapache2-mod-evasive/usr/lib/apache2/modules/mod_evasive.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jvdmr/mod_evasive/c2a6b8cd7610cb1d9995a5d40285b82b48a7407e/dist/libapache2-mod-evasive/usr/lib/apache2/modules/mod_evasive.so -------------------------------------------------------------------------------- /docker-build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | for tp in test/* 4 | do 5 | echo 6 | echo "Building test container" 7 | docker build . --target test --build-arg "test_path=${tp}" -t mod_evasive_test || exit 1 8 | echo "Starting test container" 9 | docker run --rm -t --name=mod_evasive_test -d -p 1980:80 mod_evasive_test 10 | echo "Running test" 11 | ${tp}/test.sh 12 | echo "Stopping test container" 13 | docker kill mod_evasive_test 14 | done 15 | 16 | echo 17 | echo "Building packaging container" 18 | docker build . --target package -t mod_evasive_package || exit 1 19 | echo "Packaging mod for Debian" 20 | docker run --rm -t --name=mod_evasive_package -v `pwd`/dist:/opt/jvdmr/apache2/mod_evasive/dist mod_evasive_package bash debian-build.sh 21 | echo "Done." 22 | -------------------------------------------------------------------------------- /mod_evasive.conf: -------------------------------------------------------------------------------- 1 | # vim:ts=4 2 | 3 | DOSEnabled true 4 | DOSHashTableSize 3079 5 | DOSPageCount 2 6 | DOSSiteCount 50 7 | DOSPageInterval 1 8 | DOSSiteInterval 1 9 | DOSBlockingPeriod 10 10 | # DOSEmailNotify you@yourdomain.com 11 | # DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" 12 | # DOSLogDir "/var/lock/mod_evasive" 13 | # DOSWhitelist 127.0.0.1 14 | # DOSWhitelistUri white.*regex 15 | # DOSHTTPStatus 429 16 | 17 | -------------------------------------------------------------------------------- /mod_evasive13.c: -------------------------------------------------------------------------------- 1 | /* $Id: mod_evasive.c,v 1.3 2005/10/08 19:17:14 jonz Exp $ */ 2 | 3 | /* 4 | mod_evasive for Apache 1.3 5 | Copyright (c) by Jonathan A. Zdziarski 6 | 7 | LICENSE 8 | 9 | This program is free software; you can redistribute it and/or 10 | modify it under the terms of the GNU General Public License 11 | as published by the Free Software Foundation; version 2 12 | of the License. 13 | 14 | This program is distributed in the hope that it will be useful, 15 | but WITHOUT ANY WARRANTY; without even the implied warranty of 16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 17 | GNU General Public License for more details. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with this program; if not, write to the Free Software 21 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 22 | 23 | */ 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | 37 | #include "httpd.h" 38 | #include "http_core.h" 39 | #include "http_config.h" 40 | #include "http_log.h" 41 | #include "http_request.h" 42 | 43 | module MODULE_VAR_EXPORT evasive_module; 44 | 45 | /* BEGIN DoS Evasive Maneuvers Definitions */ 46 | 47 | #define MAILER "/bin/mail -t %s" 48 | #define LOG( A, ... ) { openlog("mod_evasive", LOG_PID, LOG_DAEMON); syslog( A, __VA_ARGS__ ); closelog(); } 49 | 50 | #define DEFAULT_HASH_TBL_SIZE 3079ul // Default hash table size 51 | #define DEFAULT_PAGE_COUNT 2 // Default max page hit count/interval 52 | #define DEFAULT_SITE_COUNT 50 // Default max site hit count/interval 53 | #define DEFAULT_PAGE_INTERVAL 1 // Default 1 second page interval 54 | #define DEFAULT_SITE_INTERVAL 1 // Default 1 second site interval 55 | #define DEFAULT_BLOCKING_PERIOD 10 // Default block time (Seconds) 56 | #define DEFAULT_LOG_DIR "/tmp" 57 | 58 | /* END DoS Evasive Maneuvers Definitions */ 59 | 60 | /* BEGIN NTT (Named Timestamp Tree) Headers */ 61 | 62 | enum { ntt_num_primes = 28 }; 63 | 64 | /* ntt root tree */ 65 | struct ntt { 66 | long size; 67 | long items; 68 | struct ntt_node **tbl; 69 | }; 70 | 71 | /* ntt node (entry in the ntt root tree) */ 72 | struct ntt_node { 73 | char *key; 74 | time_t timestamp; 75 | long count; 76 | struct ntt_node *next; 77 | }; 78 | 79 | /* ntt cursor */ 80 | struct ntt_c { 81 | long iter_index; 82 | struct ntt_node *iter_next; 83 | }; 84 | 85 | struct ntt *ntt_create(long size); 86 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key); 87 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); 88 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); 89 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); 90 | int ntt_destroy(struct ntt *ntt); 91 | int ntt_delete(struct ntt *ntt, const char *key); 92 | long ntt_hashcode(struct ntt *ntt, const char *key); 93 | 94 | /* END NTT (Named Timestamp Tree) Headers */ 95 | 96 | 97 | /* BEGIN DoS Evasive Maneuvers Globals */ 98 | 99 | struct ntt *hit_list; // Our dynamic hash table 100 | struct ntt *white_list = NULL; // White list table 101 | 102 | static unsigned long hash_table_size = DEFAULT_HASH_TBL_SIZE; 103 | static int page_count = DEFAULT_PAGE_COUNT; 104 | static int page_interval = DEFAULT_PAGE_INTERVAL; 105 | static int site_count = DEFAULT_SITE_COUNT; 106 | static int site_interval = DEFAULT_SITE_INTERVAL; 107 | static int blocking_period = DEFAULT_BLOCKING_PERIOD; 108 | static char *log_dir = NULL; 109 | static char *email_notify = NULL; 110 | static char *sys_command = NULL; 111 | int is_whitelisted(const char *ip); 112 | static const char *whitelist(cmd_parms *cmd, void *mconfig, char *ip); 113 | 114 | /* END DoS Evasive Maneuvers Globals */ 115 | 116 | static void evasive_child_init(server_rec *s, pool *p) 117 | { 118 | hit_list = ntt_create(hash_table_size); 119 | } 120 | 121 | static int check_access(request_rec *r) 122 | { 123 | int ret = OK; 124 | 125 | /* BEGIN Evasive Maneuvers Code */ 126 | 127 | if (r->prev == NULL && r->main == NULL && hit_list != NULL) { 128 | unsigned long address = r->connection->remote_addr.sin_addr.s_addr; 129 | char *text_add = inet_ntoa(r->connection->remote_addr.sin_addr); 130 | char hash_key[2048]; 131 | struct ntt_node *n; 132 | time_t t = time(NULL); 133 | 134 | /* Check whitelist */ 135 | 136 | if (is_whitelisted(text_add)) 137 | return OK; 138 | 139 | /* First see if the IP itself is on "hold" */ 140 | snprintf(hash_key, 2048, "%ld", address); 141 | n = ntt_find(hit_list, hash_key); 142 | 143 | if (n != NULL && t-n->timestamptimestamp = time(NULL); 148 | 149 | /* Not on hold, check hit stats */ 150 | } else { 151 | 152 | /* Has URI been hit too much? */ 153 | snprintf(hash_key, 2048, "%ld_%s", address, r->uri); 154 | n = ntt_find(hit_list, hash_key); 155 | if (n != NULL) { 156 | 157 | /* If URI is being hit too much, add to "hold" list and 403 */ 158 | if (t-n->timestampcount>=page_count) { 159 | ret = FORBIDDEN; 160 | snprintf(hash_key, 2048, "%ld", address); 161 | ntt_insert(hit_list, hash_key, time(NULL)); 162 | } else { 163 | 164 | /* Reset our hit count list as necessary */ 165 | if (t-n->timestamp>=page_interval) { 166 | n->count=0; 167 | } 168 | } 169 | n->timestamp = t; 170 | n->count++; 171 | } else { 172 | ntt_insert(hit_list, hash_key, t); 173 | } 174 | 175 | /* Has site been hit too much? */ 176 | snprintf(hash_key, 2048, "%ld_SITE", address); 177 | n = ntt_find(hit_list, hash_key); 178 | if (n != NULL) { 179 | 180 | /* If site is being hit too much, add to "hold" list and 403 */ 181 | if (t-n->timestampcount>=site_count) { 182 | ret = FORBIDDEN; 183 | snprintf(hash_key, 2048, "%ld", address); 184 | ntt_insert(hit_list, hash_key, time(NULL)); 185 | } else { 186 | 187 | /* Reset our hit count list as necessary */ 188 | if (t-n->timestamp>=site_interval) { 189 | n->count=0; 190 | } 191 | } 192 | n->timestamp = t; 193 | n->count++; 194 | } else { 195 | ntt_insert(hit_list, hash_key, t); 196 | } 197 | } 198 | 199 | /* Perform email notification and system functions */ 200 | if (ret == FORBIDDEN) { 201 | char filename[1024]; 202 | struct stat s; 203 | FILE *file; 204 | 205 | snprintf(filename, sizeof(filename), "%s/dos-%s", log_dir != NULL ? log_dir : DEFAULT_LOG_DIR, text_add); 206 | if (stat(filename, &s)) { 207 | file = fopen(filename, "w"); 208 | if (file != NULL) { 209 | fprintf(file, "%ld\n", getpid()); 210 | fclose(file); 211 | 212 | LOG(LOG_ALERT, "Blacklisting address %s: possible attack.", text_add) 213 | if (email_notify != NULL) { 214 | snprintf(filename, sizeof(filename), MAILER, email_notify); 215 | file = popen(filename, "w"); 216 | if (file != NULL) { 217 | fprintf(file, "To: %s\n", email_notify); 218 | fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", text_add); 219 | fprintf(file, "mod_evasive HTTP Blacklisted %s\n", text_add); 220 | pclose(file); 221 | } 222 | } 223 | 224 | if (sys_command != NULL) { 225 | snprintf(filename, sizeof(filename), sys_command, text_add); 226 | system(filename); 227 | } 228 | 229 | } else { 230 | LOG(LOG_ALERT, "Couldn't open logfile %s: %s",filename, strerror(errno)); 231 | } 232 | 233 | } /* if (temp file does not exist) */ 234 | 235 | } /* if (ret == FORBIDDEN) */ 236 | 237 | } /* if (r->prev == NULL && r->main == NULL && hit_list != NULL) */ 238 | 239 | /* END Evasive Maneuvers Code */ 240 | 241 | if (ret == FORBIDDEN 242 | && (ap_satisfies(r) != SATISFY_ANY || !ap_some_auth_required(r))) { 243 | ap_log_rerror(APLOG_MARK, APLOG_NOERRNO|APLOG_ERR, r, 244 | "client denied by server configuration: %s", 245 | r->filename); 246 | } 247 | 248 | return ret; 249 | } 250 | 251 | static void evasive_child_exit(server_rec *s, pool *p) 252 | { 253 | ntt_destroy(hit_list); 254 | free(email_notify); 255 | free(sys_command); 256 | } 257 | 258 | 259 | /* BEGIN NTT (Named Timestamp Tree) Functions */ 260 | 261 | static unsigned long ntt_prime_list[ntt_num_primes] = 262 | { 263 | 53ul, 97ul, 193ul, 389ul, 769ul, 264 | 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 265 | 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 266 | 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 267 | 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 268 | 1610612741ul, 3221225473ul, 4294967291ul 269 | }; 270 | 271 | 272 | /* Find the numeric position in the hash table based on key and modulus */ 273 | 274 | long ntt_hashcode(struct ntt *ntt, const char *key) { 275 | unsigned long val = 0; 276 | for (; *key; ++key) val = 5 * val + *key; 277 | return(val % ntt->size); 278 | } 279 | 280 | /* Creates a single node in the tree */ 281 | 282 | struct ntt_node *ntt_node_create(const char *key) { 283 | char *node_key; 284 | struct ntt_node* node; 285 | 286 | node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); 287 | if (node == NULL) { 288 | return NULL; 289 | } 290 | if ((node_key = strdup(key)) == NULL) { 291 | free(node); 292 | return NULL; 293 | } 294 | node->key = node_key; 295 | node->timestamp = time(NULL); 296 | node->next = NULL; 297 | return(node); 298 | } 299 | 300 | /* Tree initializer */ 301 | 302 | struct ntt *ntt_create(long size) { 303 | long i = 0; 304 | struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); 305 | 306 | if (ntt == NULL) 307 | return NULL; 308 | while (ntt_prime_list[i] < size) { i++; } 309 | ntt->size = ntt_prime_list[i]; 310 | ntt->items = 0; 311 | ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); 312 | if (ntt->tbl == NULL) { 313 | free(ntt); 314 | return NULL; 315 | } 316 | return(ntt); 317 | } 318 | 319 | /* Find an object in the tree */ 320 | 321 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { 322 | long hash_code; 323 | struct ntt_node *node; 324 | 325 | if (ntt == NULL) return NULL; 326 | 327 | hash_code = ntt_hashcode(ntt, key); 328 | node = ntt->tbl[hash_code]; 329 | 330 | while (node) { 331 | if (!strcmp(key, node->key)) { 332 | return(node); 333 | } 334 | node = node->next; 335 | } 336 | return((struct ntt_node *)NULL); 337 | } 338 | 339 | /* Insert a node into the tree */ 340 | 341 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { 342 | long hash_code; 343 | struct ntt_node *parent; 344 | struct ntt_node *node; 345 | struct ntt_node *new_node = NULL; 346 | 347 | if (ntt == NULL) return NULL; 348 | 349 | hash_code = ntt_hashcode(ntt, key); 350 | parent = NULL; 351 | node = ntt->tbl[hash_code]; 352 | 353 | while (node != NULL) { 354 | if (strcmp(key, node->key) == 0) { 355 | new_node = node; 356 | node = NULL; 357 | } 358 | 359 | if (new_node == NULL) { 360 | parent = node; 361 | node = node->next; 362 | } 363 | } 364 | 365 | if (new_node != NULL) { 366 | new_node->timestamp = timestamp; 367 | new_node->count = 0; 368 | return new_node; 369 | } 370 | 371 | /* Create a new node */ 372 | new_node = ntt_node_create(key); 373 | new_node->timestamp = timestamp; 374 | new_node->timestamp = 0; 375 | 376 | ntt->items++; 377 | 378 | /* Insert */ 379 | if (parent) { /* Existing parent */ 380 | parent->next = new_node; 381 | return new_node; /* Return the locked node */ 382 | } 383 | 384 | /* No existing parent; add directly to hash table */ 385 | ntt->tbl[hash_code] = new_node; 386 | return new_node; 387 | } 388 | 389 | /* Tree destructor */ 390 | 391 | int ntt_destroy(struct ntt *ntt) { 392 | struct ntt_node *node, *next; 393 | struct ntt_c c; 394 | 395 | if (ntt == NULL) return -1; 396 | 397 | node = c_ntt_first(ntt, &c); 398 | while(node != NULL) { 399 | next = c_ntt_next(ntt, &c); 400 | ntt_delete(ntt, node->key); 401 | node = next; 402 | } 403 | 404 | free(ntt->tbl); 405 | free(ntt); 406 | ntt = (struct ntt *) NULL; 407 | 408 | return 0; 409 | } 410 | 411 | /* Delete a single node in the tree */ 412 | 413 | int ntt_delete(struct ntt *ntt, const char *key) { 414 | long hash_code; 415 | struct ntt_node *parent = NULL; 416 | struct ntt_node *node; 417 | struct ntt_node *del_node = NULL; 418 | 419 | if (ntt == NULL) return -1; 420 | 421 | hash_code = ntt_hashcode(ntt, key); 422 | node = ntt->tbl[hash_code]; 423 | 424 | while (node != NULL) { 425 | if (strcmp(key, node->key) == 0) { 426 | del_node = node; 427 | node = NULL; 428 | } 429 | 430 | if (del_node == NULL) { 431 | parent = node; 432 | node = node->next; 433 | } 434 | } 435 | 436 | if (del_node != NULL) { 437 | 438 | if (parent) { 439 | parent->next = del_node->next; 440 | } else { 441 | ntt->tbl[hash_code] = del_node->next; 442 | } 443 | 444 | free(del_node->key); 445 | free(del_node); 446 | ntt->items--; 447 | 448 | return 0; 449 | } 450 | 451 | return -5; 452 | } 453 | 454 | /* Point cursor to first item in tree */ 455 | 456 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { 457 | 458 | c->iter_index = 0; 459 | c->iter_next = (struct ntt_node *)NULL; 460 | return(c_ntt_next(ntt, c)); 461 | } 462 | 463 | /* Point cursor to next iteration in tree */ 464 | 465 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { 466 | long index; 467 | struct ntt_node *node = c->iter_next; 468 | 469 | if (ntt == NULL) return NULL; 470 | 471 | if (node) { 472 | if (node != NULL) { 473 | c->iter_next = node->next; 474 | return (node); 475 | } 476 | } 477 | 478 | if (! node) { 479 | while (c->iter_index < ntt->size) { 480 | index = c->iter_index++; 481 | 482 | if (ntt->tbl[index]) { 483 | c->iter_next = ntt->tbl[index]->next; 484 | return(ntt->tbl[index]); 485 | } 486 | } 487 | } 488 | return((struct ntt_node *)NULL); 489 | } 490 | 491 | /* END NTT (Named Pointer Tree) Functions */ 492 | 493 | /* BEGIN Configuration Functions */ 494 | 495 | static const char * 496 | get_hash_tbl_size(cmd_parms *cmd, void *dconfig, char *value) { 497 | long n = strtol(value, NULL, 0); 498 | 499 | if (n<=0) 500 | hash_table_size = DEFAULT_HASH_TBL_SIZE; 501 | else 502 | hash_table_size = n; 503 | 504 | return NULL; 505 | } 506 | 507 | static const char * 508 | get_page_count(cmd_parms *cmd, void *dconfig, char *value) { 509 | long n = strtol(value, NULL, 0); 510 | if (n<=0) 511 | page_count = DEFAULT_PAGE_COUNT; 512 | else 513 | page_count = n; 514 | 515 | return NULL; 516 | } 517 | 518 | static const char * 519 | get_site_count(cmd_parms *cmd, void *dconfig, char *value) { 520 | long n = strtol(value, NULL, 0); 521 | if (n<=0) 522 | site_count = DEFAULT_SITE_COUNT; 523 | else 524 | site_count = n; 525 | 526 | return NULL; 527 | } 528 | 529 | static const char * 530 | get_page_interval(cmd_parms *cmd, void *dconfig, char *value) { 531 | long n = strtol(value, NULL, 0); 532 | if (n<=0) 533 | page_interval = DEFAULT_PAGE_INTERVAL; 534 | else 535 | page_interval = n; 536 | 537 | return NULL; 538 | } 539 | 540 | static const char * 541 | get_site_interval(cmd_parms *cmd, void *dconfig, char *value) { 542 | long n = strtol(value, NULL, 0); 543 | if (n<=0) 544 | site_interval = DEFAULT_SITE_INTERVAL; 545 | else 546 | site_interval = n; 547 | 548 | return NULL; 549 | } 550 | 551 | static const char * 552 | get_blocking_period(cmd_parms *cmd, void *dconfig, char *value) { 553 | long n = strtol(value, NULL, 0); 554 | if (n<=0) 555 | blocking_period = DEFAULT_BLOCKING_PERIOD; 556 | else 557 | blocking_period = n; 558 | 559 | return NULL; 560 | } 561 | 562 | static const char * 563 | get_log_dir(cmd_parms *cmd, void *dconfig, char *value) { 564 | if (value != NULL && value[0] != 0) { 565 | if (log_dir != NULL) 566 | free(log_dir); 567 | log_dir = strdup(value); 568 | } 569 | 570 | return NULL; 571 | } 572 | 573 | static const char * 574 | get_email_notify(cmd_parms *cmd, void *dconfig, char *value) { 575 | if (value != NULL && value[0] != 0) { 576 | if (email_notify != NULL) 577 | free(email_notify); 578 | email_notify = strdup(value); 579 | } 580 | 581 | return NULL; 582 | } 583 | 584 | static const char * 585 | get_sys_command(cmd_parms *cmd, void *dconfig, char *value) { 586 | if (value != NULL && value[0] != 0) { 587 | if (sys_command != NULL) 588 | free(sys_command); 589 | sys_command = strdup(value); 590 | } 591 | 592 | return NULL; 593 | } 594 | 595 | static const char *whitelist(cmd_parms *cmd, void *mconfig, char *ip) { 596 | char entry[128]; 597 | 598 | if (white_list == NULL) 599 | white_list = ntt_create(53ul); 600 | snprintf(entry, sizeof(entry), "%s", ip); 601 | ntt_insert(white_list, entry, time(NULL)); 602 | 603 | return NULL; 604 | } 605 | 606 | /* END Configuration Functions */ 607 | 608 | int is_whitelisted(const char *ip) { 609 | char hashkey[128]; 610 | char octet[4][4]; 611 | char *dip; 612 | char *oct; 613 | int i = 0; 614 | 615 | memset(octet, 0, 16); 616 | dip = strdup(ip); 617 | if (dip == NULL) 618 | return 0; 619 | 620 | oct = strtok(dip, "."); 621 | while(oct != NULL && i<4) { 622 | if (strlen(oct)<=3) 623 | strcpy(octet[i], oct); 624 | i++; 625 | oct = strtok(NULL, "."); 626 | } 627 | free(dip); 628 | 629 | /* Exact Match */ 630 | snprintf(hashkey, sizeof(hashkey), "%s", ip); 631 | if (ntt_find(white_list, hashkey)!=NULL) 632 | return 1; 633 | 634 | /* IPv4 Wildcards */ 635 | snprintf(hashkey, sizeof(hashkey), "%s.*.*.*", octet[0]); 636 | if (ntt_find(white_list, hashkey)!=NULL) 637 | return 1; 638 | 639 | snprintf(hashkey, sizeof(hashkey), "%s.%s.*.*", 640 | octet[0], octet[1]); 641 | if (ntt_find(white_list, hashkey)!=NULL) 642 | return 1; 643 | 644 | snprintf(hashkey, sizeof(hashkey), "%s.%s.%s.*", 645 | octet[0], octet[1], octet[2]); 646 | if (ntt_find(white_list, hashkey)!=NULL) 647 | return 1; 648 | 649 | /* No match */ 650 | return 0; 651 | } 652 | 653 | static command_rec command_table[] = { 654 | 655 | { "DOSWhitelist", whitelist, NULL, RSRC_CONF, ITERATE, 656 | "Whitelist an IP or Wildcard. "}, 657 | 658 | { "DOSHashTableSize", get_hash_tbl_size, NULL, RSRC_CONF, TAKE1, 659 | "Set size of hash table. " }, 660 | 661 | { "DOSPageCount", get_page_count, NULL, RSRC_CONF, TAKE1, 662 | "Set maximum page hit count per interval. " }, 663 | 664 | { "DOSSiteCount", get_site_count, NULL, RSRC_CONF, TAKE1, 665 | "Set maximum site hit count per interval. " }, 666 | 667 | { "DOSPageInterval", get_page_interval, NULL, RSRC_CONF, TAKE1, 668 | "Set page interval. " }, 669 | 670 | { "DOSSiteInterval", get_site_interval, NULL, RSRC_CONF, TAKE1, 671 | "Set site interval. " }, 672 | 673 | { "DOSLogDir", get_log_dir, NULL, RSRC_CONF, TAKE1, 674 | "Set log dir. "}, 675 | 676 | { "DOSEmailNotify", get_email_notify, NULL, RSRC_CONF, TAKE1, 677 | "Set email notification. "}, 678 | 679 | { "DOSSystemCommand", get_sys_command, NULL, RSRC_CONF, TAKE1, 680 | "Set system command. "}, 681 | 682 | { "DOSBlockingPeriod", get_blocking_period, NULL, RSRC_CONF, TAKE1, 683 | "Set blocking period for detected DoS IPs. "}, 684 | 685 | { NULL } 686 | }; 687 | 688 | module MODULE_VAR_EXPORT evasive_module = { 689 | STANDARD_MODULE_STUFF, 690 | NULL, /* initializer */ 691 | NULL, /* dir config creator */ 692 | NULL, /* dir config merger */ 693 | NULL, /* server config creator */ 694 | NULL, /* server config merger */ 695 | command_table, /* command table */ 696 | NULL, /* handlers */ 697 | NULL, /* filename translation */ 698 | NULL, /* check_user_id */ 699 | NULL, /* check auth */ 700 | check_access, /* check access */ 701 | NULL, /* type_checker */ 702 | NULL, /* fixups */ 703 | NULL, /* logger */ 704 | NULL, /* header parser */ 705 | evasive_child_init, /* child_init */ 706 | evasive_child_exit, /* child_exit */ 707 | NULL /* post read-request */ 708 | }; 709 | 710 | -------------------------------------------------------------------------------- /mod_evasive20.c: -------------------------------------------------------------------------------- 1 | // vim:ts=4:shiftwidth=4:et 2 | /* 3 | mod_evasive for Apache 2 4 | Copyright (c) by Jonathan A. Zdziarski 5 | 6 | LICENSE 7 | 8 | This program is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU General Public License 10 | as published by the Free Software Foundation; either version 2 11 | of the License, or (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 21 | 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | #include 35 | 36 | #include "httpd.h" 37 | #include "http_core.h" 38 | #include "http_config.h" 39 | #include "http_log.h" 40 | #include "http_request.h" 41 | 42 | module AP_MODULE_DECLARE_DATA evasive_module; 43 | 44 | /* BEGIN DoS Evasive Maneuvers Definitions */ 45 | 46 | #define MAILER "/bin/mail %s" 47 | #define LOG( A, ... ) { openlog("mod_evasive", LOG_PID, LOG_DAEMON); syslog( A, __VA_ARGS__ ); closelog(); } 48 | 49 | #define DEFAULT_HASH_TBL_SIZE 3079ul // Default hash table size 50 | #define DEFAULT_PAGE_COUNT 2 // Default maximum page hit count per interval 51 | #define DEFAULT_SITE_COUNT 50 // Default maximum site hit count per interval 52 | #define DEFAULT_PAGE_INTERVAL 1 // Default 1 Second page interval 53 | #define DEFAULT_SITE_INTERVAL 1 // Default 1 Second site interval 54 | #define DEFAULT_BLOCKING_PERIOD 10 // Default for Detected IPs; blocked for 10 seconds 55 | #define DEFAULT_LOG_DIR "/tmp" // Default temp directory 56 | #define DEFAULT_HTTP_REPLY HTTP_FORBIDDEN // Default HTTP Reply code (403) 57 | 58 | /* END DoS Evasive Maneuvers Definitions */ 59 | 60 | /* BEGIN NTT (Named Timestamp Tree) Headers */ 61 | 62 | enum { ntt_num_primes = 28 }; 63 | 64 | /* ntt root tree */ 65 | struct ntt { 66 | long size; 67 | long items; 68 | struct ntt_node **tbl; 69 | }; 70 | 71 | /* ntt node (entry in the ntt root tree) */ 72 | struct ntt_node { 73 | char *key; 74 | time_t timestamp; 75 | long count; 76 | struct ntt_node *next; 77 | }; 78 | 79 | /* ntt cursor */ 80 | struct ntt_c { 81 | long iter_index; 82 | struct ntt_node *iter_next; 83 | }; 84 | 85 | struct ntt *ntt_create(unsigned long size); 86 | int ntt_destroy(struct ntt *ntt); 87 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key); 88 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); 89 | int ntt_delete(struct ntt *ntt, const char *key); 90 | long ntt_hashcode(struct ntt *ntt, const char *key); 91 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); 92 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); 93 | 94 | /* END NTT (Named Timestamp Tree) Headers */ 95 | 96 | 97 | /* BEGIN DoS Evasive Maneuvers Globals */ 98 | 99 | typedef struct { 100 | int enabled; 101 | char *context; 102 | struct ntt *hit_list; // Our dynamic hash table 103 | unsigned long hash_table_size; 104 | int page_count; 105 | int page_interval; 106 | int site_count; 107 | int site_interval; 108 | int blocking_period; 109 | char *email_notify; 110 | char *log_dir; 111 | char *system_command; 112 | int http_reply; 113 | } evasive_config; 114 | 115 | static const char *whitelist(cmd_parms *cmd, void *dconfig, const char *ip); 116 | int is_whitelisted(const char *ip, evasive_config *cfg); 117 | 118 | /* END DoS Evasive Maneuvers Globals */ 119 | 120 | static void * create_dir_conf(apr_pool_t *p, char *context) 121 | { 122 | context = context ? context : "(undefined context)"; 123 | /* Create a new hit list for this listener */ 124 | evasive_config *cfg = apr_pcalloc(p, sizeof(evasive_config)); 125 | if (cfg) { 126 | cfg->enabled = 0; 127 | cfg->context = strdup(context); 128 | cfg->hash_table_size = DEFAULT_HASH_TBL_SIZE; 129 | cfg->hit_list = ntt_create(cfg->hash_table_size); 130 | cfg->page_count = DEFAULT_PAGE_COUNT; 131 | cfg->page_interval = DEFAULT_PAGE_INTERVAL; 132 | cfg->site_count = DEFAULT_SITE_COUNT; 133 | cfg->site_interval = DEFAULT_SITE_INTERVAL; 134 | cfg->email_notify = NULL; 135 | cfg->log_dir = NULL; 136 | cfg->system_command = NULL; 137 | cfg->http_reply = DEFAULT_HTTP_REPLY; 138 | } 139 | 140 | return cfg; 141 | } 142 | 143 | static const char *whitelist(cmd_parms *cmd, void *dconfig, const char *ip) 144 | { 145 | evasive_config *cfg = (evasive_config *) dconfig; 146 | char entry[128]; 147 | snprintf(entry, sizeof(entry), "WHITELIST_%s", ip); 148 | ntt_insert(cfg->hit_list, entry, time(NULL)); 149 | 150 | return NULL; 151 | } 152 | 153 | 154 | static int access_checker(request_rec *r) 155 | { 156 | evasive_config *cfg = (evasive_config *) ap_get_module_config(r->per_dir_config, &evasive_module); 157 | 158 | int ret = OK; 159 | 160 | /* BEGIN DoS Evasive Maneuvers Code */ 161 | 162 | if (cfg->enabled && r->prev == NULL && r->main == NULL && cfg->hit_list != NULL) { 163 | char hash_key[2048]; 164 | struct ntt_node *n; 165 | time_t t = time(NULL); 166 | 167 | /* Check whitelist */ 168 | if (is_whitelisted(r->connection->remote_ip, cfg)) 169 | return OK; 170 | 171 | /* First see if the IP itself is on "hold" */ 172 | n = ntt_find(cfg->hit_list, r->connection->remote_ip); 173 | 174 | if (n != NULL && t-n->timestampblocking_period) { 175 | 176 | /* If the IP is on "hold", make it wait longer in 403 land */ 177 | ret = cfg->http_reply; 178 | n->timestamp = time(NULL); 179 | 180 | /* Not on hold, check hit stats */ 181 | } else { 182 | 183 | /* Has URI been hit too much? */ 184 | snprintf(hash_key, 2048, "%s_%s", r->connection->remote_ip, r->uri); 185 | n = ntt_find(cfg->hit_list, hash_key); 186 | if (n != NULL) { 187 | 188 | /* If URI is being hit too much, add to "hold" list and 403 */ 189 | if (t-n->timestamppage_interval && n->count>=cfg->page_count) { 190 | ret = cfg->http_reply; 191 | ntt_insert(cfg->hit_list, r->connection->remote_ip, time(NULL)); 192 | } else { 193 | 194 | /* Reset our hit count list as necessary */ 195 | if (t-n->timestamp>=cfg->page_interval) { 196 | n->count=0; 197 | } 198 | } 199 | n->timestamp = t; 200 | n->count++; 201 | } else { 202 | ntt_insert(cfg->hit_list, hash_key, t); 203 | } 204 | 205 | /* Has site been hit too much? */ 206 | snprintf(hash_key, 2048, "%s_SITE", r->connection->remote_ip); 207 | n = ntt_find(cfg->hit_list, hash_key); 208 | if (n != NULL) { 209 | 210 | /* If site is being hit too much, add to "hold" list and 403 */ 211 | if (t-n->timestampsite_interval && n->count>=cfg->site_count) { 212 | ret = cfg->http_reply; 213 | ntt_insert(cfg->hit_list, r->connection->remote_ip, time(NULL)); 214 | } else { 215 | 216 | /* Reset our hit count list as necessary */ 217 | if (t-n->timestamp>=cfg->site_interval) { 218 | n->count=0; 219 | } 220 | } 221 | n->timestamp = t; 222 | n->count++; 223 | } else { 224 | ntt_insert(cfg->hit_list, hash_key, t); 225 | } 226 | } 227 | 228 | /* Perform email notification and system functions */ 229 | if (ret == cfg->http_reply) { 230 | char filename[1024]; 231 | struct stat s; 232 | FILE *file; 233 | 234 | snprintf(filename, sizeof(filename), "%s/dos-%s", cfg->log_dir != NULL ? cfg->log_dir : DEFAULT_LOG_DIR, r->connection->remote_ip); 235 | if (stat(filename, &s)) { 236 | file = fopen(filename, "w"); 237 | if (file != NULL) { 238 | fprintf(file, "%ld\n", getpid()); 239 | fclose(file); 240 | 241 | LOG(LOG_ALERT, "Blacklisting address %s: possible DoS attack.", r->connection->remote_ip); 242 | if (cfg->email_notify != NULL) { 243 | snprintf(filename, sizeof(filename), MAILER, cfg->email_notify); 244 | file = popen(filename, "w"); 245 | if (file != NULL) { 246 | fprintf(file, "To: %s\n", cfg->email_notify); 247 | fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", r->connection->remote_ip); 248 | fprintf(file, "mod_evasive HTTP Blacklisted %s\n", r->connection->remote_ip); 249 | pclose(file); 250 | } 251 | } 252 | 253 | if (cfg->system_command != NULL) { 254 | snprintf(filename, sizeof(filename), cfg->system_command, r->connection->remote_ip); 255 | system(filename); 256 | } 257 | 258 | } else { 259 | LOG(LOG_ALERT, "Couldn't open logfile %s: %s",filename, strerror(errno)); 260 | } 261 | 262 | } /* if (temp file does not exist) */ 263 | 264 | } /* if (ret == cfg->http_reply) */ 265 | 266 | } /* if (r->prev == NULL && r->main == NULL && cfg->hit_list != NULL) */ 267 | 268 | /* END DoS Evasive Maneuvers Code */ 269 | 270 | if (ret == cfg->http_reply 271 | && (ap_satisfies(r) != SATISFY_ANY || !ap_some_auth_required(r))) { 272 | ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 273 | "client denied by server configuration: %s", 274 | r->filename); 275 | } 276 | 277 | return ret; 278 | } 279 | 280 | int is_whitelisted(const char *ip, evasive_config *cfg) { 281 | char hashkey[128]; 282 | char octet[4][4]; 283 | char *dip; 284 | char *oct; 285 | int i = 0; 286 | 287 | memset(octet, 0, 16); 288 | dip = strdup(ip); 289 | if (dip == NULL) 290 | return 0; 291 | 292 | oct = strtok(dip, "."); 293 | while(oct != NULL && i<4) { 294 | if (strlen(oct)<=3) 295 | strcpy(octet[i], oct); 296 | i++; 297 | oct = strtok(NULL, "."); 298 | } 299 | free(dip); 300 | 301 | /* Exact Match */ 302 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s", ip); 303 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 304 | return 1; 305 | 306 | /* IPv4 Wildcards */ 307 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.*.*.*", octet[0]); 308 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 309 | return 1; 310 | 311 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.*.*", octet[0], octet[1]); 312 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 313 | return 1; 314 | 315 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.%s.*", octet[0], octet[1], octet[2]); 316 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 317 | return 1; 318 | 319 | /* No match */ 320 | return 0; 321 | } 322 | 323 | static apr_status_t destroy_config(void *dconfig) { 324 | evasive_config *cfg = (evasive_config *) dconfig; 325 | if (cfg != NULL) { 326 | ntt_destroy(cfg->hit_list); 327 | free(cfg->email_notify); 328 | free(cfg->log_dir); 329 | free(cfg->system_command); 330 | free(cfg); 331 | } 332 | return APR_SUCCESS; 333 | } 334 | 335 | 336 | /* BEGIN NTT (Named Timestamp Tree) Functions */ 337 | 338 | static unsigned long ntt_prime_list[ntt_num_primes] = 339 | { 340 | 53ul, 97ul, 193ul, 389ul, 769ul, 341 | 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 342 | 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 343 | 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 344 | 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 345 | 1610612741ul, 3221225473ul, 4294967291ul 346 | }; 347 | 348 | 349 | /* Find the numeric position in the hash table based on key and modulus */ 350 | 351 | long ntt_hashcode(struct ntt *ntt, const char *key) { 352 | unsigned long val = 0; 353 | for (; *key; ++key) val = 5 * val + *key; 354 | return(val % ntt->size); 355 | } 356 | 357 | /* Creates a single node in the tree */ 358 | 359 | struct ntt_node *ntt_node_create(const char *key) { 360 | char *node_key; 361 | struct ntt_node* node; 362 | 363 | node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); 364 | if (node == NULL) { 365 | return NULL; 366 | } 367 | if ((node_key = strdup(key)) == NULL) { 368 | free(node); 369 | return NULL; 370 | } 371 | node->key = node_key; 372 | node->timestamp = time(NULL); 373 | node->next = NULL; 374 | return(node); 375 | } 376 | 377 | /* Tree initializer */ 378 | 379 | struct ntt *ntt_create(unsigned long size) { 380 | long i = 0; 381 | struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); 382 | 383 | if (ntt == NULL) 384 | return NULL; 385 | while (ntt_prime_list[i] < size) { i++; } 386 | ntt->size = ntt_prime_list[i]; 387 | ntt->items = 0; 388 | ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); 389 | if (ntt->tbl == NULL) { 390 | free(ntt); 391 | return NULL; 392 | } 393 | return(ntt); 394 | } 395 | 396 | /* Find an object in the tree */ 397 | 398 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { 399 | long hash_code; 400 | struct ntt_node *node; 401 | 402 | if (ntt == NULL) return NULL; 403 | 404 | hash_code = ntt_hashcode(ntt, key); 405 | node = ntt->tbl[hash_code]; 406 | 407 | while (node) { 408 | if (!strcmp(key, node->key)) { 409 | return(node); 410 | } 411 | node = node->next; 412 | } 413 | return((struct ntt_node *)NULL); 414 | } 415 | 416 | /* Insert a node into the tree */ 417 | 418 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { 419 | long hash_code; 420 | struct ntt_node *parent; 421 | struct ntt_node *node; 422 | struct ntt_node *new_node = NULL; 423 | 424 | if (ntt == NULL) return NULL; 425 | 426 | hash_code = ntt_hashcode(ntt, key); 427 | parent = NULL; 428 | node = ntt->tbl[hash_code]; 429 | 430 | while (node != NULL) { 431 | if (strcmp(key, node->key) == 0) { 432 | new_node = node; 433 | node = NULL; 434 | } 435 | 436 | if (new_node == NULL) { 437 | parent = node; 438 | node = node->next; 439 | } 440 | } 441 | 442 | if (new_node != NULL) { 443 | new_node->timestamp = timestamp; 444 | new_node->count = 0; 445 | return new_node; 446 | } 447 | 448 | /* Create a new node */ 449 | new_node = ntt_node_create(key); 450 | new_node->timestamp = timestamp; 451 | new_node->count = 0; 452 | 453 | ntt->items++; 454 | 455 | /* Insert */ 456 | if (parent) { /* Existing parent */ 457 | parent->next = new_node; 458 | return new_node; /* Return the locked node */ 459 | } 460 | 461 | /* No existing parent; add directly to hash table */ 462 | ntt->tbl[hash_code] = new_node; 463 | return new_node; 464 | } 465 | 466 | /* Tree destructor */ 467 | 468 | int ntt_destroy(struct ntt *ntt) { 469 | struct ntt_node *node, *next; 470 | struct ntt_c c; 471 | 472 | if (ntt == NULL) return -1; 473 | 474 | node = c_ntt_first(ntt, &c); 475 | while(node != NULL) { 476 | next = c_ntt_next(ntt, &c); 477 | ntt_delete(ntt, node->key); 478 | node = next; 479 | } 480 | 481 | free(ntt->tbl); 482 | free(ntt); 483 | ntt = (struct ntt *) NULL; 484 | 485 | return 0; 486 | } 487 | 488 | /* Delete a single node in the tree */ 489 | 490 | int ntt_delete(struct ntt *ntt, const char *key) { 491 | long hash_code; 492 | struct ntt_node *parent = NULL; 493 | struct ntt_node *node; 494 | struct ntt_node *del_node = NULL; 495 | 496 | if (ntt == NULL) return -1; 497 | 498 | hash_code = ntt_hashcode(ntt, key); 499 | node = ntt->tbl[hash_code]; 500 | 501 | while (node != NULL) { 502 | if (strcmp(key, node->key) == 0) { 503 | del_node = node; 504 | node = NULL; 505 | } 506 | 507 | if (del_node == NULL) { 508 | parent = node; 509 | node = node->next; 510 | } 511 | } 512 | 513 | if (del_node != NULL) { 514 | 515 | if (parent) { 516 | parent->next = del_node->next; 517 | } else { 518 | ntt->tbl[hash_code] = del_node->next; 519 | } 520 | 521 | free(del_node->key); 522 | free(del_node); 523 | ntt->items--; 524 | 525 | return 0; 526 | } 527 | 528 | return -5; 529 | } 530 | 531 | /* Point cursor to first item in tree */ 532 | 533 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { 534 | 535 | c->iter_index = 0; 536 | c->iter_next = (struct ntt_node *)NULL; 537 | return(c_ntt_next(ntt, c)); 538 | } 539 | 540 | /* Point cursor to next iteration in tree */ 541 | 542 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { 543 | long index; 544 | struct ntt_node *node = c->iter_next; 545 | 546 | if (ntt == NULL) return NULL; 547 | 548 | if (node) { 549 | if (node != NULL) { 550 | c->iter_next = node->next; 551 | return (node); 552 | } 553 | } 554 | 555 | if (! node) { 556 | while (c->iter_index < ntt->size) { 557 | index = c->iter_index++; 558 | 559 | if (ntt->tbl[index]) { 560 | c->iter_next = ntt->tbl[index]->next; 561 | return(ntt->tbl[index]); 562 | } 563 | } 564 | } 565 | return((struct ntt_node *)NULL); 566 | } 567 | 568 | /* END NTT (Named Pointer Tree) Functions */ 569 | 570 | 571 | /* BEGIN Configuration Functions */ 572 | 573 | static const char * 574 | get_enabled(cmd_parms *cmd, void *dconfig, const char *value) { 575 | evasive_config *cfg = (evasive_config *) dconfig; 576 | cfg->enabled = (strcmp("true", value) == 0) ? 1 : 0; 577 | return NULL; 578 | } 579 | 580 | static const char * 581 | get_hash_tbl_size(cmd_parms *cmd, void *dconfig, const char *value) { 582 | evasive_config *cfg = (evasive_config *) dconfig; 583 | long n = strtol(value, NULL, 0); 584 | 585 | if (n<=0) { 586 | cfg->hash_table_size = DEFAULT_HASH_TBL_SIZE; 587 | } else { 588 | cfg->hash_table_size = n; 589 | } 590 | cfg->hit_list = ntt_create(cfg->hash_table_size); 591 | 592 | return NULL; 593 | } 594 | 595 | static const char * 596 | get_page_count(cmd_parms *cmd, void *dconfig, const char *value) { 597 | evasive_config *cfg = (evasive_config *) dconfig; 598 | long n = strtol(value, NULL, 0); 599 | if (n<=0) { 600 | cfg->page_count = DEFAULT_PAGE_COUNT; 601 | } else { 602 | cfg->page_count = n; 603 | } 604 | 605 | return NULL; 606 | } 607 | 608 | static const char * 609 | get_site_count(cmd_parms *cmd, void *dconfig, const char *value) { 610 | evasive_config *cfg = (evasive_config *) dconfig; 611 | long n = strtol(value, NULL, 0); 612 | if (n<=0) { 613 | cfg->site_count = DEFAULT_SITE_COUNT; 614 | } else { 615 | cfg->site_count = n; 616 | } 617 | 618 | return NULL; 619 | } 620 | 621 | static const char * 622 | get_page_interval(cmd_parms *cmd, void *dconfig, const char *value) { 623 | evasive_config *cfg = (evasive_config *) dconfig; 624 | long n = strtol(value, NULL, 0); 625 | if (n<=0) { 626 | cfg->page_interval = DEFAULT_PAGE_INTERVAL; 627 | } else { 628 | cfg->page_interval = n; 629 | } 630 | 631 | return NULL; 632 | } 633 | 634 | static const char * 635 | get_site_interval(cmd_parms *cmd, void *dconfig, const char *value) { 636 | evasive_config *cfg = (evasive_config *) dconfig; 637 | long n = strtol(value, NULL, 0); 638 | if (n<=0) { 639 | cfg->site_interval = DEFAULT_SITE_INTERVAL; 640 | } else { 641 | cfg->site_interval = n; 642 | } 643 | 644 | return NULL; 645 | } 646 | 647 | static const char * 648 | get_blocking_period(cmd_parms *cmd, void *dconfig, const char *value) { 649 | evasive_config *cfg = (evasive_config *) dconfig; 650 | long n = strtol(value, NULL, 0); 651 | if (n<=0) { 652 | cfg->blocking_period = DEFAULT_BLOCKING_PERIOD; 653 | } else { 654 | cfg->blocking_period = n; 655 | } 656 | 657 | return NULL; 658 | } 659 | 660 | static const char * 661 | get_log_dir(cmd_parms *cmd, void *dconfig, const char *value) { 662 | evasive_config *cfg = (evasive_config *) dconfig; 663 | if (value != NULL && value[0] != 0) { 664 | if (cfg->log_dir != NULL) 665 | free(cfg->log_dir); 666 | cfg->log_dir = strdup(value); 667 | } 668 | 669 | return NULL; 670 | } 671 | 672 | static const char * 673 | get_email_notify(cmd_parms *cmd, void *dconfig, const char *value) { 674 | evasive_config *cfg = (evasive_config *) dconfig; 675 | if (value != NULL && value[0] != 0) { 676 | if (cfg->email_notify != NULL) 677 | free(cfg->email_notify); 678 | cfg->email_notify = strdup(value); 679 | } 680 | 681 | return NULL; 682 | } 683 | 684 | static const char * 685 | get_system_command(cmd_parms *cmd, void *dconfig, const char *value) { 686 | evasive_config *cfg = (evasive_config *) dconfig; 687 | if (value != NULL && value[0] != 0) { 688 | if (cfg->system_command != NULL) 689 | free(cfg->system_command); 690 | cfg->system_command = strdup(value); 691 | } 692 | 693 | return NULL; 694 | } 695 | 696 | static const char * 697 | get_http_reply(cmd_parms *cmd, void *dconfig, const char *value) { 698 | evasive_config *cfg = (evasive_config *) dconfig; 699 | long reply = strtol(value, NULL, 0); 700 | if (reply <= 0) { 701 | cfg->http_reply = HTTP_FORBIDDEN; 702 | } else { 703 | cfg->http_reply = reply; 704 | } 705 | 706 | return NULL; 707 | } 708 | 709 | /* END Configuration Functions */ 710 | 711 | static const command_rec access_cmds[] = 712 | { 713 | AP_INIT_TAKE1("DOSEnabled", get_enabled, NULL, RSRC_CONF, 714 | "Enable mod_evasive (either globally or in the virtualhost where it is specified)"), 715 | 716 | AP_INIT_TAKE1("DOSHashTableSize", get_hash_tbl_size, NULL, RSRC_CONF, 717 | "Set size of hash table"), 718 | 719 | AP_INIT_TAKE1("DOSPageCount", get_page_count, NULL, RSRC_CONF, 720 | "Set maximum page hit count per interval"), 721 | 722 | AP_INIT_TAKE1("DOSSiteCount", get_site_count, NULL, RSRC_CONF, 723 | "Set maximum site hit count per interval"), 724 | 725 | AP_INIT_TAKE1("DOSPageInterval", get_page_interval, NULL, RSRC_CONF, 726 | "Set page interval"), 727 | 728 | AP_INIT_TAKE1("DOSSiteInterval", get_site_interval, NULL, RSRC_CONF, 729 | "Set site interval"), 730 | 731 | AP_INIT_TAKE1("DOSBlockingPeriod", get_blocking_period, NULL, RSRC_CONF, 732 | "Set blocking period for detected DoS IPs"), 733 | 734 | AP_INIT_TAKE1("DOSEmailNotify", get_email_notify, NULL, RSRC_CONF, 735 | "Set email notification"), 736 | 737 | AP_INIT_TAKE1("DOSLogDir", get_log_dir, NULL, RSRC_CONF, 738 | "Set log dir"), 739 | 740 | AP_INIT_TAKE1("DOSSystemCommand", get_system_command, NULL, RSRC_CONF, 741 | "Set system command on DoS"), 742 | 743 | AP_INIT_ITERATE("DOSWhitelist", whitelist, NULL, RSRC_CONF, 744 | "IP-addresses wildcards to whitelist"), 745 | 746 | AP_INIT_ITERATE("DOSHTTPStatus", get_http_reply, NULL, RSRC_CONF, 747 | "HTTP reply code"), 748 | 749 | { NULL } 750 | }; 751 | 752 | static void register_hooks(apr_pool_t *p) { 753 | ap_hook_access_checker(access_checker, NULL, NULL, APR_HOOK_MIDDLE); 754 | apr_pool_cleanup_register(p, NULL, apr_pool_cleanup_null, destroy_config); 755 | }; 756 | 757 | module AP_MODULE_DECLARE_DATA evasive_module = 758 | { 759 | STANDARD20_MODULE_STUFF, 760 | create_dir_conf, 761 | NULL, 762 | NULL, 763 | NULL, 764 | access_cmds, 765 | register_hooks 766 | }; 767 | 768 | -------------------------------------------------------------------------------- /mod_evasive24.c: -------------------------------------------------------------------------------- 1 | // vim:ts=4:shiftwidth=4:et 2 | /* 3 | mod_evasive for Apache 2 4 | Copyright (c) by Jonathan A. Zdziarski 5 | 6 | LICENSE 7 | 8 | This program is free software; you can redistribute it and/or 9 | modify it under the terms of the GNU General Public License 10 | as published by the Free Software Foundation; either version 2 11 | of the License, or (at your option) any later version. 12 | 13 | This program is distributed in the hope that it will be useful, 14 | but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | GNU General Public License for more details. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program; if not, write to the Free Software 20 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 21 | 22 | */ 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include // getpid(2) 33 | 34 | #define PCRE2_CODE_UNIT_WIDTH 8 35 | #include 36 | 37 | #include "httpd.h" 38 | #include "http_core.h" 39 | #include "http_config.h" 40 | #include "http_log.h" 41 | #include "http_main.h" 42 | #include "http_request.h" 43 | 44 | /* BEGIN DoS Evasive Maneuvers Definitions */ 45 | 46 | AP_DECLARE_MODULE(evasive); 47 | 48 | #define MAILER "/bin/mail %s" 49 | 50 | #define DEFAULT_HASH_TBL_SIZE 3079UL // Default hash table size 51 | #define DEFAULT_PAGE_COUNT 2 // Default maximum page hit count per interval 52 | #define DEFAULT_SITE_COUNT 50 // Default maximum site hit count per interval 53 | #define DEFAULT_PAGE_INTERVAL 1 // Default 1 Second page interval 54 | #define DEFAULT_SITE_INTERVAL 1 // Default 1 Second site interval 55 | #define DEFAULT_BLOCKING_PERIOD 10 // Default for Detected IPs; blocked for 10 seconds 56 | #define DEFAULT_LOG_DIR "/tmp" // Default temp directory 57 | #define DEFAULT_HTTP_REPLY HTTP_FORBIDDEN // Default HTTP Reply code (403) 58 | 59 | /* END DoS Evasive Maneuvers Definitions */ 60 | 61 | /* BEGIN NTT (Named Timestamp Tree) Headers */ 62 | 63 | enum { ntt_num_primes = 28 }; 64 | 65 | /* ntt root tree */ 66 | struct ntt { 67 | size_t size; 68 | size_t items; 69 | struct ntt_node **tbl; 70 | }; 71 | 72 | /* ntt node (entry in the ntt root tree) */ 73 | struct ntt_node { 74 | char *key; 75 | apr_time_t timestamp; 76 | size_t count; 77 | struct ntt_node *next; 78 | }; 79 | 80 | /* ntt cursor */ 81 | struct ntt_c { 82 | size_t iter_index; 83 | struct ntt_node *iter_next; 84 | }; 85 | 86 | static struct ntt *ntt_create(size_t size); 87 | static int ntt_destroy(struct ntt *ntt); 88 | static struct ntt_node *ntt_find(struct ntt *ntt, const char *key); 89 | static struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, apr_time_t timestamp); 90 | static int ntt_delete(struct ntt *ntt, const char *key); 91 | static size_t ntt_hashcode(const struct ntt *ntt, const char *key); 92 | static struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); 93 | static struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); 94 | 95 | /* END NTT (Named Timestamp Tree) Headers */ 96 | 97 | 98 | /* BEGIN DoS Evasive Maneuvers Globals */ 99 | 100 | struct pcre_node { 101 | pcre2_code *re; 102 | pcre2_match_data *match_data; 103 | }; 104 | 105 | struct pcre_vector { 106 | struct pcre_node *data; 107 | size_t size; 108 | }; 109 | 110 | struct ip_node { 111 | union { 112 | struct in_addr v4; 113 | struct in6_addr v6; 114 | } ip; 115 | 116 | union { 117 | uint32_t v4; 118 | struct in6_addr v6; 119 | } mask; 120 | 121 | char family; // AF_INET or AF_INET6 122 | }; 123 | 124 | struct ip_vector { 125 | struct ip_node *data; 126 | size_t size; 127 | }; 128 | 129 | typedef struct { 130 | int enabled; 131 | struct ntt *hit_list; // Our dynamic hash table 132 | size_t hash_table_size; 133 | struct pcre_vector uri_whitelist; 134 | struct pcre_vector uri_targetlist; 135 | struct pcre_vector uri_blocklist; 136 | struct ip_vector ip_whitelist; 137 | unsigned int page_count; 138 | int page_interval; 139 | unsigned int site_count; 140 | int site_interval; 141 | int blocking_period; 142 | char *email_notify; 143 | char *log_dir; 144 | char *system_command; 145 | int http_reply; 146 | } evasive_config; 147 | 148 | static int is_whitelisted(const apr_sockaddr_t *client, const evasive_config *cfg); 149 | 150 | static int is_uri_whitelisted(const char *uri, const evasive_config *cfg); 151 | static int is_uri_targeted(const char *uri, const evasive_config *cfg); 152 | static int is_uri_blocklisted(const char *uri, const evasive_config *cfg); 153 | 154 | /* END DoS Evasive Maneuvers Globals */ 155 | 156 | static void * ev_reallocarray(void *ptr, size_t nmemb, size_t size) 157 | { 158 | if (size && nmemb > SIZE_MAX / size) { 159 | errno = ENOMEM; 160 | return NULL; 161 | } 162 | 163 | return realloc(ptr, nmemb * size); 164 | } 165 | 166 | 167 | static void * create_dir_conf(apr_pool_t *p, __attribute__((unused)) char *context) 168 | { 169 | /* Create a new hit list for this listener */ 170 | evasive_config *cfg = apr_palloc(p, sizeof(evasive_config)); 171 | if (!cfg) { 172 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Failed to allocate configuration"); 173 | return NULL; 174 | } 175 | 176 | *cfg = (evasive_config) { 177 | .enabled = 0, 178 | .hit_list = ntt_create(DEFAULT_HASH_TBL_SIZE), 179 | .hash_table_size = DEFAULT_HASH_TBL_SIZE, 180 | .uri_whitelist = (struct pcre_vector) { .data = NULL, .size = 0 }, 181 | .uri_targetlist = (struct pcre_vector) { .data = NULL, .size = 0 }, 182 | .uri_blocklist = (struct pcre_vector) { .data = NULL, .size = 0 }, 183 | .ip_whitelist = (struct ip_vector) { .data = NULL, .size = 0 }, 184 | .page_count = DEFAULT_PAGE_COUNT, 185 | .page_interval = DEFAULT_PAGE_INTERVAL, 186 | .site_count = DEFAULT_SITE_COUNT, 187 | .site_interval = DEFAULT_SITE_INTERVAL, 188 | .blocking_period = DEFAULT_BLOCKING_PERIOD, 189 | .email_notify = NULL, 190 | .log_dir = NULL, 191 | .system_command = NULL, 192 | .http_reply = DEFAULT_HTTP_REPLY, 193 | }; 194 | if (!cfg->hit_list) 195 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Failed to allocate hashtable"); 196 | 197 | return cfg; 198 | } 199 | 200 | static int parse_wildcard(const char *ip, struct in_addr *addr, uint32_t *mask) 201 | { 202 | char *dip; 203 | const char *oct; 204 | char *safeptr; 205 | int i = 0; 206 | uint32_t ip_byte = 0, mask_byte = 0; 207 | unsigned long val; 208 | char *endptr; 209 | 210 | dip = strdup(ip); 211 | if (!dip) 212 | goto err; 213 | 214 | oct = strtok_r(dip, ".", &safeptr); 215 | while(oct != NULL && i < 4) { 216 | if (oct[0] == '\0' || strlen(oct) > 3) 217 | goto err; 218 | 219 | if (oct[0] == '*' && oct[1] == '\0') { 220 | ip_byte += 0; 221 | mask_byte += 0; 222 | } else { 223 | errno = 0; 224 | val = strtoul(oct, &endptr, 10); 225 | if (errno || *endptr != '\0' || val > 255) 226 | goto err; 227 | 228 | ip_byte += val; 229 | mask_byte += 255; 230 | } 231 | 232 | i++; 233 | if (i < 4) { 234 | ip_byte <<= 8; 235 | mask_byte <<= 8; 236 | } 237 | 238 | oct = strtok_r(NULL, ".", &safeptr); 239 | } 240 | 241 | if (oct || i != 4) 242 | goto err; 243 | 244 | free(dip); 245 | 246 | addr->s_addr = htobe32(ip_byte); 247 | *mask = htobe32(mask_byte); 248 | return 1; 249 | err: 250 | free(dip); 251 | return -1; 252 | } 253 | 254 | static void ipv6_cidr_bits_to_mask(unsigned long cidr_bits, struct in6_addr *mask) 255 | { 256 | for (unsigned i = 0; i < 4; i++) { 257 | if (cidr_bits == 0) { 258 | mask->s6_addr32[i] = 0; 259 | } else if (cidr_bits >= 32) { 260 | mask->s6_addr32[i] = ~UINT32_C(0); 261 | } else { 262 | mask->s6_addr32[i] = htobe32(~((UINT32_C(1) << (32 - cidr_bits)) - 1)); 263 | } 264 | 265 | if (cidr_bits >= 32) 266 | cidr_bits -= 32; 267 | else 268 | cidr_bits = 0; 269 | } 270 | } 271 | 272 | static void ipv6_apply_mask(struct in6_addr *restrict addr, const struct in6_addr *restrict mask) 273 | { 274 | for (unsigned i = 0; i < 4; i++) 275 | addr->s6_addr32[i] &= mask->s6_addr32[i]; 276 | } 277 | 278 | static const char *whitelist_ip(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *ip) 279 | { 280 | evasive_config *cfg = (evasive_config *) dconfig; 281 | struct in_addr ipv4; 282 | struct in6_addr ipv6, maskv6; 283 | struct ip_node *newdata; 284 | const char *ip_parse = ip; 285 | char *ip_copy = NULL; 286 | const char *cidr_split; 287 | char *endptr; 288 | char family; 289 | char wildcard = 0; 290 | unsigned long mask_bits; 291 | uint32_t maskv4; 292 | int rc; 293 | 294 | cidr_split = strchr(ip, '/'); 295 | if (cidr_split) { 296 | ip_copy = strndup(ip, cidr_split - ip); 297 | if (!ip_copy) { 298 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "DOSWhitelist: OOM"); 299 | return NULL; 300 | } 301 | 302 | ip_parse = ip_copy; 303 | } 304 | 305 | if (strchr(ip_parse, '*') != NULL) { 306 | family = AF_INET; 307 | wildcard = 1; 308 | rc = parse_wildcard(ip_parse, &ipv4, &maskv4); 309 | } else if (strchr(ip_parse, ':') != NULL) { 310 | family = AF_INET6; 311 | rc = inet_pton(AF_INET6, ip_parse, &ipv6); 312 | } else { 313 | family = AF_INET; 314 | rc = inet_pton(AF_INET, ip_parse, &ipv4); 315 | } 316 | 317 | if (cidr_split) 318 | free(ip_copy); 319 | 320 | if (rc != 1) { 321 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "DOSWhitelist: Invalid IP address '%s'", ip); 322 | return NULL; 323 | } 324 | 325 | if (cidr_split) { 326 | errno = 0; 327 | mask_bits = strtoul(cidr_split + 1, &endptr, 10); 328 | if (errno || *endptr != '\0' || mask_bits == 0 || mask_bits > (family == AF_INET ? 32 : 128)) { 329 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "DOSWhitelist: Invalid IP CIDR range '%s'", ip); 330 | return NULL; 331 | } 332 | } else { 333 | mask_bits = family == AF_INET ? 32 : 128; 334 | } 335 | 336 | if (!wildcard) { 337 | if (family == AF_INET) { 338 | maskv4 = ~((UINT32_C(1) << (32 - mask_bits)) - 1); 339 | maskv4 = htobe32(maskv4); 340 | ipv4.s_addr &= maskv4; 341 | } else { 342 | ipv6_cidr_bits_to_mask(mask_bits, &maskv6); 343 | ipv6_apply_mask(&ipv6, &maskv6); 344 | } 345 | } 346 | 347 | newdata = ev_reallocarray(cfg->ip_whitelist.data, cfg->ip_whitelist.size + 1, sizeof(*cfg->ip_whitelist.data)); 348 | if (!newdata) { 349 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "DOSWhitelist: OOM"); 350 | return NULL; 351 | } 352 | cfg->ip_whitelist.data = newdata; 353 | 354 | if (family == AF_INET) { 355 | cfg->ip_whitelist.data[cfg->ip_whitelist.size++] = (struct ip_node) { 356 | .family = AF_INET, 357 | .ip.v4 = ipv4, 358 | .mask.v4 = maskv4, 359 | }; 360 | } else { 361 | cfg->ip_whitelist.data[cfg->ip_whitelist.size++] = (struct ip_node) { 362 | .family = AF_INET6, 363 | .ip.v6 = ipv6, 364 | .mask.v6 = maskv6, 365 | }; 366 | } 367 | 368 | return NULL; 369 | } 370 | 371 | static const char *pcre_vector_push(struct pcre_vector *vec, const char *uri_re) { 372 | struct pcre_node *newdata; 373 | pcre2_code *re; 374 | int errornumber; 375 | PCRE2_SIZE erroroffset; 376 | PCRE2_SPTR pattern; 377 | pcre2_match_data *match_data; 378 | 379 | pattern = (PCRE2_SPTR) uri_re; 380 | 381 | re = pcre2_compile( 382 | pattern, /* the pattern */ 383 | PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ 384 | PCRE2_NO_AUTO_CAPTURE, /* Disable numbered capturing parentheses */ 385 | &errornumber, /* for error number */ 386 | &erroroffset, /* for error offset */ 387 | NULL); /* use default compile context */ 388 | 389 | /* Compilation failed: print the error message and exit. */ 390 | 391 | if (!re) { 392 | PCRE2_UCHAR buffer[256]; 393 | pcre2_get_error_message(errornumber, buffer, sizeof(buffer)); 394 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "PCRE2 compilation of regex '%s' failed at offset %lu: %s\n", 395 | uri_re, (unsigned long) erroroffset, buffer); 396 | return NULL; 397 | } 398 | 399 | match_data = pcre2_match_data_create_from_pattern(re, NULL); 400 | if (!match_data) { 401 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Failed to allocate PCRE2 match data"); 402 | pcre2_code_free(re); 403 | return NULL; 404 | } 405 | 406 | newdata = ev_reallocarray(vec->data, vec->size + 1, sizeof(*(vec->data))); 407 | if (!newdata) { 408 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Failed to allocate array for URI list"); 409 | pcre2_match_data_free(match_data); 410 | pcre2_code_free(re); 411 | return NULL; 412 | } 413 | vec->data = newdata; 414 | 415 | vec->data[vec->size++] = (struct pcre_node) { 416 | .re = re, 417 | .match_data = match_data, 418 | }; 419 | 420 | return NULL; 421 | } 422 | 423 | static const char *whitelist_uri(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *uri_re) 424 | { 425 | evasive_config *cfg = (evasive_config *) dconfig; 426 | 427 | return pcre_vector_push(&cfg->uri_whitelist, uri_re); 428 | } 429 | 430 | static const char *target_uri(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *uri_re) 431 | { 432 | evasive_config *cfg = (evasive_config *) dconfig; 433 | 434 | return pcre_vector_push(&cfg->uri_targetlist, uri_re); 435 | } 436 | 437 | static const char *blocklist_uri(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *uri_re) 438 | { 439 | evasive_config *cfg = (evasive_config *) dconfig; 440 | 441 | return pcre_vector_push(&cfg->uri_blocklist, uri_re); 442 | } 443 | 444 | static void pcre_vector_destroy(struct pcre_vector *vec) 445 | { 446 | for (size_t i = 0; i < vec->size; i++) { 447 | struct pcre_node *node = &vec->data[i]; 448 | pcre2_code_free(node->re); 449 | pcre2_match_data_free(node->match_data); 450 | } 451 | 452 | free(vec->data); 453 | } 454 | 455 | static int access_checker(request_rec *r) 456 | { 457 | evasive_config *cfg = (evasive_config *) ap_get_module_config(r->per_dir_config, &evasive_module); 458 | 459 | int ret = OK; 460 | const char *log_reason = NULL; 461 | 462 | /* BEGIN DoS Evasive Maneuvers Code */ 463 | 464 | if (cfg->enabled && r->prev == NULL && r->main == NULL && cfg->hit_list != NULL) { 465 | char hash_key[2048]; 466 | struct ntt_node *ip_node, *n; 467 | apr_time_t t = r->request_time / 1000 / 1000; /* convert us to s */ 468 | 469 | /* Check whitelist */ 470 | if (is_whitelisted(r->useragent_addr, cfg)) 471 | return OK; 472 | 473 | /* First see if the IP itself is on "hold" */ 474 | ip_node = ntt_find(cfg->hit_list, r->useragent_ip); 475 | 476 | if (ip_node != NULL && t-ip_node->timestampblocking_period) { 477 | 478 | /* If the IP is on "hold", make it wait longer in 403 land */ 479 | ret = cfg->http_reply; 480 | ip_node->timestamp = t; 481 | 482 | /* Not on hold, check hit stats */ 483 | } else { 484 | 485 | /* Check whitelisted uris */ 486 | if (is_uri_whitelisted(r->uri, cfg)) 487 | return OK; 488 | 489 | /* If a Targetlist is defined, and the URI is not one of the targets, then do not perform DoS detection */ 490 | if (cfg->uri_targetlist.size && !is_uri_targeted(r->uri, cfg)) 491 | return OK; 492 | 493 | /* Check blocklisted URIs */ 494 | if (is_uri_blocklisted(r->uri, cfg)) { 495 | if (!ip_node || t-ip_node->timestamp>=cfg->blocking_period) 496 | log_reason = "URI blocklist"; 497 | ret = cfg->http_reply; 498 | ntt_insert(cfg->hit_list, r->useragent_ip, t); 499 | } else { 500 | /* Has URI been hit too much? */ 501 | snprintf(hash_key, sizeof(hash_key), "%s_%s", r->useragent_ip, r->uri); 502 | 503 | n = ntt_find(cfg->hit_list, hash_key); 504 | if (n != NULL) { 505 | 506 | /* If URI is being hit too much, add to "hold" list and 403 */ 507 | if (t-n->timestamppage_interval && n->count>=cfg->page_count) { 508 | if (!ip_node || t-ip_node->timestamp>=cfg->blocking_period) 509 | log_reason = "URI DOS"; 510 | ret = cfg->http_reply; 511 | ntt_insert(cfg->hit_list, r->useragent_ip, t); 512 | } else { 513 | 514 | /* Reset our hit count list as necessary */ 515 | if (t-n->timestamp>=cfg->page_interval) { 516 | n->count=0; 517 | } 518 | } 519 | n->timestamp = t; 520 | n->count++; 521 | } else { 522 | ntt_insert(cfg->hit_list, hash_key, t); 523 | } 524 | 525 | /* Has site been hit too much? */ 526 | snprintf(hash_key, sizeof(hash_key), "%s_SITE", r->useragent_ip); 527 | n = ntt_find(cfg->hit_list, hash_key); 528 | if (n != NULL) { 529 | 530 | /* If site is being hit too much, add to "hold" list and 403 */ 531 | if (t-n->timestampsite_interval && n->count>=cfg->site_count) { 532 | if (!ip_node || t-ip_node->timestamp>=cfg->blocking_period) 533 | log_reason = "site DOS"; 534 | ret = cfg->http_reply; 535 | ntt_insert(cfg->hit_list, r->useragent_ip, t); 536 | } else { 537 | 538 | /* Reset our hit count list as necessary */ 539 | if (t-n->timestamp>=cfg->site_interval) { 540 | n->count=0; 541 | } 542 | } 543 | n->timestamp = t; 544 | n->count++; 545 | } else { 546 | ntt_insert(cfg->hit_list, hash_key, t); 547 | } 548 | } 549 | } 550 | 551 | /* Perform email notification and system functions */ 552 | if (ret == cfg->http_reply) { 553 | char filename[1024]; 554 | struct stat s; 555 | FILE *file; 556 | 557 | snprintf(filename, sizeof(filename), "%s/dos-%s", cfg->log_dir != NULL ? cfg->log_dir : DEFAULT_LOG_DIR, r->useragent_ip); 558 | if (stat(filename, &s)) { 559 | file = fopen(filename, "w"); 560 | if (file != NULL) { 561 | fprintf(file, "%ld\n", (long int)getpid()); 562 | fclose(file); 563 | 564 | ap_log_rerror(APLOG_MARK, APLOG_WARNING, 0, r, "Blacklisting address %s: possible DoS attack.", r->useragent_ip); 565 | if (cfg->email_notify != NULL) { 566 | snprintf(filename, sizeof(filename), MAILER, cfg->email_notify); 567 | file = popen(filename, "w"); 568 | if (file != NULL) { 569 | fprintf(file, "To: %s\n", cfg->email_notify); 570 | fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", r->useragent_ip); 571 | fprintf(file, "mod_evasive HTTP Blacklisted %s\n", r->useragent_ip); 572 | pclose(file); 573 | } 574 | } 575 | 576 | if (cfg->system_command != NULL) { 577 | snprintf(filename, sizeof(filename), cfg->system_command, r->useragent_ip); 578 | int systemRet = system(filename); 579 | if(systemRet == -1){ 580 | ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Couldn't execute %s %s ", filename, strerror(errno)); 581 | } 582 | } 583 | 584 | } else { 585 | ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Couldn't open logfile %s: %s",filename, strerror(errno)); 586 | } 587 | 588 | } /* if (temp file does not exist) */ 589 | 590 | } /* if (ret == cfg->http_reply) */ 591 | 592 | } /* if (r->prev == NULL && r->main == NULL && cfg->hit_list != NULL) */ 593 | 594 | /* END DoS Evasive Maneuvers Code */ 595 | 596 | if (log_reason && ret == cfg->http_reply 597 | && (ap_satisfies(r) != SATISFY_ANY || !ap_some_auth_required(r))) { 598 | ap_log_rerror(APLOG_MARK, APLOG_NOTICE, 0, r, 599 | "[host %s] [resource \"%s\"] [reason %s] client denied by server configuration", 600 | r->hostname, r->filename, log_reason); 601 | } 602 | 603 | return ret; 604 | } 605 | 606 | static int is_whitelisted(const apr_sockaddr_t *client, const evasive_config *cfg) { 607 | switch (client->family) { 608 | case AF_INET: 609 | case AF_INET6: 610 | break; 611 | default: 612 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Invalid client family 0x%x", client->family); 613 | return 0; 614 | } 615 | 616 | for (size_t i = 0; i < cfg->ip_whitelist.size; i++) { 617 | const struct ip_node *node = &cfg->ip_whitelist.data[i]; 618 | int rc; 619 | 620 | if (node->family != client->family) 621 | continue; 622 | 623 | if (client->family == AF_INET) { 624 | struct in_addr addrv4 = client->sa.sin.sin_addr; 625 | addrv4.s_addr &= node->mask.v4; 626 | rc = memcmp(&node->ip.v4, &addrv4, sizeof(node->ip.v4)); 627 | } else { 628 | struct in6_addr addrv6 = client->sa.sin6.sin6_addr; 629 | ipv6_apply_mask(&addrv6, &node->mask.v6); 630 | rc = memcmp(&node->ip.v6, &addrv6, sizeof(node->ip.v6)); 631 | } 632 | 633 | if (rc == 0) 634 | return 1; 635 | } 636 | 637 | /* No match */ 638 | return 0; 639 | } 640 | 641 | static int pcre_vector_match(const char *uri, const struct pcre_vector *vec) { 642 | int rc; 643 | 644 | PCRE2_SPTR subject; 645 | size_t subject_length; 646 | 647 | subject = (PCRE2_SPTR) uri; 648 | subject_length = strlen((const char *)subject); 649 | 650 | for (size_t i = 0; i < vec->size; i++) { 651 | const struct pcre_node *node = &vec->data[i]; 652 | 653 | rc = pcre2_match( 654 | node->re, /* the compiled pattern */ 655 | subject, /* the subject string */ 656 | subject_length, /* the length of the subject */ 657 | 0, /* start at offset 0 in the subject */ 658 | 0, /* default options */ 659 | node->match_data, /* block for storing the result */ 660 | NULL); /* use default match context */ 661 | 662 | if (rc >= 0) { 663 | // match 664 | return 1; 665 | } 666 | } 667 | 668 | // no match 669 | return 0; 670 | } 671 | 672 | static int is_uri_whitelisted(const char *uri, const evasive_config *cfg) { 673 | return pcre_vector_match(uri, &cfg->uri_whitelist); 674 | } 675 | 676 | static int is_uri_targeted(const char *uri, const evasive_config *cfg) { 677 | return pcre_vector_match(uri, &cfg->uri_targetlist); 678 | } 679 | 680 | static int is_uri_blocklisted(const char *uri, const evasive_config *cfg) { 681 | return pcre_vector_match(uri, &cfg->uri_blocklist); 682 | } 683 | 684 | static apr_status_t destroy_config(void *dconfig) { 685 | evasive_config *cfg = (evasive_config *) dconfig; 686 | if (cfg != NULL) { 687 | ntt_destroy(cfg->hit_list); 688 | pcre_vector_destroy(&cfg->uri_whitelist); 689 | pcre_vector_destroy(&cfg->uri_targetlist); 690 | pcre_vector_destroy(&cfg->uri_blocklist); 691 | free(cfg->ip_whitelist.data); 692 | free(cfg->email_notify); 693 | free(cfg->log_dir); 694 | free(cfg->system_command); 695 | /* cfg is pool allocated */ 696 | } 697 | return APR_SUCCESS; 698 | } 699 | 700 | 701 | /* BEGIN NTT (Named Timestamp Tree) Functions */ 702 | 703 | static const size_t ntt_prime_list[ntt_num_primes] = 704 | { 705 | 53UL, 97UL, 193UL, 389UL, 769UL, 706 | 1543UL, 3079UL, 6151UL, 12289UL, 24593UL, 707 | 49157UL, 98317UL, 196613UL, 393241UL, 786433UL, 708 | 1572869UL, 3145739UL, 6291469UL, 12582917UL, 25165843UL, 709 | 50331653UL, 100663319UL, 201326611UL, 402653189UL, 805306457UL, 710 | 1610612741UL, 3221225473UL, 4294967291UL 711 | }; 712 | 713 | /* Get the next prime bigger or equal than the given number */ 714 | 715 | static size_t ntt_prime_get_next(size_t n) { 716 | for (size_t i = 0; i < ntt_num_primes; i++) { 717 | if (ntt_prime_list[i] >= n) 718 | return ntt_prime_list[i]; 719 | } 720 | 721 | return ntt_prime_list[ntt_num_primes - 1]; 722 | } 723 | 724 | 725 | /* Find the numeric position in the hash table based on key and modulus */ 726 | 727 | static size_t ntt_hashcode(const struct ntt *ntt, const char *key) { 728 | size_t val = 0; 729 | for (; *key; ++key) val = 5 * val + *key; 730 | return(val % ntt->size); 731 | } 732 | 733 | /* Creates a single node in the tree */ 734 | 735 | static struct ntt_node *ntt_node_create(const char *key, apr_time_t timestamp) { 736 | char *node_key; 737 | struct ntt_node* node; 738 | 739 | node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); 740 | if (node == NULL) { 741 | return NULL; 742 | } 743 | if ((node_key = strdup(key)) == NULL) { 744 | free(node); 745 | return NULL; 746 | } 747 | *node = (struct ntt_node) { 748 | .key = node_key, 749 | .timestamp = timestamp, 750 | .count = 0, 751 | .next = NULL, 752 | }; 753 | return(node); 754 | } 755 | 756 | /* Tree initializer */ 757 | 758 | static struct ntt *ntt_create(size_t size) { 759 | struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); 760 | 761 | if (ntt == NULL) 762 | return NULL; 763 | ntt->size = ntt_prime_get_next(size); 764 | ntt->items = 0; 765 | ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); 766 | if (ntt->tbl == NULL) { 767 | free(ntt); 768 | return NULL; 769 | } 770 | return(ntt); 771 | } 772 | 773 | /* Find an object in the tree */ 774 | 775 | static struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { 776 | size_t hash_code; 777 | struct ntt_node *node; 778 | 779 | if (ntt == NULL) return NULL; 780 | 781 | hash_code = ntt_hashcode(ntt, key); 782 | node = ntt->tbl[hash_code]; 783 | 784 | while (node) { 785 | if (!strcmp(key, node->key)) { 786 | return(node); 787 | } 788 | node = node->next; 789 | } 790 | return((struct ntt_node *)NULL); 791 | } 792 | 793 | /* Whether a node is outdated */ 794 | 795 | static int ntt_node_is_outdated(const struct ntt_node *node, apr_time_t timestamp) { 796 | return timestamp - node->timestamp >= 6 * 60 * 60; /* 6 hours */ 797 | } 798 | 799 | /* Copy a node into the tree; only used during tree growth */ 800 | 801 | static void ntt_grow_copy(struct ntt *ntt, struct ntt_node *node, apr_time_t timestamp) { 802 | size_t hash_code; 803 | struct ntt_node **curr; 804 | 805 | /* Ignore outdated entries */ 806 | if (ntt_node_is_outdated(node, timestamp)) { 807 | free(node->key); 808 | free(node); 809 | return; 810 | } 811 | 812 | hash_code = ntt_hashcode(ntt, node->key); 813 | curr = &ntt->tbl[hash_code]; 814 | 815 | while (*curr) { 816 | /* No need to compare keys, since the original tree should not have duplicates */ 817 | curr = &(*curr)->next; 818 | } 819 | 820 | node->next = NULL; 821 | *curr = node; 822 | ntt->items++; 823 | } 824 | 825 | /* Grow the tree */ 826 | 827 | static int ntt_grow(struct ntt *ntt, apr_time_t timestamp) { 828 | struct ntt tmp_ntt; 829 | struct ntt_node **new_tbl; 830 | size_t new_size; 831 | 832 | new_size = ntt_prime_get_next(ntt->size + 1); 833 | if (new_size == ntt->size) { 834 | errno = EOVERFLOW; 835 | return -1; 836 | } 837 | 838 | new_tbl = calloc(new_size, sizeof(struct ntt_node *)); 839 | if (!new_tbl) 840 | return -1; 841 | 842 | tmp_ntt = (struct ntt) { 843 | .size = new_size, 844 | .items = 0, 845 | .tbl = new_tbl, 846 | }; 847 | 848 | for (size_t i = 0; i < ntt->size; i++) { 849 | struct ntt_node *node; 850 | 851 | node = ntt->tbl[i]; 852 | while (node) { 853 | struct ntt_node *next; 854 | 855 | next = node->next; 856 | ntt_grow_copy(&tmp_ntt, node, timestamp); 857 | node = next; 858 | } 859 | } 860 | 861 | free(ntt->tbl); 862 | 863 | ap_log_error(APLOG_MARK, APLOG_INFO, 0, ap_server_conf, "Resized hash table from %zu to %zu", 864 | ntt->size, new_size); 865 | 866 | *ntt = tmp_ntt; 867 | 868 | return 0; 869 | } 870 | 871 | /* Insert a node into the tree */ 872 | 873 | static struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, apr_time_t timestamp) { 874 | size_t hash_code; 875 | struct ntt_node *parent; 876 | struct ntt_node *node; 877 | struct ntt_node *new_node = NULL; 878 | 879 | if (ntt == NULL || ntt->items == SIZE_MAX) return NULL; 880 | 881 | /* Grow on 75% utilization */ 882 | if (((ntt->size * 3) / 4) < ntt->items) { 883 | if (ntt_grow(ntt, timestamp) < 0) { 884 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Failed to increase hashtable of size %zu and %zu entries: %s", 885 | ntt->size, ntt->items, strerror(errno)); 886 | return NULL; 887 | } 888 | } 889 | 890 | hash_code = ntt_hashcode(ntt, key); 891 | parent = NULL; 892 | node = ntt->tbl[hash_code]; 893 | 894 | while (node != NULL) { 895 | if (strcmp(key, node->key) == 0) { 896 | new_node = node; 897 | node = NULL; 898 | break; 899 | } 900 | 901 | /* Delete outdated entries */ 902 | if (ntt_node_is_outdated(node, timestamp)) { 903 | struct ntt_node *next = node->next; 904 | 905 | if (parent) 906 | parent->next = next; 907 | else 908 | ntt->tbl[hash_code] = next; 909 | 910 | free(node->key); 911 | free(node); 912 | ntt->items--; 913 | node = next; 914 | continue; 915 | } 916 | 917 | parent = node; 918 | node = node->next; 919 | } 920 | 921 | if (new_node != NULL) { 922 | new_node->timestamp = timestamp; 923 | new_node->count = 0; 924 | return new_node; 925 | } 926 | 927 | /* Create a new node */ 928 | new_node = ntt_node_create(key, timestamp); 929 | 930 | ntt->items++; 931 | 932 | /* Insert */ 933 | if (parent) { /* Existing parent */ 934 | parent->next = new_node; 935 | return new_node; /* Return the locked node */ 936 | } 937 | 938 | /* No existing parent; add directly to hash table */ 939 | ntt->tbl[hash_code] = new_node; 940 | return new_node; 941 | } 942 | 943 | /* Tree destructor */ 944 | 945 | static int ntt_destroy(struct ntt *ntt) { 946 | struct ntt_node *node, *next; 947 | struct ntt_c c; 948 | 949 | if (ntt == NULL) return -1; 950 | 951 | node = c_ntt_first(ntt, &c); 952 | while(node != NULL) { 953 | next = c_ntt_next(ntt, &c); 954 | ntt_delete(ntt, node->key); 955 | node = next; 956 | } 957 | 958 | free(ntt->tbl); 959 | free(ntt); 960 | 961 | return 0; 962 | } 963 | 964 | /* Delete a single node in the tree */ 965 | 966 | static int ntt_delete(struct ntt *ntt, const char *key) { 967 | size_t hash_code; 968 | struct ntt_node *parent = NULL; 969 | struct ntt_node *node; 970 | struct ntt_node *del_node = NULL; 971 | 972 | if (ntt == NULL) return -1; 973 | 974 | hash_code = ntt_hashcode(ntt, key); 975 | node = ntt->tbl[hash_code]; 976 | 977 | while (node != NULL) { 978 | if (strcmp(key, node->key) == 0) { 979 | del_node = node; 980 | node = NULL; 981 | } 982 | 983 | if (del_node == NULL) { 984 | parent = node; 985 | node = node->next; 986 | } 987 | } 988 | 989 | if (del_node != NULL) { 990 | 991 | if (parent) { 992 | parent->next = del_node->next; 993 | } else { 994 | ntt->tbl[hash_code] = del_node->next; 995 | } 996 | 997 | free(del_node->key); 998 | free(del_node); 999 | ntt->items--; 1000 | 1001 | return 0; 1002 | } 1003 | 1004 | return -5; 1005 | } 1006 | 1007 | /* Point cursor to first item in tree */ 1008 | 1009 | static struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { 1010 | 1011 | c->iter_index = 0; 1012 | c->iter_next = (struct ntt_node *)NULL; 1013 | return(c_ntt_next(ntt, c)); 1014 | } 1015 | 1016 | /* Point cursor to next iteration in tree */ 1017 | 1018 | static struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { 1019 | size_t index; 1020 | struct ntt_node *node = c->iter_next; 1021 | 1022 | if (ntt == NULL) return NULL; 1023 | 1024 | if (node) { 1025 | c->iter_next = node->next; 1026 | return (node); 1027 | } 1028 | 1029 | while (c->iter_index < ntt->size) { 1030 | index = c->iter_index++; 1031 | 1032 | if (ntt->tbl[index]) { 1033 | c->iter_next = ntt->tbl[index]->next; 1034 | return(ntt->tbl[index]); 1035 | } 1036 | } 1037 | 1038 | return((struct ntt_node *)NULL); 1039 | } 1040 | 1041 | /* END NTT (Named Pointer Tree) Functions */ 1042 | 1043 | 1044 | /* BEGIN Configuration Functions */ 1045 | 1046 | static const char * 1047 | get_enabled(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1048 | evasive_config *cfg = (evasive_config *) dconfig; 1049 | 1050 | if (strcmp("true", value) == 0) { 1051 | cfg->enabled = 1; 1052 | } else if (strcmp("false", value) == 0) { 1053 | cfg->enabled = 0; 1054 | } else { 1055 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSEnabled value '%s', mod_evasive disabled.", value); 1056 | cfg->enabled = 0; 1057 | } 1058 | 1059 | return NULL; 1060 | } 1061 | 1062 | static const char * 1063 | get_hash_tbl_size(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1064 | evasive_config *cfg = (evasive_config *) dconfig; 1065 | char *endptr; 1066 | long n; 1067 | 1068 | errno = 0; 1069 | n = strtol(value, &endptr, 0); 1070 | if (errno || *endptr != '\0' || n <= 0) { 1071 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSHashTableSize value '%s', using default %lu.", 1072 | value, DEFAULT_HASH_TBL_SIZE); 1073 | cfg->hash_table_size = DEFAULT_HASH_TBL_SIZE; 1074 | } else { 1075 | cfg->hash_table_size = n; 1076 | 1077 | ntt_destroy(cfg->hit_list); 1078 | cfg->hit_list = ntt_create(cfg->hash_table_size); 1079 | if (!cfg->hit_list) 1080 | ap_log_error(APLOG_MARK, APLOG_ERR, 0, ap_server_conf, "Failed to allocate hashtable"); 1081 | } 1082 | 1083 | return NULL; 1084 | } 1085 | 1086 | static const char * 1087 | get_page_count(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1088 | evasive_config *cfg = (evasive_config *) dconfig; 1089 | char *endptr; 1090 | long n; 1091 | 1092 | errno = 0; 1093 | n = strtol(value, &endptr, 0); 1094 | if (errno || *endptr != '\0' || n <= 0 || n > UINT_MAX) { 1095 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSPageCount value '%s', using default %d.", 1096 | value, DEFAULT_PAGE_COUNT); 1097 | cfg->page_count = DEFAULT_PAGE_COUNT; 1098 | } else { 1099 | cfg->page_count = n; 1100 | } 1101 | 1102 | return NULL; 1103 | } 1104 | 1105 | static const char * 1106 | get_site_count(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1107 | evasive_config *cfg = (evasive_config *) dconfig; 1108 | char *endptr; 1109 | long n; 1110 | 1111 | errno = 0; 1112 | n = strtol(value, &endptr, 0); 1113 | if (errno || *endptr != '\0' || n <= 0 || n > UINT_MAX) { 1114 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSSiteCount value '%s', using default %d.", 1115 | value, DEFAULT_SITE_COUNT); 1116 | cfg->site_count = DEFAULT_SITE_COUNT; 1117 | } else { 1118 | cfg->site_count = n; 1119 | } 1120 | 1121 | return NULL; 1122 | } 1123 | 1124 | static const char * 1125 | get_page_interval(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1126 | evasive_config *cfg = (evasive_config *) dconfig; 1127 | char *endptr; 1128 | long n; 1129 | 1130 | errno = 0; 1131 | n = strtol(value, &endptr, 0); 1132 | if (errno || *endptr != '\0' || n <= 0 || n > INT_MAX) { 1133 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSPageInterval value '%s', using default %d.", 1134 | value, DEFAULT_PAGE_INTERVAL); 1135 | cfg->page_interval = DEFAULT_PAGE_INTERVAL; 1136 | } else { 1137 | cfg->page_interval = n; 1138 | } 1139 | 1140 | return NULL; 1141 | } 1142 | 1143 | static const char * 1144 | get_site_interval(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1145 | evasive_config *cfg = (evasive_config *) dconfig; 1146 | char *endptr; 1147 | long n; 1148 | 1149 | errno = 0; 1150 | n = strtol(value, &endptr, 0); 1151 | if (errno || *endptr != '\0' || n <= 0 || n > INT_MAX) { 1152 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSSiteInterval value '%s', using default %d.", 1153 | value, DEFAULT_SITE_INTERVAL); 1154 | cfg->site_interval = DEFAULT_SITE_INTERVAL; 1155 | } else { 1156 | cfg->site_interval = n; 1157 | } 1158 | 1159 | return NULL; 1160 | } 1161 | 1162 | static const char * 1163 | get_blocking_period(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1164 | evasive_config *cfg = (evasive_config *) dconfig; 1165 | char *endptr; 1166 | long n; 1167 | 1168 | errno = 0; 1169 | n = strtol(value, &endptr, 0); 1170 | if (errno || *endptr != '\0' || n <= 0 || n > INT_MAX) { 1171 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSBlockingPeriod value '%s', using default %d.", 1172 | value, DEFAULT_BLOCKING_PERIOD); 1173 | cfg->blocking_period = DEFAULT_BLOCKING_PERIOD; 1174 | } else { 1175 | cfg->blocking_period = n; 1176 | } 1177 | 1178 | return NULL; 1179 | } 1180 | 1181 | static const char * 1182 | get_log_dir(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1183 | evasive_config *cfg = (evasive_config *) dconfig; 1184 | if (value != NULL && value[0] != 0) { 1185 | if (cfg->log_dir != NULL) 1186 | free(cfg->log_dir); 1187 | cfg->log_dir = strdup(value); 1188 | } 1189 | 1190 | return NULL; 1191 | } 1192 | 1193 | static const char * 1194 | get_email_notify(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1195 | evasive_config *cfg = (evasive_config *) dconfig; 1196 | if (value != NULL && value[0] != 0) { 1197 | if (cfg->email_notify != NULL) 1198 | free(cfg->email_notify); 1199 | cfg->email_notify = strdup(value); 1200 | } 1201 | 1202 | return NULL; 1203 | } 1204 | 1205 | static const char * 1206 | get_system_command(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1207 | evasive_config *cfg = (evasive_config *) dconfig; 1208 | if (value != NULL && value[0] != 0) { 1209 | if (cfg->system_command != NULL) 1210 | free(cfg->system_command); 1211 | cfg->system_command = strdup(value); 1212 | } 1213 | 1214 | return NULL; 1215 | } 1216 | 1217 | static const char * 1218 | get_http_reply(__attribute__((unused)) cmd_parms *cmd, void *dconfig, const char *value) { 1219 | evasive_config *cfg = (evasive_config *) dconfig; 1220 | char *endptr; 1221 | long n; 1222 | 1223 | errno = 0; 1224 | n = strtol(value, &endptr, 0); 1225 | if (errno || *endptr != '\0' || ((n < 99 || n > 599) && n != OK && n != DECLINED)) { 1226 | ap_log_error(APLOG_MARK, APLOG_WARNING, 0, ap_server_conf, "Invalid DOSHTTPStatus value '%s', using default %d.", 1227 | value, HTTP_FORBIDDEN); 1228 | cfg->http_reply = HTTP_FORBIDDEN; 1229 | } else { 1230 | cfg->http_reply = n; 1231 | } 1232 | 1233 | return NULL; 1234 | } 1235 | 1236 | /* END Configuration Functions */ 1237 | 1238 | static const command_rec access_cmds[] = 1239 | { 1240 | AP_INIT_TAKE1("DOSEnabled", get_enabled, NULL, RSRC_CONF, 1241 | "Enable mod_evasive (either globally or in the virtualhost where it is specified)"), 1242 | 1243 | AP_INIT_TAKE1("DOSHashTableSize", get_hash_tbl_size, NULL, RSRC_CONF, 1244 | "Set size of hash table"), 1245 | 1246 | AP_INIT_TAKE1("DOSPageCount", get_page_count, NULL, RSRC_CONF, 1247 | "Set maximum page hit count per interval"), 1248 | 1249 | AP_INIT_TAKE1("DOSSiteCount", get_site_count, NULL, RSRC_CONF, 1250 | "Set maximum site hit count per interval"), 1251 | 1252 | AP_INIT_TAKE1("DOSPageInterval", get_page_interval, NULL, RSRC_CONF, 1253 | "Set page interval"), 1254 | 1255 | AP_INIT_TAKE1("DOSSiteInterval", get_site_interval, NULL, RSRC_CONF, 1256 | "Set site interval"), 1257 | 1258 | AP_INIT_TAKE1("DOSBlockingPeriod", get_blocking_period, NULL, RSRC_CONF, 1259 | "Set blocking period for detected DoS IPs"), 1260 | 1261 | AP_INIT_TAKE1("DOSEmailNotify", get_email_notify, NULL, RSRC_CONF, 1262 | "Set email notification"), 1263 | 1264 | AP_INIT_TAKE1("DOSLogDir", get_log_dir, NULL, RSRC_CONF, 1265 | "Set log dir"), 1266 | 1267 | AP_INIT_TAKE1("DOSSystemCommand", get_system_command, NULL, RSRC_CONF, 1268 | "Set system command on DoS"), 1269 | 1270 | AP_INIT_ITERATE("DOSWhitelist", whitelist_ip, NULL, RSRC_CONF, 1271 | "IP-addresses wildcards to whitelist"), 1272 | 1273 | AP_INIT_ITERATE("DOSWhitelistUri", whitelist_uri, NULL, RSRC_CONF, 1274 | "Files/paths regexes to whitelist"), 1275 | 1276 | AP_INIT_ITERATE("DOSTargetlistUri", target_uri, NULL, RSRC_CONF, 1277 | "Files/paths regexes to target"), 1278 | 1279 | AP_INIT_ITERATE("DOSBlocklistUri", blocklist_uri, NULL, RSRC_CONF, 1280 | "Files/paths regexes to blocklist"), 1281 | 1282 | AP_INIT_ITERATE("DOSHTTPStatus", get_http_reply, NULL, RSRC_CONF, 1283 | "HTTP reply code"), 1284 | 1285 | { NULL } 1286 | }; 1287 | 1288 | static void register_hooks(apr_pool_t *p) { 1289 | ap_hook_access_checker(access_checker, NULL, NULL, APR_HOOK_FIRST-5); 1290 | apr_pool_cleanup_register(p, NULL, apr_pool_cleanup_null, destroy_config); 1291 | }; 1292 | 1293 | module AP_MODULE_DECLARE_DATA evasive_module = 1294 | { 1295 | STANDARD20_MODULE_STUFF, 1296 | create_dir_conf, 1297 | NULL, 1298 | NULL, 1299 | NULL, 1300 | access_cmds, 1301 | register_hooks, 1302 | AP_MODULE_FLAG_NONE 1303 | }; 1304 | -------------------------------------------------------------------------------- /mod_evasive24win.c: -------------------------------------------------------------------------------- 1 | // vim:ts=4:shiftwidth=4:et 2 | /* 3 | mod_evasive for Apache 2 4 | Copyright (c) by Jonathan A. Zdziarski 5 | 6 | Windows port by Gregg Smith 7 | Apache 2.4 compatibility and many improvements by Joris Vandermeersch 8 | 9 | LICENSE 10 | 11 | This program is free software; you can redistribute it and/or 12 | modify it under the terms of the GNU General Public License 13 | as published by the Free Software Foundation; either version 2 14 | of the License, or (at your option) any later version. 15 | 16 | This program is distributed in the hope that it will be useful, 17 | but WITHOUT ANY WARRANTY; without even the implied warranty of 18 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 | GNU General Public License for more details. 20 | 21 | You should have received a copy of the GNU General Public License 22 | along with this program; if not, write to the Free Software 23 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 24 | 25 | */ 26 | 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #ifdef _MSC_VER 34 | # define snprintf _snprintf 35 | #endif 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | #include "apr_time.h" 43 | 44 | #define PCRE2_CODE_UNIT_WIDTH 8 45 | #include 46 | 47 | #include "httpd.h" 48 | #include "http_core.h" 49 | #include "http_config.h" 50 | #include "http_log.h" 51 | #include "http_request.h" 52 | 53 | #ifdef APLOG_USE_MODULE 54 | APLOG_USE_MODULE(evasive); 55 | #endif 56 | 57 | #if AP_MODULE_MAGIC_AT_LEAST(20111130,0) 58 | #define remote_ip client_ip 59 | #endif 60 | 61 | module AP_MODULE_DECLARE_DATA evasive_module; 62 | 63 | /* BEGIN DoS Evasive Maneuvers Definitions */ 64 | 65 | #define DEFAULT_HASH_TBL_SIZE 3079ul // Default hash table size 66 | #define DEFAULT_PAGE_COUNT 2 // Default maximum page hit count per interval 67 | #define DEFAULT_SITE_COUNT 50 // Default maximum site hit count per interval 68 | #define DEFAULT_PAGE_INTERVAL 1 // Default 1 Second page interval 69 | #define DEFAULT_SITE_INTERVAL 1 // Default 1 Second site interval 70 | #define DEFAULT_BLOCKING_PERIOD 10 // Default for Detected IPs; blocked for 10 seconds 71 | #define DEFAULT_LOG_DIR "/temp" // Default temp directory 72 | #define DEFAULT_HTTP_REPLY HTTP_FORBIDDEN // Default HTTP Reply code (403) 73 | 74 | /* END DoS Evasive Maneuvers Definitions */ 75 | 76 | /* BEGIN NTT (Named Timestamp Tree) Headers */ 77 | 78 | enum { ntt_num_primes = 28 }; 79 | 80 | /* ntt root tree */ 81 | struct ntt { 82 | long size; 83 | long items; 84 | struct ntt_node **tbl; 85 | }; 86 | 87 | /* ntt node (entry in the ntt root tree) */ 88 | struct ntt_node { 89 | char *key; 90 | time_t timestamp; 91 | long count; 92 | struct ntt_node *next; 93 | }; 94 | 95 | /* ntt cursor */ 96 | struct ntt_c { 97 | long iter_index; 98 | struct ntt_node *iter_next; 99 | }; 100 | 101 | struct ntt *ntt_create(unsigned long size); 102 | int ntt_destroy(struct ntt *ntt); 103 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key); 104 | struct ntt_node *ntt_re_find(struct ntt *ntt, const char *key); 105 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); 106 | int ntt_delete(struct ntt *ntt, const char *key); 107 | long ntt_hashcode(struct ntt *ntt, const char *key); 108 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); 109 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); 110 | 111 | /* END NTT (Named Timestamp Tree) Headers */ 112 | 113 | 114 | /* BEGIN DoS Evasive Maneuvers Globals */ 115 | 116 | struct pcre_node { 117 | pcre2_code *re; 118 | struct pcre_node *next; 119 | }; 120 | 121 | typedef struct { 122 | int enabled; 123 | char *context; 124 | struct ntt *hit_list; // Our dynamic hash table 125 | unsigned long hash_table_size; 126 | struct pcre_node *uri_whitelist; 127 | int page_count; 128 | int page_interval; 129 | int site_count; 130 | int site_interval; 131 | int blocking_period; 132 | char *log_dir; 133 | char *system_command; 134 | int http_reply; 135 | } evasive_config; 136 | 137 | static const char *whitelist(cmd_parms *cmd, void *dconfig, const char *ip); 138 | int is_whitelisted(const char *ip, evasive_config *cfg); 139 | 140 | static const char *whitelist_uri(cmd_parms *cmd, void *dconfig, const char *uri_re); 141 | int is_uri_whitelisted(const char *uri, evasive_config *cfg); 142 | 143 | /* END DoS Evasive Maneuvers Globals */ 144 | 145 | static void * create_dir_conf(apr_pool_t *p, char *context) 146 | { 147 | context = context ? context : "(undefined context)"; 148 | /* Create a new hit list for this listener */ 149 | evasive_config *cfg = apr_pcalloc(p, sizeof(evasive_config)); 150 | if (cfg) { 151 | cfg->enabled = 0; 152 | cfg->context = strdup(context); 153 | cfg->hash_table_size = DEFAULT_HASH_TBL_SIZE; 154 | cfg->hit_list = ntt_create(cfg->hash_table_size); 155 | cfg->uri_whitelist = NULL; 156 | cfg->page_count = DEFAULT_PAGE_COUNT; 157 | cfg->page_interval = DEFAULT_PAGE_INTERVAL; 158 | cfg->site_count = DEFAULT_SITE_COUNT; 159 | cfg->site_interval = DEFAULT_SITE_INTERVAL; 160 | cfg->log_dir = NULL; 161 | cfg->system_command = NULL; 162 | cfg->http_reply = DEFAULT_HTTP_REPLY; 163 | } 164 | 165 | return cfg; 166 | } 167 | 168 | static const char *whitelist(cmd_parms *cmd, void *dconfig, const char *ip) 169 | { 170 | evasive_config *cfg = (evasive_config *) dconfig; 171 | char entry[128]; 172 | snprintf(entry, sizeof(entry), "WHITELIST_%s", ip); 173 | ntt_insert(cfg->hit_list, entry, time(NULL)); 174 | 175 | return NULL; 176 | } 177 | 178 | static const char *whitelist_uri(cmd_parms *cmd, void *dconfig, const char *uri_re) 179 | { 180 | evasive_config *cfg = (evasive_config *) dconfig; 181 | struct pcre_node *node; 182 | 183 | node = (struct pcre_node *) malloc(sizeof(struct pcre_node)); 184 | if (node == NULL) { 185 | return NULL; 186 | } 187 | 188 | int errornumber; 189 | PCRE2_SIZE erroroffset; 190 | 191 | PCRE2_SPTR pattern; 192 | pattern = (PCRE2_SPTR) uri_re; 193 | 194 | node->re = pcre2_compile( 195 | pattern, /* the pattern */ 196 | PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */ 197 | 0, /* default options */ 198 | &errornumber, /* for error number */ 199 | &erroroffset, /* for error offset */ 200 | NULL); /* use default compile context */ 201 | 202 | /* Compilation failed: print the error message and exit. */ 203 | 204 | if (node->re == NULL) 205 | { 206 | PCRE2_UCHAR buffer[256]; 207 | pcre2_get_error_message(errornumber, buffer, sizeof(buffer)); 208 | printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset, 209 | buffer); 210 | return NULL; 211 | } 212 | 213 | node->next = cfg->uri_whitelist; 214 | cfg->uri_whitelist = node; 215 | return NULL; 216 | } 217 | 218 | static int access_checker(request_rec *r) 219 | { 220 | evasive_config *cfg = (evasive_config *) ap_get_module_config(r->per_dir_config, &evasive_module); 221 | 222 | int ret = OK; 223 | 224 | /* BEGIN DoS Evasive Maneuvers Code */ 225 | 226 | if (cfg->enabled && r->prev == NULL && r->main == NULL && cfg->hit_list != NULL) { 227 | char hash_key[2048]; 228 | struct ntt_node *n; 229 | time_t t = time(NULL); 230 | 231 | /* Check whitelist */ 232 | if (is_whitelisted(r->useragent_ip, cfg)) 233 | return OK; 234 | 235 | /* First see if the IP itself is on "hold" */ 236 | n = ntt_find(cfg->hit_list, r->useragent_ip); 237 | 238 | if (n != NULL && t-n->timestampblocking_period) { 239 | 240 | /* If the IP is on "hold", make it wait longer in 403 land */ 241 | ret = cfg->http_reply; 242 | n->timestamp = time(NULL); 243 | 244 | /* Not on hold, check hit stats */ 245 | } else { 246 | 247 | /* Check whitelisted uris */ 248 | if (is_uri_whitelisted(r->uri, cfg)) 249 | return OK; 250 | 251 | /* Has URI been hit too much? */ 252 | snprintf(hash_key, 2048, "%s_%s", r->useragent_ip, r->uri); 253 | n = ntt_find(cfg->hit_list, hash_key); 254 | if (n != NULL) { 255 | 256 | /* If URI is being hit too much, add to "hold" list and 403 */ 257 | if (t-n->timestamppage_interval && n->count>=cfg->page_count) { 258 | ret = cfg->http_reply; 259 | ntt_insert(cfg->hit_list, r->useragent_ip, time(NULL)); 260 | } else { 261 | 262 | /* Reset our hit count list as necessary */ 263 | if (t-n->timestamp>=cfg->page_interval) { 264 | n->count=0; 265 | } 266 | } 267 | n->timestamp = t; 268 | n->count++; 269 | } else { 270 | ntt_insert(cfg->hit_list, hash_key, t); 271 | } 272 | 273 | /* Has site been hit too much? */ 274 | snprintf(hash_key, 2048, "%s_SITE", r->useragent_ip); 275 | n = ntt_find(cfg->hit_list, hash_key); 276 | if (n != NULL) { 277 | 278 | /* If site is being hit too much, add to "hold" list and 403 */ 279 | if (t-n->timestampsite_interval && n->count>=cfg->site_count) { 280 | ret = cfg->http_reply; 281 | ntt_insert(cfg->hit_list, r->useragent_ip, time(NULL)); 282 | } else { 283 | 284 | /* Reset our hit count list as necessary */ 285 | if (t-n->timestamp>=cfg->site_interval) { 286 | n->count=0; 287 | } 288 | } 289 | n->timestamp = t; 290 | n->count++; 291 | } else { 292 | ntt_insert(cfg->hit_list, hash_key, t); 293 | } 294 | } 295 | 296 | /* Perform system functions */ 297 | if (ret == cfg->http_reply) { 298 | char filename[1024]; 299 | FILE *file; 300 | char evasive_timestamp[APR_CTIME_LEN]; 301 | 302 | snprintf(filename, sizeof(filename), "%s/dos-%s", cfg->log_dir != NULL ? cfg->log_dir : DEFAULT_LOG_DIR, r->useragent_ip); 303 | file = fopen(filename, "w"); 304 | if (file != NULL) { 305 | apr_ctime(evasive_timestamp, apr_time_now()); 306 | fprintf(file, "%s\nPID: %ld\n", evasive_timestamp, getpid()); 307 | fprintf(file, "Blacklisting address %s: possible DoS attack.\n", r->useragent_ip); 308 | fclose(file); 309 | 310 | /* This should be possible in Windows, consider it Experimental */ 311 | if (cfg->system_command != NULL) { 312 | snprintf(filename, sizeof(filename), cfg->system_command, r->useragent_ip); 313 | system(filename); 314 | } 315 | 316 | } 317 | 318 | } /* if (ret == cfg->http_reply) */ 319 | 320 | } /* if (r->prev == NULL && r->main == NULL && cfg->hit_list != NULL) */ 321 | 322 | /* END DoS Evasive Maneuvers Code */ 323 | 324 | /* Give a hoot, don't pollute the Apache's error log ok? 325 | * 326 | * if (ret == cfg->http_reply 327 | * && (ap_satisfies(r) != SATISFY_ANY || !ap_some_auth_required(r))) { 328 | * ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, 329 | * "client denied by server configuration: %s", 330 | * r->filename); 331 | * } 332 | */ 333 | return ret; 334 | } 335 | 336 | int is_whitelisted(const char *ip, evasive_config *cfg) { 337 | char hashkey[128]; 338 | char octet[4][4]; 339 | char *dip; 340 | char *oct; 341 | int i = 0; 342 | 343 | memset(octet, 0, 16); 344 | dip = strdup(ip); 345 | if (dip == NULL) 346 | return 0; 347 | 348 | oct = strtok(dip, "."); 349 | while(oct != NULL && i<4) { 350 | if (strlen(oct)<=3) 351 | strcpy(octet[i], oct); 352 | i++; 353 | oct = strtok(NULL, "."); 354 | } 355 | free(dip); 356 | 357 | /* Exact Match */ 358 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s", ip); 359 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 360 | return 1; 361 | 362 | /* IPv4 Wildcards */ 363 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.*.*.*", octet[0]); 364 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 365 | return 1; 366 | 367 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.*.*", octet[0], octet[1]); 368 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 369 | return 1; 370 | 371 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.%s.*", octet[0], octet[1], octet[2]); 372 | if (ntt_find(cfg->hit_list, hashkey)!=NULL) 373 | return 1; 374 | 375 | /* No match */ 376 | return 0; 377 | } 378 | 379 | int is_uri_whitelisted(const char *path, evasive_config *cfg) { 380 | 381 | int rc; 382 | pcre2_match_data *match_data; 383 | 384 | PCRE2_SPTR subject; 385 | size_t subject_length; 386 | 387 | subject = (PCRE2_SPTR) path; 388 | subject_length = strlen((char *)subject); 389 | 390 | struct pcre_node *node; 391 | node = cfg->uri_whitelist; 392 | 393 | while (node != NULL) { 394 | match_data = pcre2_match_data_create_from_pattern(node->re, NULL); 395 | 396 | rc = pcre2_match( 397 | node->re, /* the compiled pattern */ 398 | subject, /* the subject string */ 399 | subject_length, /* the length of the subject */ 400 | 0, /* start at offset 0 in the subject */ 401 | 0, /* default options */ 402 | match_data, /* block for storing the result */ 403 | NULL); /* use default match context */ 404 | 405 | pcre2_match_data_free(match_data); /* Release memory used for the match */ 406 | 407 | if (rc >= 0) { 408 | // match 409 | return 1; 410 | } 411 | 412 | node = node->next; 413 | } 414 | 415 | // no match 416 | return 0; 417 | } 418 | 419 | static apr_status_t destroy_config(void *dconfig) { 420 | evasive_config *cfg = (evasive_config *) dconfig; 421 | if (cfg != NULL) { 422 | ntt_destroy(cfg->hit_list); 423 | free(cfg->log_dir); 424 | free(cfg->system_command); 425 | free(cfg); 426 | } 427 | return APR_SUCCESS; 428 | } 429 | 430 | 431 | /* BEGIN NTT (Named Timestamp Tree) Functions */ 432 | 433 | static unsigned long ntt_prime_list[ntt_num_primes] = 434 | { 435 | 53ul, 97ul, 193ul, 389ul, 769ul, 436 | 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 437 | 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 438 | 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 439 | 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 440 | 1610612741ul, 3221225473ul, 4294967291ul 441 | }; 442 | 443 | 444 | /* Find the numeric position in the hash table based on key and modulus */ 445 | 446 | long ntt_hashcode(struct ntt *ntt, const char *key) { 447 | unsigned long val = 0; 448 | for (; *key; ++key) val = 5 * val + *key; 449 | return(val % ntt->size); 450 | } 451 | 452 | /* Creates a single node in the tree */ 453 | 454 | struct ntt_node *ntt_node_create(const char *key) { 455 | char *node_key; 456 | struct ntt_node* node; 457 | 458 | node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); 459 | if (node == NULL) { 460 | return NULL; 461 | } 462 | if ((node_key = strdup(key)) == NULL) { 463 | free(node); 464 | return NULL; 465 | } 466 | node->key = node_key; 467 | node->timestamp = time(NULL); 468 | node->next = NULL; 469 | return(node); 470 | } 471 | 472 | /* Tree initializer */ 473 | 474 | struct ntt *ntt_create(unsigned long size) { 475 | long i = 0; 476 | struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); 477 | 478 | if (ntt == NULL) 479 | return NULL; 480 | while (ntt_prime_list[i] < size) { i++; } 481 | ntt->size = ntt_prime_list[i]; 482 | ntt->items = 0; 483 | ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); 484 | if (ntt->tbl == NULL) { 485 | free(ntt); 486 | return NULL; 487 | } 488 | return(ntt); 489 | } 490 | 491 | /* Find an object in the tree */ 492 | 493 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { 494 | long hash_code; 495 | struct ntt_node *node; 496 | 497 | if (ntt == NULL) return NULL; 498 | 499 | hash_code = ntt_hashcode(ntt, key); 500 | node = ntt->tbl[hash_code]; 501 | 502 | while (node) { 503 | if (!strcmp(key, node->key)) { 504 | return(node); 505 | } 506 | node = node->next; 507 | } 508 | return((struct ntt_node *)NULL); 509 | } 510 | 511 | /* Insert a node into the tree */ 512 | 513 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { 514 | long hash_code; 515 | struct ntt_node *parent; 516 | struct ntt_node *node; 517 | struct ntt_node *new_node = NULL; 518 | 519 | if (ntt == NULL) return NULL; 520 | 521 | hash_code = ntt_hashcode(ntt, key); 522 | parent = NULL; 523 | node = ntt->tbl[hash_code]; 524 | 525 | while (node != NULL) { 526 | if (strcmp(key, node->key) == 0) { 527 | new_node = node; 528 | node = NULL; 529 | } 530 | 531 | if (new_node == NULL) { 532 | parent = node; 533 | node = node->next; 534 | } 535 | } 536 | 537 | if (new_node != NULL) { 538 | new_node->timestamp = timestamp; 539 | new_node->count = 0; 540 | return new_node; 541 | } 542 | 543 | /* Create a new node */ 544 | new_node = ntt_node_create(key); 545 | new_node->timestamp = timestamp; 546 | new_node->count = 0; 547 | 548 | ntt->items++; 549 | 550 | /* Insert */ 551 | if (parent) { /* Existing parent */ 552 | parent->next = new_node; 553 | return new_node; /* Return the locked node */ 554 | } 555 | 556 | /* No existing parent; add directly to hash table */ 557 | ntt->tbl[hash_code] = new_node; 558 | return new_node; 559 | } 560 | 561 | /* Tree destructor */ 562 | 563 | int ntt_destroy(struct ntt *ntt) { 564 | struct ntt_node *node, *next; 565 | struct ntt_c c; 566 | 567 | if (ntt == NULL) return -1; 568 | 569 | node = c_ntt_first(ntt, &c); 570 | while(node != NULL) { 571 | next = c_ntt_next(ntt, &c); 572 | ntt_delete(ntt, node->key); 573 | node = next; 574 | } 575 | 576 | free(ntt->tbl); 577 | free(ntt); 578 | ntt = (struct ntt *) NULL; 579 | 580 | return 0; 581 | } 582 | 583 | /* Delete a single node in the tree */ 584 | 585 | int ntt_delete(struct ntt *ntt, const char *key) { 586 | long hash_code; 587 | struct ntt_node *parent = NULL; 588 | struct ntt_node *node; 589 | struct ntt_node *del_node = NULL; 590 | 591 | if (ntt == NULL) return -1; 592 | 593 | hash_code = ntt_hashcode(ntt, key); 594 | node = ntt->tbl[hash_code]; 595 | 596 | while (node != NULL) { 597 | if (strcmp(key, node->key) == 0) { 598 | del_node = node; 599 | node = NULL; 600 | } 601 | 602 | if (del_node == NULL) { 603 | parent = node; 604 | node = node->next; 605 | } 606 | } 607 | 608 | if (del_node != NULL) { 609 | 610 | if (parent) { 611 | parent->next = del_node->next; 612 | } else { 613 | ntt->tbl[hash_code] = del_node->next; 614 | } 615 | 616 | free(del_node->key); 617 | free(del_node); 618 | ntt->items--; 619 | 620 | return 0; 621 | } 622 | 623 | return -5; 624 | } 625 | 626 | /* Point cursor to first item in tree */ 627 | 628 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { 629 | 630 | c->iter_index = 0; 631 | c->iter_next = (struct ntt_node *)NULL; 632 | return(c_ntt_next(ntt, c)); 633 | } 634 | 635 | /* Point cursor to next iteration in tree */ 636 | 637 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { 638 | long index; 639 | struct ntt_node *node = c->iter_next; 640 | 641 | if (ntt == NULL) return NULL; 642 | 643 | if (node) { 644 | if (node != NULL) { 645 | c->iter_next = node->next; 646 | return (node); 647 | } 648 | } 649 | 650 | if (! node) { 651 | while (c->iter_index < ntt->size) { 652 | index = c->iter_index++; 653 | 654 | if (ntt->tbl[index]) { 655 | c->iter_next = ntt->tbl[index]->next; 656 | return(ntt->tbl[index]); 657 | } 658 | } 659 | } 660 | return((struct ntt_node *)NULL); 661 | } 662 | 663 | /* END NTT (Named Pointer Tree) Functions */ 664 | 665 | 666 | /* BEGIN Configuration Functions */ 667 | 668 | static const char * 669 | get_enabled(cmd_parms *cmd, void *dconfig, const char *value) { 670 | evasive_config *cfg = (evasive_config *) dconfig; 671 | cfg->enabled = (strcmp("true", value) == 0) ? 1 : 0; 672 | return NULL; 673 | } 674 | 675 | static const char * 676 | get_hash_tbl_size(cmd_parms *cmd, void *dconfig, const char *value) { 677 | evasive_config *cfg = (evasive_config *) dconfig; 678 | long n = strtol(value, NULL, 0); 679 | 680 | if (n<=0) { 681 | cfg->hash_table_size = DEFAULT_HASH_TBL_SIZE; 682 | } else { 683 | cfg->hash_table_size = n; 684 | } 685 | cfg->hit_list = ntt_create(cfg->hash_table_size); 686 | 687 | return NULL; 688 | } 689 | 690 | static const char * 691 | get_page_count(cmd_parms *cmd, void *dconfig, const char *value) { 692 | evasive_config *cfg = (evasive_config *) dconfig; 693 | long n = strtol(value, NULL, 0); 694 | if (n<=0) { 695 | cfg->page_count = DEFAULT_PAGE_COUNT; 696 | } else { 697 | cfg->page_count = n; 698 | } 699 | 700 | return NULL; 701 | } 702 | 703 | static const char * 704 | get_site_count(cmd_parms *cmd, void *dconfig, const char *value) { 705 | evasive_config *cfg = (evasive_config *) dconfig; 706 | long n = strtol(value, NULL, 0); 707 | if (n<=0) { 708 | cfg->site_count = DEFAULT_SITE_COUNT; 709 | } else { 710 | cfg->site_count = n; 711 | } 712 | 713 | return NULL; 714 | } 715 | 716 | static const char * 717 | get_page_interval(cmd_parms *cmd, void *dconfig, const char *value) { 718 | evasive_config *cfg = (evasive_config *) dconfig; 719 | long n = strtol(value, NULL, 0); 720 | if (n<=0) { 721 | cfg->page_interval = DEFAULT_PAGE_INTERVAL; 722 | } else { 723 | cfg->page_interval = n; 724 | } 725 | 726 | return NULL; 727 | } 728 | 729 | static const char * 730 | get_site_interval(cmd_parms *cmd, void *dconfig, const char *value) { 731 | evasive_config *cfg = (evasive_config *) dconfig; 732 | long n = strtol(value, NULL, 0); 733 | if (n<=0) { 734 | cfg->site_interval = DEFAULT_SITE_INTERVAL; 735 | } else { 736 | cfg->site_interval = n; 737 | } 738 | 739 | return NULL; 740 | } 741 | 742 | static const char * 743 | get_blocking_period(cmd_parms *cmd, void *dconfig, const char *value) { 744 | evasive_config *cfg = (evasive_config *) dconfig; 745 | long n = strtol(value, NULL, 0); 746 | if (n<=0) { 747 | cfg->blocking_period = DEFAULT_BLOCKING_PERIOD; 748 | } else { 749 | cfg->blocking_period = n; 750 | } 751 | 752 | return NULL; 753 | } 754 | 755 | static const char * 756 | get_log_dir(cmd_parms *cmd, void *dconfig, const char *value) { 757 | evasive_config *cfg = (evasive_config *) dconfig; 758 | if (value != NULL && value[0] != 0) { 759 | if (cfg->log_dir != NULL) 760 | free(cfg->log_dir); 761 | cfg->log_dir = strdup(value); 762 | } 763 | 764 | return NULL; 765 | } 766 | 767 | static const char * 768 | get_system_command(cmd_parms *cmd, void *dconfig, const char *value) { 769 | evasive_config *cfg = (evasive_config *) dconfig; 770 | if (value != NULL && value[0] != 0) { 771 | if (cfg->system_command != NULL) 772 | free(cfg->system_command); 773 | cfg->system_command = strdup(value); 774 | } 775 | 776 | return NULL; 777 | } 778 | 779 | static const char * 780 | get_http_reply(cmd_parms *cmd, void *dconfig, const char *value) { 781 | evasive_config *cfg = (evasive_config *) dconfig; 782 | long reply = strtol(value, NULL, 0); 783 | if (reply <= 0) { 784 | cfg->http_reply = HTTP_FORBIDDEN; 785 | } else { 786 | cfg->http_reply = reply; 787 | } 788 | 789 | return NULL; 790 | } 791 | 792 | /* END Configuration Functions */ 793 | 794 | static const command_rec access_cmds[] = 795 | { 796 | AP_INIT_TAKE1("DOSEnabled", get_enabled, NULL, RSRC_CONF, 797 | "Enable mod_evasive (either globally or in the virtualhost where it is specified)"), 798 | 799 | AP_INIT_TAKE1("DOSHashTableSize", get_hash_tbl_size, NULL, RSRC_CONF, 800 | "Set size of hash table"), 801 | 802 | AP_INIT_TAKE1("DOSPageCount", get_page_count, NULL, RSRC_CONF, 803 | "Set maximum page hit count per interval"), 804 | 805 | AP_INIT_TAKE1("DOSSiteCount", get_site_count, NULL, RSRC_CONF, 806 | "Set maximum site hit count per interval"), 807 | 808 | AP_INIT_TAKE1("DOSPageInterval", get_page_interval, NULL, RSRC_CONF, 809 | "Set page interval"), 810 | 811 | AP_INIT_TAKE1("DOSSiteInterval", get_site_interval, NULL, RSRC_CONF, 812 | "Set site interval"), 813 | 814 | AP_INIT_TAKE1("DOSBlockingPeriod", get_blocking_period, NULL, RSRC_CONF, 815 | "Set blocking period for detected DoS IPs"), 816 | 817 | AP_INIT_TAKE1("DOSLogDir", get_log_dir, NULL, RSRC_CONF, 818 | "Set log dir"), 819 | 820 | /* This should be possible in Windows, consider it Experimental */ 821 | AP_INIT_TAKE1("DOSSystemCommand", get_system_command, NULL, RSRC_CONF, 822 | "Set system command on DoS"), 823 | 824 | AP_INIT_ITERATE("DOSWhitelist", whitelist, NULL, RSRC_CONF, 825 | "IP-addresses wildcards to whitelist"), 826 | 827 | AP_INIT_ITERATE("DOSWhitelistUri", whitelist_uri, NULL, RSRC_CONF, 828 | "Files/paths regexes to whitelist"), 829 | 830 | AP_INIT_ITERATE("DOSHTTPStatus", get_http_reply, NULL, RSRC_CONF, 831 | "HTTP reply code"), 832 | 833 | { NULL } 834 | }; 835 | 836 | static void register_hooks(apr_pool_t *p) { 837 | ap_hook_access_checker(access_checker, NULL, NULL, APR_HOOK_MIDDLE); 838 | apr_pool_cleanup_register(p, NULL, apr_pool_cleanup_null, destroy_config); 839 | }; 840 | 841 | module AP_MODULE_DECLARE_DATA evasive_module = 842 | { 843 | STANDARD20_MODULE_STUFF, 844 | create_dir_conf, 845 | NULL, 846 | NULL, 847 | NULL, 848 | access_cmds, 849 | register_hooks 850 | }; 851 | 852 | -------------------------------------------------------------------------------- /mod_evasiveNSAPI.c: -------------------------------------------------------------------------------- 1 | /* 2 | mod_dosevasive/1.8 for NSAPI 3 | 4 | Copyright 2002 by Jonathan A. Zdziarski. All rights reserved. 5 | 6 | LICENSE 7 | ------- 8 | 9 | This distribution may be freely distributed in its original form. 10 | License is granted to make modifications to the source for internal, 11 | private use only, provided you retain this notice, disclaimers, author's 12 | copyright, and credits. 13 | 14 | 15 | DISCLAIMER 16 | ---------- 17 | 18 | THIS SOFTWARE IS PROVIDE "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, 19 | INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 20 | AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO WAY SHALL THE 21 | AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, 22 | OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 23 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 24 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 25 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 27 | OF THE POSSIBILITY OF SUCH DAMAGE. 28 | 29 | */ 30 | 31 | /* This is a port to NSAPI from mod_dosevasive/1.8 for Apache 2.0 32 | 2003-10-29 Reine Persson 33 | */ 34 | 35 | #include 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | 47 | #include 48 | 49 | 50 | /* BEGIN DoS Evasive Maneuvers Definitions */ 51 | 52 | #define DEFAULT_LOG_DIR "/tmp" 53 | #define MAILER "/bin/mail %s" 54 | #define LOG( A, ... ) { openlog("mod_dosevasive", LOG_PID, LOG_DAEMON); syslog( A, __VA_ARGS__ ); closelog(); } 55 | 56 | #define DEFAULT_HASH_TBL_SIZE 3079ul // Default hash table size 57 | #define DEFAULT_PAGE_COUNT 2 // Default maximum page hit count per interval 58 | #define DEFAULT_SITE_COUNT 50 // Default maximum site hit count per interval 59 | #define DEFAULT_PAGE_INTERVAL 1 // Default 1 Second page interval 60 | #define DEFAULT_SITE_INTERVAL 1 // Default 1 Second site interval 61 | #define DEFAULT_BLOCKING_PERIOD 10 // Default for Detected IPs; blocked for 10 seconds 62 | 63 | /* END DoS Evasive Maneuvers Definitions */ 64 | 65 | static CRITICAL mod_dosevasive_crit; 66 | 67 | /* BEGIN NTT (Named Timestamp Tree) Headers */ 68 | 69 | enum { ntt_num_primes = 28 }; 70 | 71 | /* ntt root tree */ 72 | struct ntt { 73 | long size; 74 | long items; 75 | struct ntt_node **tbl; 76 | }; 77 | 78 | /* ntt node (entry in the ntt root tree) */ 79 | struct ntt_node { 80 | char *key; 81 | time_t timestamp; 82 | long count; 83 | struct ntt_node *next; 84 | }; 85 | 86 | /* ntt cursor */ 87 | struct ntt_c { 88 | long iter_index; 89 | struct ntt_node *iter_next; 90 | }; 91 | 92 | struct ntt *ntt_create(long size); 93 | int ntt_destroy(struct ntt *ntt); 94 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key); 95 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp); 96 | int ntt_delete(struct ntt *ntt, const char *key); 97 | long ntt_hashcode(struct ntt *ntt, const char *key); 98 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c); 99 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c); 100 | 101 | /* END NTT (Named Timestamp Tree) Headers */ 102 | 103 | 104 | /* BEGIN DoS Evasive Maneuvers Globals */ 105 | 106 | struct ntt *hit_list; // Our dynamic hash table 107 | 108 | static unsigned long hash_table_size = DEFAULT_HASH_TBL_SIZE; 109 | static int page_count = DEFAULT_PAGE_COUNT; 110 | static int page_interval = DEFAULT_PAGE_INTERVAL; 111 | static int site_count = DEFAULT_SITE_COUNT; 112 | static int site_interval = DEFAULT_SITE_INTERVAL; 113 | static int blocking_period = DEFAULT_BLOCKING_PERIOD; 114 | static char *log_dir = NULL; 115 | static char *email_notify = NULL; 116 | static char *system_command = NULL; 117 | 118 | static const char * whitelist(const char *ip); 119 | int is_whitelisted(const char *ip); 120 | static int destroy_hit_list(void *not_used); 121 | 122 | /* END DoS Evasive Maneuvers Globals */ 123 | 124 | static char * 125 | itemize(char *str,char delim) 126 | { 127 | static char *nextitem = NULL; 128 | char *result; 129 | 130 | if(str) 131 | nextitem=str; 132 | if(!nextitem) 133 | return(NULL); 134 | result=nextitem; 135 | while(*nextitem && *nextitem!=delim) 136 | ++nextitem; 137 | if(*nextitem) 138 | *nextitem++='\0'; 139 | else 140 | nextitem=NULL; 141 | return(result); 142 | } 143 | 144 | 145 | NSAPI_PUBLIC int 146 | mod_dosevasive_init(pblock *pb, Session *sn, Request *rq) 147 | { 148 | char *ip,*stmp,*white_list=NULL; 149 | int itmp; 150 | 151 | mod_dosevasive_crit = crit_init(); 152 | if ((itmp=atoi(pblock_findval("DOSHashTableSize", pb))) != 0 ) 153 | hash_table_size=itmp; 154 | if ((itmp=atoi(pblock_findval("DOSPageCount", pb))) != 0 ) 155 | page_count=itmp; 156 | if ((itmp=atoi(pblock_findval("DOSSiteCount", pb))) != 0 ) 157 | site_count=itmp; 158 | if ((itmp=atoi(pblock_findval("DOSPageInterval", pb))) != 0 ) 159 | page_interval=itmp; 160 | if ((itmp=atoi(pblock_findval("DOSSiteInterval", pb))) != 0 ) 161 | site_interval=itmp; 162 | if ((itmp=atoi(pblock_findval("DOSBlockingPeriod", pb))) != 0 ) 163 | blocking_period=itmp; 164 | if ((stmp=pblock_findval("DOSLogDir", pb)) != NULL ) 165 | log_dir=stmp; 166 | if ((stmp=pblock_findval("DOSEmailNotify", pb)) != NULL ) 167 | email_notify=stmp; 168 | if ((stmp=pblock_findval("DOSSystemCommand", pb)) != NULL ) 169 | system_command=stmp; 170 | 171 | white_list=pblock_findval("DOSWhitelist", pb); 172 | 173 | hit_list = ntt_create(hash_table_size); 174 | 175 | if ( white_list != NULL ) { 176 | ip=itemize(white_list,','); 177 | while( ip != NULL ) { 178 | whitelist(ip); 179 | ip=itemize(NULL,','); 180 | } 181 | } 182 | return REQ_PROCEED; 183 | } 184 | 185 | NSAPI_PUBLIC int 186 | mod_dosevasive_check(pblock *pb, Session *sn, Request *rq) 187 | { 188 | int ret = REQ_PROCEED; 189 | 190 | /* BEGIN DoS Evasive Maneuvers Code */ 191 | 192 | if (pblock_findval("NS_original_uri",rq->vars) == NULL && pblock_findval("referer",rq->headers) == NULL && hit_list != NULL) { 193 | char hash_key[2048]; 194 | struct ntt_node *n; 195 | time_t t = time(NULL); 196 | 197 | /* Check whitelist */ 198 | if (is_whitelisted(pblock_findval("ip",sn->client))) 199 | return REQ_PROCEED; 200 | 201 | /* First see if the IP itself is on "hold" */ 202 | n = ntt_find(hit_list, pblock_findval("ip",sn->client)); 203 | 204 | if (n != NULL && t-n->timestamptimestamp = time(NULL); 209 | 210 | /* Not on hold, check hit stats */ 211 | } else { 212 | 213 | /* Has URI been hit too much? */ 214 | snprintf(hash_key, 2048, "%s_%s", pblock_findval("ip",sn->client), pblock_findval("uri",rq->reqpb)); 215 | n = ntt_find(hit_list, hash_key); 216 | if (n != NULL) { 217 | 218 | /* If URI is being hit too much, add to "hold" list and 403 */ 219 | if (t-n->timestampcount>=page_count) { 220 | ret = REQ_ABORTED; 221 | ntt_insert(hit_list, pblock_findval("ip",sn->client), time(NULL)); 222 | } else { 223 | 224 | /* Reset our hit count list as necessary */ 225 | if (t-n->timestamp>=page_interval) { 226 | n->count=0; 227 | } 228 | } 229 | n->timestamp = t; 230 | n->count++; 231 | } else { 232 | 233 | ntt_insert(hit_list, hash_key, t); 234 | } 235 | 236 | /* Has site been hit too much? */ 237 | snprintf(hash_key, 2048, "%s_SITE", pblock_findval("ip",sn->client)); 238 | n = ntt_find(hit_list, hash_key); 239 | if (n != NULL) { 240 | 241 | /* If site is being hit too much, add to "hold" list and 403 */ 242 | if (t-n->timestampcount>=site_count) { 243 | ret = REQ_ABORTED; 244 | ntt_insert(hit_list, pblock_findval("ip",sn->client), time(NULL)); 245 | } else { 246 | 247 | /* Reset our hit count list as necessary */ 248 | if (t-n->timestamp>=site_interval) { 249 | n->count=0; 250 | } 251 | } 252 | n->timestamp = t; 253 | n->count++; 254 | } else { 255 | ntt_insert(hit_list, hash_key, t); 256 | } 257 | } 258 | 259 | /* Perform email notification and system functions */ 260 | if (ret == REQ_ABORTED) { 261 | char filename[1024]; 262 | struct stat s; 263 | FILE *file; 264 | 265 | snprintf(filename, sizeof(filename), "%s/dos-%s", log_dir != NULL ? log_dir : DEFAULT_LOG_DIR, pblock_findval("ip",sn->client)); 266 | if (stat(filename, &s)) { 267 | file = fopen(filename, "w"); 268 | if (file != NULL) { 269 | fprintf(file, "%ld\n", getpid()); 270 | fclose(file); 271 | 272 | LOG(LOG_ALERT, "Blacklisting address %s: possible DoS attack.",pblock_findval("ip",sn->client)); 273 | if (email_notify != NULL) { 274 | snprintf(filename, sizeof(filename), MAILER, email_notify); 275 | file = popen(filename, "w"); 276 | if (file != NULL) { 277 | fprintf(file, "To: %s\n", email_notify); 278 | fprintf(file, "Subject: HTTP BLACKLIST %s\n\n", pblock_findval("ip",sn->client)); 279 | fprintf(file, "mod_dosevasive HTTP Blacklisted %s\n", pblock_findval("ip",sn->client)); 280 | pclose(file); 281 | } else { 282 | LOG(LOG_ALERT, "Couldn't open logfile %s: %s",filename, strerror(errno)); 283 | } 284 | } 285 | 286 | if (system_command != NULL) { 287 | snprintf(filename, sizeof(filename), system_command, pblock_findval("ip",sn->client)); 288 | system(filename); 289 | } 290 | 291 | } 292 | 293 | } /* if (temp file does not exist) */ 294 | 295 | } /* if (ret == REQ_ABORTED) */ 296 | 297 | } /* if (vars->NS_Original_uri == NULL && headers->referer == NULL && hit_list != NULL) */ 298 | 299 | /* END DoS Evasive Maneuvers Code */ 300 | 301 | if (ret == REQ_ABORTED ) { 302 | log_error(LOG_SECURITY,"mod_dosevasive_check",sn,rq,"client denied by server configuration: %s",pblock_findval("uri",rq->reqpb)); 303 | protocol_status(sn, rq, PROTOCOL_FORBIDDEN, NULL); 304 | } 305 | return ret; 306 | } 307 | 308 | 309 | static const char *whitelist(const char *ip) 310 | { 311 | char entry[128]; 312 | snprintf(entry, sizeof(entry), "WHITELIST_%s", ip); 313 | ntt_insert(hit_list, entry, time(NULL)); 314 | 315 | return NULL; 316 | } 317 | 318 | 319 | int is_whitelisted(const char *ip) { 320 | char hashkey[128]; 321 | char octet[4][4]; 322 | char *dip; 323 | char *oct; 324 | int i = 0; 325 | 326 | memset(octet, 0, 16); 327 | dip = strdup(ip); 328 | if (dip == NULL) 329 | return 0; 330 | 331 | oct = strtok(dip, "."); 332 | while(oct != NULL && i<4) { 333 | if (strlen(oct)<=3) 334 | strcpy(octet[i], oct); 335 | i++; 336 | oct = strtok(NULL, "."); 337 | } 338 | free(dip); 339 | 340 | /* Exact Match */ 341 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s", ip); 342 | if (ntt_find(hit_list, hashkey)!=NULL) 343 | return 1; 344 | 345 | /* IPv4 Wildcards */ 346 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.*.*.*", octet[0]); 347 | if (ntt_find(hit_list, hashkey)!=NULL) 348 | return 1; 349 | 350 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.*.*", octet[0], octet[1]); 351 | if (ntt_find(hit_list, hashkey)!=NULL) 352 | return 1; 353 | 354 | snprintf(hashkey, sizeof(hashkey), "WHITELIST_%s.%s.%s.*", octet[0], octet[1], octet[2]); 355 | if (ntt_find(hit_list, hashkey)!=NULL) 356 | return 1; 357 | 358 | /* No match */ 359 | return 0; 360 | } 361 | 362 | static int destroy_hit_list(void *not_used) { 363 | ntt_destroy(hit_list); 364 | free(log_dir); 365 | free(email_notify); 366 | free(system_command); 367 | return 0; 368 | } 369 | 370 | 371 | /* BEGIN NTT (Named Timestamp Tree) Functions */ 372 | 373 | static unsigned long ntt_prime_list[ntt_num_primes] = 374 | { 375 | 53ul, 97ul, 193ul, 389ul, 769ul, 376 | 1543ul, 3079ul, 6151ul, 12289ul, 24593ul, 377 | 49157ul, 98317ul, 196613ul, 393241ul, 786433ul, 378 | 1572869ul, 3145739ul, 6291469ul, 12582917ul, 25165843ul, 379 | 50331653ul, 100663319ul, 201326611ul, 402653189ul, 805306457ul, 380 | 1610612741ul, 3221225473ul, 4294967291ul 381 | }; 382 | 383 | 384 | /* Find the numeric position in the hash table based on key and modulus */ 385 | 386 | long ntt_hashcode(struct ntt *ntt, const char *key) { 387 | unsigned long val = 0; 388 | for (; *key; ++key) val = 5 * val + *key; 389 | return(val % ntt->size); 390 | } 391 | 392 | /* Creates a single node in the tree */ 393 | 394 | struct ntt_node *ntt_node_create(const char *key) { 395 | char *node_key; 396 | struct ntt_node* node; 397 | 398 | node = (struct ntt_node *) malloc(sizeof(struct ntt_node)); 399 | if (node == NULL) { 400 | return NULL; 401 | } 402 | if ((node_key = strdup(key)) == NULL) { 403 | free(node); 404 | return NULL; 405 | } 406 | node->key = node_key; 407 | node->timestamp = time(NULL); 408 | node->next = NULL; 409 | return(node); 410 | } 411 | 412 | /* Tree initializer */ 413 | 414 | struct ntt *ntt_create(long size) { 415 | long i = 0; 416 | struct ntt *ntt = (struct ntt *) malloc(sizeof(struct ntt)); 417 | 418 | if (ntt == NULL) 419 | return NULL; 420 | while (ntt_prime_list[i] < size) { i++; } 421 | ntt->size = ntt_prime_list[i]; 422 | ntt->items = 0; 423 | ntt->tbl = (struct ntt_node **) calloc(ntt->size, sizeof(struct ntt_node *)); 424 | if (ntt->tbl == NULL) { 425 | free(ntt); 426 | return NULL; 427 | } 428 | return(ntt); 429 | } 430 | 431 | /* Find an object in the tree */ 432 | 433 | struct ntt_node *ntt_find(struct ntt *ntt, const char *key) { 434 | long hash_code; 435 | struct ntt_node *node; 436 | 437 | if (ntt == NULL) return NULL; 438 | 439 | hash_code = ntt_hashcode(ntt, key); 440 | node = ntt->tbl[hash_code]; 441 | 442 | while (node) { 443 | if (!strcmp(key, node->key)) { 444 | return(node); 445 | } 446 | node = node->next; 447 | } 448 | return((struct ntt_node *)NULL); 449 | } 450 | 451 | /* Insert a node into the tree */ 452 | 453 | struct ntt_node *ntt_insert(struct ntt *ntt, const char *key, time_t timestamp) { 454 | long hash_code; 455 | struct ntt_node *parent; 456 | struct ntt_node *node; 457 | struct ntt_node *new_node = NULL; 458 | 459 | if (ntt == NULL) return NULL; 460 | 461 | hash_code = ntt_hashcode(ntt, key); 462 | parent = NULL; 463 | node = ntt->tbl[hash_code]; 464 | 465 | crit_enter(mod_dosevasive_crit); /*Lock*/ 466 | 467 | while (node != NULL) { 468 | if (strcmp(key, node->key) == 0) { 469 | new_node = node; 470 | node = NULL; 471 | } 472 | 473 | if (new_node == NULL) { 474 | parent = node; 475 | node = node->next; 476 | } 477 | } 478 | 479 | if (new_node != NULL) { 480 | new_node->timestamp = timestamp; 481 | new_node->count = 0; 482 | crit_exit(mod_dosevasive_crit); /*Unlock*/ 483 | return new_node; 484 | } 485 | 486 | /* Create a new node */ 487 | new_node = ntt_node_create(key); 488 | new_node->timestamp = timestamp; 489 | new_node->timestamp = 0; 490 | 491 | ntt->items++; 492 | 493 | /* Insert */ 494 | if (parent) { /* Existing parent */ 495 | parent->next = new_node; 496 | crit_exit(mod_dosevasive_crit); /*Unlock*/ 497 | return new_node; /* Return the locked node */ 498 | } 499 | 500 | /* No existing parent; add directly to hash table */ 501 | ntt->tbl[hash_code] = new_node; 502 | crit_exit(mod_dosevasive_crit); /*Unlock*/ 503 | return new_node; 504 | } 505 | 506 | /* Tree destructor */ 507 | 508 | int ntt_destroy(struct ntt *ntt) { 509 | struct ntt_node *node, *next; 510 | struct ntt_c c; 511 | 512 | if (ntt == NULL) return -1; 513 | 514 | node = c_ntt_first(ntt, &c); 515 | while(node != NULL) { 516 | next = c_ntt_next(ntt, &c); 517 | ntt_delete(ntt, node->key); 518 | node = next; 519 | } 520 | 521 | free(ntt->tbl); 522 | free(ntt); 523 | ntt = (struct ntt *) NULL; 524 | 525 | return 0; 526 | } 527 | 528 | /* Delete a single node in the tree */ 529 | 530 | int ntt_delete(struct ntt *ntt, const char *key) { 531 | long hash_code; 532 | struct ntt_node *parent = NULL; 533 | struct ntt_node *node; 534 | struct ntt_node *del_node = NULL; 535 | 536 | if (ntt == NULL) return -1; 537 | 538 | hash_code = ntt_hashcode(ntt, key); 539 | node = ntt->tbl[hash_code]; 540 | 541 | while (node != NULL) { 542 | if (strcmp(key, node->key) == 0) { 543 | del_node = node; 544 | node = NULL; 545 | } 546 | 547 | if (del_node == NULL) { 548 | parent = node; 549 | node = node->next; 550 | } 551 | } 552 | 553 | if (del_node != NULL) { 554 | 555 | if (parent) { 556 | parent->next = del_node->next; 557 | } else { 558 | ntt->tbl[hash_code] = del_node->next; 559 | } 560 | 561 | free(del_node->key); 562 | free(del_node); 563 | ntt->items--; 564 | 565 | return 0; 566 | } 567 | 568 | return -5; 569 | } 570 | 571 | /* Point cursor to first item in tree */ 572 | 573 | struct ntt_node *c_ntt_first(struct ntt *ntt, struct ntt_c *c) { 574 | 575 | c->iter_index = 0; 576 | c->iter_next = (struct ntt_node *)NULL; 577 | return(c_ntt_next(ntt, c)); 578 | } 579 | 580 | /* Point cursor to next iteration in tree */ 581 | 582 | struct ntt_node *c_ntt_next(struct ntt *ntt, struct ntt_c *c) { 583 | long index; 584 | struct ntt_node *node = c->iter_next; 585 | 586 | if (ntt == NULL) return NULL; 587 | 588 | if (node) { 589 | if (node != NULL) { 590 | c->iter_next = node->next; 591 | return (node); 592 | } 593 | } 594 | 595 | if (! node) { 596 | while (c->iter_index < ntt->size) { 597 | index = c->iter_index++; 598 | 599 | if (ntt->tbl[index]) { 600 | c->iter_next = ntt->tbl[index]->next; 601 | return(ntt->tbl[index]); 602 | } 603 | } 604 | } 605 | return((struct ntt_node *)NULL); 606 | } 607 | 608 | /* END NTT (Named Pointer Tree) Functions */ 609 | -------------------------------------------------------------------------------- /test/00_regular_config/etc/mod_evasive.conf: -------------------------------------------------------------------------------- 1 | # vim:ts=4 2 | 3 | DOSEnabled true 4 | DOSHashTableSize 3079 5 | DOSPageCount 2 6 | DOSSiteCount 50 7 | DOSPageInterval 1 8 | DOSSiteInterval 1 9 | DOSBlockingPeriod 10 10 | # DOSEmailNotify you@yourdomain.com 11 | # DOSSystemCommand "su - someuser -c '/sbin/... %s ...'" 12 | # DOSLogDir "/var/lock/mod_evasive" 13 | # DOSWhitelist 127.0.0.1 14 | DOSWhitelistUri white.* 15 | # DOSHTTPStatus 429 16 | 17 | -------------------------------------------------------------------------------- /test/00_regular_config/etc/sites.conf: -------------------------------------------------------------------------------- 1 | # vim:ts=4 2 | 3 | Options Indexes FollowSymLinks 4 | AllowOverride None 5 | Require all granted 6 | 7 | 8 | 9 | ServerName a.site 10 | 11 | DocumentRoot /opt/jvdmr/apache2/mod_evasive/www 12 | 13 | DOSEnabled true 14 | DOSWhitelistUri white.*uri 15 | 16 | 17 | 18 | ServerName b.site 19 | 20 | DocumentRoot /opt/jvdmr/apache2/mod_evasive/www 21 | 22 | DOSEnabled true 23 | DOSSiteCount 10 24 | DOSPageCount 10 25 | 26 | -------------------------------------------------------------------------------- /test/00_regular_config/test.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | # test.pl: small script to test mod_evasive's effectiveness 4 | # - requires https virtualhosts a.site and b.site to be setup, each with their own mod_evasive config 5 | 6 | #use IO::Socket; 7 | use IO::Socket::SSL; 8 | use strict; 9 | 10 | sub request { 11 | my($address,$uri,$i) = @_; 12 | my($response); 13 | my($SOCKET) = new IO::Socket::INET( Proto => "tcp", 14 | PeerAddr=> "127.0.0.1:1980"); 15 | # my($SOCKET) = new IO::Socket::SSL( Proto => "tcp", 16 | # PeerAddr=> "127.0.0.1:443"); 17 | if (! defined $SOCKET) { die $!; } 18 | print $SOCKET "GET $uri?$i HTTP/1.1\r\n"; 19 | print $SOCKET "Host: $address\r\n\r\n"; 20 | $response = <$SOCKET>; 21 | chomp $response; 22 | print "$i - $address: $response\n"; 23 | close($SOCKET); 24 | } 25 | 26 | for(0..900) { 27 | request "a.site", "/j_spring_security_check", $_; 28 | } 29 | for(0..50) { 30 | request "b.site", "/", $_; 31 | } 32 | for(0..100) { 33 | request "a.site", "/whitelisted-uri", $_; 34 | } 35 | print "done.\n" 36 | -------------------------------------------------------------------------------- /test/00_regular_config/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 4 | ${DIR}/test.pl 5 | -------------------------------------------------------------------------------- /test/00_regular_config/www/j_spring_security_check: -------------------------------------------------------------------------------- 1 | dummy test file 2 | -------------------------------------------------------------------------------- /test/00_regular_config/www/whitelisted-uri: -------------------------------------------------------------------------------- 1 | foo 2 | -------------------------------------------------------------------------------- /test/01_no_config/etc/mod_evasive.conf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jvdmr/mod_evasive/c2a6b8cd7610cb1d9995a5d40285b82b48a7407e/test/01_no_config/etc/mod_evasive.conf -------------------------------------------------------------------------------- /test/01_no_config/etc/sites.conf: -------------------------------------------------------------------------------- 1 | # vim:ts=4 2 | 3 | Options Indexes FollowSymLinks 4 | AllowOverride None 5 | Require all granted 6 | 7 | 8 | 9 | ServerName a.site 10 | 11 | DocumentRoot /opt/jvdmr/apache2/mod_evasive/www 12 | 13 | 14 | 15 | ServerName b.site 16 | 17 | DocumentRoot /opt/jvdmr/apache2/mod_evasive/www 18 | 19 | -------------------------------------------------------------------------------- /test/01_no_config/test.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | # test.pl: small script to test mod_evasive's effectiveness 4 | # - requires https virtualhosts a.site and b.site to be setup, each with their own mod_evasive config 5 | 6 | #use IO::Socket; 7 | use IO::Socket::SSL; 8 | use strict; 9 | 10 | sub request { 11 | my($address,$uri,$i) = @_; 12 | my($response); 13 | my($SOCKET) = new IO::Socket::INET( Proto => "tcp", 14 | PeerAddr=> "127.0.0.1:1980"); 15 | if (! defined $SOCKET) { die $!; } 16 | print $SOCKET "GET $uri?$i HTTP/1.1\r\n"; 17 | print $SOCKET "Host: $address\r\n\r\n"; 18 | $response = <$SOCKET>; 19 | chomp $response; 20 | print "$i - $address: $response\n"; 21 | close($SOCKET); 22 | } 23 | 24 | for(0..900) { 25 | request "a.site", "/j_spring_security_check", $_; 26 | } 27 | print "done.\n" 28 | -------------------------------------------------------------------------------- /test/01_no_config/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 4 | ${DIR}/test.pl 5 | -------------------------------------------------------------------------------- /test/01_no_config/www/j_spring_security_check: -------------------------------------------------------------------------------- 1 | dummy test file 2 | -------------------------------------------------------------------------------- /test/01_no_config/www/whitelisted-uri: -------------------------------------------------------------------------------- 1 | foo 2 | -------------------------------------------------------------------------------- /test/02_reproduce_segfault/etc/mod_evasive.conf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jvdmr/mod_evasive/c2a6b8cd7610cb1d9995a5d40285b82b48a7407e/test/02_reproduce_segfault/etc/mod_evasive.conf -------------------------------------------------------------------------------- /test/02_reproduce_segfault/etc/sites.conf: -------------------------------------------------------------------------------- 1 | # vim:ts=4 2 | 3 | Options Indexes FollowSymLinks 4 | AllowOverride None 5 | Require all granted 6 | 7 | 8 | 9 | ServerName a.site 10 | 11 | DocumentRoot /opt/jvdmr/apache2/mod_evasive/www 12 | 13 | 14 | 15 | ServerName b.site 16 | 17 | DocumentRoot /opt/jvdmr/apache2/mod_evasive/www 18 | 19 | -------------------------------------------------------------------------------- /test/02_reproduce_segfault/test.pl: -------------------------------------------------------------------------------- 1 | #!/usr/bin/perl 2 | 3 | # test.pl: small script to test mod_evasive's effectiveness 4 | # - requires https virtualhosts a.site and b.site to be setup, each with their own mod_evasive config 5 | 6 | #use IO::Socket; 7 | use IO::Socket::SSL; 8 | use strict; 9 | 10 | sub request { 11 | my($address,$uri,$i) = @_; 12 | my($response); 13 | my($SOCKET) = new IO::Socket::INET( Proto => "tcp", 14 | PeerAddr=> "127.0.0.1:1980"); 15 | if (! defined $SOCKET) { die $!; } 16 | print $SOCKET "GET $uri?$i HTTP/1.1\r\n"; 17 | print $SOCKET "Host: $address\r\n\r\n"; 18 | $response = <$SOCKET>; 19 | chomp $response; 20 | print "$i - $address: $response\n"; 21 | close($SOCKET); 22 | } 23 | 24 | for(0..900) { 25 | request "a.site", "/j_spring_security_check", $_; 26 | } 27 | print "done.\n" 28 | -------------------------------------------------------------------------------- /test/02_reproduce_segfault/test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 4 | ${DIR}/test.pl 5 | docker exec -it mod_evasive_test service apache2 graceful 6 | sleep 5 7 | ${DIR}/test.pl 8 | -------------------------------------------------------------------------------- /test/02_reproduce_segfault/www/j_spring_security_check: -------------------------------------------------------------------------------- 1 | dummy test file 2 | -------------------------------------------------------------------------------- /test/02_reproduce_segfault/www/whitelisted-uri: -------------------------------------------------------------------------------- 1 | foo 2 | --------------------------------------------------------------------------------