Create a self signed dummy SSL certificate in APACHE

* Generating a Private Key and CSR

We assume you have openssl module/package installed on your system or server .
The openssl toolkit is used to generate an RSA Private Key and CSR (Certificate Signing Request). It can also be used to generate self-signed certificates which can be used for testing purposes or internal usage. The utility used to do all of these tasks is known simply as openssl. It should be installed in the /usr/local/ssl/bin directory. You may want to add this directory to your PATH, or copy or link the openssl utility to a directory that is already in your PATH so that you do not have to type the full path to the executable. The examples below will assume that openssl is in a location that is accessible to you without using the full path to the command.

The first step is to create your RSA Private Key. This key is a 1024 bit RSA key which is encrypted using Triple-DES and stored in a PEM format so that it is readable as ASCII text. We will use several files as random seed enhancers which will help to make the key more secure. Text files that have been compressed with a utility such as gzip are good choices. The key is generated using the following command, where file1:file2:etc represents the random compressed files.

$ openssl genrsa -des3 -rand file1:file2:file3:file4:file5 -out server.key 1024

The command will prompt you for a pass-phrase and then store the key in the file server.key. It is critical that the pass-phrase be secure and not forgotten. If either the key is lost, or the pass-phrase is forgotten, the certificate will be useless! It cannot be stressed enough how important the private key is to the certificate. If the private key and pass-phrase are compromised, the certificate will have to be revoked, costing you the price of the certificate all over again if you have paid an authority for the certificate. It may be a wise idea to back this file up to secure media, such as tape or diskette.

One unfortunate side-effect of the pass-phrased private key is that Apache will ask for the pass-phrase each time the web server is started. Obviously this is not necessarily convenient as someone will not always be around to type in the pass-phrase, such as after a reboot or crash. mod_ssl includes the ability to use an external program in place of the built-in pass-phrase dialog, however, this is not necessarily the most secure option either. It is possible to remove the Triple-DES encryption from the key, thereby no longer needing to type in a pass-phrase. If the private key is no longer encrypted, it is critical that this file only be readable by the root user! If your system is ever compromised and a third party obtains your unencrypted private key, the corresponding certificate will need to be revoked. With that being said, use the following command to remove the pass-phrase from the key:

$ openssl rsa -in server.key -out server.pem

Once the private key is generated a Certificate Signing Request can be generated. The CSR is then used in one of two ways. Ideally, the CSR will be sent to a Certificate Authority, such as Thawte or Verisign who will verify the identity of the requestor and issue a signed certificate. The second option is to self-sign the CSR, which will be demonstrated in the next section.

During the generation of the CSR, you will be prompted for several pieces of information. These are the X.509 attributes of the certificate. One of the prompts will be for “Common Name (e.g., YOUR name)“. It is important that this field be filled in with the fully qualified domain name of the server to be protected by SSL. If the website to be protected will be, then enter at this prompt. The command to generate the CSR is as follows:

$ openssl req -new -key server.key -out server.csr

A sample CSR generation session is shown below, with sample responses shown in bold:

$ openssl req -new -key server.key -out server.csr
Using configuration from /usr/local/ssl/openssl.cnf
Enter PEM pass phrase:Enter pass phrase here

You are about to be asked to enter information that will be incorporated into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank.

For some fields there will be a default value, If you enter ‘.’, the field will be left blank.


Country Name (2 letter code) [AU]:IN
State or Province Name (full name) [Some-State]:Maharshtra
Locality Name (eg, city) []:Mumbai
Organization Name (eg, company) [Internet Widgits Pty Ltd]:ITQuery Tech
Organizational Unit Name (eg, section) []: Web

Common Name (eg, YOUR name) []
Email Address []

Please enter the following ‘extra’ attributes to be sent with your certificate request
A challenge password []:
An optional company name []:

Generating a Self-Signed Certificate

At this point you will need to generate a self-signed certificate because you either don’t plan on having your certificate signed by a CA, or you wish to test your new SSL implementation while the CA is signing your certificate. In my experience dealing with Thawte, it can take up to a week or more before receiving your signed certificate. The time it takes to receive the certificate will vary based on how quickly they receive your required documentation. This temporary certificate will generate an error in the client browser to the effect that the signing certificate authority is unknown and not trusted.

To generate a temporary certificate which is good for 60 days, issue the following command:

$ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Try following these steps incase if you do not want to ssl certificate with passphrase, since it ask everytime you restart your apache service. Ensure that you have correct certificate name with your apache config.

$openssl rsa -in server.key -out server.key.nopass

Installing the Private Key and Certificate

When Apache with mod_ssl is installed, it creates several directories in the Apache config directory. The location of this directory will differ depending on how Apache was compiled. If using my instructions on compiling Apache, the config directory is /usr/local/apache/etc. The directories mod_ssl creates include ssl.crt, ssl.csr, and ssl.key. These are good locations to store server certificates, CSRs, and private keys, respectively. If there will be multiple SSL enabled hosts on one server, it may be good practice to name the files with the fully qualified domain name of the SSL enabled host.

When adding SSL enabled virtualhosts to the web server, I prefer to keep all of the SSL virtualhosts in a separate file. This insures that all SSL hosts can be easily found in one location and helps to keep the httpd.conf file from growing too large. The SSL virtualhosts will be kept in a file called ssl.conf. In order for Apache to recognize and parse this file, it must be included in the httpd.conf file with the following directive:

Include /usr/local/apache/etc/ssl.conf

Configuring SSL Enabled Virtual Hosts

Extensive examples of SSL configurations for a virtualhost are included as part of the /usr/local/apache/etc/httpd.conf.default file installed with mod_ssl. Please refer to this file and to the mod_ssl documentation for more detailed information on configuration options. A basic SSL enabled virtualhost will appear as follows in the ssl.conf file:

# SSL Virtual Hosts

DocumentRoot /usr/local/apache/share/htdocs
ScriptAlias /cgi-bin/ /usr/local/apache/share/htdocs/cgi-bin/
SSLEngine on
SSLCertificateFile /usr/local/apache/etc/ssl.crt/server.crt
SSLCertificateKeyFile /usr/local/apache/etc/ssl.key/server.pem
SetEnvIf User-Agent “.*MSIE.*” nokeepalive ssl-unclean-shutdown
CustomLog /usr/local/apache/var/log/ssl_request_log \”%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \”%r\” %b”


This will create an SSL virtualhost named, which is accessed via port 443 (the standard port for https) on the default IP address of the web server. It is possible to add as many additional virtualhosts as there are IP addresses that the web server listens to. Simply add additional virtualhost blocks inside of the and tags. Due to the nature of the SSL encryption of the HTTP traffic, it is NOT possible to have name-based (HTTP1.1) SSL virtual hosts. To create a new SSL virtualhost on a different IP address, simply replace _default_ with the IP address of the virtualhost.

Restart apache to load the new changed configuration file.

— Test the configuration file (httpd.conf).
# apachectl configtest

— Restart the apache
# apachectl restart

Posted in Apache, Unix/Linux | Tagged , , , | Leave a comment

Apache Tomcat and Apache HTTP web server integration (mod_jk vs mod_proxy)

Apache Tomcat and Apache HTTP web server integration –

1. I would advice to use Apache http web server module “mod_jk” instead of “mod_proxy” because of following reasons –


  • It has greater control to manage the request/response internally between Apache’s http and tomcat server.
  • This will enable to have internal software load balancing with greater control options, if required.
  • It is more secure then mod_proxy.
  • Detailed log mechanism to figure out any communication errors.
  • Greater control over option what you want to server from which server internally (ie. static content from http server and java content from tomcat)
  • Support for large AJP packet sizes (“mod_proxy_ajp” does not support large 8K+ packet sizes).
  • Advanced node failure detection (if load balancer mechanism used).

* Only biggest advantage of using mod_proxy* module is easy and short configuration in Apache conf file to achieve integration.

2. SSL certificate should be installed on Apache’s http server instead of tomcat.
3. Tomcat should be running on separate port other than standard http and https port.
4. Apache’s http webserver should be running on standard http and https ports. It is easy feasible to secure Apache’s http server instead of tomcat server, since tomcat is not a full featured web server.

Posted in Apache, Unix/Linux | Tagged , , , | 1 Comment

Tips on Ant script

Tokenizer user input

ANT can be used as great tool for tokenizing user input during application builiding process. This script will take a string from user input and tokenize in multiple string.

Limitation : Currently this script tokenize single seperator only.


[input] Enter site name
[input] Enter seperator
[echo] www
[echo] google
[echo] com

The script is as follows :

<?xml version=”1.0″ encoding=”UTF-8″?>
<project name=”Split input parameter” basedir=”.” default=”split”>

<taskdef resource=”net/sf/antcontrib/antlib.xml”>
<pathelement location=”${basedir}/lib/ant-contrib-1.0b3.jar”/>

<scriptdef name=”split” language=”javascript”>
<attribute name=”value”/>
<attribute name=”sep”/>
<attribute name=”prefix”/>
values = attributes.get(“value”).split(attributes.get(“sep”));
str = “”;
for(i=0; i<values.length; i++) {
str = str + “,” + values[i];
str = str.substring(str.indexOf(“,”) + 1, str.length);
project.setNewProperty(attributes.get(“prefix”),    str);

<target name=”split” description=”Tokenised input parameter”>
<input message=”Enter site name” addproperty=”site”/>
<input message=”Enter seperator” addproperty=”seperator”/>
<split value=”${site}” sep=”${seperator}” prefix=”value”/>
<property name=”list” value=”${value}”/>
<for list=”${list}” param=”letter”>
<echo message=”@{letter}”/>

Posted in ANT | 1 Comment

Add user or linux/unix user creation

Add user or linux/unix user creation

#adduser <User_Name>
This will create a user with default home directory settings defined on system

ie. Home directory path(when user log into system will see this directory) will  be  /home/User_Name

If you want to add custom path for user’s home directory

#adduser <User_Name> -d /opt/User_Name
Here you are assigning home directory with option -d

If you want to add custom home directory path and add user into an existing group.

#adduser <User_Name> -d /opt/User_Name -g Group_Name

Adding a parameter -g will assign this new user under given existing group along with custom home directory path.

Force user to change password on their first successful login

#chage -d 0 User_Name


Posted in Unix/Linux | 1 Comment

SQL query output in CSV format (MySQL)

SQL query output in CSV format (MySQL).

You can have your SQL Query saved as a file “QUERY.sql”

INTO OUTFILE ‘/tmp/DataFile_output.csv’

Now run this query

$mysql -uuser_name -ppassword databasename < /path/to/sqlfile/QUERY.sql

Even this this can be schedule in cron for cronjob routine.


Posted in Database, Shell script | Tagged | Leave a comment

FTP Script to transfer only changed files

FTP Script to transfer only changed files using FTP protocol

Save below script as “”

# File:
# Description:  Setup Environment Variables for FTP task by itquery

REMOTE_FTP_SERVER=   # Server where to put the Incremental Load files
REMOTE_FTP_USER=ftpuser                # User to login at REMOTE_FTP_USER
REMOTE_FTP_PASSWORD=ftppassword #Passwd for FTP usr at REMOTE_FTP_USR
REMOTE_FTP_DIR=/opt/remoteftparea   # Directory where to put the files
SOURCE_DIR=/opt/localftparea                   # Directory from where file is FTP’d

TIMESTAMP=`date +%d%m%Y`
LOGFILE=/opt/FTP_$TIMESTAMP.log     # Log file

log() { echo “`date +%H:%M` – $1” >> $LOGFILE; }


Save below script as

# File:
# Description:  Trasfer file if they are changed and are more than 0 byte onto remote area # using FTP protocol task by itquery
. `dirname $0`/

log “$0 – Start of Execution”
# Get ready for FTP, from the source directory
# Use additonal USER’s environment variable of $HOME/.bash_profile file for ftp transfer. ~/.bash_profile

# Checks if the remote server is responding
/bin/ping “$REMOTE_FTP_SERVER” 64 1 >>$LOGFILE
if [ $? -ne 0 ]
log ” Server (“$REMOTE_FTP_SERVER”) is not responding…FTP aborted”
exit 1

# Transfer only new/files greater than 0 byte files via FTP.
for FILE in `ls -1  $SOURCE_DIR`
FoundFile=`find  $FILE -mtime -2 |wc -l`
if [ “$FoundFile” -gt “0” ]
echo “Transferring $FILE now..”
put $FILE
echo “Nothing to Trasnsfer”

#Archiving the FTP’d file to a new location $SOURCE_DIR/Done
log “$0 – End of Execution”
exit 0

Posted in Shell script, Unix/Linux | Tagged , | Leave a comment

How JQuery’s .load() works???

Have you ever wondered how JQuery’s .load() api works? well i did and tried to figure out something similar and this is what i came up with.

var loadData = (function () {
  var _this;

  return {
    response: null,
    url: null,
    writeDataOfId: null,
    data: null,
    writeDataToId: null,
    dummyDiv: null,

    init: function (url, writeDataOfId, writeDataToId) {
      if (!url && !writeDataOfId && !writeDataToId) {
        return; // don't do anything if none of the parameters are present
      _this = this;
      this.writeDataToId = document.getElementById(writeDataToId);
      if (!this.writeDataToId) {
      this.url = url;
      this.writeDataOfId = writeDataOfId;
    ajax: function () {
      var xhr = null;
      try {
        xhr = new window.XMLHttpRequest();
      } catch (e) {
        try {
          xhr = new window.ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
          throw new Error('Not Supported');
      if (xhr) {'GET', this.url, false);
        xhr.onreadystatechange = function () {
          if (xhr.readyState == 4) {
            if (xhr.status == 200) {
              _this.response = xhr.responseText;
            } else {
              throw new Error('Error Occurred!!!');
    writeData: function () {
      var elem;
      if (!this.response) {
      this.dummyDiv = document.createElement('div'); //dummy div to hold the data so that dom methods can be
                                                     //performed to get the elements.
      this.dummyDiv.innerHTML = this.response;
      elem = this.findElem();
      if (elem) {
        this.writeDataToId.innerHTML = elem.innerHTML;
      } else {
        throw new Error('Error Occurred!!!');
      this.dummyDiv = null; // free the memory after the use of dummyDiv is done.
    findElem: function () {
      var i = 0, allTags = this.dummyDiv.getElementsByTagName('*'), l = allTags.length, elem;
      for (; i < l; i++) {
        elem = allTags[i];
        if (elem.getAttribute('id') === this.writeDataOfId) {
          return elem;
      return null;

// and in dom ready make a call like this

loadData.init(<url>, <id u want to get data of>, <id in which you want to write the data>);

I know this is not so good of a post, but hope this gives you a little bit of idea what i’m trying to say.

Cheers!!! 😉

Posted in UI-Development | Tagged , | Leave a comment

SubVersion Integration with multiple Microsoft Active Directory for user authentication

* Download source of APR from here. And follow these steps.

# tar -zxvf apr-version.tar.gz
# cd apr-version
# ./configure
# make
# make install

* Download source of APR Utils from APR from And follow these steps.

# tar -zxvf apr-util-version.tar.gz
# cd apr-util-version
# ./configure
# make
# make install

* Download source of subversion from And follow these steps.

# tar -zxvf subversion-version.tar.gz
# cd subversion-version
# ./configure –with-apr=/path/to/apr/instalation –with-apr-util=/path/to/apr-util/installation
# make
# make install

* Download apache from And compile it with SSL and proxy support for SVN access.

# tar -zxvf httpd-version.tar.gz
# cd httpd-version
# ./configure –prefix=PREFIX –enable-modules=all –enable-mods-shared=most –enable-module=ldap authnz_ldap ssl proxy –enable-mods-shared=ldap authnz_ldap ssl proxy –with-apr=/path/to/apr/instalation –with-apr-util=/path/to/apr-util/installation
# make all
# make install

* Now compile svn modules for apache. Go back to source of subversion and follow these steps.

# ./configure –with-apxs=/path/to/apache2/bin/apxs
# rm /usr/local/lib/libsvn*
# make clean && make && make install

After the make install, the Subversion shared libraries are in /usr/local/lib/. should be installed in /path/to/apache/modules/.

* Now edit httpd.conf located in /path/to/apache/conf/ and add following lines and save the file.

LoadModule dav_svn_module     modules/
LoadModule authz_svn_module   modules/

* Create SVN Repository.(Creating SVN Repository)
* Edit httpd.conf.

<VirtualHost *:443>
SSLEngine On
LoadModule python_module lib/modules/
# Work around authz and SVNListParentPath issue
RedirectMatch ^(/svn)$ $1/
<Location /svn/>
DAV svn
SVNParentPath “/opt/snv/data/repositories”
SVNReposName “SubVersion Respository”
AuthzSVNAccessFile “/opt/svn/data/conf/svn_access_file”
SVNListParentPath On
Allow from all
AuthType Basic
AuthName “AD system authentication eg. firstname_lastname”
AuthBasicProvider ldap-1 ldap-2 ldap-3 svn-file-users
Require valid-user

* create user and pass
# htpasswd -m -c  /opt/svn/data/conf/svn_access_file user1

Posted in Apache, SVN, Unix/Linux | Tagged , , , | Leave a comment

SED on-liners

Stream Editor or SED on-liners :
##To print line first 10 from a file
$sed -q10 filename.txt

## Find and replace pattern text
$sed ‘s/find_text/replace_text/g’ file.txt

Posted in Shell script, Unix/Linux | Tagged | Leave a comment

Securing Apache

First and foremost thing is to make sure you have insalled the latest apache and security patches.

– 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 and think that 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:

Order Deny,Allow
Deny from all
Options None
AllowOverride None

Order Allow,Deny
Allow from all

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

Order allow,deny
Deny from all
Satisfy All

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

Or by IP:

Order Deny,Allow
Deny from all
Allow from

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

Posted in Apache, Unix/Linux | Tagged | Leave a comment