Monday, September 1, 2014

21 Books to make you an extreme tech master

Learning is an important part of our life. A habit of reading a lot of books not only keeps updated with technology but also formalizes your knowledge as compared to random google searches and reading through articles. Every book may or may not help you in your day to day job but surely will make you a different person once you have read and mastered the concepts thoroughly. Also every book or author's style may or may not click with you immediately, therefore it is important to keep a lot of books in your arsenal.

This is a collection of few books I would like to recommend to anyone who wants to learn tech stuff. Sometimes if I have to guide beginners into reading a new book, this is what I recommend.

This is a very small list of books and I wanted to keep a motivational journal for my own reference and revisions.
Some of these books I had read more than 5 years back and I still remember their awesomeness. I will keep on updating this page as I get time. This is going to be very big.


  • Programming Groovy
by Venkat Subramaniam

Groovy is a dynamic language. The syntax is very similar to Java and I decided to learn about it because I came across it for a small project.


  • Maven by Example 
  • Maven: The Complete Reference

  • Apache Maven 3 Cookbook

The above three books should be good enough to get a good grasp on maven.  For any problems and tricks stack overflow is the best place to search.

Web Applications and Security

  • XSS Attacks: Cross Site Scripting Exploits and Defense
by Seth Fogie, Jeremiah Grossman, Robert Hansen, Anton Rager, Petko D. Petkov

This is quite a powerful book if you want to master cross site scripting concepts and move beyond alert('xss').

  • SQL Injection Attacks and Defense
Quite a powerful book if you want to get into the complexities of SQL injection. Even though SQL injection is considered trivial these days, but actually it requires a lot of understanding of the involved databases, configuration involved and what works or not. Which could be enough to turn a begineer off.

  • Web Application Hackers Handbook

  • High Performance Websites
You are missing a lot of details on how websites work and what are the essential parameters to be considered while evaluating the performance of web pages. A lot of case studies from Yahoo. Written by a guy who worked on enhancing the performance of Yahoo products. Must read.

General Security

  • Hacking: The Art of Exploitation, 2nd Edition

One of the best books out there to get a general idea of what goes under the hood. The buffer overflow explanation is extrememly good and it also deals with several proetections and exploitation techniques. For some reason the book provides you enough clarity.

  • Hacking Exposed series
Hacking Exposed: Network Security Secrets and Solutions, Sixth Edition
by Stuart McClure , Joel Scambray , George Kurtz

Exploitation and Tools

  • Chained Exploits: Advanced Hacking Attacks from Start to Finish
Andrew Whitaker (Author), Keatron Evans (Author), Jack Voth (Author)

This book deals with security in a very practical and enjoyable way making it very easy to understand real life security challenges. And how do you put the security tools to their practical use.

  • Buffer Overflow Attacks: Detect, Exploit, Prevent
by Jason Deckard

Totally focused on Buffer overflow attacks and their exploitation. Expert mode turned on.

  • Writing Security Tools and Exploits
by James C. Foster, Vincent T. Liu

  • The Shellcoder's Handbook: Discovering and Exploiting Security Holes
by Chris Anley

If you are into assembly and shellcoding techniques. This book would be an extreme fun. Shellcode is the small piece of machine code that you try to get executed while exploiting a buffer overflow.

Matering Wireshark and Network analysis

  • Practical Packet Analysis, 2nd Edition
Using Wireshark to Solve Real-World Network Problems

  • Wireshark & Ethereal Network Protocol Analyzer Toolkit
(Jay Beale's Open Source Security)

Network packet analysis is a skill that a majority of professionals lack. These books would turn you into 'The One' who reads and understands whats going on the wire. Troubleshooting network related problems and mapping them with real life use cases.

Cryptography (programming)

  • Java Cryptography
By Jonathan Knudsen

It is a little old book. But very well written. Most of the concepts have not changed as far as JCE and JCA is concerned. There are not many well written books that cover Java cryptography. Have you ever wondered what exactly a Secure Random is? What is its significance. How to use the Java JCE to encrypt stuff, how to use different encryption algorithms and key sizes effectively to encrypt and decrypt data.

Linux related

  • Bash Cookbook
Solutions and Examples for bash UsersBy Carl Albing, JP Vossen, Cameron Newham

This book turns you in a master of bash shell. Minute differences that always puzzle even the experts and by learning them you can show off.

  • SSH, The Secure Shell: The Definitive Guide
By Daniel J. Barrett, Richard E. Silverman

Everything you wanted to know about the SSH protocol.

  • Build your own Linux
Linux from Scratch project

By far the best Linux oriented and free book. Learn how to create your Linux. Compile all the packages, assemble your own tools, compile your own kernel. You learn what all basic stuff is required to build a Linux system. If you know what you are looking for, you can build an extremely sophisticated Linux that deals with a specialized job and very small too.

  • The Linux Kernel Module Programming Guide
        Peter Jay Salzman
        Michael Burian
        Ori Pomerantz

This is a free book. Its old, but it is very good for understanding the basics of Kernel modules and how they work. You ca also write and compile your own hello world kernel module. It covers lots of basics, so if you want to grab an idea about the low level working of the internals, then you should give it a quick read. I am reading it, because while investigating Linux kernel related vulnerabilities, sometimes you need to understand how the whole kernel module/driver procedure simply works. A lot of times vulnerabilities are reported in the kernel, however it does not necessarily mean that your Linux is vulnerable. There are lots of ifs, oohs and aahs involved. And only a hawk eyed kernel expert can tell you the difference. 

Sunday, August 31, 2014

JSSE based SSL ciphersuite tester

Just performs a handshake with the list of JSSE ciphers with the SSL server. If handshake is successful it marks it as a success. This is more of a test for Java based SSL clients which use JSSE for SSL/TLS communication. This code relies heavily on the underlying implementation provided by Java JDK/JSSE. Use it with 1.7 as a lot of cipher support has been added. As I mentioned, this is not a true SSL cipher scanner, because it depends on what ciphersuites have been enabled by JSSE. The server might support other ciphers that are not yet implemented by JSSE, but they wont turn up in the results. Actually if you can read from the raw SSL handshake packets, you can understand what the server SSL supports, you do not need java implementation for that.

package com.ssl.test;

import java.util.ArrayList;
import java.util.Collections;


public class SSLTesting {

 private static final int PORT_TARGET = 443;
 private static final String HOST = "";
 private static final String PROTO_SSLV3 = "SSLv3";
 private static final String PROTO_TLSV1 = "TLSv1";
 private static final String PROTO_TLSV11 = "TLSv1.1";
 private static final String PROTO_TLSV12 = "TLSv1.2";
 private static final boolean VERBOSE = false;
 // Note 1: Standard names for all the cipher suites, not all are yet implemented

 // Note 2: All the ones supported by Java 7
 //See Note 2.
 private static final String jsseCiphersDisabledByDefault = "TLS_DH_anon_WITH_AES_256_CBC_SHA256:TLS_ECDH_anon_WITH_AES_256_CBC_SHA:TLS_DH_anon_WITH_AES_256_CBC_SHA:"
    //See Note 2.
 private static final String jsseCiphersEnabledByDefault = "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384:TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384:TLS_RSA_WITH_AES_256_CBC_SHA256:"
 //A lot of them are not yet supported on jsse, See Note 1.
 private static final String jsseCompleteCipherList = "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA:SSL_DH_anon_EXPORT_WITH_RC4_40_MD5:SSL_DH_anon_WITH_3DES_EDE_CBC_SHA:"
   + "TLS_DH_anon_WITH_AES_128_CBC_SHA:TLS_DH_anon_WITH_AES_128_CBC_SHA256:TLS_DH_anon_WITH_AES_128_GCM_SHA256:TLS_DH_anon_WITH_AES_256_CBC_SHA:"
 public static void main(String[] args) throws Exception {
  String ciphers = jsseCiphersEnabledByDefault + ":" + jsseCiphersDisabledByDefault;
  System.out.println("Using Hostname : port = " + HOST + " : " + PORT_TARGET);
  //test enabled and the ones that disabled by default
   testSSL(HOST, PORT_TARGET, PROTO_SSLV3, ciphers);
   testSSL(HOST, PORT_TARGET, PROTO_TLSV1, ciphers);
   testSSL(HOST, PORT_TARGET, PROTO_TLSV11, ciphers);
   testSSL(HOST, PORT_TARGET, PROTO_TLSV12, ciphers);
  //test weak ciphers
  /* testSSL(HOST, PORT_TARGET, PROTO_SSLV3, jsseCiphersDisabledByDefault);
   testSSL(HOST, PORT_TARGET, PROTO_TLSV1, jsseCiphersDisabledByDefault);
   testSSL(HOST, PORT_TARGET, PROTO_TLSV11, jsseCiphersDisabledByDefault);
   testSSL(HOST, PORT_TARGET, PROTO_TLSV12, jsseCiphersDisabledByDefault);*/

 private static void testSSL(String hostname, int port, String version, String cipherSuitesToTest) {
  try {
   System.out.println("Protocol : " + version);
   ArrayList success = new ArrayList();
   ArrayList unsupported = new ArrayList();
   ArrayList fail = new ArrayList();
   SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory
   SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);
   //set the SSL version to be used
   String[] prots = { version };

   String[] cipherSuitesClient = cipherSuitesToTest.split(":");

   for (String ciphers : cipherSuitesClient) {
    socket = (SSLSocket) factory.createSocket(hostname, port);
    String[] array = { ciphers };
    //try making a handshake
    try {
    } catch ( e) {
    } catch (java.lang.IllegalArgumentException e){
     if (e.getMessage().contains("Unsupported ciphersuite") || e.getMessage().contains("Cannot support"))
    catch (Exception e) {
     System.out.println(ciphers + ":" + e.getClass() + " "
       + e.getMessage());
   System.out.println("Testing " + version + " ciphers. Count: "
     + cipherSuitesClient.length);
   System.out.println("Successful Handshake count = "
     + success.size());
   for (String name : success) {
    System.out.println("[" + version + "]" + " +" + name);
   System.out.println("Unsupported list. Count = " + unsupported.size());
   for (String name : unsupported) {
    System.out.println("[" + version + "]" + "XXX " + name);

   System.out.println("Handshake Failed Count = " + fail.size());
   for (String name : fail) {
     System.out.println("[" + version + "]" + "-" + name);

  } catch (Exception e) {

Saturday, August 30, 2014

Java/JSSE Handshake SSL/TLS exceptions

If you are facing some of the below errors, it might mean you are using a Java that does not have the support for the thing you are trying to do:

Example 1: Illegal argument exceptions for protocol version
You are enabling TLS 1.1 and TLS 1.2, but it may give you an exception if you are using Java 1.6. 1.6 does not support TLS 1.1 and TLS 1.2. You can check here as it supports only SSLv3 and TLSv1 (See Support classes and Interfaces section and see the possible values for SSLContext):

String[] protocols = {"TLSv1.1", "TLSv1.2"};
socket = (SSLSocket) factory.createSocket(hostname, port);

Protocol : TLSv1.1
java.lang.IllegalArgumentException: TLSv1.1
    at com.ssl.test.SSLTesting.testSSL(
    at com.ssl.test.SSLTesting.main(
Protocol : TLSv1.2
java.lang.IllegalArgumentException: TLSv1.2
    at com.ssl.test.SSLTesting.testSSL(
    at com.ssl.test.SSLTesting.main(

So, as an example, when I check, I see that my eclipse is still using 1.6 for execution.

So I need to change it to 1.7 to destroy these ugly exceptions. :D. You can check the page for JSSE 7. and see the values for SSLContext. Changed to 1.7.

Example 2: Cannot support cipher exceptions:

Cannot support exceptions again point to the use of an incorrect JRE like 1.6. However, unsupported exception (that you can get while using 1.7) might mean that the ciphersuite is still not implemented in JSSE 1.7.
To get a list of a complete list of JSSE cipher names you can use this link:

However, you must know that these are only the names that JSSE is going to use, some of the ciphers are still not implemented and can be expected to be implemented in Java 8. To see what all ciphers are implemendted in 1.7, you can use this link, check the Cipher suite section:

java.lang.IllegalArgumentException: Cannot support TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA with currently installed providers
    at com.ssl.test.SSLTesting.testSSL(

Friday, August 15, 2014

SSL/TLS cipher testing notes

I am trying to gather some freely available tools, techniques and links that can help running SSL/TLS related tests. The more I learn, the more stuff I will add. SSL/TLS is not that simple, you cannot rely on the output of just 1 tool. You also need to understand how that tool/script works internally.

Tools and scripts (will keep adding)

Testing might be affected with what openssl version you have installed, because older versions may not have support for newer cipher suites or higher protocols. So while testing you need to take this into consideration.

1. Nmap ssl-enum-ciphers script

nmap --script ssl-enum-ciphers -p 443 hostname

2. sslscan.

Uses openssl internally. If you compile it on redhat, you may run into compilation issues because EC crypto is not there in openssl in redhat (depending on your version). If you are not interested in testing EC, then you can comment out the lines as mentioned in my previous post:

3. ssl_tests
ssl_tests is a shell script that uses sslscan and openssl internally to connect.

4. Using OpenSSL directly
openssl s_client -connect host:port

5. sslyze
root@kali:~# sslyze --tlsv1

6. TestSSLServer : A simple java program that does the same kind of testing. The program uses plain sockets and raw packet level inspection and does not depend on any provider like JSSE or Openssl as such. So it is very good for learning at raw packet level as to how do you know whether compression is supported or not. The program also checks CRIME and BEAST status by checking the compression support in the connection and inspecting the protocol version. You can see how it does that in the comments.

However, I would recommend you develop your own understand about CRIME/BEAST working and its latest status depending on your own application implementation rather than relying on the output of the testing program. Things and assumptions keep changing with time.

Original reference:

To be continued..

Helpful references for testing

TLS learning

[*]  Listing of Openssl ciphers (meaning of examples like ALL:!ADH:@STRENGTH)

[*]  A little advanced but good learning material about TLS

[*]  Explains a lot of common SSL problems in a very simple way.

[*]  Understanding the meaning of a cipher string like DHE-RSA-AES256-SHA

[*]  High/Low/Med grade ciphers

SSL/TLS best practices


Products using SSL

[*] Postgres using SSL (How to test SSL being used)


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

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...
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...
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...
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)


password requisite 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 remember=5 retry=3

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 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 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

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
Account locked due to 6 failed logins

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

Account locked due to 9 failed logins

Received disconnect from 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.


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.


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
   kp = keyPairGenerator.generateKeyPair();

  } catch (NoSuchAlgorithmException e) {
  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) {
  } catch (NoSuchAlgorithmException e) {
  } catch (NoSuchPaddingException e) {
  } catch (IllegalBlockSizeException e) {
  } catch (BadPaddingException e) {
  return null;

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

  return null;



public class Main {

  * @param args
 public static void main(String[] args) {

 private static void asymmetricEncryptionSimple() {
  AsymmetricKeyHelper keyHelper = new AsymmetricKeyHelper();
  KeyPair keyPair = keyHelper.keyPair();
  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));