Migraine free Java SSL management

I recently had the need to turn a JAVA web application into SSL only. While the configuration is almost painless (-Dhttps.port=443 -Dhttp.port=disabled), the certificate management wasn’t quite as effective, due to a certain lack of clear documentation (where have I heard that again?).

We start assuming you already have your OpenSSL generated key/crt files, because that’s what happened here, but stay tuned:

$ openssl pkcs12 -export -in CertificateChain.pem -inkey Certificate.key -out Certificate.pkcs12 -name HostAlias -noiter -nomaciter

With this done you have a PKCS12 KeyStore you can use for the web server, much like the PEM/KEY you would use in Apache. Then, you use this configuration to properly load it:

-Dhttps.keyStoreType=PKCS12 -Dhttps.keyStore=/absolute/path/to/certificate.pkcs12 -Dhttps.keyStorePassword=KeyStorePassword

It may seem like nothing, but the keyStoreType part made the difference between a proper certificate chain and an unsigned chain localhost/localhost, which caused me major migraine for the good part of an afternoon.

With this said and done you can start the application/server and see to it that the certificate now lists itself properly and with all the needed CAs attached to it.


Self-Signed Certificate with Subject Alternative Names (SAN) [AntiFUD]

Wrangling obscure OpenSSL functions to create and publish SSL certificates has always been kind of a mess. If you want(ed) to create a valid self-signed certificate for multi domains or, at least, and, you most likely were out of luck.

There is a lot of wrong or partial documentation on the subject, but is… well… wrong and/or incomplete. It is thus time for another episode of AntiFUD.

The problem

You have multiple paths of the same website to cover for, but a single CN. If you use then will result in invalid SSL certificate, and vice versa. Suppose you have the following domain names:

  • *

In such a scenario there is no real victory no matter what you choose to use as a CN: the most used wildcard CN, *, is of no use either because it matches with and, but not with The only way to address all these issues is to create and sign a X.509 v3 SSL certificate, to allow SAN. The SAN extension has been introduce to resolve all of these problems, allowing the validity of multiple domains/subdomains within the same certificate.

Creating the certificate

We have to start by creating an alternative configuration file to use with OpenSSL, and list the server names we need. As mentioned below we also have to enable the usage of v3 extensions.

# mkdir certificates
# cd certificates
# cp /etc/ssl/openssl.cnf ./example-com.cnf

We can now edit the file and adjust as needed:

[ req ]
x509_extensions = v3_ca
req_extensions = v3_req

[ usr_cert ]
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment

[ v3_ca ]

[ alt_names ]
DNS.1 =
DNS.2 =
DNS.3 = *

In the default file, parameters such as req_extensions and keyUsage are commented out, while subjectAltName is missing. We have to add it to v3_req and v3_ca, and create the respective section. It can be created anywhere in the file, but it is generally appended to the bottom. Since the CN is (or, at least, should be) ignored in the presence of SAN, we insert all the names in the alt_names field.

With the configuration in place we can now create the certificate:

# openssl genrsa -out example-com.key 4096
# openssl req -new -config example-com.cnf -key example-com.key -out example-com.csr
# openssl x509 -req -in example-com.csr -CA rootCA.pem -CAkey rootCA.key -CAserial -out example-com.crt -days 365  -extfile example-com.cnf -extensions v3_ca

The deviation from the standard procedure is the addition of the v3 during the CA sign. We do this by using -extfile example-com.cnf to use the custom configurations, and specifying -extensions v3_ca to make sure SAN are passed through and saved in the signed certificate.

To make sure it worked you can do the following:

# openssl x509 -in example-com.crt -text -noout
        X509v3 extensions:
            X509v3 Subject Alternative Name:
      ,, DNS:*
            X509v3 Subject Key Identifier:
            X509v3 Authority Key Identifier:

            X509v3 Basic Constraints:

The only thing left to do is to set up the certificates in the server, and everything will work as intended.


RSA/DSA ssh(d) keys, a synthetic guide

There is a lot of useless and cryptic information in regard to any type of encryption, typical as per USA’s FUD standards. I’ll post here a synthesis of the steps necessary to wave plain text password logins goodbye.

I’ll assume you already have the private/public key couple by now, if not you can use puttygen. This topic is well covered, although they have a tendency to suggest a low level of encryption. Isn’t it strange how for apparently “anybody” an 8 letter password, or a 2048 bit key, is enough for everyone? For the record, I used a 4096 bit DSA key.

I will also assume that you’re setting up a server on Linux, so ymmv.

Coming back to the topic at hand, you have a private key, that you use to login from your computer, and a public key that you will deploy to one or more PCs/servers. The public key will probably look like this:

Comment: "dsa-key-[DATE]"

This won’t work in most cases, as SSHD expects a certain format. You will then have to convert that key into this:


The beginning of the line is ssh-dss for DSA keys, ssh-rsa for RSA keys. With this line of text in hand, you can open ~/.ssh/authenticated_keys on your servers, copy the key data into it, and save.

The last thing to do is to reconfigure the sshd.

ServerKeyBits 1024
AuthorizedKeysFile      %h/.ssh/authorized_keys
PasswordAuthentication no

While checking the configuration I noticed that the ephemeral key size (ServerKeyBits) was defaulted to 1 kilobit. ONE FREAKING KILOBIT. To give you a comparison, in 2002 on IRC channels we used DH with 2048 bits of encryption. That’s 13 years ago. For chat. You might want to turn it up several notches.

For the server to actually use the key you provided, you will need to uncomment the AuthorizedKeysFile, keep in mind that the path may differ. It could be .ssh/authorized_keys on CentOS, %h/.ssh/authorized_keys on Ubuntu, so on and so forth.

AFTER you made sure you can actually log in with your DSA/RSA key, you will disable plain text authentication by uncommenting AuthorizedKeysFile and setting it to no.

This is all the black magic involved in it, without the convoluted mess that always surrounds OpenSSL/SSHD documentations.


Minty to the rescue, tales of LVM basics and recoveries

In this post I’ll document a few replicable techniques that might help the less experts in managing and recovering a faulty hard drive with LVM in use. Note: it may contain Windows and Virtual Machines.

Why Windows?

Due to my gaming and drawing habits, even though I love the freedom of OpenSource platforms, I find myself using Win7 most of the time. We could argue that in this day and age it’s not even necessary, and I would be better off with a XenServer and a couple passthroughs to run everything in parallel, and I would agree with you. But I’m also lazy, and why fix something that is not broken? In any case all headless servers expertise came to no use when I found myself having to deal with a faulty LVM of a root partition in a notebook hard drive. Sort of a jackpot, of a kind. While LVM have undoubtedly their advantages, I find myself more comfortable in the physical realm rather than the logical. So I wasn’t much of an expert in that regard, and the notebook wouldn’t properly load making all the usual on-machine troubleshooting useless. Being a linux installation I couldn’t even just plug it into my main PC and scan the extN, since I am sporting Win7 for my daily routines. But then it dawned on me…

Why not virtual Zoidberg?

Given the monstrous specs of my PC, and the marvels of virtualization and passthrough technology, I thought to put them all to use and resurrect my dusty VMware Workstation I had lying around for such a long time. While attaching the external hard drive to a USB3 port, I could simply pass-through it to the *nix virtual machine, and while at it I’d try that neat Linux Mint distro I wanted to try for so long (and hence the name of the article). At this point it becomes a simple *nix recovery, which is for the best.

Dealing with LVMs

I armed myself with what documentation I could find, and started going at it:

# pvscan
  PV /dev/sda5   VG mint-vg   lvm2 [9,76 GiB / 0    free]
  Total: 1 [9,76 GiB] / in use: 1 [9,76 GiB] / in no VG: 0 [0   ]
# lvm pvs
  PV         VG      Fmt  Attr PSize PFree
  /dev/sda5  mint-vg lvm2 a--  9,76g    0

# lvm vgs
  VG      #PV #LV #SN Attr   VSize VFree
  mint-vg   1   2   0 wz--n- 9,76g    0 
# vgdisplay
  --- Volume group ---
  VG Name               mint-vg
  System ID             
  Format                lvm2
  Metadata Areas        1
  Metadata Sequence No  6
  VG Access             read/write
  VG Status             resizable
  MAX LV                0
  Cur LV                2
  Open LV               2
  Max PV                0
  Cur PV                1
  Act PV                1
  VG Size               9,76 GiB
  PE Size               4,00 MiB
  Total PE              2498
  Alloc PE / Size       2498 / 9,76 GiB
  Free  PE / Size       0 / 0   
  VG UUID               [UUID]

# lvm lvs
  LV     VG      Attr      LSize Pool Origin Data%  Move Log Copy%  Convert
  root   mint-vg -wi-ao--- 8,76g                                           
  swap_1 mint-vg -wi-ao--- 1,00g
# lvdisplay
  --- Logical volume ---
  LV Path                /dev/mint-vg/root
  LV Name                root
  VG Name                mint-vg
  LV UUID                [UUID]
  LV Write Access        read/write
  LV Creation host, time mint, 2015-02-08 22:44:19 +0100
  LV Status              available
  # open                 1
  LV Size                8,76 GiB
  Current LE             2242
  Segments               2
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:0
  --- Logical volume ---
  LV Path                /dev/mint-vg/swap_1
  LV Name                swap_1
  VG Name                mint-vg
  LV UUID                [UUID]
  LV Write Access        read/write
  LV Creation host, time mint, 2015-02-08 22:44:19 +0100
  LV Status              available
  # open                 2
  LV Size                1,00 GiB
  Current LE             256
  Segments               1
  Allocation             inherit
  Read ahead sectors     auto
  - currently set to     256
  Block device           252:1

What does this all mean? Let’s divide it for simplicity. When not dealing with physical partitions but with LVM, there are three different actors in play: physical volumes, volume groups, and logical volumes:

  • Physical Volumes: (pvscan, lvm pvs) are the classical partitions. They can be grouped into a single Volume Group to virtualize disk space and access and only handle space as a virtual entity.
  • Volume Group: (lvm vgs, vgdisplay) can be considered as a union of partitions. Just like logical volumes in RAID setups, VGs support the addition (and/or removal) of drives from it, which makes it easier to silently expand the space available without touching a partition. Suppose for example that we want an additional hard drive in our PC, we can mount the new hard drive, format it and attach it to our current VG. From there we can simply “expand” the Logical Volume(s) we want the additional space to go to, and it’s done. No need to mount partitions in directories or similar, it just becomes a de-facto stripe.
  • Logical Volume: (lvm lvs, lvdisplay) the usable “virtual” partition. These LVs can be mounted just like the good ol’ partitions, and can be used as such. If an hard drive is added to the VG we can simply expand it to make use of the new space. At the same time, we will have no need to take in accounting different mounting problems since it’s just a (possibly striped on various hard drives of different sizes) partition.

With this knowledge at hand, after understanding the concepts of LVMs, it was a matter of simply using mount /dev/<VGNAME>/root /mnt, and recover what salvageable data I had left. A question I never found myself asking (for obvious reasons) was to be asked, though: “what if the damage to the hard drive was fatal for just coincidence, and could I just fix and reuse it for less than critical events?”.

Once upon a time, in a bad block far, far away…

While everybody agrees that a bad block is a great signal for “duck and cover”, I’ve always been more of an inquisitorial type. Armed with a live Mint distro and an idiot proof documentation, I proceeded to simply do the following:

# badblocks /dev/sda > ./bad-blocks
# fsck -l ./bad-blocks /dev/sda

While reinstalling ex novo a new OS, I thought it would be helpful, in order to avoid the pesky “Unrecovered read error – auto reallocate failed” to leave a GB or two as unallocated space, for all intents and purposes. So far everything has worked fine, let’s hope and pray that it will continue to do so, but given the hard drive reassignment to non-aggressive duties, it probably will.


XenServer fix script

In a previous article (Fixing XenServer error “Unable to find partition containing kernel”) I described how to fix a recurring problem after patching XenServer 6.2 installations. While the fix is known from years it’s never been adopted, and different distros (such as Ubuntu LTS 14.04) fail to boot properly when the (on dom0) gets reset to its default state.

Being the lazy person that I am I decided to set up a script to do the work for me, after all we’re admins, not monkeys.

PATCHED=$(grep "_entry" $GRUBCONF | wc -l)
if [ $PATCHED -eq 2 ]; then
  echo " is already patched"
  echo "Patching to fix boot..."
  sed -i 's/_entry}":/_entry}":\n                        arg = "0"\n                    elif arg.strip() == "${next_entry}":/' $GRUBCONF
  PATCHED=$(grep "_entry" $GRUBCONF | wc -l)
  if [ $PATCHED -eq 2 ]; then
    echo "- Patch was applied successfully."
    echo "- There was a problem while applying the patch."

This does just what I/we used to do manually: detects if has been reverted and, if not, patches it up. Supplementary tests added for paranoia 🙂


Better OSSEC syslog parsing for Splunk

Just as predicted by the documentation, the syslog parsing of the OSSEC app for Splunk was a bit meh: while it would work in several instances it would terribly fail in others, like HTTP access for example. Below you can find the current version I’m using, which also provide additional fields that can be used for reports.

#REGEX = ossec:.*?(Location:.*;)\s*(user: [^;]+;\s*)?(\w{3} \d+ [\d:]+ \w+ )?(.*)$
#FORMAT = message::$4
REGEX = ossec:.*?(Location: (.*?);)\s*(srcip: ([a-f0-9:\.]+);\s*)?(user: [^;]+;\s*)?([a-f0-9:\.]+ ([a-zA-Z\-]+ [a-zA-Z\-]+) )?(\[\w{3} \w{3} \d+ \d+:\d+:\d+\.\d+ \d+\]\s*|\w{3}$
FORMAT = ossec_location::$2 ossec_srcip::$4 ossec_httpusergroup::$7 ossec_msgtimestamp::$8 message::$9

What you see commented out are the original instructions that can be safely removed. The new REGEX is more complex than the original, maybe too much, but through this I can extract more information that were previously hidden, or not easily accessible, and at the same time remove redundant timestamps while having all the important messages correctly extracted.

If you have suggestions, feel free to comment below.


OSSEC Agent/Server + Splunk installation

There is a lot of documentation to be read about the installation of OSSEC, but it’s usually sparse and focused either on a local autonomous setup or on hundreds of VMs setups. In this article we will navigate through the necessary steps to set up a small OSSEC installation with the OSSEC agent running offsite on a web/mail server and the OSSEC server running onsite. Additionally we will take a look at Splunk and install it on the OSSEC server machine, which will make it easier to manage bigger volumes of data later on.


In order to compile and install OSSEC you will need build-essential on Ubuntu machines and MySQL/PostgreSQL for database support. You can read more details about this here.

Agent/Server installation

Installing the agent and the server is as easy as running the script (after checksumming it) and answering a few questions, although you should keep (most of) the defaults since they’re solid, and then build up on them.

# wget
# wget
# cat ossec-hids-_checksum.txt
MD5 (ossec-hids-.tar.gz) = MD5SUM
SHA1 (ossec-hids-.tar.gz) = SHA1SUM
MD5 (ossec-agent-.exe) = MD5SUM_EXE
SHA1 (ossec-agent-.exe) = SHA1SUM_EXE

# md5sum ossec-hids-.tar.gz
MD5 (ossec-hids-.tar.gz) = MD5SUM
# sha1sum ossec-hids-.tar.gz
SHA1 (ossec-hids-.tar.gz) = SHA1SUM

# tar -zxvf ossec-hids-*.tar.gz
# cd ossec-hids-*
# ./
Basic server/agent configuration

After the server configuration, you will need to manage the agents. On the server you will use manage_agents command to insert a number of agents with their ids, names and ip addresses.

* OSSEC HIDS v2.8 Agent manager.       *
* The following options are available: *
   (A)dd an agent (A).
   (E)xtract key for an agent (E).
   (L)ist already added agents (L).
   (R)emove an agent (R).
Choose your action: A,E,L,R or Q:

After adding the agents on the server, you need to extract the agent keys.

Choose your action: A,E,L,R or Q: e

Available agents:
   ID: 001, Name: NAME, IP: IP
Provide the ID of the agent to extract the key (or '\q' to quit): 001

Agent key information for '001' is:

You now need to add the hash to the agent, through manage_client.

* OSSEC HIDS v2.8 Agent manager.       *
* The following options are available: *
   (I)mport key from the server (I).
Choose your action: I or Q: i

* Provide the Key generated by the server.
* The best approach is to cut and paste it.
*** OBS: Do not include spaces or new lines.

Paste it here (or '\q' to quit): IMPORTANT_HASH

Agent information:
   IP Address:IP

Confirm adding it?(y/n): y

If you remembered to configure the firewall rules properly, allowing traffic on UDP 1514, you should now have them synced upon restart. If everything is working as expected you will find the ossec-agentd connection in the logs within /var/ossec/logs/ossec.log: ossec-agentd(4102): INFO: Connected to the server (hostname/ipaddress:1514).

Adding global agent configurations

One of the smart moves that extend the capability of OSSEC is the possibility to push configurations to the agents. Anyone who managed a botnet knows how powerful this can be, and OSSEC is no exception. Let’s suppose we’re behind a static IP, say, by logging in through SSH, moving files through FTP and changing configuration files around we would generate a lot of white noise, but we can fix that by adding a simple agent configuration on our server side:

After a reset of the OSSEC processes the agent.conf will be pushed/pulled, and the IP should be now successfully white-listed. This method also allows to set specific rules for sets of agents, by specifying the names to which the configurations apply.

Agent configuration: we need to go deeper

As explained in this article, stopping to the defaults is no good practice. While all the base scenarios have been covered, specific needs have not. Using multi-user hosting or logging? You need to add these logs manually. Mail servers? These too. For some reasons you have verbose MySQL logging? This will need to be added too. That’s easily done by simply appending the specified logs and type to either the agent ossec.conf or the server agent.conf, whichever suits your needs best:



Remember that you can use wildcards and strftime for the logs, but not together. Also there are a few pitfalls in using wildcards you should be aware of.

Tweaking the server for Splunk

At this point we have a working agent/server configuration, but we want to push it a step further to make use of Splunk. Even though my setup has OSSEC and Splunk sharing the same machine I chose a syslog client configuration, and the reason is simple: through the use of syslog_output I am able to increase the granularity by raising or lowering the alert level as I see fit, while also allowing me to add a separate OSSEC server elsewhere without the need to reconfigure Splunk. It’s a win-win. The changes are to be made inside ossec.conf:

You should put the syslog_output before the <rules> tag. This is all it takes to be ready for Splunk

Where to start Splunking

Silly puns aside, we will need the Splunk software and the Reporting and Management for OSSEC. Given my setup I downloaded the deb package on the server, and the app tgz on my workstation. The installation is as easy as running a few commands:

# dpkg -i splunk---.deb
# /opt/splunk/bin/splunk enable boot-start -user splunk

On a Ubuntu server this will install the required files, and make it start on boot running as splunk user. Before running it though, we need to make a change that will allow us to receive information from OSSEC. The following code can be added in the inputs.conf after the [default] section:

disabled = false
sourcetype = ossec

This will start the UDP server, as per our mission. There are other modes available if you chose not to use the syslog_output method, but I will not go into that for now, I will just leave you the app documentation as reference.

At this point most of our work is done. Once the server is started (with service splunk start in my case) you can connect to it through its web interface, which should be up at http://ipaddress:8000/ and perfectly running. After the login you can navigate to App > Manage Apps… and click Install app from file, selecting the app tgz we downloaded earlier. If everything has been done correctly data should be now flowing, and a simple sourcetype=”ossec” query should hold all the collected information.

What to do with it, you ask? Well, that’s your job now 🙂


Solution to XenServer VM landing on initramfs

In my journey through XenServer lands, I once experienced a change in the UUID of the root partition, which resulted in a failed boot and being dropped into initramfs. Although this solution should have worked just fine, I either didn’t know of it at the time or it wouldn’t work for some reason.

While inside the VM initramfs I also had the pleasure of not having any text editor of sorts: no vi, no vim, no nano. Nothing at all. Even though I found the new UUID through the use of ls -al /dev/disk/by-uuid/ (and some guesswork), I had no way to edit the grub configuration. So, after some trial and error, I came up with the following:

(initramfs) mount /dev/xvda1 /mnt; cd /mnt
(initramfs) cp grub.cfg grub2.cfg
(initramfs) cat grub2.cfg | sed s///g > grub.cfg

After the proper root partition UUID was set in place, a reboot was all it took to set the machine back up and running.


Fixing XenServer error “Unable to find partition containing kernel”

Edit: I provided a scripted solution in this article. To know why the error happens and its fixes just keep reading.

Error: Starting VM ” – The bootloader for this VM returned an error — did the VM installation succeed? Unable to find partition containing kernel

This has been the major nightmare I had so far with XenServer machines. When upgrading distros it might just so happen they will refused to boot forever after, in my case it affects Ubuntu 14.04.x, not officially supported. Let’s look at the solutions.


Although the fix is in Citrix’s repository since 2012, give or take, it has not been streamed to the executables yet for some uncertain reasons. If you open /usr/lib/python2.4/site-packages/grub/ at line 428 you see:

if arg.strip() == "${saved_entry}":
    arg = "0"

This causes a problem during the parsing and two lines should be added:

if arg.strip() == "${saved_entry}":
    arg = "0"
elif arg.strip() == "${next_entry}":
    arg = "0"

After the file has been modified and saved you will be able to properly start the virtual machines. This holds currently true for Ubuntu 14.04 & 14.04.1 LTS server installations, but might also work for other distributions. Also take in consideration that applying some patches to the host might revert this change, so you might need to do it again at some point in the future.

Modifying grub.cfg

This might not be enough if the problem does not relate to PyGrub but rather to the configuration file itself. While on the host machine, you can run the following command:

# EDITOR=vi xe-edit-bootloader -n  -p 1

This command will prepare and mount the drives assigned to the virtual machine, edit the boot loader configuration in vi and after quitting from vi will unmount and cleanup. If you installed Grub2 or you made mistakes in its configuration, this will allow you to edit it from inside the host machine, after which you will be able to properly boot it up.


XenServer VMs and easy autostart

One of the most tedious tasks I find myself doing on XS installation is switching VMs’ autostart off and on. While no big deal it got boring real fast. I thus crafted a couple bash scripts to be run on the XS host that speed the task up.

pool=$(xe pool-list | sed -n "s/.*\uuid.*: \(.*\)/\1/p" | awk '{ system("xe pool-param-get param-name=other-config param-key=auto_poweron uuid="$0" 2>&1") }' | sed 's/Error: Key auto_poweron not found in map/false/g' | sed 's/false/INACTIVE/g' | sed 's/true/ACTIVE/g')
list=$(xe vm-list | sed -n "s/.*\(uuid\|name-label\).*)[ ]*: \(.*\)/\2/p" | awk '{ print $0; } NR%2==1 { system("xe vm-param-get param-name=other-config param-key=auto_poweron uuid="$0" 2>&1" ) }' | sed 's/Error: Key auto_poweron not found in map/false/g' | awk '{id=$0; getline; atrun=$0; getline; print atrun " " $0 " [" id "]"; }' | sort -k 2 | grep -v "Transfer VM for VDI" | grep -v "Control domain on host" )
active=$(echo "$list" | sed -n "s/true \(.*\)/\1/p")
inactive=$(echo "$list" | sed -n "s/false \(.*\)/\1/p")
echo -e "\nAuto restart in the pool is $pool\n\n"
if [ "$active" != "" ]; then
  echo -e "*** VIRTUAL MACHINES AUTO RESTARTING ***************\n\n$active\n\n"
if [ "$inactive" != "" ]; then
  echo -e "*** VIRTUAL MACHINES _NOT_ AUTO RESTARTING *********\n\n$inactive\n\n"

This script will parse all the VMs while skipping a few system instances, and will clearly show which ones are starting automatically, together with the corresponding UUID, so no guesswork or matching is needed.

# ./

Auto restart in the pool is ACTIVE





With our UUID in hand, we can now enable/disable it through this tiny script:

if [ "$2" == "true" -o "$2" == "false" ]; then
        xe vm-param-set other-config:auto_poweron=$2 uuid=$1
        echo Correct syntax: $0 \ \

With these two scripts the task becomes checking the VM name and switching it on/off in a matter of seconds. Mission complete.