Sunday, December 16, 2012

Denial of Service (DoS) attacks

The goal of a Denial of Service (DoS) attack is to disrupt some legitimate activity, such as browsing Web pages, email functionality or the transfer of money from your bank account. It could even shutdown the whole Web server. This denial-of-service effect is achieved by sending messages to the target machine such that the “message” interferes with its operation and makes it hang, crash, reboot, or do useless work.
In a majority of cases, the attacker’s aim is to deprive clients of desired server functionality.
One way to interfere with legitimate operations is to exploit vulnerabilities on the target machine or application, by sending specially crafted requests targeting the given vulnerability (usually done with tools like Metasploit). Another way is to send a vast number of messages, which consume some key resource of the target machine, such as bandwidth, CPU time, memory, etc. The target application, machine, or network spends all of its critical resources on handling the attack traffic, and cannot attend to legitimate clients.
Of course, to generate such a vast number of requests, the attacker must possess a very powerful machine — with a sufficiently fast processor — and a lot of available network bandwidth. For the attack to be successful, it has to overload the target’s resources. This means that an attacker’s machine must be able to generate more traffic than a target, or its network infrastructure, can handle.

Attack scenario

Here is a simple scenario: an attacker sends a large number of requests to a Web server — for example, a website that hosts HD image files at a particular URL, say www.example.com/images/HD_images.html. Let’s also assume that this page contains about 50-60 images. Now, every time a user reloads this page, it consumes a large portion of the Web server’s bandwidth. Now, here, an attacker could design a separate HTML page, with an iframe embedded in it, like what’s shown below:
<html>
    <iframe src=http://www.example.com/images/HD_images.html width=2 height=2></iframe>
</html>
Let’s suppose that instead of a single iframe, the attacker copies and pastes the above code 1,000 times in the same page, and also adds a meta refresh tag as follows:
<html>
    <head>
        <meta http-equiv="refresh" content="2">
    </head>
    <iframe src=http://www.example.com/images/HD_images.html width=2 height=2></iframe>
    <iframe src=http://www.example.com/images/HD_images.html width=2 height=2></iframe>
    :
    :
    : (1000 times)
</html>
Such a page, when loaded, will send the same request 1,000 times every 2 seconds, and will consume a lot of the Web server’s bandwidth. Thus, the target server will not be able to respond to other clients, and eventually, legitimate clients will be denied services from the server.
Now let us assume that an attacker would like to launch a DoS attack on example.com by bombarding it with numerous messages. Also assume that example.com has abundant resources and considerable bandwidth (which is most often the case). It is then difficult for the attackers to generate a sufficient number of messages from a single machine (as in the above scenario) to overload those resources.
However, imagine the consequences if they got 100,000 machines under their control, in order to simultaneously generate requests to example.com. Each of the attacking machines (compromised machines that have been infected by malicious code) may be only moderately provisioned (have a slow processor and be on a mere modem link), but together, they form a formidable attack network — which, with proper use, could overwhelm even a well-provisioned victim site. This is a distributed denial-of-service (DDoS) attack, and the machines under the attacker’s control are termed as zombies/agents.
Other Useful links:
Tools for DOS, DDOS
http://packetstormsecurity.org/distributed/
source: http://www.linuxforu.com/2011/12/cyber-attacks-explained-packet-spoofing/

20 ways to Secure your Apache Configuration

Here are 20 things you can do to make your apache configuration more secure.
Disclaimer: The thing about security is that there are no guarantees or absolutes. These suggestions should make your server a bit tighter, but don't think your server is necessarily secure after following these suggestions.
Additionally some of these suggestions may decrease performance, or cause problems due to your environment. It is up to you to determine if any of the changes I suggest are not compatible with your requirements. In other words proceed at your own risk.

First, make sure you've installed latest security patches

There is no sense in putting locks on the windows, if your door is wide open. As such, if you're not patched up there isn't really much point in continuing any longer on this list. Go ahead and bookmark this page so you can come back later, and patch your server.

Hide the Apache Version number, and other sensitive information.

By default many Apache installations tell the world what version of Apache you're running, what operating system/version you're running, and even what Apache Modules are installed on the server. Attackers can use this information to their advantage when performing an attack. It also sends the message that you have left most defaults alone.
There are two directives that you need to add, or edit in your httpd.conf file:
ServerSignature Off
ServerTokens Prod
The ServerSignature appears on the bottom of pages generated by apache such as 404 pages, directory listings, etc.
The ServerTokens directive is used to determine what Apache will put in the Server HTTP response header. By setting it to Prod it sets the HTTP response header as follows:
Server: Apache
If you're super paranoid you could change this to something other than "Apache" by editing the source code, or by using mod_security (see below).

Make sure apache is running under its own user account and group

Several apache installations have it run as the user nobody. So suppose both Apache, and your mail server were running as nobody an attack through Apache may allow the mail server to also be compromised, and vise versa.
User apache
Group apache

Ensure that files outside the web root are not served

We don't want apache to be able to access any files out side of its web root. So assuming all your web sites are placed under one directory (we will call this /web), you would set it up as follows:
<Directory />
  Order Deny,Allow
  Deny from all
  Options None
  AllowOverride None
</Directory>
<Directory /web>
  Order Allow,Deny
  Allow from all
</Directory>
Note that because we set Options None and AllowOverride None this will turn off all options and overrides for the server. You now have to add them explicitly for each directory that requires an Option or Override.

Turn off directory browsing

You can do this with an Options directive inside a Directory tag. Set Options to either None or -Indexes
Options -Indexes

Turn off server side includes

This is also done with the Options directive inside a Directory tag. Set Options to either None or -Includes
Options -Includes

Turn off CGI execution

If you're not using CGI turn it off with the Options directive inside a Directory tag. Set Options to either None or -ExecCGI
Options -ExecCGI

Don't allow apache to follow symbolic links

This can again can be done using the Options directive inside a Directory tag. Set Options to either None or -FollowSymLinks
Options -FollowSymLinks

Turning off multiple Options

If you want to turn off all Options simply use:
Options None
If you only want to turn off some separate each option with a space in your Options directive:
Options -ExecCGI -FollowSymLinks -Indexes

Turn off support for .htaccess files

This is done in a Directory tag but with the AllowOverride directive. Set it to None.
AllowOverride None
If you require Overrides ensure that they cannot be downloaded, and/or change the name to something other than .htaccess. For example we could change it to .httpdoverride, and block all files that start with .ht from being downloaded as follows:
AccessFileName .httpdoverride
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy All
</Files>

Run mod_security

mod_security is a super handy Apache module written by Ivan Ristic, the author of Apache Security from O'Reilly press.
You can do the following with mod_security:
  • Simple filtering
  • Regular Expression based filtering
  • URL Encoding Validation
  • Unicode Encoding Validation
  • Auditing
  • Null byte attack prevention
  • Upload memory limits
  • Server identity masking
  • Built in Chroot support
  • And more

Disable any unnecessary modules

Apache typically comes with several modules installed. Go through the apache module documentation and learn what each module you have enabled actually does. Many times you will find that you don't need to have the said module enabled.
Look for lines in your httpd.conf that contain LoadModule. To disable the module you can typically just add a # at the beginning of the line. To search for modules run:
grep LoadModule httpd.conf
Here are some modules that are typically enabled but often not needed: mod_imap, mod_include, mod_info, mod_userdir, mod_status, mod_cgi, mod_autoindex.

Make sure only root has read access to apache's config and binaries

This can be done assuming your apache installation is located at /usr/local/apache as follows:
chown -R root:root /usr/local/apache
chmod -R o-rwx /usr/local/apache

Lower the Timeout value

By default the Timeout directive is set to 300 seconds. You can decrease help mitigate the potential effects of a denial of service attack.
Timeout 45

Limiting large requests

Apache has several directives that allow you to limit the size of a request, this can also be useful for mitigating the effects of a denial of service attack.
A good place to start is the LimitRequestBody directive. This directive is set to unlimited by default. If you are allowing file uploads of no larger than 1MB, you could set this setting to something like:
LimitRequestBody 1048576
If you're not allowing file uploads you can set it even smaller.
Some other directives to look at are LimitRequestFields, LimitRequestFieldSize and LimitRequestLine. These directives are set to a reasonable defaults for most servers, but you may want to tweak them to best fit your needs. See the documentation for more info.

Limiting the size of an XML Body

If you're running mod_dav (typically used with subversion) then you may want to limit the max size of an XML request body. The LimitXMLRequestBody directive is only available on Apache 2, and its default value is 1 million bytes (approx 1mb). Many tutorials will have you set this value to 0 which means files of any size may be uploaded, which may be necessary if you're using WebDAV to upload large files, but if you're simply using it for source control, you can probably get away with setting an upper bound, such as 10mb:
LimitXMLRequestBody 10485760

Limiting Concurrency

Apache has several configuration settings that can be used to adjust handling of concurrent requests. The MaxClients is the maximum number of child processes that will be created to serve requests. This may be set too high if your server doesn't have enough memory to handle a large number of concurrent requests.
Other directives such as MaxSpareServers, MaxRequestsPerChild, and on Apache2 ThreadsPerChild, ServerLimit, and MaxSpareThreads are important to adjust to match your operating system, and hardware.

Restricting Access by IP

If you have a resource that should only by accessed by a certain network, or IP address you can enforce this in your apache configuration. For instance if you want to restrict access to your intranet to allow only the 176.16 network:
Order Deny,Allow
Deny from all
Allow from 176.16.0.0/16
Or by IP:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1

Adjusting KeepAlive settings

According to the Apache documentation using HTTP Keep Alive's can improve client performance by as much as 50%, so be careful before changing these settings, you will be trading performance for a slight denial of service mitigation.
KeepAlive's are turned on by default and you should leave them on, but you may consider changing the MaxKeepAliveRequests which defaults to 100, and the KeepAliveTimeout which defaults to 15. Analyze your log files to determine the appropriate values.

Run Apache in a Chroot environment

chroot allows you to run a program in its own isolated jail. This prevents a break in on one service from being able to effect anything else on the server.
It can be fairly tricky to set this up using chroot due to library dependencies. I mentioned above that the mod_security module has built in chroot support. It makes the process as simple as adding a mod_security directive to your configuration:
SecChrootDir /chroot/apache

Path-traversal (a.k.a. directory traversal) attacks

Path Traversal

Web servers are generally set up to restrict public access to a specific portion of the server’s filesystem, typically called the “Web document root” directory. This directory contains files and any scripts that provide Web application functionality.
In a path-traversal attack, an intruder manipulates a URL in such a way that the Web server executes, or reveals the contents of, a file anywhere on the server — including outside the document root. Such attacks take advantage of special-character sequences in URL input parameters, cookies and HTTP request headers.
The most basic path traversal attack uses the ../ character sequence to alter the document or resource location requested in a URL. Although most Web servers prevent this method from escaping the Web document root, alternate encodings of the ../ sequence, such as Unicode-encoding, can bypass basic security filters. Even if a Web server properly restricts path-traversal attempts in the URL path, any application that exposes an HTTP-based interface is also potentially vulnerable to such attacks.
Note: For UNIX systems, the parent directory is ../ while in Windows it is ...

Attack Scenario 1

The valid URL http://www.example.com/scripts/database.php?report=quarter1.txt is used to display a text file. However, manipulating it into a malicious URL like
http://www.example.com/scripts/database.php?report=../scripts/database.php%00txt will force the PHP application to display the source code of the database.php file, treating it as a text file whose contents are to be displayed.
The attacker uses the ../ sequence to traverse one directory above the “current” directory, and enter the /scripts directory. The %00 sequence is used both to bypass a simple file extension check, and to cutoff the extension when the file is read and processed by PHP. This example highlights the critical importance of always checking and cleaning user-supplied input before allowing it to be processed.

Attack Scenario 2

The PHP code below accepts a username, and then opens a file specific to that username. It can be exploited by passing a username that causes it to refer to a different file:
$username = $_GET['user'];
$filename = "/home/users/$username";
readfile($filename);
Let’s suppose a normal URL is www.example.com/profile.php?user=arpit.pdf. If an attacker passes a changed query string to make a malicious URL like www.example.com/profile.php?user=../../etc/passwd then PHP will read /etc/passwd and output that to the attacker.
Path-traversal attacks mostly target an application’s file upload, download, and display functionalities, like those often found in work-flow applications (where users can share documents); in blogging and auction applications (when users upload images); and in informational applications (when users retrieve documents like ebooks, technical manuals, and company reports).
In many cases, there may be security measures in place — filters for forward or backward slashes — but here too, attackers can try simple encoded representations of traversal sequences, such as those shown the following table.
Table 1: Some encoding schemes
CharacterURL encoding16-bit Unicode encodingDouble URL encoding</>
dot%2e%u002e%252e
forward slash%2f%u2215%252f
backslash%5c%u2216%255c

The time for security

Path traversal attacks can be addressed with the following security measures:
  1. There’s really no good reason for Apache to be allowed to serve files outside of its document root. Any request for files outside the document root is highly suspect, so we’ll restrict it to a directory structure with the following directives in the httpd.conffile:
    <Directory />
    Order Deny, Allow
    Deny from all
    Options none
    AllowOverride none
    </Directory>
    <Directory www>
    Order Allow, Deny
    Allow from all
    Options -Indexes
    </Directory>
    (Replace the www directory name with whatever you’ve called your Web server’s document root. The Options -Indexes line in the <Directory www> section disables directory browsing, securing the server from directory-traversal attacks.)
  2. Apart from this, ensure the user account of the Web server or Web application is given the least read permissions possible for files outside the Web document root. Also, change the default locations of your Web root directories.
  3. After performing all relevant decoding and Canonicalisation of user-submitted filenames, validate all inputs so that only an expected character set (such as alpha-numeric) is accepted. The validation routine should be especially aware of shell meta-characters such as / and “and” command-concatenation characters (&& for Windows shells and the semi-colon for UNIX shells).
  4. Set a hard limit for the length of a user-supplied value. Note that this step should be applied to every parameter passed between the client and server, not just parameters the user is expected to modify via text boxes or similar input fields.
  5. The application should use a predefined list of permissible file types, and reject any request for a different type. It is better to do this before the decoding and Canonicalisation has been performed.
  6. Any request containing path-traversal sequences should be logged as an attempted security breach, generating an alert to an administrator, terminating the user’s session, and if applicable, suspending the user’s account.
  7. realpath() and basename() are two functions PHP provides to help avoid directory-traversal attacks. realpath() translates any . or .. in a path, resulting in the correct absolute path for a file. For example, the $filename in Attack Scenario 2, passed to realpath(), would return just /etc/passwd. On the other hand, basename() strips the directory part of a name, leaving just the filename itself. Using these two functions, it is possible to rewrite the script of Attack Scenario 2in a much more secure manner:
    $username = basename(realpath($_GET['user']));
    $filename = "/home/users/$username";
    readfile($filename);

Tools of the secure trade

  1. Dotdotpwn is a very flexible Perl-based intelligent fuzzer tool, which detects several directory-traversal vulnerabilities on HTTP/FTP servers. For Windows systems, it also detects the presence of boot.ini on vulnerable systems through directory-traversal vulnerabilities. It is available for free download on its website, along with its documentation.
  2. This web resource contains many path-traversal URLs that are frequently used by attackers. This domain also contains other good resources on security and ethical hacking.

Source-code disclosure

Source-code disclosure, another variant of the path-traversal attack, is a widely prevalent vulnerability in Web applications, which lets attackers extract source code and configuration files. Such vulnerabilities are found mostly in websites that offer to download files using dynamic scripts.
The attacker uses this technique to obtain the source code of server-side scripts like ASP, JSP or PHP files, to discover Web application logic, including database structure, source code comments, parameters and other possibly exploitable vulnerabilities of the code. Let’s understand this using a simple attack scenario.

An attack scenario

Let’s assume a website uses the following PHP code, which initiates a file download from the server:
<?php
if(isset($_GET[‘file’]))
{
    $file = $_GET[‘file’];
    readfile($file);
}
?>
A valid URL for the above script is http://www.example.com/downloads.php?file=arpit.zip, but the attacker’s malicious URL could be http://www.example.com/downloads.php?file=login.php, which returns to the attacker the contents of the file login.php. With this, the attacker learns about the filters and checks in login.php, and even the names of other crucial database and systems configuration files.
To secure your application from source-code disclosure, the application should use a predefined list of permissible file types, and reject any request for a different type.

Directory listing leakage

This is a commonly-found vulnerability in many Web servers. When a Web server receives a request for a directory rather than an actual file, it may respond in one of three ways:
  1. It may return a (configurable) default resource within the directory, such as index.html, home.html, default.htm, default.asp, default.aspx, index.php, etc.
  2. It may return an HTTP status code 403 error message, indicating that the request is not permitted.
  3. It may return a listing showing the contents of the directory. This happens when default resources are not present in the directory.
In many situations, directory listings do not have any relevance to security. For example, disclosing the listing of an images directory may be completely inconsequential. Indeed, directory listings are often intentionally allowed because they provide a built-in means of navigating sites containing static content. But still, some files and directories are often, unintentionally, left within the Web root of servers, including:
  • Application-generated files: Web-authoring applications often generate files that find their way to the server. A good example is a popular FTP client, WS_FTP, which places a log file into each folder it transfers to the Web server. Since people often transfer folders in bulk, the log files themselves are transferred, exposing file paths and allowing the attacker to enumerate all files. Another example is CityDesk, which places a list of all files in the root folder of the site, in a file named citydesk.xml.
  • Configuration-management files: Configuration-management tools create many files with metadata. Again, these files are frequently transferred to the website. CVS, the most popular configuration-management tool, keeps its files in a special folder named CVS. This folder is created as a sub-folder of every user-created folder, and it contains the files Entries, Repository, and Root.
  • Backup files: Text editors often create backup files with extensions such as ~, .bak, .old, .bkp, and .swp. When changes are performed directly on the server, backup files remain there. Even when created on a development server or workstation, by virtue of a bulk folder FTP transfer, they end up on the production server.
  • Exposed application files: Script-based applications often consist of files not meant to be accessed directly, but instead used as libraries or subroutines. Exposure happens if these files’ extensions are not recognised by the Web server as a script. Instead of executing the script, the server sends the full source code in response to a request. With access to the source code, the attacker can look for security-related bugs. Also, these files can sometimes be manipulated to circumvent application logic.
  • Web server’s crucial information: This is often displayed at the end of the listing page, and contains the server name, version number and other important information. Such information can be used to launch specific exploits against the Web server.
Apart from the above, there are many other files which should not be disclosed publicly, such as temporary files, renamed old files, user’s private home folders, etc.
Now, the question is regarding how attackers can gain access to directory listings. I am not going the route of guessing the path of a crucial directory via URI. For this, attackers can simply use Google’s advanced search operators (now it’s obviously a prerequisite to know Google’s advanced search operators, site:, inurl:, intext:, intitle:, etc).
Note: I once again stress that neither LFY nor I are responsible for the misuse of the information given in this article. The attack techniques are meant to give you the knowledge that you need to protect your own infrastructure. You will be held solely responsible for any misuse of this knowledge.

OS Commanding

OS commanding (a.k.a. OS command execution, shell injection) is a vulnerability in websites that lets attackers execute operating system commands through the manipulation of application input. It occurs when scripts execute external commands that are constructed using unsanitised input data. Such commands will run with the privileges of the component (database server, Web application server, Web server, wrapper or application) that executed the command. This lets the attacker gain access to otherwise unreachable areas (e.g., operating system directories and files), inject unexpected and dangerous commands, upload malicious programs or even obtain passwords directly from the operating system. The diagram below illustrates this. An OS commanding attack An OS commanding attack OS commanding vulnerabilities are frequently found in Perl and PHP scripts, because these programming environments encourage programmers to reuse operating system binaries. However, there are also chances of such vulnerabilities in Java and ASP. Let’s take a look at a few Perl and PHP examples. The following Perl CGI code is part of a Web application for server administration. This function allows administrators to specify a directory on the server, and view a summary of its disk usage: #!/usr/bin/perl use strict; use CGI qw(:standard escapeHTML); print header, start_html(""); print "
";
my $command = "du -h --exclude php* /var/www/html";
$command= $command.param("dir");
$command=`$command`;
print "$commandn";
print end_html;

When used as intended, this script simply appends the value of the 
user-supplied dir parameter to the end of a specific command, which 
it executes, and displays the results. A normal usage URL might be 
something like http://www.example.com/cgi-bin/showinfo.pl?dir=/public.

This functionality can be exploited in various ways, by supplying 
crafted input containing shell characters that have a special meaning
 to the command interpreter. For example, the pipe character (|) is
 used to redirect output from one process to the input of another, 
enabling the chaining of multiple commands. An attacker can leverage
 this to inject a second command (and retrieve its output) with a 
malicious URL such as 
http://www.example.com/cgi-bin/showinfo.pl?dir=/public|%20cat&20/etc/passwd. 

Here, the original du command’s output is redirected as input to the
 cat /etc/passwd command, which simply ignores it, and just outputs 
the contents of the passwd file.
Note: Most operating systems restrict access to system files. Also, 
the advent of shadow passwords has rendered this specific attack less
 useful than it previously was. Still, damaging attacks can be made 
by obtaining .php files which may contain database hostnames, 
usernames and passwords, or other configuration data, or by obtaining
 the database files themselves.

PHP also provides functions, such as passthru() and exec(), and the 
back-tick operator, to execute external programs. Consider the 
following PHP code, which displays a list of files in a particular 
user’s home folder:
$output = `ls -al /home/$username`;
echo $output;

A valid URL for this might be 
http://www.example.com/viewfiles.php?username=arpit. 
If a semicolon is used in the input, it will mark the end of the 
first command, and the beginning of a second. An example of a 
malicious URL would be 
http://www.example.com/viewfiles.php?username=arpit;cat%20/etc/passwd,
 which again displays the contents of the passwd file.

With such a vulnerability, attackers can execute any binary on the
 server like starting a telnet server, logging in to it with the 
privileges of a Web server user, performing exploits to gain root 
access, and perhaps attacking other hosts that are reachable from 
the compromised server.

The time for security

OS commanding is on the list of least-addressed vulnerabilities, but
 the following security measures can help curb it considerably:

    Remove the execution bit from the everyone group (-rwxrwxrw-) 
for OS commands. The Web server user account will not be able to 
execute the targeted command even if an attacker is able to trick 
the Web application into attempting to execute it.
    Validate all input fields for characters like ;, |, / or %00. 
Now, since the list of such characters can be endless, the best thing
 would be to only allow the expected input, and filter out everything 
else — create a whitelist of acceptable inputs that strictly conform
 to specifications, and reject any other input, or transform it into
 acceptable input. For example, to neutralise the ampersand character
 (&) that appears in user data, and which needs to be a part of an 
HTML page, it must be converted to &.
    As additional security, you can also try filtering out command 
directory names such as bin, sbin, opt.

Source: http://www.linuxforu.com