Showing posts with label web application security. Show all posts
Showing posts with label web application security. Show all posts

Wednesday, April 01, 2015

toolsmith: Rapid Assessment of Web Resources (RAWR!)

In memory and honor of Leonard Nimoy (1931-2015): “Of all the souls I have encountered in my travels, his was the most... human.”

Prerequisites
Typically *nix, tested here on Ubuntu & Kali
Kali and Ubuntu recommended, virtual machine or physical

Overview

Confession, and it shouldn’t be a shocker: I’m a huge military science fiction fan. As such, John Ringo is one of my absolute favorites. I’m in the midst of his Black Tide Rising campaign, specifically Book 2, To Sail a Darkling Sea. As we contemplate this month’s ISSA Journal topic, Security Architecture/Security Management, let’s build a bit on this theme of dark seas as we look out at our probable futures. Keren Elazari (she is speaking at RSA 2015, where you may well be reading this in print), in her April 2015 Scientific American article, How To Survive Cyberwar, states that “in the coming years, cyberattacks will almost certainly intensify, and that is a problem for all of us. Now that everyone is connected in some way to cyberspace - through our phones, our laptops, our corporate networks – we are all vulnerable.” If you haven’t caught up with this perspective yet, wake up. I’m a Premera customer, you with me? Ringo starts Chapter 1 of To Sail a Darkling Sea with Sir Edmund Burke: “When bad men combine, the good must associate; else they will fall, one by one, an unpitied sacrifice in a contemptible struggle.
You’ll therefore forgive me if I stay on a bit of a pentesting & assessment run having just covered Faraday last month, but it’s for good reason. While unable to be specific, I can tell you that, at multiple intervals in the last few of months, I have seen penetration testing and the brilliant testers executing them, provide extraordinary value for their “customers”. One way to try and avoid sailing the darkling, compromised seas of the Intarwebs is with a robust penetration testing program, as integral to security management as any governance, risk, and compliance program. Bad men combine, we know that; the good must pentest. J
Let’s put philosophy into action this month with Adam Byers’ RAWR (NJ Ouchn, our friend @toolswatch, is on the RAWR team too). I asked Adam for the typical tool author’s contribution to the column and was treated to such robust content that I’m going to take a slightly different approach this month we’re I’ll weave in Adam’s feedback throughout as we take RAWR on a walkabout. For a proper introduction per Adam: "RAWR was designed to ease the process of the mapping, discovery, and reporting phases of an assessment with a focus primarily on web resources. It was built to be quick, scalable, and productive for the assessor. From the ground up, it accepts input from multiple different known scanning solutions, as well as leveraging NMap if no pre-existing scan data is available.  The goal of RAWR is to consolidate and capture the pieces of information that are most useful while performing a web assessment, and produce output that is normalized and functional.  There are many common checks performed in the process of a web assessment, each yielding information that is useful. The problem is that there are many different tools capable of gathering these singular bits of data, and each one produces output unlike the last. This further complicates the job that the assessor is tasked to perform, because producing a report that effectively compiles all of this information is the end goal.  With RAWR we want to take any type of relevant input, perform enumeration, and effectively pass the data on to the next phase - whether that phase be a tool, a person, or the end report itself.”
If you’ve conducted an assessment at any time, unless you’re working for one of those cookie cutter, CEH-certified checklist compliance mills, you’ve run into the issue of many different tools gathering data but generating output unlike the last. Outstanding efforts such as RAWR contribute greatly to the collaborate, combine, and complete cause, resulting in improved results and happier customers.
Adam also indicated that in addition to assessments, RAWR is useful during audits. Its ability to capture artifacts such as screenshots of disclaimer statements and login banners drastically reduces the amount of time it takes to complete audit tasks. The RAWR roadmap includes full header specification (including cookies), email/SMS notifications (already in the dev branch), better DNS functionality, and the acceptance of new input formats. The RAWR development pipeline also includes database integration for comparison and differential analysis of historical scan data via a PostgreSQL database, allowing trending as an example.
With that in mind, let’s begin our exploration.

Ready RAWR!



Some quick installation and setup notes. I initially installed RAWR on Kali but received rather buggy and incomplete results. Suspecting more of a Kali libs issue versus a RAWR shortcoming, I moved to an Ubuntu instance and received far better results.
At an Ubuntu terminal prompt, I executed:
cd rawr
sudo ./install.sh
The RAWR installer will help acquire dependencies including Ghost or phantomJS, python-lxml for parsing XML and HTML, and python-pygraphviz to create PNG diagrams from a site crawl. You’ll be asked to confirm for installation of missing dependencies; on Kali nmap is native, but phantomJS, DPE (from @toolswatch), and others will need to be installed. If you end up with pygraphviz errors on Ubuntu you may need to force installation with sudo apt-get install python-pygraphviz then run ./install.sh -u.

Run RAWR!

Adam provided us details for a typical assessment with RAWR, we’ll follow his steps and provide results as we go along.

Adam: A typical assessment begins with performing enumeration with RAWR. Executing something like rawr -a -o -r -x -S3 --dns gives us quite a bit of information to work with.

toolsmith: I ran ./rawr.py holisticinfosec.org -p fuzzdb -a -o -r -x -S3 –ssl --dns. To use FuzzDB Common Ports, I set -p fuzzdb. The -a switch is used to include all open ports in the CSV output and the Threat Matrix. The –o switch grabs HTTP OPTIONS, -r acquires robots.txt, and –x pulls down crossdomain.xml. The -S3 flag controls crawl intensity, 3 is default, --ssl tells nmap to call enum-ciphers.nse for more in-depth SSL data, and --dns queries Bing for other hostnames and adds them to the queue. Results are written to a log directory, specifically /rawr/log_20150321-143627_rawr on my Ubuntu instance. Therein, a cornucopia of useful results abound.
Adam: The Attack Surface (Threat) Matrix provides a quick view of ports on hosts; as well as patterns that reveal clustered services, similar host configurations, HA setups, and potential firewalls.

toolsmith: As seen in Figure 1, my Threat Matrix does not offer much to be concerned about, just 80 and 443 listening.

Figure 1 – RAWR Threat Matrix results

Adam: We can take serverinfo.csv and use it as a checklist, notating any interesting hosts and possible vulnerabilities.  Because we specified '-a' in the command line, all port data is included in the output regardless of whether or not it is web based.

toolsmith: The server information feature returns results for url, ipv4, port, returncode, hostnames, title, robots, script, file_includes, ssl_cert-daysleft, ssl_cert-validityperiod, ssl_cert-md5, ssl_cert-sha-1, ssl_cert-notbefore, ssl_cert-notafter, cpe, cve, service_version, server, endurl, date, content-type, description, author, revised, docs, passwordfields, email_addresses, html5, comments, defpass, and diagram. As seen in Figure 2, my serverinfo.csv provides a sample of such details.

Figure 2 – RAWR server information
Adam: The ‘index’ HTML report provides a dynamic (jQuery-driven) way to sift through screenshots and information captured from each host. While performing a site spider, RAWR pulls meta data from any docs found, which usually hands us a list of usernames, email addresses, domains, server names, phone numbers, and more in an HTML format, linked to in the index report. Also available via the index is a report that addresses the security headers of the target scope, alerting the assessor of improperly configured web sites and services.

toolsmith: I’ll share the results of each of the three succinct reports generated. Figure 3 represents the initial index report.

Figure 3 – RAWR Index Report
Figure 4 indicates the Nmap results.

Figure 4 – RAWR Nmap Scan Report
Figure 5 displays the security headers report. This report includes definitions from https://securityheaders.com to provide clarity.

Figure 5 – RAWR Security Headers Report
Figure 6 provides the results of the metadata extracted during the RAWR scan.

Figure 6 – RAWR Metadata Report
Adam: For web-focused testing, we also use the '--proxy' switch to push all of the traffic through Portswigger’s BurpSuite or OWASP Zed Attack Proxy.  RAWR isn't a vulnerability scanner, so it's helpful to leverage an interception proxy for further scans and session data when we go hunting.  Most IDS/IPS configurations will not alert on any of RAWR's activity aside from the initial NMap scan, as every request is a valid HTTP call to a verified host.

toolsmith: I ran RAWR separately through Burp with the --proxy switch enabled, this is a fabulous way to build an initial footprint, then proceed with more aggressive web application security testing. You can customize your RAWR scans via /rawr/conf/settings.py, including the user-agent (useful when you want to be uniquely identified during assessments), Nmap speed, CSV settings, spider aggression, and default ports.  
Keep in mind, you should only be using RAWR against resources you are authorized to assess.

In Conclusion

Adam reminds us that no one tool does it all and that it would be great to see more integration and data synchronicity between different tool sets. RAWR developers seek to overcome this by facilitating its acceptance of multiple input formats, as well as outputs like JSON, CSV, ShelvDB, and the aforementioned planned PostgreSQL integration.  There are also word lists for hydra and input lists for NMap; as well as other lists with Dirbuster, Nikto, and MetaSploit in mind. As information security tools developers work to build tools that are modular and scalable, so too should they consider making them compatible. Great work here by Adam and team, I really look forward to continued RAWR development and the principles it aligns with. A bright beacon in the darkling sea, if you will.
Ping me via email or Twitter if you have questions (russ at holisticinfosec dot org or @holisticinfosec).
Cheers…until next month.

Acknowledgements

Adam Byers (@al14s), RAWR (@RapidWebEnum) project lead
Tom Moore (@c0ncealed)

Friday, April 05, 2013

toolsmith: Implementing Redmine for Secure Project Management



Prerequisites/dependencies
VMWare for this methodology or a dedicated installation platform if installed from ISO

Introduction
From Redline for March’s toolsmith to Redmine for April’s, we’ll change pace from hacker space to the realm of secure project management. Following is a shortened version of a much longer Redmine study written for the SANS Reading Room as part of graduate school requirements and released jointly with ISSA.
Security and collaborative project management should not be exclusive. Software designed to support secure project management and security-oriented projects can be both feature rich and hardened against attacks. Web applications such as Redmine offer just such a solution and can embrace the needs of project managers and security practitioners alike. Redmine is project management and bug tracking software built on Ruby on Rails with a focus on collaboration, functionality, and when enhanced with specific plugins, can be configured securely to facilitate security-oriented projects. As a productivity platform, Redmine allows convenient team workflow while embracing the needs of virtual or mobile project members with a focus on socially oriented processes. We’ll explore the secure implementation and configuration of a Redmine server, and then transition into step-by-step details for managing a real world web application penetration testing project using Redmine. This will include the distribution of a virtual machine ready-built for real world use during such projects, pre-configured with a project template based on workflow in the SANS 542 Web Application Penetration Testing course.

From the TurnKey Redmine Web page: “Redmine is a Rails web application that provides integrated project management features, issue tracking, and support for multiple version control programs. It includes calendar and Gantt charts to aid visual representation of projects and their deadlines. It also features multi-project support, role based access control, a per-project wiki, and project forums”. Additionally, a tool such as Redmine allows the convergence of software and security testing. As a software configuration management (SCM) tool, Redmine is ideally suited to projects related to software development. That said, the security expertise required to security test software needs equal consideration and project management. “Sometimes security, or pen-testers for short - work on the same test team as functionality testers; other times, pen-testers work as security consultants and are hired by the software development company to perform security tests”[1]. Regardless of who solicits the use of pen-testers, the related pen-test is a project, and Redmine is the ideal application to provide the agile, flexible platform pen-testers need to coordinate their efforts with the help of a PM or team lead.

Installation

Redmine installation and configuration using a TurnKey Linux Redmine appliance built on a Debian-based Linux distribution, is reasonably straightforward. Your ability to install a Linux operating system from an ISO file on a dedicated machine, or configuring a VMware virtual machine is assumed. It is also assumed you have control of or access to an Active Directory domain for LDAP authentication to Redmine, as it allows for more robust user management. As referenced later, the IP address of the Redmine instance was 192.168.248.16 and 192.168.248.248 for the domain controller. The stable version of the TurnKey virtual Redmine appliance (version 12) running on a lean instance of Debian Squeeze (CLI only, no X11 GUI) via VMWare Workstation 9 was utilized for this research. Note, readers will find running the shell via Putty or a client where you can cut and paste installation strings easier as the VMWare tools aren’t effective without the GUI. This TurnKey Redmine appliance relies on Passenger, a module for Apache that hosts Ruby on Rails applications, and supports the use of SSL/TLS (configured by default) and ModSecurity for better security.
As of this writing the current version of Redmine was 2.2.1 and will be described herein. The installed version of Redmine on the TurnKey appliance is 1.4.4; this guidance will include its upgrade to Redmine 2.2.1.
First, download the Turnkey Linux VM appliance and open it in VMWare.  The first boot routine will ask you to create passwords for the root account, the MySQL root user, and the Redmine admin. When the routine completes you should be presented the TurnKey Linux Configuration Console as seen in Figure 1.

FIGURE 1TurnKey Linux Configuration Console
In the Hardening section, the process of disabling the services you don’t intend to use will be discussed. Take a snapshot of the virtual machine at this point and name the snapshot Base Install.

Update the Redmine version from a command prompt on the Redmine server as follows:
1.                   apt-get update
2.                   apt-get upgrade
3.                   apt-get install locate
4.                   updatedb
5.                   cd /var/www
6.                   mv redmine redmine -old
7.                   hg clone --updaterev 2.0-stable https://bitbucket.org/redmine/redmine-all redmine
8.                   cp redmine -old/config/database.yml redmine/config/database.yml
9.                   cp -r redmine-old/files/ redmine/files/
10.               chown -R root:www-data /var/www/ redmine
11.               cd redmine
12.               gem install bundler
13.               gem install test-unit
14.               bundle install --without development test rmagick
15.               mkdir public/plugin_assets
16.               rake generate_secret_token
17.               rake db:migrate RAILS_ENV=production
18.               chown -R www-data:www-data files log tmp public/plugin_assets
19.               rake redmine:plugins:migrate RAILS_ENV=production
20.               chmod -R 755 files log/ tmp/ public/plugin_assets
21.               rake tmp:cache:clear
22.               rake tmp:sessions:clear
Run the script /var/www/redmine/script/about to confirm the version upgrade.

LDAP authentication is inherent to Redmine but requires a bit of setup. The example Active Directory domain name utilized via a virtual Windows Server 2008 domain controller was REDMINE. The user redminer was established as the service-like account utilized by Redmine to access the directory. Do not user a domain administrator account for this user. Should your Redmine instance be compromised so too then would be your domain. Via your browser, as the Redmine admin user, navigate to Administration then LDAP Authentication. Refer to the Redmine LDAP Authentication page via the Redmine WIKI but refer to the following example configuration as successfully utilized for this research seen in Figure 2.

FIGURE 2: LDAP Configuration
Select Save then, assuming a correct configuration, you should receive indication of a successful connection when you click Test on the resulting Authentication Modes page.

Refer to the SANS Reading Room version regarding additional installation and hardening steps and don’t skip! These are important:
·         Installation
o   Pixel Cookers theme for a streamlined, tech-centric look as well as the
o   Email settings
o   Plugin installation (Ldap Sync, Scrum2B, Screenshot, Monitoring & Controlling)
·         Hardening
o   Disable unnecessary services
o   Tighten down SSH
o   Restrict Redmine web access to HTTPS only
o   Implement UFW (the uncomplicated firewall)

Engaging With Redmine

Following is a step by step description of a penetration testing engagement where Redmine is utilized to provide project support for a team of three.
The first and most important steps to undertake are the elimination of all unwanted permissions for the Non member and Anonymous roles. Login to Redmine as the admin user and select Administration | Roles and permissions | Non member | Uncheck all | Save. Repeat this process for the Anonyomous roles. These steps will ensure that you don’t inadvertently expose project data to those who don’t have explicit permission to view it. Next, to add users for this project, select Administration | Groups to add a group called PenTesters.  From Administration | Users add three users with appropriately defined login names pentester1 (Fred), pentester2 (Wilma), pentester3 (Barney), and pentestpm (BamBam) and add them to the PenTesters group. Remember these users need to also have been created in the domain you’re utilizing for LDAP authentication. Via the Administration menu, under Projects, create a project called Web Application Pentest. The activities related to this project are drawn directly from tasks outlined in the SANS 542: Web App Penetration Testing and Ethical Hacking course as well as the Samurai Web Testing Framework. Select all Modules and Trackers for the project. You’ll note that Monitoring and Controlling by Project and Scrum2b are available as implemented during the installation phase described earlier. These plugins will be described in more detail as their use is inherent to agile project management for projects such as penetration testing.
Redmine allows the creation of subprojects as well; the Web Application Pentest project should be divided into four subprojects named as follows: 1-Recon, 2-Mapping, 3-Discovery, and 4-Exploitation. Add each of them from Redmine Web Application Pentest project page and remember to enable all Modules and Trackers.
Add the user accounts for the three penetration testers and the project PM user as project and subproject members via the Members tab as seen in Figure 3.

FIGURE 3: Pen-test Project Members
Return to the project overview, select 1-Recon under subprojects, and add a new issue. File a bug for each recon phase task you’d like completed, with the applicable start and due dates. You can upload related files, screenshots (thanks to the plugin installed earlier), and designate an assignee, as well as watchers.
Under Settings for each project or subproject you define you can establish issue categories. This is an ideal method by which to establish penetration testing activities for each subproject. As an example, the recon phase of a web application penetration test includes general recon along with DNS and Whois lookups, search engine analysis, social network analysis, and location analysis. Establishing each of these as issues categories will then allow bugs (tasks) to be filed specific to each category. Each bug can in turn be assigned a pen-tester with start and end dates, along with files that might be useful to complete the task. Location analysis could include gleaning location data from victim Tweets as described in Violent Python[2]. Twitter provides an API to developers which allows information gathering about individuals (potential penetration test targets). A script from Violent Python to help in this information gathering can be uploaded into the Redmine bug, Location data from Tweets as seen in Figure 4.

FIGURE 4: Bug (task) assigned to Fred, with helper code
As bugs are added, assigned, and/or updated, if configured to communicate verbosely, Redmine will email notices to the appropriate parties. The email as seen in Figure 5 was received as a function of filing the bug in Figure 4.

FIGURE 5: Email notice for bug (task) filed
This allows real-time communication among penetration testers or any project participants defined in your Redmine deployment. As pen-testers generate findings, they can be uploaded to the associated bug, and if versioning is required, managed via the Mercurial SCM offering as described during installation.
Bug status can be tracked as New, In Progress, Resolved, Feedback, and Closed or Rejected, and each bug can be assigned a priority and estimated time. As completed, actual time spent on each bug can be tracked too. Overall project time allotments as defined in the bug then track quite nicely via the Redmine Gantt functionality as seen in Figure 6.

FIGURE 6: Redmine Gantt functionality
Scrum2b

The concept of agile software development has, over time, been applied directly to project management. Consider the use of Scrum methodology as part of agile project management. According to Agile Project Management with Scrum, “the heart of Scrum lies in the iteration. The team takes a look at the requirements, considers the available technology, and evaluates its own skills and capabilities. It then collectively determines how to build the functionality, modifying its approach daily as it encounters new complexities, difficulties, and surprises. The team figures out what needs to be done and selects the best way to do it. This creative process is the heart of the Scrum’s productivity”[3]. These creative processes, assessment of capabilities, and changing complexities and surprises are also inherent to any penetration test and as such, the agile project management framework is an ideal way to coordinate pen-test projects. The Scrum2b plugin for Redmine is well suited to answer this calling. If each phase of the pen-test is considered a sprint as defined by the Scrum process, the planning and awareness necessary to support the sprint is essential. The Scrum2b interface is a virtual Scrum Board that allows project participants to track activities by bug and members while editing the bug on the fly with the appropriate permission. The pentestpm user, as project manager, could adjust task’s percentage of completion right from Scrum2b using the time slider.

FIGURE 7: Scrum2b Scrum Board for pen-testers
If the assignee needs to jump right to the bug, the plugin is fully hyperlink enabled. The Scrum Board allows filtering the view by members and issues. New issues can also be added right from the Scrum Board.

Monitoring & Controlling

All projects require the right balance of monitoring and controlling, and penetration tests are no exception. The Monitoring and Controlling Project Work process includes “gathering, recording, and documenting project information that provides project status, measurements of progress, and forecasting to update cost and schedule information that is reported to stakeholders, project team members, management, and others”[4]. The Monitoring & Controlling plugin for Redmine shines in this capacity. Established as a convenient left-pane menu item with the Pixel Cookers theme, this plugin creates a dashboard for project data organized by Tasks Management, Time Management, and Human Resource Management. Tasks Management tracks Tasks by Status, Tasks by Category, and Task Management (manageability). Applied again to the context of a pen-test project, Figure 8 represents the Recon phase of a pen-test.

FIGURE 8: Monitoring & Controlling Tasks Management
Refer again to the SANS Reading Room version, page 17, for more regarding Time & Human Resources Management with the Redmine Monitoring & Controlling plugin.

In Conclusion

Project management includes a certain amount of tedium, but Redmine configured with the aforementioned plugins allows for a refreshing, dynamic approach to the overall secure project management lifecycle. While no system is ever absolutely secure (a serious Ruby on Rails SQL injection flaw was disclosed as this paper was written), the appropriate hardening steps can help ensure enhanced protection. Steady maintenance and diligence will also serve you well. The convenience of an implementation such as TurnKey Redmine makes keeping the entire system up to date quite easy.
A version of a TurnKey Redmine virtual machine as discussed here will be made available to readers via the HolisticInfoSec Skydrive. This instance will include a web application project template, with predefined subprojects, issue categories and bugs, again as defined in the SANS 542 course. Readers will need only create users, assign dates and members, and establish access to an LDAP service.
Ping me via email if you have questions or suggestions for topic via russ at holisticinfosec dot org or hit me on Twitter @holisticinfosec.
Cheers…until next month.

References


[1] Gallagher, Jeffries, and Landauer (2006). Hunting Security Bugs, Redmond, WA: Microsoft Press.
[2] O'Connor, T. (2013). Violent python. (p. 229). Walthm, MA: Syngress.
[3] Schwaber, K. (2004). Agile project management with scrum.
[4] Heldman, K. (2009). Pmp: Project management professional exam study guide. (Fifth ed.). Indianapolis, IN: Sybex.

Tuesday, December 04, 2012

toolsmith: ModSecurity for IIS



Part 2 of 2 - Web Application Security Flaw Discovery and Prevention

Prerequisites/dependencies
Windows OS with IIS (Win2k8 used for this article)
SQL Server Express 2004 SP4 and Management Studio Express for vulnerable web app
.NET Framework 4.0 for ModSecurity IIS

Introduction

December’s issue continues where we left off in November with part two in our series on web application security flaw discovery and prevention. In November we discussed Arachni, the high-performance, modular, open source web application security scanning framework. This month we’ll follow the logical work flow from Arachni’s distributed, high-performance scan results to how to use the findings as part of mitigation practices. One of Arachni’s related features is WAF Realtime Virtual Patching.
Trustwave Spider Lab’s Ryan Barnett has discussed the concept of dynamic application scanning testing (DAST) data that can be imported into a web application firewall (WAF) for targeted remediation. This discussion included integrating export data from Arachni into ModSecurity, the cross–platform, open source WAF for which he is the OWASP ModSecurity Core Rule Set (CRS) project leader. I reached out to Ryan for his feedback with particular attention to ModSecurity for IIS, Microsoft’s web server.
He indicated that WAF technology has gained traction as a critical component of protecting live web applications for a number of key reasons, including:
1)      Gaining insight into HTTP transactional data that is not provided by default web server logging
2)      Utilizing Virtual Patching to quickly remediate identified vulnerabilities
3)      Addressing PCI DSS Requirement 6.6
The ModSecurity project is just now a decade old (first released in November 2002), has matured significantly over the years, and is the most widely deployed WAF in existence protecting millions of websites. “Until recently, ModSecurity was only available as an Apache web server module. That changed, however, this past summer when Trustwave collaborated with the Microsoft Security Response Center (MSRC) to bring the ModSecurity WAF to the both the Internet Information Services (IIS) and nginx web server platforms.  With support for these platforms, ModSecurity now runs on approximately 85% of internet web servers.” 
Among the features that make ModSecurity so popular, there are a few key capabilities that make it extremely useful:
It has an extensive audit engine which allows the user to capture the full inbound and outbound HTTP data.  This is not only useful when reviewing attack data but is also extremely valuable for web server administrators who need to trouble-shoot errors.
·         It includes a powerful, event-driven rules language which allows the user to create very specific and accurate filters to detect web-based attacks and vulnerabilities.
·         It includes an advanced Lua API which provides the user with a full-blown scripting language to define complex logic for attack and vulnerability mitigation.
·         It also includes the capability to manipulate live transactional data.  This can be used for a variety of security purposes including setting hacker traps, implementing anti-CSRF tokens, or Cryptographic HASH tokens to prevent data manipulation.
In short, Ryan states that ModSecurity is extremely powerful and provides a very flexible web application defensive framework that allows organizations to protect their web applications and quickly respond to new threats.
I also sought details from Greg Wroblewski, Microsoft’s lead developer for ModSecurity IIS.
“As ModSecurity was originally developed as an Apache web server module, it was technically challenging to bring together two very different architectures. The team managed to accomplish that by creating a thin layer abstracting ModSecurity for Apache from the actual server API. During the development process it turned out that the new layer is flexible enough to create another ModSecurity port for the nginx web server. In the end, the security community received a new cross-platform firewall, available for the three most widely used web servers.
The current ModSecurity development process (still open, recently migrated to GitHub) preserves compatibility of features between three ported versions. For the IIS version, only features that rely on specific web server behavior show functional differences from the Apache version, while the nginx version currently lacks some of the core features (like response scanning and content injection) due to limited extensibility of the server. Most ModSecurity configuration files can be used without any modifications between Apache and IIS servers. The upcoming release of the RTM version for IIS will include a sample of ModSecurity OWASP Core Rule Set in the installer.

Installing ModSecurity for IIS

In order to test the full functionality of ModSecurity for IIS I needed to create an intentionally vulnerable web application and did so following guidelines provided by Metasploit Unleashed. The author wrote these guidelines for Windows XP SP2, I chose Windows Server 2008 just to be contrarian. I first established a Win2k8 virtual machine, enabled the IIS role, downloaded and installed SQL Server 2005 Express SP4, .NET Framework 4.0, as well as SQL Server 2005 Management Studio Express, then downloaded and the ModSecurity IIS 2.7.1 installer. We’ll configure ModSecurity IIS after building our vulnerable application. When configuring SQL Server 2005 Express ensure you enable SQL Server Authentication, and set the password to something you’ll use in the connection string established in Web.config. I used p@ssw0rd1 to meet required complexity. J Note: It’s “easier” to build a vulnerable application using SQL Server 2005 Express rather than 2008 or later; for time’s sake and reduced troubleshooting just work with 2005. We’re in test mode here, not production. That said, remember, you’re building this application to be vulnerable by design. Conduct this activity only in a virtual environment and do not expose it to the Internet. Follow the Metasploit guidelines carefully but remember to establish a proper connection string in the Web.config (line 4) and build it from this sample I’m hosting for you rather than the one included with the guidelines. As an example, I needed to establish my actual server name rather than localhost, I defined my database name as crapapp instead of WebApp per the guidelines, and used p@ssw0rd1 instead of password1 as described:
I also utilized configurations recommended for the pending ModSecurity IIS install so go with my version.
Once you’re finished with your vulnerable application build you should browse to http://localhost and first pass credentials that you know will fail to ensure database connectivity. Then test one of the credential pairs established in the users table, admin/s3cr3t as an example. If all has gone according to plan you should be treated to a successful login message as seen in Figure 1.

FIGURE 1: A successful login to CrapApp
ModSecurity IIS installation details are available via TechNet but I’ll walk you through a bit of it to help overcome some of the tuning issues I ran into. Make sure you have the full version of .NET 4.0 installed and patch it in full before you execute the ModSecurity IIS installer you downloaded earlier.
Download the ModSecurity OWASP Core Rule Set (CRS) and as a starting point copy the files from the base_rules to the crs directory you create in C:\inetpub\wwwroot. Also put the test.conf file I’m also hosting for you in C:\inetpub\wwwroot. This will call the just-mentioned ModSecurity OWASP Core Rule Set (CRS) that Ryan maintains and also allow you to drop any custom rules you may wish to create right in test.conf.
There are a few elements to be comfortable with here. Watch the Windows Application logs via Event Viewer to both debug any errors you receive as well as ModSecurity alerts once properly configured. I’m hopeful that the debugging time I spent will help save you a few hours, but watch those logs regardless. Also make regular use of the Internet Information Services (IIS) Manger to refresh the DefaultAppPool under Application Pools as well as restart the IIS instance after you make config changes. Finally, this experimental installation intended to help get you started is running in active mode versus passive. It will both detect and block what the CRS notes as malicious. As such, you’ll want to initially comment out all the HTTP Policy rules in order to play with the CrapApp we built above. To do so, open modsecurity_crs_30_http_policy.conf in the crs directory and comment out all lines that start with SecRule. Again, we’re in experiment mode here. Don’t deploy ModSecurity in production with the SecDefaultAction directive set to "block" without a great deal of testing in passive mode first or you’ll likely blackhole known good traffic.

Using ModSecurity and virtual patching to protect applications

Now that we’re fully configured, I’ll show you the results of three basic detections then close with a bit of virtual patching for your automated web application protection pleasure. Figure 2 is a mashup of a login in attempt via our CrapApp with a path traversal attack and the resulting detection and block as noted in the Windows Application log.

FIGURE 2: Path traversal attack against CrapApp denied
Similarly, a simple SQL injection such as ‘1=1-- against the same form field results in the following Application log entry snippet:
[msg "SQL Injection Attack: Common Injection Testing Detected"] [data "Matched Data: ' found within ARGS:txtLogin: '1=1--"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.6"] [maturity "9"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"]

Note the various tags including a match to the appropriate OWASP Top 10 entry as a well as the relevant section of the PCI DSS.
Ditto if we pop in a script tag via the txtLogin parameter:
[data "Matched Data: "] [ver "OWASP_CRS/2.2.6"] [maturity "8"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/XSS"] [tag "WASCTC/WASC-8"] [tag "WASCTC/WASC-22"] [tag "OWASP_TOP_10/A2"] [tag "OWASP_AppSensor/IE1"] [tag "PCI/6.5.1"]
    
Finally, we’re ready to connect our Arachni activities in Part 1 of this campaign to our efforts with ModSecurity IIS. There are a couple of ways to look at virtual patching as amply described by Ryan. His latest focus has been more on dynamic application scanning testing as actually triggered via ModSecurity. There is now Lua scripting that integrates ModSecurity and Arachni over RPC where a specific signature hit from ModSecurity will contact the Arachni service and kick off a targeted scan. At last check this code was still experimental and likely to be challenging with the IIS version of ModSecurity. That said we can direct our focus in the opposite direction to utilize Ryan’s automated virtual patching script, arachni2modsec.pl, where we gather Arachi scan results and automatically convert the XML export into rules for ModSecurity. These custom rules will then protect the vulnerabilities discovered by Arachni while you haggle with the developers over how long it’s going to take them to actually fix the code.
To test this functionality I scanned the CrapApp from Arachni instance on the Ubuntu VM I built for last month’s article. I also set the SecDefaultAction directive set to "pass" in my test.conf file to ensure the scanner is not blocked while it discovers vulnerabilities. Currently the arachni2modsec.pl script writes rules specifically for SQL Injection, Cross-site Scripting, Remote File Inclusion, Local File Inclusion, and HTTP Response Splitting. The process is simple; assuming the results file is results.xml, arachni2modsec.pl –f results.xml will create modsecurity_crs_48_virtual_patches.conf. On my ModSecurity IIS VM I’d then copy modsecurity_crs_48_virtual_patches.conf into the C:\inetpub\wwwroot\crs directory and refresh the DefaultAppPool. Figure 3 gives you an idea of the resulting rule.  

FIGURE 3: arachni2modsec script creates rule for ModSecurity IIS
Note how the rule closely resembles the alert spawned when I passed the simple SQL injection attack to CrapApp earlier in the article. Great stuff, right?

In Conclusion

What a great way to wrap up 2012 with the conclusion of this two-part series on Web Application Security Flaw Discovery and Prevention. I’m thrilled with the performance of ModSecurity for IIS and really applaud Ryan and Greg for their efforts. There are a number of instances where I intend to utilize the ModSecurity port for IIS and will share feedback as I gather data. Please let me know how it’s working for you as well should you choose to experiment and/or deploy.
Good luck and Merry Christmas.
Stay tuned to vote for the 2012 Toolsmith Tool of the year starting December 15th.
Ping me via email if you have questions (russ at holisticinfosec dot org).
Cheers…until next month.

Acknowledgements

Ryan Barnett, Trustwave Spider Labs, Security Researcher Lead
Greg Wroblewski, Microsoft, Senior Security Developer

Moving blog to HolisticInfoSec.io

toolsmith and HolisticInfoSec have moved. I've decided to consolidate all content on one platform, namely an R markdown blogdown sit...