Friday, June 13, 2014

How to Setup Chroot SFTP in Suse 11

Setup a chrooted SSH sftp account. (Tested on Suse 11 and OpenSSH) 
We will create a low privileged sftp directory where lets say the users can upload their stuff without exposing our internal filesystem. First, add a user with a home directory, we don't want this user to access ssh via a shell, only for sftp, that's why we are setting the shell to /bin/false. Chrooted shell is a different chapter, so not discussing it here. And you can confirm the settings of newly added bobuser in /etc/passwd.

test:~ # useradd -d /home/bobuser -s /bin/false -m bobuser
test:~ # cat /etc/passwd | grep bobuser
bobuser:x:1505:100::/home/bobuser:/bin/false

Set the password for bobuser, or else you it will not allow you to login if the password is not set.

passwd bobuser
Changing password for bobuser.
New password:
BAD PASSWORD: it is based on a dictionary word
Retype new password:
Password changed.

Add the following settings in /etc/ssh/sshd_config file.

#Sftp/chroot Settings for bobuser in /etc/ssh/sshd_config
#Change LogLevel to debug and check errors (if any) in /var/log/messages
Subsystem sftp internal-sftp

#Sftp/chroot Settings for bobuser
Match User bobuser
   X11Forwarding no
   AllowTcpForwarding no
   ForceCommand internal-sftp
   ChrootDirectory /home/bobuser

Also add bobuser to the allow users list. This is a good practice to set can use ssh/sftp to login.

AllowUsers alexuser bobuser

Now restart the ssh service. And try connecting.

r00ter127:~ # service sshd restart
Shutting down SSH daemon done
Starting SSH daemon done
r00ter127:~ # sftp bobuser@localhost
Connecting to localhost...
Password:
Read from remote host localhost: Connection reset by peer
Couldn't read packet: Connection reset by peer
Ouch..We need to read the errors in /var/log/messages, we had already set it to debug level. There are some requirements expected by the ssh daemon

Jan 25 11:30:27 r00ter127 sshd[10220]: debug1: PAM: establishing credentials
Jan 25 11:30:27 r00ter127 sshd[10220]: fatal: bad ownership or modes for chroot directory "/home/bobuser"
Set the ownership of the home and parent directories to root. That's a requirement.

test:~ # ls -ld /home/bobuser/
drwxr-xr-x 5 bobuser users 4096 Jun 13 12:21 /home/bobuser/
test:~ # chown root:root /home/bobuser
test:~ # ls -ld /home/bobuser/
drwxr-xr-x 5 root root 4096 Jun 13 12:21 /home/bobuser/
We are set with the permissions now.

r00ter127:~ # sftp bobuser@localhost
Connecting to localhost...
Password:
subsystem request failed on channel 0
Couldn't read packet: Connection reset by peer
If you get the above error, then it means there is some problem invoking the sftp server. And the ssh logs are not very helpful in this regard. Make sure you are using the internal-sftp:

Subsystem sftp internal-sftp
...
   ForceCommand internal-sftp
And then.. you are done.

r00ter127:~ # sftp bobuser@localhost
Connecting to localhost...
Password:
sftp> pwd
Remote working directory: /


Monday, June 9, 2014

PAM module security settings for beginners - Suse 11

Pam modules security settings for beginners(Tested on Suse 11)
Configuring Pluggable Authentication Modules for security could be tricky sometimes. A lot of times people are looking for ways to prevent brute force and password guessing attempts on their ssh. But understanding the working of pam modules, testing them correctly surely takes some time. I am trying to list down here what I have tried and tested. There are 4 modules, cracklib, pwhistory, faildelay and tally. You can explore the man pages for detailed options that are supported, however here is the tricky part: depending on the modules version installed in your Linux, and in some cases depending on the Linux distro as well, the actual behavior may vary and some of the options listed in the man page may not even work. This adds a lot of confusion and frustration on how to get it to work. So define clearly your goals first, and then try out settings as listed in the man pages. Also make a note of where you are adding the rules, and finally a round to testing to ensure, things work as expected.

Few checkpoints, if you face problems when your pam module does not work as intended:

1. Ensure you understand the documented behavior of the module, its purpose, results, limitations etc.
2. Make a note of the PAM rule that you are adding, and the meaning of its parameters
3. Make a note of which file you are adding the rule to (e.g. the rule common-auth, common-password) it may not work if you have added it to the wrong file. :)
4. Well the version you are using, or the distro you are using, may have bugs as well. You need to check and google out any such possibility.
5. Well, if some option is not working in your module, even when it is listed in its man page, probably you are reading the documentation for a newer version
6. Is there any log file that this module writes to, where you can see its behavior?

cracklib is being used for enforcing strong password rules.
faildelay is to make the password prompt delay by a period of time when supplied with a wrong password, which reduces the efficiency of password guessing/brute forcing attacks.
pwhistory is to maintain a history of old passwords, so that users do not reuse their old passwords
pam_tally is to maintain a counter of bad login attempts and to lock the account for a given time, when the counter exceeds the set threshold. The useful feature is to reset the counter when a successful attempt occurs. This again is helpful in reduces the efficiency of password guessing/brute forcing attacks.

(The config files in Suse are in /etc/pam.d/common-auth/account/password):
Using cracklib and pwhistory #Password rules for the creation of strong passwords
- at least one special character (ocredit)
- at least one digit (dcredit)
- at least one lower case letter (lcredit)
- at least one upper case letter (ucredit)
- has a minimum length of 8 characters (minlen)

/etc/pam.d/common-password:

password requisite pam_cracklib.so difok=4 minlen=8 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1 maxrepeat=3

#Dont allow previously set passwords, This will remember upto 5 previous passwords.
#The old passwords are stored in /etc/security/opasswd
password required pam_pwhistory.so remember=5 retry=3


Testing
Those password rules do not work for root account. However for non-root accounts, you can try changing them. The errors however could be misleading. For e.g. you may get "password is too simple", even when u have a long password but you forgot to include a special character. So read the manual and keep trying.

faildelay: Brute force and password guessing attack protection
This means when you provide a bad password, the next password prompt would come after 5 seconds (or more). Which is a discouraging thing for automated brute forcing programs. This combined with strong password rules, and locking mechanism with pam_tally provide a good level of protection. /etc/pam.d/common-auth:

#Faildelay to delay the appearance of prompt (mitigation of brute force and password guessing attacks)
#delay is in micro seconds
auth required pam_faildelay.so delay=5000000


Testing for faildelay
Provide a bad password and the next password prompt should appear after 5 seconds.

pam_tally: Temporary account locking and automatic unlocking
You can use pam_tally to lock accounts which pass the defined threshold.(set with deny)

#Locking accounts temporarily when bad passwords are supplied (mitigating brute force and password guessing attacks)
#It uses the tally counter
auth required pam_tally.so deny=5 lock_time=1 unlock_time=60


Testing for pam_tally
By default, the pam_tally module will use /var/log/faillog log file. If you want to see the contents, run faillog command :

test:~ # faillog
Login Failures Maximum Latest On
alexuser 0 0 06/09/14 15:37:20 +0000 test.system.com



Try logging in and providing wrong passwords, with every wrong attempt, the pam_tally would increment Failure count. Once it goes beyond the threshold of 5, it will start locking you for 60 seconds for every bad password you provide. Only after 60 seconds it will accept a password. If you provide the correct password, the faillog is cleared.


test:~ # ssh alexuser@localhost
Password:
Password:
Password:
Account locked due to 6 failed logins

Received disconnect from 127.0.0.1: 2: Too many authentication failures for alexuser
test:~ # ssh alexuser@localhost
Password:
Password:
Account locked due to 8 failed logins

Password:
Account locked due to 9 failed logins

Received disconnect from 127.0.0.1: 2: Too many authentication failures for alexuser


Now you wait for 60 seconds and try logging again, this time provide correct password in first try (or else it will again start the lock period of 60 sec) and the system should log you in. Now you can run faillog and it will be empty because it got reset by your successful login.




References:
http://linux.die.net/man/8/pam_cracklib
http://linux.die.net/man/8/pam_tally

Saturday, June 7, 2014

Java code: Simple RSA encryption and decryption code

A simple program to generate 1024 bit RSA key pair, and perform simple encryption and decryption. No a big deal. Two classes: AsymetricKeyHelper and Main. AsymmetricKeyHelper.java:
/*AsymmetricKeyHelper.java*/
package com.work.crypto;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class AsymmetricKeyHelper {

 //Generates an RSA public private key pair
 public KeyPair keyPair() {
  KeyPair kp = null;
  try {
   KeyPairGenerator keyPairGenerator = KeyPairGenerator
     .getInstance("RSA");
   keyPairGenerator.initialize(1024);
   kp = keyPairGenerator.generateKeyPair();

  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  return kp;
 }

 //does the encryption
 public byte[] encrypt(byte[] clearTest, Key key) {
  try {
   Cipher cipher = Cipher.getInstance(key.getAlgorithm());
   cipher.init(Cipher.ENCRYPT_MODE, key);
   return cipher.doFinal(clearTest);
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  } catch (NoSuchPaddingException e) {
   e.printStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.printStackTrace();
  } catch (BadPaddingException e) {
   e.printStackTrace();
  }
  return null;
 }

 //does the decryption
 public byte[] decrypt(byte[] cipherText, PrivateKey private1) {
  try {
   Cipher cipher;
   System.out.println(private1.getAlgorithm());
   cipher = Cipher.getInstance(private1.getAlgorithm());
   cipher.init(Cipher.DECRYPT_MODE, private1);
   return cipher.doFinal(cipherText);
  } catch (NoSuchAlgorithmException e1) {
   e1.printStackTrace();
  } catch (NoSuchPaddingException e1) {
   e1.printStackTrace();
  } catch (InvalidKeyException e) {
   e.printStackTrace();
  } catch (IllegalBlockSizeException e) {
   e.printStackTrace();
  } catch (BadPaddingException e) {
   e.printStackTrace();
  }

  return null;
 }

}

Main.java:
/*Main.java*/
package com.work.crypto;

import java.security.KeyPair;

public class Main {

 /**
  * @param args
  */
 public static void main(String[] args) {
  asymmetricEncryptionSimple();
 }

 private static void asymmetricEncryptionSimple() {
  AsymmetricKeyHelper keyHelper = new AsymmetricKeyHelper();
  KeyPair keyPair = keyHelper.keyPair();
  System.out.println(keyPair.getPublic().getAlgorithm());
    
  String plainText = "You little Monkey.I am a cryptographer";
  
  byte[] cipherText = keyHelper.encrypt(plainText.getBytes(), keyPair.getPublic());
  //Print the encrypted text, it is in binary. So it will look ugly.
  System.out.println(new String(cipherText));
  
  byte[] clearDecrypt = keyHelper.decrypt(cipherText, keyPair.getPrivate());
  //Create a string out of the byte array
  System.out.println(new String(clearDecrypt));
 }

}


Friday, May 30, 2014

Linux: Compilation of 31 Bash tips and tricks - Part 2 (16-31)

The next part of tips.

These are picked from various sources and usually are helpful to me in my day to day work, so you do not have to read the man pages everytime. I do not remember all the sources, so I will quote the source wherever I remember. If you know the source, please let me know.

I know I have written it in a very clumsy way, without too much explaining of the underlying context and theory or any references. But I hope to make it beginner friendly.

Here we go:

16. [Bash usage tip/security]
Enable a 15 minute timeout for bash. Helps in security best practices.

Let's say you want to auto-logout of your bash shell after 15 minutes of inactivity. This is sometimes an important security requirement as well. You can set this code in the global /etc/profile or for specific user in ~/.bash_profile. This piece essentially creates a readonly environment variable when a user logs in


#Add this in /etc/profile, tested in SUSE
TMOUT=900
readonly TMOUT
export TMOUT

17. [Bash usage tip/security]
Disable command execution in Less.

Well if you don't know this, you can execute commands in less, vi etc
To disable this in less, you need to set an environment variable called LESSSECURE.

export LESSSECURE=1

18. [Bash usage tip/security]
Executing bash commands in vi, less, and more:


in vi -> :!bash
in less -> !bash
in more -> !bash

19. [Bash usage tip/security]
Setting an environment variable as READONLY:


readonly TMOUT
export TMOUT

20. [Bash usage tip/security]
Disable bash builtins using enable. This might help if you are trying something like a restricted shell. I must warn you, its risky.


enable -n <builtin_name>

21. [Bash usage tip]
Useful commands in vi


:set list -special chars
:set nu -line numbers
:.! ls - Add a . before ! during command execution and it will dump the output in the current screen.
:r! <cmd> -same thing, dump the cmd output
:%!xxd - Turn vim into a hexeditor, :%xxd -r to reverse.
q: -command history
:%TOhtml -create an html file body

22. [Shell scripting tip]
Command execution in a subshell. Shell scripting tip.

$(command) is the same as `command`

$(ls) gives you the output of ls
so does `ls`.

23. [Bash usage tip]
env and export -p

Use the env (or export -p) command to see only those variables that have been exported and would be available to a subshell.

24. [Bash usage tip ]
set command:

Use the set command to see the value of all variables and function definitions in the current shell. The list produced by env is a subset of the list produced by set, since not all variables are exported.

25. [Shell scripting tip]
Looping over vars with spaces like "My Folder".


for file in "$@"
    do
    chmod 0750 "$file"
done

26. [Shell scripting tip]
Difference between: "$*" and "$@".



for file in "$*" will expand to:
for file in "file1 file2 file3 My File.txt"

The above will not help if the filename has spaces, like My File.txt, bash would treat it as two files, My and File.txt, and thereafter producing an error like My not found.

for file in "$@"
will expand to:
for file in "file1" "file2" "file3" "My File.txt"

27. [Shell scripting tip]
Number of args can be accessed by ${#}. 


28. [Shell scripting tip]
 Quick sed handy examples, when I read those examples I recall the logic, otherwise the theory confuses me.

Replace password hash in shadow file, if you use -i it will replace in the original file, so be careful:

sed -e '/^user:/s/:[^:]*:/:newpassword:/' /etc/shadow

Change the param value to 3 in sshd_config file

sed -i "s/\(\#MaxAuthTries.*\)/MaxAuthTries 3/g" /etc/ssh/sshd_config

Replace all digits

sed -e 's/[[:digit:]]//g'

Replace all other than digits (Use ^ to negate)

sed -e 's/[^[:digit:]]//g'
Replace all alpha-numeric

sed -e 's/[[:alnum:]]//g'
Replace all other than alphanumeric (special chars)

sed -e 's/[^[:alnum:]]//g'
29. [Performance monitoring tip]
 Listing Apache httpd processes and threads.


List httpd processes:
ps -elf | grep httpd

List httpd worker threads:
ps -elfT | grep httpd


30. [Shell scripting tip]
Using readlink and dirname in shell scripts to get absolute path and directory name.


If you want to read the absolute path for a file use:
readlink -f
$ readlink -f ./file.txt would return
/home/file.txt

For only the directory:
dirname
dirname /etc/passwd returns /etc
31. [ Bash usage tip]
Use CTRL-R to go through the history of commands.


1. Ctrl-R and then type command, it gives the most recent one. Press Ctrl -R more times.
2. Exit anytime using Ctrl-C
3. Edit using arrow keys

Thursday, May 22, 2014

Linux: Compilation of 31 Bash tips and tricks - Part 1 (1-15)

I thought I will start capturing all the personal favorite/useful/bombastic/flamboyant  tips that I use frequently and that I forget regularly. Basically if I have to revise all my bash tricks, I would quickly walk over these tips that I collected over a period of time. BTW, I am adding the tips in parts, and I have added part 2 here:
http://rhosted.blogspot.in/2014/05/linux-compilation-of-bash-tips-and_30.html

These are picked from various sources and usually are helpful to me in my day to day work, so you do not have to read the man pages everytime. I do not remember all the sources, so I will quote the source wherever I remember. If you know the source, please let me know.

I know I have written it in a very clumsy way, without too much explaining of the underlying context and theory or any references. But I hope to make it beginner friendly.

Differences between bash and sh:

http://www.gnu.org/software/bash/manual/html_node/Major-Differences-From-The-Bourne-Shell.html

Bash documentation home:
http://www.gnu.org/software/bash/manual/html_node/index.html#SEC_Contents

Here we go:

1. [Bash usage tip]
Text navigation shortcuts (to make you look like a pro).
These shortcuts are pretty handy and save a lot of your time when you have remembered them. In the beginning I struggled, but later after some practice I find them very easy to use.:

Ctrl - A --- Start
Ctrl - E ---- End
Ctrl - U ---- Cut before the cursor
Ctrl - K ---- Cut after the cursor
Ctrl - Y ---- Paste
Ctrl - T ---- Swap chars before cursor
Ctrl - W ---- Delete word left top the cursor
Ctrl - L ---- Clean the screen
Esc- f/Esc - Right arrow ---- Jump 1 word fwd
Esc-b/Esc - Left arrow ---- Jump 1 word backward

2. [Bash usage tip]
Delete Control M or crlf chars in a text file transferred from windows.
 So basically when you transfer text files to and from a *Nix machine. The transfer tool auto-detects that it is a text file and performs an EOL conversion. However, this does not happen 'automatically' if you have explicitly set the transfer mode to "Binary", or your text files are inside a binary file like zip, or tar.gz.:


When you try to execute a shell script having CRLF chars, you get an error of sort:
# ./shellscript.sh
-bash: ./shellscript.sh: /bin/sh^M: bad interpreter: No such file or directory
You can remove them by the simple use of sed. However, the trick is to type in Ctrl-M character.
sed -i 's/^M//' <filename>

Windows uses CR-LF (carriage and return) for line endings, while *nix uses only return (LF). Type Ctrl - m like this:

Ctrl -V then Ctrl M.

 Print/check for Ctrl M chars in a file using cat:

cat -v <filename>
# cat -v shellscript.sh
#!/bin/sh^M
echo "Hello world!"^M

3.[Bash usage tip]
 Quickly setting date and time:

date -s "8 DEC 2013 18:30:00"
Errors: date: invalid date"
4. [Bash usage tip]
 Size of a directory:

du -sh /root
       17G /root

5. [Bash usage tip]
 View ports tcp (t),udp (u) and  LISTENing (l), along with their corresponding processes (p) and use numbers (n)  (netstat hyphen TOO-LP-N):

netstat -tulpn


6. [Bash usage/Shell scripting tip]
 Cut a field correctly, by use of translate and squeez (tr) to squeez the tab/space formatting. e.g. the following returns the pid.
tr for translate and cut are very important tools for parsing a command line output. The -s option of tr followed by the whitespace character " ", squeezes the whitespace characters (including tabs) and reduces its occurrence to a single whitespace. If we do not use tr, then cut will have some problems identifying the correct field due to multiple occurrence of spaces and tabs.:
ps -ef | grep -i weblogic.name=adminserver | tr -s " " | cut -d" " -f2

7. [Bash usage/Shell scripting tip]
 Redirect output to a file and to standard output at the same time using tee:
 You wanted to save the output of netstat in a file using redirection operator '>' but at the same time wanted to see it on the screen. Use tee and |
netstat -tnlp | tee aaa.txt

8. [Shell scripting tip]
 Set -e file to exit upon error (useful in shell scripts):
 This is quite useful if you have a shell script which has commands that depend on the success of the previous command. For e.g. login to ssh and read a remote file. Using set -e, would make sure that the script exits execution if any of the commands return an error.

#!/bin/bash
#Exit immediately if you see an error.
set -e
....

9. [Shell scripting tip]
 Set -x to see debug output (useful in shell scripts):


#!/bin/bash
#Prints a lot of debugging output
set -x
....

10. [Bash usage tip]
 Use screen to detach, reattach or share the terminal: 
This will help you to run a command that runs overnight, disconnect the remote session and go home. Then come back later next day to re attach to the screen and see how it went.

screen (to simply start a screen, see help for detailed options)
Ctrl -D to detach from the screen
screen -r to re attach
screen -x to attach to an existing screen.
If you are unable to locate screen in your linux, perhaps you need to install it, which isnt very difficult.
11. [Bash usage tip]
 Install open source xming from sourcefourge to setup XWindows display:

You need this when you are running a program that requires a GUI window to be displayed, but if the display variable is not set correctly it fails to start the GUI screen.
For e.g. when you run the weblogic patch utility bsu.sh through putty or a remote terminal. You will get an error of sort:
"No X11 DISPLAY variable was set, but this program performed an operation which requires it."

I should write a separate article on how to setup Xming and display correctly with putty. I know I struggled a lot for the first time. :/
Here is some rough information on how it works: What basically happens is that when you install and start Xming on your windows box, it starts an X11 server which listens for incoming X11 information. Then on your remote linux prompt you set up the DISPLAY information to point to your windows box ip. After that when you start a GUI based program, the X11/GUI information is thrown to the ip set in DISPLAY and the listening server on your windows grabs it and displays the GUI to you.

And BTW, you can also avoid this problem by directly logging into the Desktop environment (if installed) in your linux machine through the console.

http://sourceforge.net/projects/xming/

12. [Bash/Linux usage tip]
 Setup a chrooted ssh sftp account. Yes, you can do it! (Tested on Suse) 

Add a user with a home directory:

useradd -d /home/bobuser -m bobuser

#Sftp/chroot Settings for bobuser in /etc/ssh/sshd_config
#Change LogLevel to debug and check errors (if any) in /var/log/messages
Subsystem sftp internal-sftp

#Sftp/chroot Settings for bobuser
Match User bobuser
   X11Forwarding no
   AllowTcpForwarding no
   ForceCommand internal-sftp
   ChrootDirectory /home/bobuser
Now restart the ssh service. And try connecting.

r00ter127:~ # service sshd restart
Shutting down SSH daemon done
Starting SSH daemon done
r00ter127:~ # sftp bobuser@localhost
Connecting to localhost...
Password:
Read from remote host localhost: Connection reset by peer
Couldn't read packet: Connection reset by peer
Ouch..We need to read the errors in /var/log/messages, we had already set it to debug level. There are some requirements expected by the ssh daemon

Jan 25 11:30:27 r00ter127 sshd[10220]: debug1: PAM: establishing credentials
Jan 25 11:30:27 r00ter127 sshd[10220]: fatal: bad ownership or modes for chroot directory "/home/bobuser"
Set the ownership of the home and parent directories to root. That's a requirement. chown root:root /home/bobuser

r00ter127:~ # sftp bobuser@localhost
Connecting to localhost...
Password:
subsystem request failed on channel 0
Couldn't read packet: Connection reset by peer
If you get the above error, then it means there is some problem invoking the sftp server. And the ssh logs are not very helpful in this regard. Make sure you are using the internal-sftp:

Subsystem sftp internal-sftp
...
   ForceCommand internal-sftp
And then.. you are done.

r00ter127:~ # sftp bobuser@localhost
Connecting to localhost...
Password:
sftp> pwd
Remote working directory: /

13. [Bash usage/Security tip]
 Audacious use of history to read a file, e.g. read the /etc/passwd file using history:


history -r /etc/passwd
history

14.[Bash usage tip]
 Use 'which' and 'type' to differentiate if a command is a binary command or a shell builtin.:


which history
type history


15. [Bash usage/Security tip]
What is the hashing algorithm used in my /etc/shadow:
Well, this could be useful if someone asks you whats the hashing algorithm being used to secure the OS passwords. Higher the number, more secure the algorithm. This tip is incomplete actually. You must also know what algorithms are supported by your Linux distro, and how to change the algo to a stronger one. You will also have to change the passwords so that they are hashed with the new algorithm.

$1 -> md5
$2a -> Blowfish
$5 -> Sha256
$6 -> Sha512

Go to part 2:
http://rhosted.blogspot.in/2014/05/linux-compilation-of-bash-tips-and_30.html

Tuesday, February 18, 2014

Testing for HTTP TRACE PUT DELETE methods on web server using Nikto

Intro

Since I received useful feedback on the article on SSL scanning tools. Here is another useful tool "nikto" that I use frequently to check the common security related misconfigurations on my Apache httpd web server. Basically a lot of times we try fixing a web server for security problems, most of the times we are not sure if we fixed the issue. Using a light weight scanner to quickly test your results could be extremely useful as you dont want to wait for those bulky Qualys and Nessus scan reports.

Nikto is a perl script and requires you to have a perl setup installed. It is a web based vulnerability scanner that tests your web server for common misconfigurations. Read more on its homepage.

Download


Get it from here:

http://cirt.net/nikto2

Use cases

My favorite use of Nikto is to test three very important things on my web server:

  1. The HTTP methods that are allowed on my web server
  2. Is directory listing enabled ?
  3. How much information my server is revealing about itself, the version numbers, modules being loaded etc.

Short info on those 3 points:
As a short rule, you should not have methods other than HEAD/GET/POST and OPTIONS allowed on your web server. Why? Because the other methods like TRACE/PUT/DELETE etc are rarely used these days and it is a good practice to turn them off.   


Directory listing is when the web server starts displaying the contents of a directory.

Information revealed: Your web server might be reporting some information to an attacker that could be of use for further attacks. Like the following HTTP headers reveal that an Apache is running version 2.2.3 and the platform is RedHat linux.


https://1x.xx.xx.xx/RSA-Crypto/
GET /RSA-Crypto/ HTTP/1.1
Host: 1x.xx.xx.xx
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:21.0) Gecko/20100101 Firefox/21.0
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://1x.xx.xx.xx/
Connection: keep-alive

HTTP/1.1 200 OK
Date: Mon, 24 Jun 2013 04:01:47 GMT
Server: Apache/2.2.3 (Red Hat)
Content-Length: 1118
Connection: close
Content-Type: text/html;charset=ISO-8859-1

Trial Run


Now suppose after enabling enough of security settings on your web server, you quickly want to test how does it look from the outside:
So you fire up Nikto:

root@bt:/pentest/web/nikto# perl nikto.pl -host https://xx.xx.xx.xx
- Nikto v2.1.4
---------------------------------------------------------------------------
+ Target IP: xx.xx.xx.xx
+ Target Hostname: xx.xx.xx.xx
+ Target Port: 443
---------------------------------------------------------------------------
+ SSL Info: Subject: /C=--/ST=SomeState/L=SomeCity/O=SomeOrganization/OU=SomeOrganizationalUnit/CN=localhost.localdomain/emailAddress=root@localhost.localdomain
Ciphers: DHE-RSA-AES256-SHA
Issuer: /C=--/ST=SomeState/L=SomeCity/O=SomeOrganization/OU=SomeOrganizationalUnit/CN=localhost.localdomain/emailAddress=root@localhost.localdomain
+ Start Time: 2013-06-22 10:36:12
---------------------------------------------------------------------------
+ Server: Apache/2.2.3 (Red Hat)
+ OSVDB-3268: /: Directory indexing found.
+ Hostname 'xx.xx.xx.xx' does not match certificate's CN 'localhost.localdomain/emailAddress=root@localhost.localdomain'
+ Apache/2.2.3 appears to be outdated (current is at least Apache/2.2.17). Apache 1.3.42 (final release) and 2.0.64 are also current.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS, TRACE
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST
+ OSVDB-3268: /./: Directory indexing found.
+ OSVDB-3268: /?mod=node&nid=some_thing&op=view: Directory indexing found.
+ OSVDB-3268: /?mod=some_thing&op=browse: Directory indexing found.
+ /./: Appending '/./' to a directory allows indexing
+ OSVDB-3268: //: Directory indexing found.
+ //: Apache on Red Hat Linux release 9 reveals the root directory listing by default if there is no index page.
+ OSVDB-3268: /?Open: Directory indexing found.
+ OSVDB-3268: /?OpenServer: Directory indexing found.
+ OSVDB-3268: /%2e/: Directory indexing found.
+ OSVDB-576: /%2e/: Weblogic allows source code or directory listing, upgrade to v6.0 SP1 or higher. http://www.securityfocus.com/bid/2513.
+ OSVDB-3268: /?mod=&op=browse: Directory indexing found.
+ OSVDB-3268: /?sql_debug=1: Directory indexing found.
Check out the following lines:

+ Server: Apache/2.2.3 (Red Hat)
+ OSVDB-3268: /: Directory indexing found.
+ Hostname 'xx.xx.xx.xx' does not match certificate's CN 'localhost.localdomain/emailAddress=root@localhost.localdomain'
+ Apache/2.2.3 appears to be outdated (current is at least Apache/2.2.17). Apache 1.3.42 (final release) and 2.0.64 are also current.
+ Allowed HTTP Methods: GET, HEAD, POST, OPTIONS, TRACE
+ OSVDB-877: HTTP TRACE method is active, suggesting the host is vulnerable to XST


So Nikto tells us that it found the directory listing enabled on this server, it found an undesirable method enabled on this server i.e TRACE and it tells us about the Apache version and its platform. It also tells you are running a very old apache version and the latest available version is 2.2.17.

Now you are sure that the changes you placed in apache config worked or not.


[Update++]
Want SSL support on Nikto?
Use cpan to install SSLeay module in perl. I hope you already have perl installed.

cpan[5]> install Net::SSLeay

SSL/TLS Cipher testing: Using SSLScan and ssl_tests

I came to know about the following good tools to check the ciphers running on you SSL service and SSL vulnerabilities.
Often we have this situation where we have various SSL enabled services running on the product, but we do not have a way of verifying the SSL cipher quality.

Use SSLScan and ssl_tests to test for weak ciphers running on your SSL service. I tested it for Apache httpd (443), tomcat (8443).
ssl_tests also tests for common SSL vulnerabilities like the SSL/TLS cipher renegotiation. sslscan primarily does a brute force for Low, medium and high grade ciphers and lists their status as 'Accepted' or 'Rejected' depending on the SSL service's response.

ssl_tests is a shell script that relies on the sslscan tool for making the checks.

Compiling sslscan is generally easy and straight forward but in case you face errors like the one I faced:

gcc -g -Wall -lssl -o sslscan sslscan.c
sslscan.c: In function ‘getCertificate’:sslscan.c:992: warning: implicit declaration of function ‘EC_KEY_print’sslscan.c:992: error: ‘union ’ has no member named ‘ec’sslscan.c:995: error: ‘union ’ has no member named ‘ec’make: *** [all] Error 1

You can tweak the source code to comment out the lines related to EC keys in sslscan.c (most probably you wont be using EC keys) :

//EC_KEY_print(stdoutBIO, publicKey->pkey.ec, 6);
//EC_KEY_print(fileBIO, publicKey->pkey.ec, 4);

Reference:

https://www.owasp.org/index.php/Testing_for_SSL-TLS_(OWASP-CM-001)