Category Archives: Network

Check if an IP is in a subnet

At some point I counted my DROP rules in my firewall and the result was kinda frightening. A lot of subnets and even more IPs...
What was really annoying was that there were a lot of IP addresses which belonged to an already blocked subnet, so I needed a script to check this for me.

It has to be a script to do this already out there in the wild. Also a machine is faster than a human. Having this in mind, why should I reinvent the wheel? So after searching a little bit on web, I found this nice perl script.

[codesyntax lang="perl"]


use strict;

use Socket qw( inet_aton );

sub ip2long($);
sub in_subnet($$);

my $ip = $ARGV[0];
my $subnet = $ARGV[1];

if( in_subnet( $ip, $subnet ) )
	print "It's in the subnet\n";
	print "It's NOT in the subnet\n";

sub ip2long($)
	return( unpack( 'N', inet_aton(shift) ) );

sub in_subnet($$)
	my $ip = shift;
	my $subnet = shift;

	my $ip_long = ip2long( $ip );

	if( $subnet=~m|(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$| )
		my $subnet = ip2long( $1 );
		my $mask = ip2long( $2 );

		if( ($ip_long & $mask)==$subnet )
			return( 1 );
	elsif( $subnet=~m|(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/(\d{1,2})$| )
		my $subnet = ip2long( $1 );
		my $bits = $2;
		my $mask = -1<<(32-$bits);

		$subnet&= $mask;

		if( ($ip_long & $mask)==$subnet )
			return( 1 );
	elsif( $subnet=~m|(^\d{1,3}\.\d{1,3}\.\d{1,3}\.)(\d{1,3})-(\d{1,3})$| )
		my $start_ip = ip2long( $1.$2 );
		my $end_ip = ip2long( $1.$3 );

		if( $start_ip<=$ip_long and $end_ip>=$ip_long )
			return( 1 );
	elsif( $subnet=~m|^[\d\*]{1,3}\.[\d\*]{1,3}\.[\d\*]{1,3}\.[\d\*]{1,3}$| )
		my $search_string = $subnet;


		if( $ip=~/^$search_string$/ )
			return( 1 );

	return( 0 );



(openssl) verify that a private key matches a certificate

A while ago I had to renew the SSL certificate for a website I'm taking care of.

How do I verify that a private key matches a certificate?
[codesyntax lang="bash"]

openssl x509 -noout -modulus -in server.crt | openssl md5
openssl rsa -noout -modulus -in server.key | openssl md5


How do I verify that a CSR matches a certificate match?
[codesyntax lang="bash"]

openssl req -noout -modulus -in server.csr | openssl md5


How to disable dnsmasq on ubuntu based distribution

dnsmasq is a lightweight DNS, TFTP, PXE, router advertisement and DHCP server. It is intended to provide coupled DNS and DHCP service to a LAN.
From time to time dnsmasq decided to resolve some hosts over a VPN tunnel to their external IP address instead the internal one. This was quite annoying... After digging a little bit I found that the root cause of all my VPN heartache was the dnsmasq daemon controlling my DNS. And, related, network-manager. Ok, so how can we disable dnsmasq?!

[codesyntax lang="bash"]

vim /etc/NetworkManager/NetworkManager.conf


Ta-da! No more problems! We're all set!

How to deal with "RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?)" problem

If you see [warn] RSA server certificate is a CA certificate (BasicConstraints: CA == TRUE !?) in you apache error.log file means you have created a cert that is intended to be used to sign other certs, but you're using that cert as your SSL cert. So, it depends how you create the SSL cert.

But how can we solve this problem?!

1. Generate private key and certificate signing request

[codesyntax lang="bash"]

openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
openssl rsa -passin pass:x -in server.pass.key -out server.key
rm server.pass.key
openssl req -new -key server.key -out server.csr


Note: when the openssl req command asks for a “challenge password”, just press return, leaving the password empty.

2. Generate SSL certificate

[codesyntax lang="bash"]

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


Set port knocking with knockd and iptables

This document describes a stealth method to externally open ports that, by default, are kept closed by the firewall.

Server side

1. Install knockd

[codesyntax lang="bash"]

apt-get install knockd


2. Configure knockd

[codesyntax lang="bash"]

vim /etc/knockd.conf


        sequence    = 2123:udp,3543:tcp,6454:udp
        seq_timeout = 5
        Start_Command     = /sbin/iptables -I INPUT -s %IP% -p tcp --dport PORT -j ACCEPT
        tcpflags    = syn
        Cmd_timeout = 3600
        Stop_Command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport PORT -j ACCEPT




  • sequence - the sequence required to open desired port
  • seq_timeout - time to wait for a sequence to complete
  • Start_Command - command to be executed when a client makes the correct port-knock
  • Stop_Command - command to be executed when Cmd_Timeout seconds have passed since Start_Command has been executed
  • Cmd_Timeout - time to wait between Start_Command and Stop_Command in seconds
  • PORT - port to be opened

3. Enable knockd


[codesyntax lang="bash"]

vim /etc/default/knockd

:%s/#KNOCKD_OPTS="-i eth1"/KNOCKD_OPTS="-i eth0"/g



4. Start knockd

[codesyntax lang="bash"]

/etc/init.d/knockd restart


Client side

1. Knock the port

[codesyntax lang="bash"]

nmap -Pn --host_timeout 201 --max-retries 0 -sU -p 2123 host; nmap -Pn --host_timeout 201 --max-retries 0 -p 3543 host; nmap -Pn --host_timeout 201 --max-retries 0 -sU -p 6454 host


2. Check if the port is open

[codesyntax lang="bash"]

telnet host PORT


Use Your Raspberry Pi as Access Point

This post describes all required steps to make your Raspberry Pi to act as a Access Point.


  • A Raspberry Pi, model B.
  • A boot SD card for the Raspberry Pi.
  • A USB WiFi device that supports "Access Point" mode.
  • An Ethernet cable to connect to the local network.


  • Please make sure you Wifi dongle supports Access Point or Master Mode.
  • This tutorial is written and tested against the stock Raspbian image. In other distributions, the nl80211 driver may be missing!
  • If you are using a Wifi dongle with Realtek chipset then you will have do an extra step which I'll describe it later.

1. Install and configure hostapd

[codesyntax lang="bash"]

sudo apt-get install hostapd iw
sudo vim /etc/hostapd/hostapd.conf



# Interface and Driver
# If you have a Wifi dongle with Realtek chipset then comment the following line and uncomment the one after

# WLAN-Settings

# ESSID visible

# Country-specific settings

# Transfer Mode

# Optional
# supported_rates=10 20 55 110 60 90 120 180 240 360 480 540

# uncomment the following to enable 802.11 Draft n
# ieee80211n=1

# Enable WMM for Draft-N
# wmm_enabled=1

# Use iw list to see which ht capabilities your wifi card has
# ht_capab=[HT40+][SHORT-GI-40][DSSS_CCK-40]

# Beacons

# Don't use MAC auth

# Max Clients

# Limit size of Datapackets

# hostapd Log settings

# temp files

# Authentification

# Encryption: WPA2 !!Don't use WEP!

# Key scheduling

# Change this, it's the network's key

You should adjust ssid, wpa_passphrase, region, channel and other settings to meet your criteria, hardware specs and country limitations for wireless networks.

2. Follow this step only if you have a Wifi dongle with Realtek chipset. Everyone else can skip this step!

First of all you need to download the  linux driver from realtek website (

[codesyntax lang="bash"]

cd RTL8188C_8192C_USB_linux_v3.4.4_4749.20121105/wpa_supplicant_hostapd/
cd wpa_supplicant_hostapd-0.8/hostapd/

sudo mv /usr/sbin/hostapd /usr/sbin/hostapd.bak
sudo mv hostapd /usr/sbin/hostapd.edimax
sudo ln -sf /usr/sbin/hostapd.edimax /usr/sbin/hostapd
sudo chown root.root /usr/sbin/hostapd
sudo chmod 755 /usr/sbin/hostapd



3. To redirect traffic we will need iptables and dnsmasq

[codesyntax lang="bash"]

sudo apt-get install dnsmasq iptables
sudo vim /etc/network/interfaces


auto lo
iface lo inet loopback

iface default inet dhcp

# Existing network
iface eth0 inet dhcp

# WLAN Interface / AP address range
allow-hotplug wlan0
auto wlan0
iface wlan0 inet static

# reset existing rules and chains
up /sbin/iptables -F
up /sbin/iptables -X
up /sbin/iptables -t nat -F

# Mask for the interface, activate port-forwarding and NAT
up iptables -A FORWARD -o eth0 -i wlan0 -s -m conntrack --ctstate NEW -j ACCEPT
up iptables -A FORWARD -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
up iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
up sysctl -w net.ipv4.ip_forward=1

# restart hostapd and dnsmasq
up /etc/init.d/hostapd restart
up /etc/init.d/dnsmasq restart

You can use any IP for the wireless interface, set in line 13. All clients will associate with an IP in this range. You also have to change line 28 to match the IP address range.
Example: If you use wlan0 address, put -s in line 28.

4. Configure dnsmasq

[codesyntax lang="bash"]

sudo vim /etc/dnsmasq.conf


# DHCP-Server active for the wlan interface

# DHCP-Server not active for the existing network

# IP-Address range / Lease-Time

5. Enable hostapd as a daemon to start when booting

[codesyntax lang="bash"]

sudo vim /etc/default/hostapd


Force Chrome to tunnel DNS requests through a SSH socks proxy

Setup a socks proxy (check this page for more details) on port 8888 (the port is not that important).

Start chrome with the following parameters:

[codesyntax lang="bash"]

chrome --proxy-server="socks5://localhost:8888"


Also we can check if this works and run the following command on the SSH server. The tcpdump will show show dns traffic for any activity in Chrome.

[codesyntax lang="bash"]

tcpdump -i eth0 port 53


Setting up a L2TP over IPSec VPN on Debian on 10 steps

This document describes the required steps to make a fully functional L2TP/IPSEC PSK VPN PSK (with pre-shared keys) on debian squeeze.

L2TP/IPSec is an advanced protocol formally standardized in IETF RFC 3193 and now the recommended replacement for PPTP where secure data encryption is required. The L2TP payload is encrypted using the standardized IPSec protocol. Regarding speed, L2TP/IPSEC encapsulates data twice making it less efficient and slightly slower than PPTP and OpenVPN.

L2TP/IPSEC uses 500/udp for the the initial key exchange, protocol 50 for the IPSEC encrypted data (ESP), 1701/udp for the initial L2TP configuration and 4500/udp for NAT traversal. L2TP/IPSec is easier to block than OpenVPN due to its reliance on fixed protocols and ports.

1. Install required packages

[codesyntax lang="bash"]

apt-get install xl2tpd openswan


Note: Answer NO when asked if an X.509 certificate for this host can be automatically created or imported. This certificate can be created and imported later using:

[codesyntax lang="bash"]

dpkg-reconfigure openswan


2. I always backup the original configuration files (you may skip this step if you want, but I highly not recommend it)

[codesyntax lang="bash"]

mv /etc/ipsec.conf /etc/ipsec.conf.orig
mv /etc/ipsec.secrets /etc/ipsec.secrets.orig
mv /etc/xl2tpd/xl2tpd.conf /etc/xl2tpd/xl2tpd.conf.orig
mv /etc/ppp/options.l2tpd /etc/ppp/options.l2tpd.orig


3. Configure the Linux Kernel using command below

[codesyntax lang="bash"]

for each in /proc/sys/net/ipv4/conf/*
    echo 0 > $each/accept_redirects
    echo 0 > $each/send_redirects


4. Configure /etc/ipsec.conf to work with PSK rather than X.509 certificates.

[codesyntax lang="bash"]

vim /etc/ipsec.conf


config setup


conn L2TP-PSK-noNAT
left=x.x.x.x # <-- replace this IP address with the IPv4 address of this machine

conn passthrough-for-non-l2tp
left=x.x.x.x # <-- replace this IPv4 address with the IPv4 address of this machine

5. Enter your prefer PSK to /etc/ipsec.secrets:

[codesyntax lang="bash"]

vim /etc/ipsec.secrets


x.x.x.x %any: "mysecretpresharedkeypassword"

Note: The first field is the IPv4 address of this machine, the second field is the remote address (I am using %any to match anything) and the third field is the PSK password in quotes. You can have multiple lines in this file should you wish to add more entries.

6. Make sure the file /etc/ipsec.secrets is readable only by root and nothing else.

[codesyntax lang="bash"]

chmod 600 /etc/ipsec.secrets


7. Setting up xl2tpd

[codesyntax lang="bash"]

vim /etc/xl2tpd/xl2tpd.conf


port = 1701
auth file = /etc/xl2tpd/l2tp-secrets
access control = no
rand source = dev

[lns default]
exclusive = no
; enter the IP range you wish to give out to your clients here
ip range = -
; address of the L2TP end of the tunnel (i.e. this machine)
local ip =
refuse authentication = yes
refuse pap = yes
refuse chap = yes
ppp debug = no
pppoptfile = /etc/ppp/options.l2tpd

8. Add PPP configuration to /etc/xl2tpd/ppp-options.xl2tpd file

[codesyntax lang="bash"]

vim /etc/ppp/options.l2tpd


# Do not support BSD compression.

# Allow all usernames to connect.
name *
lcp-echo-failure 10
lcp-echo-interval 5

# Do not authenticate incoming connections. This is handled by IPsec.

# Set the DNS servers the PPP clients will use.
ms-dns # <-- change this to the IPv4 address of your DNS server
ms-dns # <-- add extra entries if necessary

mtu 1400
mru 1400

9. IPsec configuration is done and you can verify it and you must get no errors:

[codesyntax lang="bash"]

ipsec verify


Checking your system to see if IPsec got installed and started correctly:
Version check and ipsec on-path [OK]
Linux Openswan U2.6.28/K2.6.32-5-686 (netkey)
Checking for IPsec support in kernel [OK]
NETKEY detected, testing for disabled ICMP send_redirects [OK]
NETKEY detected, testing for disabled ICMP accept_redirects [OK]
Checking that pluto is running [OK]
Pluto listening for IKE on udp 500 [OK]
Pluto listening for NAT-T on udp 4500 [OK]
Two or more interfaces found, checking IP forwarding [OK]
Checking NAT and MASQUERADEing
Checking for 'ip' command [OK]
Checking for 'iptables' command [OK]
Opportunistic Encryption Support [DISABLED]

10. (re)start openswan and xl2tpd

[codesyntax lang="bash"]

/etc/init.d/ipsec restart
/etc/init.d/xl2tpd restart


Knoppix - PXE boot install rescue

This document describes how boot a Knoppix from PXE Server. I am assuming that you already setup PXE booting BEFORE you start doing this. If you don't, and you have CentOS please read this page or if you have a Debian/Ubuntu please read this page.

We are going to use Knoppix and a NFS server required by knoppix to successfully network boot. If you don't have a NFS server or you don't know how to setup one, please read this page (this page covers only the NFS Server setup for CentOS).

First of all we are going to download Knoppix.

[codesyntax lang="bash"]

wget -c


Generating the required files to PXE boot

Knoppix has the built-in ability to auto-configure itself to network boot itself, and this makes the process rather easy. In the KNOPPIX submenu, select the Start Terminal Server option.

knoppix - VMware Player

knoppix - VMware Player

IMPORTANT NOTE! By doing this, it will start up dhcp, and many other services! Running two DHCP servers on the same subnet is generally a very bad idea!
When prompted, select the menu item to configure the terminal server, and run through that.

There are some approaches to don't start more DHCP server:
1. Start Knoppix in a Virtual Machine that has eth disconnected
2. Start Knoppix on a Physical Machine with network cable unplugged (be sure to stop DHCP Server on Knoppix before plug the cable back).

If you are looking in the /tftpboot directory you will find three files that are important to us: kernel, miniroot.gz, and pxelinux.cfg/default. The first is the kernel used to start knoppix, the second is the needed initrd to boot knoppix, and the last one contains all needed settings for your pxelinux configuration. "kernel" is a very generic kernel name, so I renamed mine to "knoppix-kernel", and the miniroot.gz to "knoppix-miniroot.gz"

[codesyntax lang="bash"]

mv /tftpboot/kernel /tftpboot/knoppix-kernel
mv /tftpboot/miniroot.gz /tftpboot/knoppix-miniroot.gz


Copy these files to your PXE booting server

[codesyntax lang="bash"]

rsync -avz --stats --progress --partial /tftpboot/knoppix* root@PXE-booting-server:/tftpboot/netboot/knoppix


PXE configuration

On you PXE booting server add the following lines on /tftpboot/pxelinux.cfg/default

[codesyntax lang="bash"]

vim /tftpboot/pxelinux.cfg/default


label knoppix
MENU LABEL knoppix
kernel /netboot/knoppix/knoppix-kernel
append nfsdir= nodhcp lang=us ramdisk_size=100000 init=/etc/init apm=power-off nomce vga=791 xmodule=fbdev initrd=/netboot/knoppix/knoppix-miniroot.gz BOOT_IMAGE=knoppix

Please note that if you want your Knoppix to boot into runlevel 2 then you have to change vga=791 to vga=normal 2

How to setup a NFS server on CentOS 6

This document describes how to configure your CentOS 6.x linux to act as a NFS Server to share any directories on your Network

Install required software

[codesyntax lang="bash"]

yum install nfs-utils


Configure NFS server

[codesyntax lang="bash"]

vim /etc/idmapd.conf


# line 5: uncomment and change to your domain name
Domain =

Configure NFS shares

[codesyntax lang="bash"]

vim /etc/exports



/home -> shared directory -> range of networks NFS permits accesses
rw -> writable
sync -> synchronize
no_root_squash -> enable root privilege
no_all_squash -> enable users' authority

Start NFS services

[codesyntax lang="bash"]

/etc/rc.d/init.d/rpcbind start
/etc/rc.d/init.d/nfslock start
/etc/rc.d/init.d/nfs start


Set services to start at boot

[codesyntax lang="bash"]

chkconfig rpcbind on
chkconfig nfslock on
chkconfig nfs on