{"id":934,"date":"2012-08-03T09:09:29","date_gmt":"2012-08-03T01:09:29","guid":{"rendered":"http:\/\/rmohan.com\/?p=934"},"modified":"2012-08-03T09:09:43","modified_gmt":"2012-08-03T01:09:43","slug":"hardening-linux-web-servers","status":"publish","type":"post","link":"https:\/\/mohan.sg\/?p=934","title":{"rendered":"Hardening Linux Web Servers"},"content":{"rendered":"<p>Security is a process, not a result. It is a process which is difficult to adopt under normal conditions; the problem is compounded when it spans several job descriptions. All the system level security in the world is rendered useless by insecure web-applications. The converse is also true\u2014programming best practices, such as always verifying user input, are useless when the code is running on a server which hasn\u2019t been properly hardened. Securing forward facing GNU\/Linux web servers can seem like a daunting task, but it can be made much easier by breaking the process into manageable portions.<\/p>\n<p>This article will cover installing, configuring and hardening free software web servers and associated software including <em>Apache 2.2.0<\/em>, <em>MySQL 5.0.18<\/em>, <em>PHP 5.1.2<\/em>, <em>Apache-Tomcat 5.5.16<\/em> and common Apache modules such as <code>mod_security<\/code>, <code>mod_ssl<\/code>, <code>mod_rewrite<\/code>, <code>mod_proxy<\/code> and <code>mod_jk<\/code>. Common security mistakes in web-applications and how to fix them will also be discussed, focusing on PHP and Java environments.<\/p>\n<p>The most common and apt analogy for security is the onion. That is to say it is a layered approach\u2014any one layer is inadequate, the onion is the sum of its layers. With that in mind, this article attempts to bridge the knowledge gap between system administrators and web developers, allowing individuals tasked with security to achieve a layered security solution.<\/p>\n<p>Only a basic understanding of GNU\/Linux and common command line tools is assumed.<\/p>\n<p>Note: due to formatting constraints, long lines of code are often broken into several smaller lines using the <code>\\<\/code> character. This is not a return and when typing in the line you should not hit the enter key, it is just to prevent line wrapping. Output from commands will also be limited to relevant fields, so the output will look slightly different when you run the commands on your system.<\/p>\n<p align=\"center\"><strong>Security is a process, not a result<\/strong><\/p>\n<h1>Security at the system level<\/h1>\n<p>System level security is one of the most crucial layers in any defense. Hardening at the system level is roughly categorized into network security and file system security.<\/p>\n<p>Network level security can be increased by securing common services such as <code>xinetd<\/code> (otherwise known as the super server) and <code>OpenSSH<\/code>, by correctly configuring or disabling them and enabling a firewall (in our case, <code>iptables<\/code>.<\/p>\n<p>File-System security can be increased by: preventing common avenues of attack, such as root kits; enabling intrusion detections systems (IDS) to verify the integrity of key configuration files; by using tools to detect and remove root kits; and by configuring your logging system so that it will log to a remote host, thereby protecting the integrity of your system logs.<\/p>\n<h2>Network security<\/h2>\n<p>The first thing you need to do to secure a system from network attacks is find out which processes are listening for connections and on which ports. There are several time tested tools available for this: <code>nmap<\/code> and <code>netstat<\/code>.<\/p>\n<h2>netstat<\/h2>\n<p>The following command will show you which ports are being listened on, the IP address of the listening socket, and which program or PID is associated with the socket (note: running as the super-user or <em>root<\/em> is necessary for the program field to work properly).<\/p>\n<p><code>$ netstat -l -n -p -t -u -w<\/code><\/p>\n<p>(<code>-l<\/code> is for listening, <code>-n<\/code> is for IP information and <code>-p<\/code> is for program\/PID information, <code>-t<\/code>, <code>-u<\/code>, <code>-w<\/code> are for <code>tcp<\/code>, <code>udp<\/code> and <code>raw<\/code> socket connections. By setting these flags, I disable displaying information about <em>unix<\/em> sockets which are not relevant to network security, as they are only used for interprocess communication on the current host.)<\/p>\n<p>The output will look something like this:<\/p>\n<p>Note: Certain columns have been omitted for space<\/p>\n<div>\n<pre>  proto Local Address      State    PID\/Program name\r\n  tcp   127.0.0.1:8005    LISTEN   4079\/java\r\n  tcp   0.0.0.0:8009      LISTEN   4079\/java\r\n  tcp   0.0.0.0:3306      LISTEN   18542\/mysqld\r\n  tcp   0.0.0.0:80        LISTEN   23736\/httpd\r\n  tcp   0.0.0.0:8080      LISTEN   4079\/java\r\n  tcp   0.0.0.0:22        LISTEN   11045\/sshd\r\n  tcp   0.0.0.0:3128      LISTEN   23283\/(squid)\r\n  tcp   127.0.0.1:25      LISTEN   24453\/master\r\n  udp   0.0.0.0:3130               23283\/(squid)\r\n  udp   0.0.0.0:32870              23283\/(squid)<\/pre>\n<\/div>\n<p>Understanding the output from netstat is pretty simple. The first field is the protocol, and you will notice that when the protocol is <code>udp<\/code>, there is no state (as obviously <code>udp<\/code> is stateless unlike <code>tcp<\/code>). The next interesting field is the Address field. <code>0.0.0.0:80<\/code> means that the server will respond to any IPs on port 80, while <code>127.0.0.1:80<\/code> means that the server is only listening to the loop back device.<\/p>\n<h2>nmap<\/h2>\n<p>Another tool in our arsenal is <code>nmap<\/code>, the network mapper. <code>nmap<\/code> is good for determining what ports and services are available on a server from other machines on the network.<\/p>\n<p>(Note: The default option is <code>-sS<\/code>. However, when the system being scanned is running a firewall, such as <code>iptables<\/code>, it won\u2019t work, as firewalls that block <code>icmp<\/code> traffic will also block the subsequent scan and the results will be meaningless. The <code>-P0<\/code> option disables pinging the host before scanning it, The <code>-O<\/code> (as in \u201coh\u201d rather than zero) is to enable <code>nmap<\/code>\u2019s operating system detection via the network stack fingerprint.)<\/p>\n<p><code>$nmap -P0 -O 10.0.2.10<\/code><\/p>\n<p>The output will look something like this:<\/p>\n<div>\n<pre> The 1661 ports scanned but not shown below are in \r\n                                    state: filtered)\r\n  PORT    STATE  SERVICE\r\n  22\/tcp  open   ssh\r\n  443\/tcp closed https\r\n\r\n  Device type: general purpose\r\n  Running: Linux 2.6.X\r\n  OS details: Linux 2.6.7 - 2.6.8\r\n  Uptime 40.462 days since Mon Dec 26 10:05:57 2005<\/pre>\n<\/div>\n<p>Now that I know what services are listening on which ports, I can go about securing them. In some cases, the solution will be disabling the unwanted service via <code>inetd<\/code>; in others, I will use <code>iptables<\/code> rules to block external access to that port.<\/p>\n<p>In the context of a web server, I would recommended disabling all services managed by <code>inetd<\/code> (if they aren\u2019t already).<\/p>\n<p><code>\/etc\/xinetd.conf<\/code> (Red Hat): this file usually has some minimalistic configuration of the logging software and then an include statement for all the files under <code>\/etc\/xinetd.d<\/code>, which are configuration files for each service run through the super server.<\/p>\n<p><code>\/etc\/inetd.conf<\/code> (Debian): Debian has a much simpler configuration layout\u2014one simple file <code>\/etc\/inetd.conf<\/code> containing one line for each service managed by <code>inetd<\/code>.<\/p>\n<h2>iptables<\/h2>\n<p>The venerable <code>iptables<\/code> has been the standard Linux firewall since the 2.4 kernel. The kernels that come with Red Hat and Debian have the proper modules enabled; however, on Debian systems you may need to install the <code>iptables<\/code> user land tools. Configuring <code>iptables<\/code> is fairly simple: <code>iptables<\/code> has chains, rules and targets. <code>iptables<\/code> has three built in chains: <code>FORWARD<\/code>, <code>INPUT<\/code>, and <code>OUTPUT<\/code>. To create an effective firewall I will append rules to chains that will be matched by connection type, source or destination address or state. In more advanced configurations, it is favorable to create custom chains and then reference them in the default chains; but, to demonstrate the basic principles, I am just going to append rules to the three default chains. When a connection is being matched against the configured rules, each rule is checked. If it matches, it is executed, if not, the next rule is tested. As such, the rules allowing traffic should be appended first, and the very last line in any chain should be a deny rule. This is the most secure firewall configuration, where everything is dropped except the explicitly allowed connections.<\/p>\n<p>If you use Debian, run:<\/p>\n<div>\n<pre>  $apt-get install iptables ( to install iptables )\r\n  $apt-cache search iptables ( to search for packages related to iptables)<\/pre>\n<\/div>\n<p>To get started with iptables I will list the current rule set using the following command:<\/p>\n<div>\n<pre>  $iptables --list<\/pre>\n<\/div>\n<p>(Note: Output has been modified due to formatting constraints.)<\/p>\n<div>\n<pre>   Chain INPUT (policy ACCEPT)\r\n   target     prot   opt     source   destination\r\n   ACCEPT     all       anywhere  anywhere \\ \r\n            state RELATED,ESTABLISHED\r\n\r\n   Chain FORWARD (policy ACCEPT)\r\n   target     prot   opt     source   destination\r\n   ACCEPT     all       anywhere anywhere   \\\r\n                        state RELATED,ESTABLISHED\r\n\r\n   Chain OUTPUT (policy ACCEPT)\r\n   target     prot   opt     source   destination\r\n   DROP       tcp       anywhere anywhere  \\\r\n                                       tcp dpt:ssh<\/pre>\n<\/div>\n<p>The partial listing above shows rules that allow incoming traffic that isn\u2019t new; that is to say: the connection has been established from inside the network. IP forwarding follows the same rule, and using <code>ssh<\/code> to connect out to other hosts is blocked.<\/p>\n<p>The flush command with no options will flush all rules; if a chain is passed, all rules in that chain will be flushed. I\u2019ll flush all rules and begin configuring the firewall.<\/p>\n<div>\n<pre>  $iptables -F \r\n    or \r\n  $iptables -F INPUT \r\n  $iptables -F FORWARD\r\n  $iptables -F OUTPUT<\/pre>\n<\/div>\n<p>Next, I am going to append the rules to the appropriate chain. A high level overview of the firewall will be the following:<\/p>\n<ol>\n<li>Allow outgoing connections initiated from the host<\/li>\n<li>Allow inbound ssh connections on port 2<\/li>\n<li>Allow inbound http connections on port 80<\/li>\n<li>Allow inbound https connections on port 443<\/li>\n<li>Block outbound ssh connections<\/li>\n<li>Block everything else<\/li>\n<\/ol>\n<div>\n<pre>  # Enable stateful filtering allowing connections \r\n  # initiated on host be allowed.\r\n  $iptables -A INPUT -m state --state \\ \r\n        RELATED,ESTABLISHED -j ACCEPT\r\n\r\n  $iptables -A OUTPUT -m state --state \\ \r\n    NEW,RELATED,ESTABLISHED -j ACCEPT\r\n\r\n  # Allow Incoming SSH, HTTP, HTTPS\r\n  $iptables -A INPUT -p tcp -m tcp \\\r\n            --dport 22 -j ACCEPT\r\n  $iptables -A INPUT -p tcp -m tcp \\\r\n            --dport 80 -j ACCEPT\r\n  $iptables -A INPUT -p tcp -m tcp \\\r\n            --dport 443 -j ACCEPT\r\n\r\n  # Allow Everything from the local host\r\n  $iptables -A INPUT -s 127.0.0.1 -j ACCEPT\r\n\r\n  # Block Outgoing SSH connections\r\n  $iptables -A OUTPUT -p tcp -m tcp \\\r\n            --dport 22 -j DROP\r\n\r\n  # Block Everything else\r\n  $iptables -A INPUT -j DROP\r\n  $iptables -A FORWARD -j DROP<\/pre>\n<\/div>\n<p>To save the changes I have made to the firewall rules I use the <code>iptables-save<\/code> command:<\/p>\n<div>\n<pre>  $iptables-save &gt; \/root\/firewall<\/pre>\n<\/div>\n<p>Later if I wanted to restore my saved rules I would run the <code>iptables-restore<\/code> command:<\/p>\n<div>\n<pre>  $iptables-restore -c \/root\/firewall<\/pre>\n<\/div>\n<p>It\u2019s a very good idea to have these rules applied at boot time; check your distribution\u2019s documentation for this. In general, on Debian systems the network configuration scripts can be used for this, and on Red-Hat systems a startup script in <code>\/etc\/init.d<\/code> is appropriate.<\/p>\n<p align=\"center\"><strong>Changing the default port that `OpenSSH` listens on is a good way to avoid brute force attacks<\/strong><\/p>\n<h2>Hardening SSH<\/h2>\n<p>The <code>OpenSSH<\/code> package comes installed by default on most distributions. The default configuration on most distributions is pretty lax and favors functionality over security. Allowing <em>root<\/em> logins, listening on all IPs on port 22, and allowing all system accounts to <code>ssh<\/code>-in are all potential security holes.<\/p>\n<p>Edit <code>\/etc\/ssh\/sshd_config<\/code> in your favorite editor and change the following lines.<\/p>\n<div>\n<pre>  # ListenAddress defines the IP address ssh will \r\n  # listen on\r\n\r\n  #ListenAddress 0.0.0.0 -&gt; ListenAddress 10.0.2.10 \r\n\r\n  #Only accept SSH protocol 2 connections\r\n  #Protocol 2,1 -&gt; Protocol 2     \r\n\r\n  #Disable root login\r\n  PermitRootLogin yes -&gt; PermitRootLogin no\r\n\r\n  #Disable allowing all system accounts to ssh in, \r\n  # only allow certain users (space delimited)\r\n  AllowUsers userName1 userName2 userName3\r\n\r\n  # Change Default port\r\n  Port 22 -&gt; Port 2200<\/pre>\n<\/div>\n<p>After making the changes, restart the SSH server for the changes to take affect:<\/p>\n<div>\n<pre>$ \/etc\/init.d\/ssh restart<\/pre>\n<\/div>\n<p align=\"center\"><strong>Partition for security<\/strong><\/p>\n<h2>File system security<\/h2>\n<p>The UNIX file system has several standard directories: <code>\/<\/code>, <code>\/tmp<\/code>, <code>\/var<\/code>, <code>\/usr<\/code> and <code>\/home<\/code>. The two that present the weakest links for a variety of attacks are <code>\/tmp<\/code> and <code>\/var<\/code>. The two most common attacks are: \u201cDenial of Service\u201d, by causing the root partition to fill up with logs or other junk (assuming all these directories are mounted on one partition); and running rootkits from the <code>\/tmp<\/code> directory.<\/p>\n<p>One solution to file system Denial of Service attacks is to have these directories mounted on their own partitions, this will prevent the <code>\/<\/code> file system from filling up and stop that avenue of attack.<\/p>\n<p>Rootkits typically write to the <code>\/tmp<\/code> directory and then attempt to run from <code>\/tmp<\/code>. A crafty way to prevent this is to mount the <code>\/tmp<\/code> directory on a separate partition with the <code>noexec<\/code>, <code>nodev<\/code>, and <code>nosuid<\/code> options enabled. This prevents binaries from being executed under <code>\/tmp<\/code>, disables any binary to be <em>suid<\/em> root, and disables any block or character devices from being created under <code>\/tmp<\/code>.<\/p>\n<p>Edit <code>\/etc\/fstab<\/code> with your favorite editor, find the line corresponding to <code>\/tmp<\/code> and change it to look like this one.<\/p>\n<div>\n<pre> \r\n\r\n  \/dev\/hda2  \/tmp  ext3  nodev,nosuid, noexec  0  0<\/pre>\n<\/div>\n<p>Wikipedia [6] defines rootkits as a set of software tools frequently used by a third party (usually an intruder) after gaining access to a computer system. This translates to custom versions of <code>ps<\/code> that won\u2019t list the irc server the attacker installed, or a custom version of <code>ls<\/code> that doesn\u2019t show certain files. Tools like <code>chkrootkit<\/code> must be run in combination with IDS systems like <code>fcheck<\/code> to prevent the successful deployment of rootkits.<\/p>\n<p><code>chkrootkit<\/code> is very simple to run, and doesn\u2019t require any installation or configuration.<\/p>\n<p>It\u2019s a good idea to run <code>chkrootkit<\/code> at regular intervals, see the script below used by <code>fcheck<\/code> for inspiration.<\/p>\n<div>\n<pre> # Use the wget utility to download the latest\r\n # version of chkrootkit\r\n\r\n wget ftp:\/\/ftp.pangeia.com.br\/pub\/seg\/pac\/chkrootkit.tar.gz\r\n tar -xzvf chkrootkit.tar.gz\r\n cd chkrootkit-version (whatever version is)\r\n .\/chkrootkit<\/pre>\n<\/div>\n<p>The next layer of file system security is maintaining and verifying the integrity of configuration files that are typically located under <code>\/etc<\/code>. Intrusion Detection Systems (IDS) allow us to create cryptographic identifiers of important configuration files and store them in a database. They are then periodically re-created and verified against those stored in the database. If there is a mis-match, the file has been changed, you know your system integrity has been violated and which aspects of it are affected. Two well known IDS packages are <code>tripwire<\/code> and <code>fcheck<\/code>, which work equally well. However, <code>fcheck<\/code> has a much simpler configuration and installation process, which is why I favored it for this article.<\/p>\n<h2>fcheck<\/h2>\n<p>Download <code>fcheck<\/code> (see resources) and unpack it. <code>fcheck<\/code> is a cross-platform <em>Perl<\/em> script which runs on UNIX and Windows systems (as long as they have Perl installed).<\/p>\n<div>\n<pre>  $mkdir \/usr\/local\/fcheck\r\n  $cp fcheck \/usr\/local\/fcheck\r\n  $cp fcheck.cfg \/usr\/local\/fcheck<\/pre>\n<\/div>\n<p>Edit <code>\/usr\/local\/fcheck\/fcheck.cfg<\/code> with your favorite editor and change the following values: <code>Directory<\/code>, <code>FileTyper<\/code>, <code>Database<\/code>, <code>Logger<\/code>, <code>TimeZone<\/code>, and <code>Signature<\/code>.<\/p>\n<div>\n<pre>  # Directories that will be monitored\r\n  # if there is a trailing \/ it will be recursive \r\n\r\n  Directory       = \/etc\/\r\n  Directory       = \/bin\/\r\n  Directory       = \/sbin\/\r\n  Directory       = \/lib\/\r\n  Directory       = \/usr\/bin\/\r\n  Directory       = \/usr\/sbin\/\r\n  Directory       = \/usr\/lib\/\r\n  TimeZone        = PST8PDT # For Pacific Standard\r\n\r\n  # Database of file signatures\r\n\r\n  DataBase        = \/usr\/local\/fcheck\/sol.dbf\r\n  Logger          = \/usr\/bin\/logger -t fcheck\r\n\r\n  # Utility to determin file type\r\n  FileTyper       = \/bin\/file \r\n\r\n  # What to use to create signatures Database of \r\n  # file signatures\r\n\r\n  $Signature      = \/usr\/bin\/md5sum#\r\n  DataBase        = \/usr\/local\/fcheck\/sol.dbf\r\n  Logger          = \/usr\/bin\/logger -tfcheck\r\n\r\n  # Utility to determin file type\r\n\r\n  FileTyper       = \/bin\/file<\/pre>\n<\/div>\n<p>Also edit the <code>fcheck<\/code> script and change the path of the configuration file to <code>\/usr\/local\/fcheck\/fcheck.cfg<\/code><\/p>\n<p>Then run <code>fcheck<\/code> for the first time to create the baseline database.<\/p>\n<div>\n<pre># Options explained:\r\n# c create the database\r\n# a is for all\r\n# d is to monitor directory creation \r\n# s is to create signatures for all files\r\n# x is for extended permissions monitoring\r\n\r\n$ .\/fcheck -cadsx<\/pre>\n<\/div>\n<p>To test that everything has been setup correctly run the following commands and <code>fcheck<\/code> should alert you to the difference.<\/p>\n<div>\n<pre>$ touch \/etc\/FOO \r\n$ .\/fcheck -adsx<\/pre>\n<\/div>\n<p><code>fcheck<\/code> should display some information about <code>\/etc\/FOO<\/code>. <code>$rm \/etc\/FOO<\/code> will prevent future messages.<\/p>\n<p>Next, create a short shell script that will be run periodically by <code>cron<\/code> and check for changes. Open your favorite editor and create <code>\/usr\/local\/bin\/fcheck_script<\/code>.<\/p>\n<p align=\"center\"><strong>When using the `cron` utility lookout for _symlink attacks_<\/strong><\/p>\n<div>\n<pre>  #!\/bin\/bash\r\n\r\n  # Use mktemp instead of $$ to prevent sym-link attacks\r\n  FCHECK_LOG=`mktemp`\r\n\r\n  # Grep for any changes  \r\n  \/usr\/local\/fcheck\/fcheck -adsx  \\ \r\n  | grep -Ev ^PROGRESS: |^STATUS:^$ &gt; $FCHECK_LOG\r\n\r\n  # If there were any changes email the sys-admin\r\n  if [-s $FCHECK_LOG ] then\r\n      \/usr\/bin\/mail -s fcheck \\\r\n      `hostname` youremail@yourprovider.com  &lt; \\\r\n       $FCHECK_LOG\r\n      \/bin\/rm $FCHECK_LOG\r\n  fi<\/pre>\n<\/div>\n<p>The <code>cron<\/code> utility will be used to run periodic checks of the file-system and will compare it to the baseline database. The following command will edit root\u2019s <em>crontab<\/em>:<\/p>\n<div>\n<pre>$ crontab -e\r\n\r\n# Add this line to run the script every 15 minutes \r\n# using nice lower priority when the system load \r\n# is high.\r\n*\/15 * * * * nice \/usr\/local\/bin\/fcheck_script &gt; \\\r\n                          \/dev\/null<\/pre>\n<\/div>\n<h2>Symlink Attacks<\/h2>\n<p>Side Note: Symlink Attacks running an IDS package usually involve running a script at a pre-configured time using the cron utility. This opens up systems to symlink attacks. Symlink Attacks rely on the attacker knowing that a certain file is going to be created at a certain time with a certain name. A common shell scripting technique that generates some randomness is the use of $$, which is the <em>PID<\/em> of the running script. However, this is vulnerable to Symlink Attacks because most PIDs are below 35K and most file systems can have 35K files. The correct technique is the use of <code>mktemp<\/code>, which is a truly random file name.<\/p>\n<h1>Install and configure common services<\/h1>\n<p>At this stage, you should have a solid base to build upon. The next step is to compile and install the software servers you will use to serve up your web applications. Installing software from source can be tedious; and there is a great temptation to use the packaged binaries that come with your distribution of choice. I would recommend against this. In a world of zero day exploits, the time it takes the package maintainer to compile and distribute the binaries may be unacceptable. By compiling from the source, you will be in full control of your security situation.<\/p>\n<h2>Apache 2.2.0<\/h2>\n<p>Now to start compiling and install the services you will be using. <em>Apache<\/em> is a good place to start, since other packages have compile time dependencies on it.<\/p>\n<p align=\"center\"><strong>Always verify the `checksums` of packages you download, if there is a mismatch start over and download it again<\/strong><\/p>\n<div>\n<pre>    md5sum httpd-2.2.0.tar.gz  \r\n    tar -xzvf httpd-2.2.0.tar.gz \r\n    .\/configure --prefix=\/usr\/local\/apache \\\r\n           --enable-ssl --enable-speling \\ \r\n           --enable-rewrite --enable-proxy  \r\n    make  \r\n    make install<\/pre>\n<\/div>\n<h2>MySQL 5.0.18<\/h2>\n<p>Download the <em>MySQL<\/em> binaries from the mysql site (see resources). This is an exception to my mantra of compiling from source\u2014since the binaries come directly from <em>MySQL<\/em>, as soon as there is an update you can download the latest version.<\/p>\n<p>Note: due to space constraints {.} is shorthand for the version of the tarball.<\/p>\n<div>\n<pre>  md5sum mysql-{.}-linux-i686-glibc23.tar.gz\r\n  cp mysql-{.}-linux-i686-glibc23.tar.gz \/usr\/local\r\n  tar -xzvf mysql-{.}-linux-i686-glibc23.tar.gz\r\n  ln -s \/usr\/local\/mysql-{.}-linux-i686-glibc23 \\\r\n                                   \/usr\/local\/mysql\r\n\r\n  groupadd mysql\r\n  useradd -g mysql mysql\r\n  cd mysql\r\n  scripts\/mysql_install_db --user=mysql\r\n  chown -R root  .\r\n  chown -R mysql data\r\n  chgrp -R mysql .\r\n  bin\/mysqld_safe --user=mysql &amp;\r\n  cp  support-files\/mysql.server \/etc\/init.d\/mysql\r\n\r\n  # Make sure that mysql is started if \r\n  # there is a reboot\r\n\r\n  cd \/etc\/rc3.d\/\r\n  ln -s \/etc\/init.d\/mysql S90mysql\r\n  ln -s \/etc\/init.d\/mysql K90mysql\r\n\r\n  # Copy the configuration file\r\n  cp support-files\/my-medium.cnf \/etc\/my.cnf<\/pre>\n<\/div>\n<h2>PHP 5.1.2<\/h2>\n<p>Now download the <em>php<\/em> package from the php.net site (see resources).<\/p>\n<div>\n<pre>  md5sum php-5.1.2.tar.gz\r\n  tar -xzvf php-5.1.2.tar.gz\r\n  .\/configure --with-prefix=\/usr\/local\/php \\ \r\n      --with-apxs2=\/usr\/local\/apache\/bin\/apxs \\\r\n      --with-mysql=\/usr\/local\/mysql\r\n  make\r\n  make install\r\n  cp php.ini-dist \/usr\/local\/php\/php.ini<\/pre>\n<\/div>\n<h2>Tomcat 5.5.16<\/h2>\n<p><em>Apache-Tomcat<\/em> is also an exception to my always compile rule.<\/p>\n<div>\n<pre>  md5sum apache-tomcat-5.5.16.tar.gz\r\n  tar -xzvf apache-tomcat-5.5.16.tar.gz<\/pre>\n<\/div>\n<h2>mod_jk<\/h2>\n<p>Download <code>mod_jk<\/code> from the the tomcat project page (see resources).<\/p>\n<div>\n<pre>  tar -xzvf jakarta-tomcat-connectors.tar.gz\r\n  cd jakarta\/jk\/native\r\n  .\/configure --with-apxs=\/usr\/local\/apache\/bin\/apxs\r\n  make\r\n  make install<\/pre>\n<\/div>\n<h2>mod_security<\/h2>\n<p><code>mod_security<\/code> is the most excellent Apache module written by Ivan Ristic.<\/p>\n<div>\n<pre>  md5sum modsecurity-apache-1.9.2.tar.gz\r\n  tar -xzvf modsecurity-apache-1.9.2.tar.gz\r\n  cd modsecurity-apache-1.9.2\/apache2\r\n  \/usr\/local\/apache\/bin\/apxs -cia mod_security.c<\/pre>\n<\/div>\n<h2>Configuring Apache 2.2.0<\/h2>\n<p>By this point, you should have installed all of the services and apache modules needed to host and secure PHP and Java environments. Now it\u2019s time to take a look at properly configuring everything for security.<\/p>\n<p align=\"center\"><strong>_Apache 2.2.0_ has the ability to list both statically compiled and shared modules with the `-M` option to `apachectl`<\/strong><\/p>\n<p><em>Apache 2.2.0<\/em> introduces a new configuration layout and new default options in the <code>httpd.conf<\/code> file. In previous versions of Apache, there was only one configuration file by default, which was <code>conf\/httpd.conf<\/code>; in the current version, the Apache project has taken another step towards its goal of making configuration more managable and modular. The <code>conf\/httpd.conf<\/code> is the main configuration file with include statements for the various configuration files under <code>conf\/extra<\/code> such as <code>httpd-ssl.conf<\/code> and <code>httpd-vhosts.conf<\/code>.<\/p>\n<p>Another new and exciting security feature in <em>Apache 2.2.0<\/em> is that the root <code>httpd.conf<\/code> access is denied to all directories. This can be confusing to users coming from previous versions such as 2.0.55 but it is a great step forward in terms of security.<\/p>\n<p>Here is the configuration directive mentioned above; I would suggest leaving it the way it is. We will allow access for specific virtual-hosts and directories later on.<\/p>\n<div>\n<pre>  # Default access control  \\\r\n  # Highly restrictive and applies \\\r\n  # to everything below it.\r\n\r\n  &lt;Directory \/&gt;\r\n    Options FollowSymLinks\r\n    AllowOverride None\r\n    Order deny,allow\r\n    Deny from all\r\n  &lt;\/Directory&gt;<\/pre>\n<\/div>\n<p>Every host, which Apache will be responsible for, will be a virtual host or \u201cvhost\u201d. So, start by uncommenting the <code>Include<\/code> directives at the bottom of <code>conf\/httpd.conf<\/code>. This is done so that the <code>httpd-vhosts.conf<\/code>, <code>httpd-ssl.conf<\/code> and <code>httpd-dedfault.conf<\/code> are included in the main <code>httpd.conf<\/code> configuration file.<\/p>\n<p>Yet another cool new feature in <em>Apache 2.2.0<\/em> is the ability to see all modules both statically compiled and shared with the <code>-M<\/code> option to <code>apachectl<\/code>.<\/p>\n<div>\n<pre>  # Edit \/usr\/local\/apache\/conf\/httpd.conf\r\n\r\n  # Move the LoadModule Statement for mod_security \r\n  # to the top of all module\r\n  # statements. This is needed to use SecChrootDir\r\n\r\n  # Add the following line to load mod_jk\r\n   LoadModule jk_module   modules\/mod_jk.so\r\n\r\n  # The default User and Group is set to daemon, \r\n  # create and apache user and group and then \r\n  # configure apache to run as such.\r\n  User apache\r\n  Group apache\r\n\r\n  # List all modules to verify that mod_jk, \r\n  # mod_security, mod_php, and mod_ssl \r\n  # are correctly installed and loaded.\r\n   \/usr\/local\/apache\/bin\/apachectl -M \r\n\r\n  # Virtual hosts \r\n\r\n  Include conf\/extra\/httpd-vhosts.conf \\\r\n  -&gt; Include conf\/extra\/httpd-vhosts.conf \r\n\r\n  # Various default settings\r\n  Include conf\/extra\/httpd-default.conf \\\r\n  -&gt; Include conf\/extra\/httpd-default.conf \r\n\r\n  # Secure (SSL\/TLS) connections\r\n   Include conf\/extra\/httpd-ssl.conf \\\r\n  -&gt; Include conf\/extra\/httpd-ssl.conf<\/pre>\n<\/div>\n<p>Now it\u2019s time to descend into the extra directory to configure virtual hosts. Open <code>httpd-vhosts.conf<\/code> in your favorite editor. Next, configure the document root to be <code>\/srv\/www\/vhost1<\/code>. Also, add the <code>AddType<\/code> directive for <em>php<\/em>. <em>PHP<\/em> files don\u2019t have to have the <code>.php<\/code> file extension. In fact, it\u2019s probably a good idea if they are <code>.html<\/code> files. By using the <code>.php<\/code> file extention you are advertizing more information about your setup than you need to.<\/p>\n<p align=\"center\"><strong>`mod_security` makes `chrooting` Apache easy!<\/strong><\/p>\n<p>Here is the full vhost configuration stanza. It is annotated with inline comments: please take the time to read through it.<\/p>\n<div>\n<pre>  # Enable mod_security engine\r\n  SecFilterEngine On\r\n\r\n  # Chroot Apache the easy way just make sure \r\n  # your web content is under the chrooted directory\r\n\r\n  # Note: The log directives must also be valid \r\n  # directories releative to the chroot dir.\r\n\r\n  # Note: THIS CANNOT GO INSIDE VHOST STANZA\r\n  # as it applies to the entire apache configuration\r\n  SecChrootDir \/chroot\/apache\r\n\r\n  # Delete the 2nd Vhost stanza as you will only be \r\n  # using one for now\r\n  &lt;VirtualHost *:80&gt;\r\n    ServerAdmin webmaster@mydomain.com\r\n    DocumentRoot \/srv\/www\/vhost1\r\n    ServerName vhost.mydomain.com\r\n    ServerAlias www.mydomain.com\r\n    ErrorLog logs\/vhost.mydomain.com-error_log\r\n    CustomLog logs\/vhost.mydomain.com-access_log \\ \r\n                        common\r\n\r\n    # The PHP engine will interpret all \r\n    # .php and .html files for php code\r\n    AddType application\/x-httpd-php .php .phtml \\ \r\n                         .html\r\n\r\n    AddType application\/x-httpd-php-source .phps\r\n\r\n    # Add a local Directory directive to override \r\n    # the global Deny From all in conf\/httpd.conf\r\n    &lt;Directory \/&gt;\r\n      Options FollowSymLinks\r\n      AllowOverride None\r\n      Order deny,allow\r\n      Allow from all\r\n    &lt;\/Directory&gt;\r\n\r\n    # Restrict Access to sensitive files\r\n    &lt;FilesMatch \"\\.(inc|txt|tar|gz|zip)$\"&gt;\r\n      Deny from all\r\n    &lt;\/FilesMatch&gt;\r\n\r\n    # Configure MOD_JK\r\n    JkWorkersFile \\\r\n             \"\/usr\/local\/apache\/conf\/workers.properties\"\r\n    JkLogFile \\\r\n               \"\/usr\/local\/apache2\/logs\/mod_jk_www.log\"\r\n    JkLogLevel info\r\n    JkLogStampFormat \"[%a %b %d %H:%M:%S %Y] \"\r\n    JkOptions +ForwardKeySize +ForwardURICompat \\ \r\n                                    -ForwardDirectories\r\n    JkRequestLogFormat \"%w %V %T\"\r\n\r\n    # Any URL that begins with \/java\/ will be \r\n    # forwarded to the java webapp in tomcat\r\n    JkMount \/java\/* ajp13\r\n\r\n    # Enable and configure MOD_SECURITY\r\n\r\n    # See the mod_security documentation \r\n    # link in resources [3]\r\n\r\n    # POST Scanning is disabled by default\r\n    SecFilterScanPOST On\r\n\r\n    # Make sure only content with standard \r\n    # encoding types is accepted\r\n    SecFilterSelective HTTP_Content-Type \\\r\n\r\n    \"!(^$|^application\/x-www-form-urlencoded$|^multipart\/form-data;)\"\r\n\r\n    # Default Action is to reject request, log, and\r\n    # then return HTTP Response 404 which is \r\n    # File Not Found. \r\n    # Another option would be 403 which is access\r\n    # denied.\r\n    SecFilterDefaultAction \"deny,log,status:404\"\r\n\r\n    # Enable URLEncoding validation. This can \r\n    # prevent Cross-Site Scripting attacks \r\n    SecFilterCheckURLEncoding On\r\n\r\n    # Catch and Prevent PHP Fatal Errors from \r\n    # being displayed to the USER\r\n    SecFilterSelective OUTPUT \"Fatal error:\" \\\r\n                    deny,status:500\r\n\r\n    # Obviously you have to code up this custom \r\n    # Error Page\r\n    ErrorDocument 500 \/php-fatal-error.html \r\n\r\n    # This can be useful to avoid stack overflow \r\n    # attacks default is 0 255 ie All bytes allowed\r\n    SecFilterForceByteRange 32 126\r\n\r\n    &lt;\/VirtualHost&gt;<\/pre>\n<\/div>\n<p>Here is the <code>mod_jk<\/code> configuration file <code>apache\/conf\/workers.properties<\/code> (referenced above):<\/p>\n<div>\n<pre>  worker.list=ajp13\r\n  workers.tomcat_home= \\\r\n        \/usr\/local\/java\/apache-tomcat-5.5.12\r\n\r\n  workers.java_home=\/usr\/local\/java\/jdk1.5.0_06\r\n  worker.ajp13.type=ajp13\r\n  worker.ajp13.host=localhost\r\n  worker.ajp13.port=8009<\/pre>\n<\/div>\n<p align=\"center\"><strong>Apache can be used to configure other web consoles such as the Tomcat Manager application<\/strong><\/p>\n<p>The configuration stanza below is a variation on an article:<\/p>\n<div>\n<pre>&lt;VirtualHost *:80&gt;\r\n  ServerAdmin webmaster@zero-analog.com\r\n  DocumentRoot \/srv\/www\/hercules.zero-analog.com\r\n  ServerName hercules.zero-analog.com\r\n  ErrorLog logs\/hercules.zero-analog-error_log\r\n  CustomLog logs\/hercules.zero-analog-access_log \\\r\n                                             common\r\n\r\n  &lt;Directory \/&gt;\r\n      Options FollowSymLinks\r\n      AllowOverride None\r\n      Order deny,allow\r\n  &lt;\/Directory&gt;\r\n\r\n  &lt;FilesMatch \"\\.(inc|txt|tar|gz|zip)$\"&gt;\r\n      Deny from all\r\n  &lt;\/FilesMatch&gt;\r\n\r\n  # This whole stanza is really to forward http \r\n  # requests to https:\/\/ tomcat manager\r\n  # so appended \/html to the rewrite target. \r\n  # since the full path is manager\/html \r\n\r\n  &lt;IfModule mod_rewrite.c&gt;\r\n   &lt;IfModule mod_ssl.c&gt;\r\n       &lt;Location \/manager&gt;\r\n         RewriteEngine on\r\n         RewriteCond %{HTTPS} !^on$ [NC]\r\n         RewriteRule . \\\r\n          https:\/\/%{HTTP_HOST}%{REQUEST_URI}\/html \\\r\n                                [L]\r\n        &lt;\/Location&gt;\r\n   &lt;\/IfModule&gt;\r\n  &lt;\/IfModule&gt;\r\n\r\n&lt;\/VirtualHost&gt;\r\n\r\n# This is the ssl-vhost under extra\/httpd-ssl.conf \r\n\r\n&lt;VirtualHost _default_:443&gt;\r\n  # General setup for the virtual host\r\n  DocumentRoot \"\/srv\/www\/outpost.zero-analog.com\"\r\n  ServerName hercules.zero-analog.com:443\r\n  ServerAdmin webmaster@zero-analog.com\r\n\r\n  ErrorLog \/usr\/local\/apache2\/logs\/error_log\r\n  TransferLog \/usr\/local\/apache2\/logs\/access_log\r\n\r\n  &lt;Directory \/&gt;\r\n    Options FollowSymLinks\r\n    AllowOverride None\r\n    Order deny,allow\r\n  &lt;\/Directory&gt;\r\n\r\n  RewriteEngine on\r\n  RewriteRule \"^\/manager$\" \\\r\n    \"https:\/\/outpost.zero-analog.com\/manager\/html\" \\\r\n                                               [R,L]\r\n\r\n   JkWorkersFile \\\r\n       \"\/usr\/local\/apache2\/conf\/workers.properties\"\r\n   JkLogFile \\\r\n       \"\/usr\/local\/apache2\/logs\/mod_jk_hercules.log\"\r\n   JkLogLevel info\r\n   JkLogStampFormat \"[%a %b %d %H:%M:%S %Y] \"\r\n   JkOptions +ForwardKeySize +ForwardURICompat \\\r\n                             -ForwardDirectories\r\n   JkRequestLogFormat \"%w %V %T\"\r\n   JkMount \/manager\/* ajp13\r\n\r\n   #   Enable\/Disable SSL for this virtual host.\r\n   SSLEngine on\r\n\r\n   # List the ciphers that the client is permitted \r\n   # to negotiate. See the mod_ssl documentation\r\n   # for a complete list.\r\n   SSLCipherSuite  ALL:!ADH:!EXPORT56:RC4+RSA: \\ \r\n         +HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL\r\n\r\n   # Server Certificate: Point SSLCertificateFile\r\n   # at a PEM encoded certificate.\r\n\r\n   SSLCertificateFile \\ \r\n                \/usr\/local\/apache\/conf\/server.crt\r\n\r\n   # Server Private Key:\r\n   SSLCertificateKeyFile \\ \r\n                \/usr\/local\/apache\/conf\/server.key\r\n\r\n   SSLOptions +FakeBasicAuth \\\r\n              +ExportCertData \\\r\n              +StrictRequire\r\n\r\n   &lt;FilesMatch \"\\.(cgi|shtml|phtml|php)$\"&gt;\r\n           SSLOptions +StdEnvVars\r\n   &lt;\/FilesMatch&gt;\r\n\r\n   &lt;Directory \"\/usr\/local\/apache2\/cgi-bin\"&gt;\r\n           SSLOptions +StdEnvVars\r\n   &lt;\/Directory&gt;\r\n\r\n   BrowserMatch \".*MSIE.*\" \\\r\n           nokeepalive ssl-unclean-shutdown \\\r\n            downgrade-1.0 force-response-1.0\r\n\r\n   # Per-Server Logging:\r\n   # The home of a custom SSL log file. \r\n   # Use this when you want a compact non-error \r\n   # SSL logfile on a virtual host basis.\r\n\r\n   # *** Note there are \\ characters in this \r\n   # string. These are not my artificial line-\r\n   # breaks, please include them ***\r\n\r\n   CustomLog \/usr\/local\/apache2\/logs\/ssl_request_log \r\n             %t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \\\"%r\\\" %b\"\r\n\r\n&lt;\/VirtualHost&gt;<\/pre>\n<\/div>\n<h2>Configuring PHP<\/h2>\n<p>I have already copied the <code>php.ini<\/code> to <code>\/usr\/local\/php\/php.ini<\/code> so that it will be read by the <em>PHP<\/em> engine at startup. By default it\u2019s fairly secure, but there are one or two things you can do to improve security.<\/p>\n<p align=\"center\"><strong>Disable PHP display_errors for security<\/strong><\/p>\n<div>\n<pre>  # Edit \/usr\/local\/php\/php.ini with your \r\n  # favorite editor\r\n\r\n  # Since you're are going through the trouble of \r\n  # hiding PHP files you might as well disable \r\n  # this as well\r\n   expose_php = On -&gt; expose_php = Off \r\n\r\n  # You really don't want users, or worse yet \r\n  # an attacker to see error messages\r\n   display_errors = On -&gt; \\\r\n      display_erros = Off \r\n\r\n  # But you do want them logged \\\r\n   log_errors = Off -&gt; log_errors = On \r\n\r\n  # Log to a file\r\n  ;error_log = filename -&gt; \\\r\n       error_log = \/var\/log\/php-err<\/pre>\n<\/div>\n<p>Another option to consider is the <em>Hardened-PHP project<\/em> (see resources section). This is the brain child of three German developers, who continously perform code audits of popular PHP applications. They also release a patch for the standard PHP code, which fixes bugs and security holes in fringe configuration cases, where the main project developers have not had the time or the desire to find a fix.<\/p>\n<h2>Configuring Tomcat<\/h2>\n<p>The main configuration files from Tomcat are under <code>$CATALINA_HOME\/conf<\/code>. The following files are of interest:<\/p>\n<ul>\n<li>tomcat-users.xml<\/li>\n<li>server.xml<\/li>\n<li>web.xml<\/li>\n<\/ul>\n<p>As you might have guessed, the <code>tomcat-users.xml<\/code> file contains user access information. It is important to create a custom user with a hard-to-guess password for the manager application.<\/p>\n<div>\n<pre>  # Edit tomcat-users.xml with your favorite \r\n  # editor and append the following line.\r\n\r\n  &lt;user username=\"bob\" password=\"subGen1us\" \\\r\n        roles=\"admin,manager,tomcat,role1\"\/&gt;<\/pre>\n<\/div>\n<p>Another important tenet of security is preventing information leakage. That\u2019s why you enable PHP pages to masquerade as html files. It\u2019s also why you want to disable directory listings in Tomcat. This is achieved by editing the <code>tomcat\/conf\/web.xml<\/code> file.<\/p>\n<div>\n<pre>  # Open web.xml in your favorite editor and \r\n  # look for the following lines:\r\n\r\n  &lt;init-param&gt;\r\n    &lt;param-name&gt;listings&lt;\/param-name&gt;\r\n    &lt;param-value&gt;false&lt;\/param-value&gt;\r\n  &lt;\/init-param&gt; \r\n\r\n  # The default value is true, which enables \r\n  # directory listings, simply change this to false\r\n  # to prevent tomcat directory listings.<\/pre>\n<\/div>\n<p>You can also hide JSP files by using a <code>servlet-mapping<\/code> directive in the webapps <code>web.xml<\/code> configuration file. The following lines will map all html files to the JSP servlet, which is internal to Tomcat.<\/p>\n<p>Note: The listing above goes in the main <code>tomcat\/conf\/web.xml<\/code>, while this listing should go in the <code>web.xml<\/code> of each application. You can put it in the main <code>web.xml<\/code>. However, there may be cases where this is undesirable.<\/p>\n<div>\n<pre>  &lt;servlet-mapping&gt;\r\n    &lt;servlet-name&gt;jsp&lt;\/servlet-name&gt;\r\n      &lt;url-pattern&gt;*.html&lt;\/url-pattern&gt;\r\n  &lt;\/servlet-mapping&gt;<\/pre>\n<\/div>\n<p>I want to restrict access to <code>apache-tomcat<\/code> to control the flow through Apache. <code>iptables<\/code> is already blocking port 8080 by default, but following the onion principle I\u2019m going to bound Tomcat to loop-back device. This will prevent direct traffic to Tomcat in case of any unforeseen circumstances such as the <code>iptables<\/code> rules being flushed.<\/p>\n<div>\n<pre> # Open sever.xml in your favorite editor \r\n # and look for the following lines:\r\n\r\n &lt;Connector port=\"8080\" maxHttpHeaderSize=\"8192\"\r\n   maxThreads=\"150\" minSpareThreads=\"25\" \r\n   maxSpareThreads=\"75\" enableLookups=\"false\" \r\n   redirectPort=\"8443\" acceptCount=\"100\"\r\n   connectionTimeout=\"20000\" \r\n   disableUploadTimeout=\"true\" \/&gt;\r\n\r\n # And change to this:\r\n\r\n  &lt;Connector port=\"8080\" maxHttpHeaderSize=\"8192\" \r\n     address=\"127.0.0.1\" maxThreads=\"150\" \r\n     minSpareThreads=\"25\" maxSpareThreads=\"75\"\r\n     enableLookups=\"false\" redirectPort=\"8443\" \r\n     acceptCount=\"100\"  connectionTimeout=\"20000\" \r\n     disableUploadTimeout=\"true\" \/&gt;<\/pre>\n<\/div>\n<h2>Configuring MySQL<\/h2>\n<p>The default MySQL installation is not very secure. This is the case when it is installed manually and also when you use your distribution\u2019s precompiled binaries. The default root password is blank, which means anyone can login is as the DBA. This is understandable, as, obviously, a DBA has to login to set the password. However, it\u2019s too easy to forget that anyone can login as the MySQL root user and anonymous users are also enabled by default.<\/p>\n<div>\n<pre># Set the root password\r\nmysqladmin -u root -h localhost password subGen1us \r\n\r\n# Once this is done, log in as the root user and \r\n# disable anonymous accounts\r\nmysql -u root -p\r\n\r\n# Drop the test database which comes installed \r\n# by default\r\nmysql&gt; drop database test;\r\n\r\n# Disable anonymous accounts\r\nmysql&gt; use mysql;\r\n\r\nmysql&gt; delete from db where User=\u2019\u2019;\r\nmysql&gt; delete from user where User=\u2019\u2019;\r\n\r\n# Change DBA NAME\r\nmysql&gt; update user set user=\"mydbadmin\" \\ \r\n          where user=\"root\";\r\n\r\nmysql&gt; flush privileges;\r\n\r\n# Make sure to login again to make sure \r\n# all the changes work\r\n\r\nmysql -u mydbadmin -p\r\npassword: subGen1us\r\n\r\n# Configure \/etc\/my.cnf for security Uncomment \r\n# the following line to disable TCP connections \r\n# to mysql.  As with tomcat this prevents remote \r\n# connections event in the even of the firewall\r\n# even in the even of the firewall rules being \r\n# flushed.\r\n\r\nskip-networking<\/pre>\n<\/div>\n<h1>Security mistakes in web applications<\/h1>\n<p>Now that you are done with configuration, it\u2019s time to put your web developer hat on. You now have a very solid base upon which to build your web applications. This brings me to the Achilles heal: the web applications themselves.<\/p>\n<h2>What is Cross Site Scripting (XSS)?<\/h2>\n<p>Wikipedia [4] defines the term Cross Site Scripting as inaccurate as it really refers to an entire class of vulnerabilities. In general XSS vulnerabilities come down to an age old security problem: not verifying user input. The most common vector of attack is when data is passed to a processing program such as a PHP or JSP script, and then printed back out to the page without being URLEncoded.<\/p>\n<p>The following (highly contrived) PHP code is vulnerable to XSS. If the database to this PHP script contains javascript, it will be executed.<\/p>\n<p align=\"center\"><strong>Never trust user input, it is the root of all evil<\/strong><\/p>\n<div>\n<pre>        # Vulnerable Code\r\n        &lt;?php\r\n                $userInput = $_GET['input'];\r\n                print $userInput;\r\n        ?&gt;\r\n\r\n        # Secure Code\r\n        &lt;?php \r\n            $userInput = urlencode($_GET['input']);\r\n            print $userInput;\r\n        ?&gt;<\/pre>\n<\/div>\n<p>JSP\u2019s or Java Servlets are no less vulnerable. First of all, it is important to understand that all JSP\u2019s are compiled to servlets the first time a JSP is called. So, the two are basically the same thing, with different source code representations.<\/p>\n<p>Here is the same vulnerability in the Java world. Note: JSP\u2019s have access to the same <code>HttpServletRequest<\/code> object as the servlets they are compiled to. So, in a JSP page, this would manifest itself as <code>request.getParameter()<\/code>.<\/p>\n<div>\n<pre>        \r\n  # Vulnerable Code\r\n  public class myServlet extends HttpServlet {\r\n    public static void doGet \r\n              (HttpServletRequest req, \r\n               HttpServletResponse res) {\r\n\r\n     \/\/ Get User Input       \r\n     String userInput = req.getParameter(\"input\");\r\n\r\n     \/\/ Print User Input to page\r\n     PrintWriter out = response.getWriter();\r\n     out.write(\"&lt;html&gt;\");\r\n     out.write(userInput);\r\n     out.write(\"&lt;\/html&gt;\");\r\n\r\n   }\r\n  }\r\n\r\n  # Secure Code\r\n  import java.net.URLEncoder;\r\n  public class myServlet extends HttpServlet {\r\n    public static void doGet \r\n              (HttpServletRequest req, \r\n               HttpServletResponse res) {\r\n\r\n       \/\/ Get User Input       \r\n       String userInput = req.getParameter(\"input\");\r\n       \/\/ URLEncode Input\r\n       userInput = \r\n            URLEncoder.encode(userInput, \"UTF-8\"); \r\n\r\n       \/\/ Print User Input to page\r\n       PrintWriter out = response.getWriter();\r\n       out.write(\"&lt;html&gt;\");\r\n       out.write(userInput);\r\n       out.write(\"&lt;\/html&gt;\");\r\n\r\n   }\r\n  }<\/pre>\n<\/div>\n<h2>What is SQL Injection?<\/h2>\n<p>SQL Injection is the ability to insert and execute arbitrary SQL code through a web-application. Like XSS attacks, it involves mishandling user input. In this case, properly escaping the input that is to become part of the SQL query. The PHP solution is to use the <code>mysql_real_escape_string<\/code> statement, and the java solution is to use <code>PreparedStatements<\/code>, with the user input as bind variables.<\/p>\n<p>The following code snippets are from Wikipedia [5]:<\/p>\n<div>\n<pre>  # Partial PHP\r\n  $query_result = mysql_query\r\n   ( \"select * from users where name = \\\"\"\r\n       .\r\n      mysql_real_escape_string($user_name)\r\n       .\r\n      \"\\\"\" );\r\n\r\n  # Partial Java, ? is the bind variable\r\n  Connection con = (acquire Connection)\r\n\r\n  PreparedStatement pstmt = \r\n    con.prepareStatement\r\n       (\"SELECT * FROM users WHERE name = ?\");\r\n\r\n  pstmt.setString(1, userInput);\r\n  ResultSet rset = pstmt.executeQuery()<\/pre>\n<\/div>\n<h1>Conclusion<\/h1>\n<p>There is no magic bullet. \u201cConclusion\u201d is a misleading heading: there is no conclusion when it comes to security. Security holes are constantly found and patched. Attackers change their methods, and security professionals respond; it is a process, rather than a result. When it&#8217;s implemented correctly, this process can mitigate or prevent the damage done by attacks.<\/p>\n<p>There is a silver lining: there is an entire community of security professionals sharing their experience, tips and tricks on the web. Sites like <a href=\"http:\/\/www.securityfocus.com\/\">Securityfocus.com<\/a> provide heaps of useful information, and the latest trends in security. It\u2019s also the home of bugtraq, a mailing list of security holes that I highly recommend you subscribe to. Sites like <a href=\"http:\/\/freshmeat.net\/\">freshmeat.net<\/a> are the yellow pages of free software projects, listing new releases and updates. All of these sites have RSS feeds, a resource I would also recommend you take advantage of to stay abreast of the latest news.<\/p>\n<h2>Resources<\/h2>\n<ul>\n<li><a href=\"http:\/\/www.geocities.com\/fcheck2000\/fcheck.html\">FCheck Main Site<\/a><\/li>\n<li><a href=\"http:\/\/software.newsforge.com\/software\/05\/05\/09\/1846213.shtml\">Useful tools for configuring iptables<\/a><\/li>\n<li><a href=\"http:\/\/www.modsecurity.org\/\">ModSecurity.org Main Site<\/a><\/li>\n<li><a href=\"http:\/\/www.modsecurity.org\/documentation\/modsecurity-apache-manual-1.9.2.html#03-configuration\">ModSecurity Documentation<\/a><\/li>\n<li><a href=\"http:\/\/dev.mysql.com\/downloads\/mysql\/5.0.html\">MySQL Download<\/a><\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Security is a process, not a result. It is a process which is difficult to adopt under normal conditions; the problem is compounded when it spans several job descriptions. All the system level security in the world is rendered useless by insecure web-applications. The converse is also true\u2014programming best practices, such as always verifying user [&#8230;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[12,20],"tags":[],"_links":{"self":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/934"}],"collection":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=934"}],"version-history":[{"count":3,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/934\/revisions"}],"predecessor-version":[{"id":937,"href":"https:\/\/mohan.sg\/index.php?rest_route=\/wp\/v2\/posts\/934\/revisions\/937"}],"wp:attachment":[{"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=934"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=934"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mohan.sg\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=934"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}