PHP Spam Injection First Aid with Apache ModSecurity
From time to time we work with clients who would like to upgrade their web sites. Often their site is composed of various one-off applications -- typically PHP-based -- that someone built for them. More often than not, these applications were not developed with security in mind.
Our first reaction is to pull the plug, analyze, and rebuild a secure and scalable solution. But pulling the plug is usually not an option. If a company relies on an application for leads or sales, they probably can't afford to shut it down for any length of time. Under these circumstances, triage is usually the best one can hope for.
Fortunately, there are a few things one can do to stem the bleeding. One of the more common problems with PHP-based applications is that they can allow the injection of malicious content, such as SQL or email spam. In some cases we find that over 95% of a client's ISP traffic is coming from spam injection. The solution? Grab an industrial size helping of Apache mod_security.
ModSecurityTM is an open source intrusion detection and prevention engine for web applications (or a web application firewall). Operating as an Apache Web server module or standalone, the purpose of ModSecurity is to increase web application security, protecting web applications from known and unknown attacks.
Essentially, it inspects web traffic passing through the web server for suspicious content as well as attempts to trigger buffer overflows, etc. When it finds such content, it can stop the traffic and/or log the incident.
To put mod_security to work for you, first, download and unpack the tarball, build and install the DSO, and update Apache’s httpd.conf file.
cd /usr/local; tar xzf /root/modsecurity-apache-1.9.4.tar.gz
cd /usr/local/modsecurity-apache-1.9.4/apache2
/usr/local/apache2/bin/apxs -cia mod_security.c
cd /usr/local/modsecurity-apache-1.9.4/apache2
/usr/local/apache2/bin/apxs -cia mod_security.c
Paste the ModSecurity minimal recommended filtering rules into your httpd.conf file. Here are the first few lines from from the online manual's Appendix A: Recommended Configuration:
# Turn ModSecurity On
SecFilterEngine On
# Reject requests with status 403
SecFilterDefaultAction "deny,log,status:403"
# Some sane defaults
SecFilterScanPOST On
SecFilterCheckURLEncoding On
SecFilterCheckUnicodeEncoding Off
If you'd just like to see if someone is trying to exploit your site, you can set up ModSecurity to simply audit your traffic. The lines
# Log rule violations, but allow the requests
SecFilterDefaultAction "log,pass"
will do that for you. However, please note that if you want to merely log rule violations without denying the traffic, you must not include any implicit validations (URL encoding validation, Unicode encoding validation, cookie format validation, and byte range restrictions) in your rules.
When you are satisfied with your rules, you can deny the traffic by changing the default action to this:
# Deny requests and log with status 403
SecFilterDefaultAction "deny,log,status:403"
Once you've got a bunch of traffic in your audit log, you can grep through it to see if you've got visitors with bad intentions:
grep -i 'to|bcc|cc' audit_log | less
or
grep -i 'to|bcc|cc' audit_log | wc -l
or
grep -i 'to|bcc|cc' audit_log | wc -l
You may find lots of suspicious lines. In fact, you may find that some spammers are including portions of books, stories, or other nonsense, presumably to get past the final recipients' Bayesian spam filters.
To block a common PHP mail injection exploit, add a rule like this to your httpd.conf file in the ModSecurity section:
# necessary to stop spammers doing mail injection into PHP mail forms!!!
SecFilterSelective ARGS_VALUES "\n[[:space:]]*(to|bcc|cc)[[:space:]]*:.*@"
SecFilterSelective ARGS_VALUES "\n[[:space:]]*(to|bcc|cc)[[:space:]]*:.*@"
The ModSecurity site also conveniently includes a package of rules, including PHP-related rules, grouped by function. Note that there are “SQL Injection Attack” rules in the “general” conf file. You can include the rule groups you want by using an "Include" directive in the ModSecurity section of your httpd.conf file; i.e. “Include conf/modsecurity-php.conf”.
These rules are a good place to start, as are the rules from gotroot.com. You may need to tweak these a little bit, and be selective in which rulesets you apply. For example, often aggregating IP addresses such as AOL proxies are blocked due to the blacklist rules, which may not be what you want.
This is only a brief introduction, but I hope you will try ModSecurity for yourself, and discover how powerful it can be.
Comments: 1 so far
Leave a comment
About Pathfinder
Follow the Blog
-
Get a monthly update on best practices for delivering successful software.
Subscribe via email
Subscribe via RSS
Categories
Topics
.NET
.NET Browser Control
2d physics
3d
3D GPS
3D physics
37signals
Acceptance Tests
Accessibility
ActionMailer
actionscript
activerecord
acts_as_ferret
Add new tag
Adium
ADO.NET Entity Framework
Adobe
Adobe AIR
adobe flex
Adobe Illustrator
Advertising
aggregation
agile
Agile Development
agile thinking
AIR
Ajax
Ajax Applications
Ajax Bookmarking
Ajax Components
Ajax Development
Ajax Examples
Ajax Experience
Ajax Frameworks
Ajax history management
Ajax Intervention
Ajax libraries
Ajax library
AJAX Obfuscation
Ajax Performance
Ajax Products
Ajax toolkit
Ajax Tools
Ajax Widgets
A list apart
Amazon
Amazon CDN
Amazon Web Services
amf
Analysis
Android
animation
Announcement
Announcements
antennae
Antipatterns
Apache
Apollo
apple
Application Architecture
Application Development
architecture
AS3
ask a UI guy
ASP.NET
ASP.NET
asterisk
Asynchronous Processing
authorization
awards
axiis
Azure
Back Button
backups
bandwidth
bandwidth profiling
Beans
beer
Benchmarking
Best Practices
BitmapData.draw
BJAX
blackberry
Blaze Advisor
blender
blog
blogging
book review
Books
braindump
browser
Browsers
Bugs
Business
Business Reasons for Ajax
Business Rules
C#
caching
campfire
Canvas
capistrano
Case Studies
CFO
Charles
checklist
chess
Chesspresso
Chicago
chicagoruby
chirb windycityrails
CIO
Cloud Computing
CloudFront
CMS
COBOL
Cocoa
code
code art
Code Generation
code generator
Color
COMET
Conference
Confluence
Consistency
Content Management
continuous integration
converget appliances
core animation
CRM
cruise
CruiseControl
CSS
cucumber
Custom Application Development
Custom Flex Component
Data Mapper
data visualization
Degrafa
deployment
deprec
Design
Design Patterns
design thinking
Desktop
Desktop RIA
Developer's Notebook
development
DHTML
Diagnose
Dojo
Domain Knowledge
don norman
Drools
drupal
dynamic languages
ease of use
EC2
Echo2
Echo3
Editorial
Entrepreneur
erb
ERP
Estimating
estimation
Ethnographic Research
events
everyblock
Excel
externalinterface
Ext JS
Extreme Programming
eye tracking
Facebook
factory
Feedback Loop
ferret
FileReference
Firebug
Firefox
Firefox Extensions
fixturereplacement
fixture replacement
fixtures
Flare
Flash
flash awards
Flash Platform
flash player
flash player 10
Flash Player optimization
Flash Remoting
Flex
Flex3
flex code generator
flex css
flexmock
Flex optimization
flex skins
flexunit
Flickr
Flock
Flow
Fluent
forms
Frameworks
FriendFeed
front end
front end development
fulltext search
functional
Games
Gauge Component
gem
getting things done
Git
github
gitignore
Golf
Google
Google Analytics
Google Analytics for Flash
Google Analytics for Flex
google android
Google calendar
google docs
Google Gadgets
Google Gears
google maps
GORM
government
g phone
Grails
Graphics
Greasemonkey
Groovy
GStreamer
GTD
Gwittir
GWT
h.264
haml
hardware
Healthcare
heuristic evaluation
Hibernate
hosting
HTML
Hudson
IBM
IDE
Ideation
IE
IE6
IE7
IE8
iGoogle
illustrator cs3
ILog
ILOG JRules
imacros
importing graphics to flex
Information Architecture
infrastructure
Innovation
Instructional Design
Interaction Design
interaction patterns design
Internship
Interview
iPhone
iPhone SDK
iPod
irb
iteration
IT Mill Toolkit
iTunes
jakob nielson
Java
javafx
Javascript
JavaScript frameworks
Javascript Libraries
JBoss Rules
Jess
Jetty
JIT
jmeter
Jobs
jQuery
JSF
JSON
JSP
JSR-94
JsUnit
laptop
Lazlo
Legacy Systems
lightweight
LinkedIn
LINQ
logging
Logical Model and Conceptual Model
Low Pro
Mac
Malware
mapping
Mash Note
Mashups
math
Meebo
metal
metaprogramming
MetaWidget
Methodology
Microformats
microsite
Microsoft
migrations
minimalism
Mobile
mobile platform
mocking
mock objects
modeling
mod_rails
monitoring
Mootools
mouse
mouse scroll
mouse wheel
Mozilla
Music
MVC
MySql
natural key
neal ford
NetNewsWire
networking
news
newspapers
nfjs
NHibernate
nokia
notebook
NSURLProtocol
obj-c
Object-Oriented
Objective-C
Object Relation Mapping (ORM)
ocmock
Office
OmniGraffle
online spreadsheets
OOAD
OOP
opengl
Open Screen
OpenSocial
Open Source
opensource
Opera
Oracle
ORM
osx
OS X
pagination
Pair Programming
palm
papervision3d
Pathfinder Development
Patterns
Peer Creation
Performance
Personas
PGN
PHP
Phusion Passenger
physics
physics engines
planning
plugin
plugins
portableapps
pragmatic
Predictions
preloader
primary key
process Web/Tech
Product Definition
Production Support
productive programer
productivity
product launch
Progressive Enhancement
project concept
project management
Project Website
Prototype
Prototyping
PureMVC
PV3D
pyro
QA
qooxdoo
Radiant CMS
rails
railscasts
Rails Environment Tests
railsrx
Really Simple History
Refactor
refactoring
References
regex
regular expressions
Requirements
Requirements
Alice Toth
Requirements Visualization
resesign
Restlet
RETE
Review
rfp
ria
Rich Interactions
rich internet applicaiton
rich internet applications
ROI
rspec
ruby
rubyamf
Ruby on Rails
Ruby on Rails testing role
S3
SaaS
Safari
San Francisco
Scalability
Scenarios
Scriptaculous
Scrum
SDLC
Search
Secretariat
Security
Selenium
SeleniumIDE
Semantic web
SEO
Server Side
shoulda
Silverlight
simplicity
skins
SOA
soapUI
Social Networking
software develoment
Software Development
Software Engineering
Software Processes
Songbird
SpiderMonkey
Sprajax
Spreadsheets
StageScaleMode
Standards
standish
starting projects
Startups
static typing
Stencils
STI
Story Telling
Structured Design
Struts
sun
surrogate key
Swing
tabs
tag
taglib
Tamarin
Tank Engine
Task Flows
tdd
teams
telephony
Tellurium
test::unit
Test Driven Development
Testing
tether
textmate
The Ajax Experience
throttling
Tilt Component
Tools
touch screen kiosk
TraceMonkey
Training
Trends
Tumblr
Tutorial
Tutorials
Twitter
ubuntu
UI
UIViewController
uml
unit testing
Unit Tests
unity3d
Usability
Usability Testing
user driven agile
User Experience
user experience design
user groups
user interface
User Interface Standards
User Research
UXD
value
Venture Capital
Video
Vision
visual analytics
visual design
visual documentation
Visualization
VLC
VML
Volta
waterfall
watij
watir
web
Web/Tech
Web 2.0
web app
Web Design
Web Development
web forms
web hosting
web infrastructure
Webkit
Weblogs
Web Services
WebSockets
Web Standards
WebTest
Widgets
will_paginate
Windows
windows mobile
WinForms
Wireframes
WordPress
workflow
work life balance
xcode
XML
XML Metadata
xp
XUL
Yahoo Map AS3 API
YUI
Zeigarnik
Zeigarnik Effect
ZendAMF
ZK
Archives
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- May 2007
- April 2007
- March 2007
- February 2007
- January 2007
- December 2006
- November 2006
- October 2006
- September 2006
- August 2006
- July 2006
- June 2006
- May 2006
- April 2006
- March 2006
Blogroll
Recent
- Elements of Testing Style
- Aesthetics and Web Design
- Asterisk-Java Testing with Groovy
- 3 Misuses of Code Comments
- Fluently NHibernate
- Digging a Hole and Covering it with Leaves — The Software Development Version
- The Importance of User Experience - Do You Understand It in Your Bones?
- Writing Your Own Protocol With NSURLProtocol
- What’s In Your Dock: iPhone edition
- Feature Fatigue

Seguridad adicional en servidores Apache con mod_security
He dado con un excelente artículo que nos explica someramente cómo detener en seco el spam procedente de inyección en formularios Web a través de mod_security, un módulo especialmente creado para Apache.
La idea es bien sencilla: mod_security es un fr…
Comment by Sergio Hernando, Monday, May 22, 2006 @ 9:32 am