Category Archives: Security

How to set bucket policies for Amazon AWS S3?

In Amazon AWS S3 Console > Select your bucket > hit Properties tab on right-hand side > Edit bucket policies button

Public bucket policy:

{
“Version”:”2008-10-17″,
“Statement”:[{
“Sid”:”MyAllowPublicRead”,
“Effect”:”Allow”,
“Principal”: {
“AWS”: “*”
},
“Action”:[“s3:GetObject”],
“Resource”:[“arn:aws:s3:::YOUR_BUCKET/*”
]
}
]
}

 

 

How to secure Amazon AWS S3 bucket and access from Android app?

Two possible approaches – differing in how credentials are used (i.e what kind of credentials are embedded in your app).

EMBEDDING COGNITO IDENTITY POOL ID IN APPLICATION

The advantage of this approach is that you do not have to embed the Access Key, Secret Key in your code – for example in a android application. Amazon creates temporary credentials for use by your client application.

Create Cognito Pool Id

In Amazon AWS Console > Cognito:

Provide a name, and it will create two roles for you too:

  • Unauthenticated Users Role
  • Authenticated Users Role (Google/Twitter/Facebook login etc.)

Create a Policy:

In Amazon AWS Console > IAM > Policies

{
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“s3:Get*”
],
“Resource”: “arn:aws:s3:::YOUR_BUCKET/*”
}
]
}

 

Attach the Policy to Roles created previously

In AWS Console > IAM > Roles

Attach Policy to both roles (or one of them depending on authenticated or unauthenticated access requirements)

Note: You can attach Roles to this Policy as well (its the same thing)

Code

package com.s3test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class S3Test {

static AWSCredentials credentials = null;
static String bucketName = “BUCKET_NAME”;
static String key = “YOUR_FILE_IN_BUCKET”;

public static void main(String[] args) {

CognitoCachingCredentialsProvider cognitoProvider = new CognitoCachingCredentialsProvider(

    ctx, // get the context for the current activity

    “whatever:whatever-whatever-whatever..”, /* Identity Pool ID */

    Regions.US_EAST_1 /* Region */

);

AmazonS3 s3 = new AmazonS3Client(cognitoProvider);

Region usWest2 = Region.getRegion(Regions.US_WEST_1);//Make sure region is same as where S3 bucket exists
s3.setRegion(usWest2);

S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
System.out.println(“Content-Type: ” + object.getObjectMetadata().getContentType());
try {
displayTextInputStream(object.getObjectContent());
} catch (IOException e) {

e.printStackTrace();
}
}

private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;

System.out.println(” ” + line);
}
System.out.println();
}
}

 

 

EMBEDDING ACCESS_KEY AND SECRET_KEY IN APPLICATION

Create a IAM User

In Amazon AWS Console > IAM :

Create a User, you will get Access Key Id, and Secret Key for that user.

Create a Policy

In Amazon AWS Console > IAM > Policies

{
“Version”: “2012-10-17”,
“Statement”: [
{
“Effect”: “Allow”,
“Action”: [
“s3:Get*”
],
“Resource”: “arn:aws:s3:::YOUR_BUCKET/*”
}
]
}

Attach this Policy to the User (Or Group, if you added user to a Group)

Use Attach button (available in the policy page) for this.

All set – Now access S3 Bucket from Java Program:

NOTE: You will need AWS-JAVA_SDK in path eg: aws-java-sdk-1.9.17.jar

package com.s3test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.S3Object;

public class S3Test {

static AWSCredentials credentials = null;
static String bucketName = “BUCKET_NAME”;
static String key = “YOUR_FILE_IN_BUCKET”;

public static void main(String[] args) {
//– credentials = new ProfileCredentialsProvider()..getCredentials();
credentials = new BasicAWSCredentials(“USER_ACCESS_KEY_ID”, “USER_SECRET_ACCESS_KEY”);
AmazonS3 s3 = new AmazonS3Client(credentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_1);//Make sure region is same as where S3 bucket exists
s3.setRegion(usWest2);

S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
System.out.println(“Content-Type: ” + object.getObjectMetadata().getContentType());
try {
displayTextInputStream(object.getObjectContent());
} catch (IOException e) {

e.printStackTrace();
}
}

private static void displayTextInputStream(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;

System.out.println(” ” + line);
}
System.out.println();
}
}

 

That’s It

How to setup https/ssl on Tomcat 6?

Generate a keystore using this command:

c:\work\keytool -genkey -alias myalias -keyalg RSA -keystore mykeystore

 

Your Tomcat server.xml should have an entry like below:

<Connector port=”8443″ protocol=”org.apache.coyote.http11.Http11Protocol”  SSLEnabled=”true”
maxThreads=”150″ scheme=”https” secure=”true”
clientAuth=”false” sslProtocol=”TLS” keystoreFile=”C:\work\mykeystore”
keystoreType=”JKS” keystorePass=”123456″ />

This may also be needed (note the SSLEngine=off ):

<Listener className=”org.apache.catalina.core.AprLifecycleListener” SSLEngine=”off” />

 

Note, your site now will work on both http and https – assuming you have not removed the http connector from server.xml

If you want to force some URLs to work only in https then add the following in web.xml:

 

<security-constraint>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>/secure/*</url-pattern>
</web-resource-collection>

<user-data-constraint>
<!– All access to this area will be SSL protected –>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

 

Now, all the URLs that are like: /secure/whatever – can be accessed only over https. If you attempt to access them over http, it will redirect to https automatically.

Note: We have generated and used a dummy certificate above, altho it works – when u open url using https://.. in your browser – you will see a warning and a red mark. To use a real ssl certificate (you will have to buy) – the steps will be slightly different.

Java program to change Active Directory user password (over SSL)?

Note, that to change Active Directory user password, connection must be made over SSL.

To enable SSL on Active Directory, and get hold of ssl certificate,  see instructions for that here.

The program:

import javax.naming.*;
import javax.naming.directory.*;
import javax.naming.ldap.*;
import java.util.*;
import java.security.*;

public class ADPasswdChange {
DirContext ldapContext;
String baseName = ",CN=Users,DC=mydomain,DC=local";
String serverIP = "localhost";

public ADPasswdChange() {

try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "Simple");
//NOTE: Replace the user and password in next two lines, this user should have privileges to change password.
//NOTE: This is NOT the user whose password is being changed.
env.put(Context.SECURITY_PRINCIPAL, "powerfuluser@mydomain.local");
env.put(Context.SECURITY_CREDENTIALS, "whateverpassword");
//NOTE: Replace localhost in next line with actual ldap host:
env.put(Context.PROVIDER_URL, "ldap://localhost:636");
env.put(Context.SECURITY_PROTOCOL, "ssl");
ldapContext = new InitialLdapContext(env, null);

}
catch (Exception e) {
System.out.println(" bind error: " + e);
e.printStackTrace();
System.exit(-1);
}
}

public void updatePassword(String username, String password) {
try {

System.out.println("1");
String quotedPassword = "\"" + password + "\"";
char unicodePwd[] = quotedPassword.toCharArray();
byte pwdArray[] = new byte[unicodePwd.length * 2];
for (int i=0; i&lt;unicodePwd.length; i++) {
pwdArray[i*2 + 1] = (byte) (unicodePwd[i] &gt;&gt;&gt; 8);
pwdArray[i*2 + 0] = (byte) (unicodePwd[i] &amp; 0xff);
}

ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("UnicodePwd", pwdArray));

ldapContext.modifyAttributes("CN=" + username + baseName, mods);

}
catch (Exception e) {
System.out.println("update password error: " + e);
System.exit(-1);
}
}

public static void main(String[] args) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
// the keystore that holds trusted root certificates
//NOTE: Replace with path to ssl certificate keystore file below.
System.setProperty("javax.net.ssl.trustStore", "C:/mydir/keystore.jks");
//NOTE: Replace with keystore password that was used while converting .cer to .jks file.
System.setProperty("javax.net.ssl.trustStorePassword", "thekeypasswd");
System.setProperty("javax.net.debug", "all");
ADPasswdChange adc = new ADPasswdChange();
//NOTE: Replace below with username whose password has to be changed and the desired password.
adc.updatePassword("user1", "change$2pass");
}
}

The above program is a slightly modified version of the one mentioned here:
http://blogs.msdn.com/b/alextch/archive/2012/05/15/how-to-set-active-directory-password-from-java-application.aspx

Space in LDAP SSL URL causes: ‘MalformedURLException: Invalid URI:’

Problem Statement:

You are trying to connect to LDAP(SSL) from a Java Program as follows:

...
prop.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
...
prop.put(Context.PROVIDER_URL, "ldap://host:636/OU=My Org,DC=domain,DC=com");
LdapContext ctx =new InitialLdapContext(prop,null);
...

And you see error message like:
MalformedURLException: Invalid URI: Invalid URI: Org,DC=domain,DC=com]


Solution

This error is caused by the space in URI. So in this case space in: ‘My Org’ part of the URL.
If you replace ‘My Org’ with ‘My%20Org’, the error should go away.

So, your code should now look like:
...
prop.put(Context.PROVIDER_URL, "ldap://host:636/OU=My%20Org,DC=domain,DC=com");
...

How to authenticate against LDAP / Active Directory?

Problem Statement

Given a User Name and Password, you want to authenticate the same against LDAP or Active Directory (AD).

Solution – Using a Java Program

Here’s a simple example:

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class Main {
 public static void main(String[] args) {

 try {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    //NOTE: Replace with appropriate ldap hostname below
    env.put(Context.PROVIDER_URL, "LDAP://ldaphost:389"); 
    //NOTE: Usually DIGEST-MD5 usually works with Windows Active Directory. If not try 'Simple'
    env.put(Context.SECURITY_AUTHENTICATION, "DIGEST-MD5"); 
    //NOTE: Replace with appropriate username and passwd in next two lines.
    env.put(Context.SECURITY_PRINCIPAL,  "putUsernameHere"); 
    env.put(Context.SECURITY_CREDENTIALS, "putPasswordHere>");   

    DirContext ctx = new InitialDirContext(env);
    ctx.close();
  } 
  catch(NamingException ne) {
    System.out.println("Error authenticating user:");
    System.out.println(ne.getMessage());
    return;
}
    System.out.println("OK, successfully authenticated user");
}

How to ssh to a remote Linux machine from behind a firewall

Problem Statement

You are behind a firewall (that allows only port 80 or 443), and therefore cannot access a remote Unix machine via ssh (port 22).

Solution

Change the port on which ssh runs on Linux Server:

Run the ssh on the Unix machine on port 443.

In dir: /etc/ssh dir locate following files: ssh_config, sshd_config (do we need to do for both files or only sshd_c0nfig?)

Here uncomment the line: #Port 22 , and change port number to 443.

Now restart ssh: /etc/init.d/sshd restart

Now ssh on the Linux server is running on port 443 (instead of default 22)

Next, ssh using Putty from your desktop

Here:

  • Under Session> Enter Server IP and Port (remember 443, and not 22).
  • If a Proxy Server is in place (its likely if you are behind a firewall) then, under Connection > Proxy enter the Proxy Details. Often people forget this step. If Proxy requires Authentication enter user (eg: user@domain.com) and passwd for that.
  • If you need to enter any Private Auth Key file (usually the case if you are accessing say Amazon EC2) do that under SSH> Auth.

Now hit Open. Hopefully everything will work out fine.

Note:

If you often get disconnected in a ssh session, becz you were idle, you must enter a value in Connections> Seconds between Keep Alives.

Note: Always follow the applicable procedures and laws of your place. Do not circumvent firewalls, if you are not allowed to.

How to: Hardening & Securing JBoss 6x

Secure (Web) Admin-Console/JMX-Console

Follow the steps here: https://community.jboss.org/wiki/SecureTheJmxConsole

Summary of the steps (There are no separate steps for Admin-Console securing, same security constraints applies to it automatically):

  • <JBOSS_HOME>/common/deploy/jmx-console.war/WEB-INF/

              web.xml & jboss-web.xml: Uncomment the Security Constraint Block.

  • <JBOSS_HOME>/server/PROFILE/conf/props

             jmx-console-users.properties: Change password here.

Remove Unnecessary Services

You may want to remove: JMS, JUDDI, Key Generator

Follow the steps here: https://community.jboss.org/wiki/JBoss6xTuningSlimming

How to enable httpS on JBoss?

Generate the Certificate:
C:\Java\bin\keytool -genkey -keystore C:\keys\mycertifcate.jks

You will be prompted with following questions.

1. Enter keystore password: 123456
Re-enter new password: 123456
2. What is your first and last name?
[Unknown]: mydomain
3. What is the name of your organizational unit?
[Unknown]: whatever
4. What is the name of your organization?
[Unknown]: whatever
5. What is the name of your City or Locality?
[Unknown]: whatever
6. What is the name of your State or Province?
[Unknown]: NY
7. What is the two-letter country code for this unit?
[Unknown]: US
8. Is CN=mydomain, OU=whatever, O=whatever, L=whatever, ST=NY, C=US correct?
[no]: yes

9. Enter key password for
(RETURN if same as keystore password):

NOTE:
In Step 2 above, where it asks for First/Last Name, you may have to enter the domain name in which you operate. Although i am not sure of this.

Place the Certificate in JBoss conf dir:
Place the mycertificate.jks inside <JBOSS_HOME>\conf\ directory.

Configure the server.xml https connector:
In this file:
<JBOSS_HOME>/server/whateverNode/deploy/jbossweb-tomcat55.sar/server.xml

Make sure the following lines are as follows (and uncommented):
<Connector port=”8443″ address=”${jboss.bind.address}”
maxThreads=”100″ strategy=”ms” maxHttpHeaderSize=”8192″
emptySessionPath=”true”
scheme=”https” secure=”true” clientAuth=”false”
keystoreFile=”${jboss.server.home.dir}/conf/mycertifcate.jks
keystorePass=”123456” sslProtocol = “TLS” />

That’s it! Tested on JBoss 4x.

NOTE: When i tried this in Linux machine, for some reason, if the first step of Certificate generation was done on Linux machine, that certificate would never work. I do not know why. So, in that case i generated it on my win desktop and transferred it to Linux machine and used it.

How to prevent DOS (denial of service) attack?

Let us assume you are hosting a web-application using a Apache Server on a Linux machine. With this configuration you can use one of these to prevent such an attack:

(i) IP Tables – this works at very low network level.

(ii) Mod Security module (with apache) – this ofcourse works at web-server level.

(iii) Mod Evasive (with apache) – this ofcourse works at web-server level. This is closest to what you may need.

(iv) Dos Deflate – this is a script that runs regularly to find offenders and block them via IP Tables.

IP Tables

IP Tables is a Linux module which is normally available by default on Linux machines, if not; you can always install it. It is capable of analyzing (for source IP Address, destination IP Address, destination Port etc.) incoming packets and doing various things with them, like letting them in, rejecting them etc.

Here are some useful commands.

To log all incoming requests

iptables -I INPUT 1 -j LOG –log-level debug –log-prefix “IPTablesLog: ”
iptables -I OUTPUT 1 -j LOG –log-level debug –log-prefix “IPTablesLog: ”
iptables -I FORWARD 1 -j LOG –log-level debug –log-prefix “IPTablesLog: “

Configure the system log (you need to do this to see logs):

Add this line to /etc/syslog.conf (NOTE: there is a tab between ‘*.debug’ and ‘/var/log/iptables.log’ – and not a space.):
*.debug /var/log/iptables.log

Restart log service:

Restart Syslog
service syslog restart

Flush IP Tables (resets IP tables such that no rules apply):

# iptables -F

Restart IP Tables (any rules added from command line will be lost):

# service iptables restart

Log packets from/to a particular IP:
iptables -I INPUT -s <TheIPHere> -j LOG –log-level debug –log-prefix “IPTablesLog: ”
iptables -I OUTPUT -d <TheIPHere> -j LOG –log-level debug –log-prefix “IPTablesLog: ”
iptables -I FORWARD d <TheIPHere> LOG –log-level debug –log-prefix “IPTablesLog: “

Log Packets for a particular destination port (always use this as the last statement):
iptables -I INPUT -p tcp –dport 80 -j LOG –log-level debug –log-prefix “IPTablesLog: “

Reject Packets from a particular source for a particular destination port:
iptables -I INPUT -s <TheIPHere> -p tcp  –dport 80 -j REJECT –reject-with icmp-port-unreachable

iptables -A INPUT -s 192.168.0.121 -p tcp  –dport 80 -j DROP

Limit Packets for a particular destination port:
iptables -I INPUT -p tcp –dport 80 -m limit –limit 10/sec –limit-burst 10 -j ACCEPT

If you want to permanently add any of the above rules you can add them to the file:/etc/sysconfig/iptables. And then restart iptables. Note that order of the commands could be important.

Mod Security

This is an module that allows you to configure Apache in a variety of useful ways. For example, preventing uploads of a certain kind, preventing access to pages with a certain extension, and so on…

URL: http://www.modsecurity.org
Download: http://www.modsecurity.org/download/direct.html

Most of the information regarding that is available on its website.
In brief the install instructions are:

a.) Download Mod Security gzip .
b.) Unzip it in some dir.
c.) Configure it by issuing command: # ./configure –with-apxs=<APACHE_HOME>/bin/apxs
d.) Compile: # make

e.) Install: # make install

f.) In <APACHE_HOME>/conf/httpd.conf add following lines (the second line is optional):

LoadFile /usr/lib/libxml2.so
#Next line is optional.
#LoadFile /usr/lib/liblua5.1.so

LoadModule security2_module modules/mod_security2.so

g.) Download the Core Rules (these are example config files for mod security)
unzip them such that they land up inside <APACHE_HOME>/conf/modsecurity/

h.) In <APACHE_HOME>/conf/httpd.conf add following lines:
Include conf/modsecurity/*.conf

The most important conf file in that dirs are:
modsecurity_crs_10_config.conf
modsecurity_crs_30_http_policy.conf

You can edit them as you see fit. And rest of the config files you can move to some other sub-dir, if you do not want them loaded.

i.) Now you can restart Apache, and you should be all set.

Now, that you have mod security, you will wonder where is the option for preventing DOS attacks? Infact, Mod Security by itself cannot prevent DOS; but it can do so in conjunction with another tool called ‘httpd guardian’.  See the SecGuardianLog option on this page: http://www.modsecurity.org/documentation/modsecurity-apache/2.1.0/modsecurity2-apache-reference.html .

This particular httpd guardian tool can also be used independently (in which case it analyzes apache logs) or in conjunction with Mod Security in which case it receives information from Mod Security; either way it analyzes input information to determine action to take. The download location of this particular tool is this:

It is available at: http://www.apachesecurity.net/tools/index.html and the download location of httpd-guardian is: http://apache-tools.cvs.sourceforge.net/viewvc/apache-tools/apache-tools/httpd-guardian?view=markup .

Mod Security is probably a great tool, but it does not seem right for the purpose of preventing DOS attacks – mainly because that is really not built into the tool, and it uses a yet another tool (httpd-guardian) to achieve it. So you get the picture, too many pieces involved etc. I have used Mod Security, but not in conjunction with httpd-guardian, so i may not be the best person to pass judgement in this regard.

Mod Evasive

This is the solution that i finally zeroed on and found to be the best solution. It is easy to configure and test.  And preventing DOS attacks is the primary purpose of this tool.

Install Instructions: http://wiki.leenox.in/index.php/Installing_mod_evasive

Download from: http://www.zdziarski.com/projects/mod_evasive/mod_evasive_1.10.1.tar.gz
Compile and Install: #<APACHE_HOME>/bin/apxs -cia mod_evasive20.c

Add to httpd.conf:
<IfModule mod_evasive.c>
DOSHashTableSize 3097
DOSPageCount 2
DOSSiteCount 50
DOSPageInterval 1
DOSSiteInterval 1
DOSBlockingPeriod 300
DOSLogDir “<PathToYourApacheLogDirHere>”
DOSEmailNotify myemal@email.com
</IfModule>

NOTE: Do not forget that even a single web page can have many images and such things, so loading a single page can also cause many requests to be sent to the server(to load images etc). So, you will need to arriveat an appropriate values for the above params yourself.
Explanation of params (this link is useful http://www.directadmin.com/forum/showthread.php?s=&threadid=10957)

DOSHashTableSize
Size of the hash table. The greater this setting, the more memory is required for the look up table, but also the faster the look ups are processed. This option will automatically round up to the nearest prime number.

DOSPageCount
Number of requests for the same page within the ‘DOSPageInterval’ interval that will get an IP address added to the blocking list.

DOSSiteCount
Same as ‘DOSPageCount’, but corresponds to the number of requests for a given site, and uses the ‘DOSSiteInterval’ interval.

DOSPageInterval
Interval for the ‘DOSPageCount’ threshold in second intervals.

DOSSiteInterval
Interval for the ‘DOSSiteCount’ threshold in second intervals.

DOSBlockingPeriod
Blocking period in seconds if any of the thresholds are met. The user will recieve a 403 (Forbidden) when blocked, and the timer will be reset each time the site gets hit when the user is still blocked.

Logs:
You can still see the log messages here whenever a IP Address is blocked:
– <APACHE_HOME>/logs/error_log ( eg: [error] [client <IPAddressHere>] client denied by server configuration: )

– <APACHE_HOME>/logs/<dos_<IP>>( A file with IP Address in its name is created here if an IP Address is blocked)

– /var/log/messages – ( eg: mod_evasive[6480]: Blacklisting address <IPAddressHere>: possible DoS attack)

You can easily test Mod Evasive. Just keep F5 pressed on a web-page of your site (the browser will load the page again and again very fast), and when mod evasive kicks in it will return 403 error.

NOTE: One thing that did not work for me was that, even when a IP Address was correctly identified and blocked, i could still continue to randomly access the web-application.

DOS Deflate

This is a shell script that runs via cron every minute, and checks the processes on that machine. If there are too many http processes initiated by a particular IP Address, it blocks that IP Address using IPTables, and will unblock the IP Address again after some time (based on configuration i.e in ddos.conf file – see the link below).

http://deflate.medialayer.com/ – this is main URL you want to see.

After looking at it, i thought it required one improvement, i.e it should not just check for all processes but should check for httpd processes (assuming u r running Apache ofcourse). For this change the following line in instrall.sh from:

netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n

to:

netstat -aptn | grep httpd | awk ‘{print $5}’ | cut -d: -f4 | sort | uniq -c | sort -n

Remember that the concept is quite striaght forward, and you can even write your own java program (if you are unconformatable with shell scripts) to achieve the same.

How do i find that i am under DOS attack?

If you are using Mod Evasive, you can see its logs or you may receive a mail from it if that is configured correctly. But, if you are not using any such thing, read on…

The most obvious thing is that your application will become ‘unexpectedly’ overloaded (and therefore unresponsive). Remember, you could be genuinely overloaded too, because your web-application is so popular! So, one key thing is that it would be ‘unexpected’, another that, most of the requests would seem to come from some specific IPs (which would further confirm that this is an auotmated attack).

On Linux, find out if there are a huge number of http processes:

Find if you have huge number of http processes (>100 is not good):
#ps -aux|grep HTTP|wc -l

#ps -aux|grep HTTP

You have more than 30 connection from a single ip. Under normal cases there is no need for that many number of connection requests from a single IP. Try to identify such ips/networks from the list you get.
#netstat -lpn|grep :80 |awk ‘{print $5}’|sort

If you identify suspicious IPs, you can block them using iptables.

NOTE: In case of DDOS (distributed denial of service) there will be more than one IP that would be suspicious, and it would be much more difficult to stop it too, as the source IP may keep changing.

If you are running an Application Server (say tomcat) – all the threads will be occupied (busy), causing the application to become unresponsive.

Is there a even better and robust solution?

Yes ofcourse, the most robust solution to this problem is to be found in expensive Hardware Load Balancers, or FireWalls.