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

#!/usr/bin/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";
}
else
{
	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;

		$search_string=~s/\./\\\./g;
		$search_string=~s/\*/\.\*/g;

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

	return( 0 );
}

[/codesyntax]

Source: http://www.mikealeonetti.com/wiki/index.php?title=Check_if_an_IP_is_in_a_subnet_in_Perl

(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

[/codesyntax]

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

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

[/codesyntax]

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
:%s/dns=dnsmasq/#dns=dnsmasq/g
:wq

[/codesyntax]

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

[/codesyntax]

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

[/codesyntax]

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

[/codesyntax]

2. Configure knockd

[codesyntax lang="bash"]

vim /etc/knockd.conf

[options]
        UseSyslog

[OpenClosePort]
        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

:wq

[/codesyntax]

Notes:

  • 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/START_KNOCKD=0/START_KNOCKD=1/g
:%s/#KNOCKD_OPTS="-i eth1"/KNOCKD_OPTS="-i eth0"/g
:wq

[/codesyntax]

 

4. Start knockd

[codesyntax lang="bash"]

/etc/init.d/knockd restart

[/codesyntax]

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

[/codesyntax]

2. Check if the port is open

[codesyntax lang="bash"]

telnet host PORT

[/codesyntax]

Use Your Raspberry Pi as Access Point

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

Prerequisites:

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

IMPORTANT NOTES:

  • 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

[/codesyntax]

---------------------------

# Interface and Driver
interface=wlan0
# If you have a Wifi dongle with Realtek chipset then comment the following line and uncomment the one after
driver=nl80211
#driver=rtl871xdrv

# WLAN-Settings
ssid=MyAP
channel=1

# ESSID visible
ignore_broadcast_ssid=0

# Country-specific settings
country_code=US
ieee80211d=1

# Transfer Mode
hw_mode=g

# 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
beacon_int=100
dtim_period=2

# Don't use MAC auth
macaddr_acl=0

# Max Clients
max_num_sta=20

# Limit size of Datapackets
rts_threshold=2347
fragm_threshold=2346

# hostapd Log settings
logger_syslog=-1
logger_syslog_level=2
logger_stdout=-1
logger_stdout_level=2

# temp files
dump_file=/tmp/hostapd.dump
ctrl_interface=/var/run/hostapd
ctrl_interface_group=0

# Authentification
auth_algs=3

# Encryption: WPA2 !!Don't use WEP!
wpa=2
wpa_key_mgmt=WPA-PSK
rsn_pairwise=CCMP

# Key scheduling
wpa_group_rekey=600
wpa_ptk_rekey=600
wpa_gmk_rekey=86400

# Change this, it's the network's key
wpa_passphrase=Very5ecretPass
---------------------------

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 (http://www.realtek.com.tw/downloads/downloadsView.aspx?Langid=1&PNid=21&PFid=48&Level=5&Conn=4&DownTypeID=3&GetDown=false&Downloads=true)

[codesyntax lang="bash"]

unzip RTL8192xC_USB_linux_v3.4.4_4749.20121105.zip
cd RTL8188C_8192C_USB_linux_v3.4.4_4749.20121105/wpa_supplicant_hostapd/
unzip wpa_supplicant_hostapd-0.8_rtw_20120803.zip
cd wpa_supplicant_hostapd-0.8/hostapd/
make

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

cd

[/codesyntax]

3. To redirect traffic we will need iptables and dnsmasq

[codesyntax lang="bash"]

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

[/codesyntax]

---------------------------
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
address 192.168.99.1
netmask 255.255.255.0
broadcast 192.168.99.255

# 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 192.168.99.0/24 -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 192.168.3.1, put -s 192.168.3.0/23 in line 28.

4. Configure dnsmasq

[codesyntax lang="bash"]

sudo vim /etc/dnsmasq.conf

[/codesyntax]

---------------------------
# DHCP-Server active for the wlan interface
interface=wlan0

# DHCP-Server not active for the existing network
no-dhcp-interface=eth0

# IP-Address range / Lease-Time
dhcp-range=interface:wlan0,192.168.99.100,192.168.99.200,infinite
---------------------------

5. Enable hostapd as a daemon to start when booting

[codesyntax lang="bash"]

sudo vim /etc/default/hostapd

[/codesyntax]
---------------------------
DAEMON_CONF="/etc/hostapd/hostapd.conf"
RUN_DAEMON=yes
---------------------------

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"

[/codesyntax]

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

[/codesyntax]

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

[/codesyntax]

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

[/codesyntax]

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

[/codesyntax]

3. Configure the Linux Kernel using command below

[codesyntax lang="bash"]

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

[/codesyntax]

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

[codesyntax lang="bash"]

vim /etc/ipsec.conf

[/codesyntax]

config setup
protostack=netkey
nat_traversal=yes
oe=off

conn L2TP-PSK-NAT
rightsubnet=vhost:%priv
also=L2TP-PSK-noNAT

conn L2TP-PSK-noNAT
authby=secret
pfs=no
auto=add
keyingtries=3
rekey=no
ikelifetime=8h
keylife=1h
type=transport
left=x.x.x.x # <-- replace this IP address with the IPv4 address of this machine
leftprotoport=17/1701
right=%any
rightprotoport=17/1701

conn passthrough-for-non-l2tp
type=passthrough
left=x.x.x.x # <-- replace this IPv4 address with the IPv4 address of this machine
leftnexthop=0.0.0.0
right=0.0.0.0
rightsubnet=0.0.0.0/0
auto=route

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

[codesyntax lang="bash"]

vim /etc/ipsec.secrets

[/codesyntax]

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

[/codesyntax]

7. Setting up xl2tpd

[codesyntax lang="bash"]

vim /etc/xl2tpd/xl2tpd.conf

[/codesyntax]

[global]
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 = 192.168.1.240 - 192.168.1.243
; address of the L2TP end of the tunnel (i.e. this machine)
local ip = 192.168.1.1
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

[/codesyntax]

# Do not support BSD compression.
nobsdcomp
passive
lock

# Allow all usernames to connect.
name *
proxyarp
ipcp-accept-local
ipcp-accept-remote
lcp-echo-failure 10
lcp-echo-interval 5
nodeflate

# Do not authenticate incoming connections. This is handled by IPsec.
noauth
refuse-chap
refuse-mschap
refuse-mschap-v2

# Set the DNS servers the PPP clients will use.
ms-dns 8.8.8.8 # <-- change this to the IPv4 address of your DNS server
ms-dns 8.8.4.4 # <-- 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

[/codesyntax]

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

[/codesyntax]

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 http://xenia.sote.hu/ftp/mirrors/knoppix/KNOPPIX_V7.0.4CD-2012-08-20-EN.iso

[/codesyntax]

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

[/codesyntax]

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

[/codesyntax]

PXE configuration

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

[codesyntax lang="bash"]

vim /tftpboot/pxelinux.cfg/default

[/codesyntax]

label knoppix
MENU LABEL knoppix
kernel /netboot/knoppix/knoppix-kernel
append nfsdir=172.20.30.1:/knoppix 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

[/codesyntax]

Configure NFS server

[codesyntax lang="bash"]

vim /etc/idmapd.conf

[/codesyntax]

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

Configure NFS shares

[codesyntax lang="bash"]

vim /etc/exports

[/codesyntax]

/home 10.0.0.0/24(rw,sync,no_root_squash,no_all_squash)

Note:
/home -> shared directory
10.0.0.0/24 -> 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

[/codesyntax]

Set services to start at boot

[codesyntax lang="bash"]

chkconfig rpcbind on
chkconfig nfslock on
chkconfig nfs on

[/codesyntax]

Source: http://www.server-world.info/en/note?os=CentOS_6&p=nfs