« IPV6 | Main | Programming »

Tuesday, September 06, 2011

Configure Exim4 to provide SMTP Relay service with SMTP Authentication and TLS enabled

Prerequisites:

  • Box running Debian Squeeze or Debian variants
  • Exim4 Package (apt-get install exim4)
  • Internet Routable Public IP Address (172.16.75.12) with reverse DNS relay.example.org


Reconfiguring Exim4

Run the command as root,
	# dpkg-reconfigure exim4-config
There are two useful scenarios while delivering mails. Smarthosts is safer option if your privoder has a SMTP server you can use.
If not, you will have to deliver them directly using your mail server. If your IP is blacklisted, or doesn't have a reverse DNS, your mails may not be delivered successfully.

Case 1: Direct delivery without Smarthost(eg: To deliver mails directly to remote SMTP servers):

		internet site; mail is sent and received directly using SMTP
		System mail name: relay.example.org
		IP-address to listen on for incoming SMTP connections: 127.0.0.1; 172.16.75.12
		Other destinations for which mail is accepted: Leave Empty
		Domains to relay mail for: * (This option will accept mail for any domain) 
		Machines to relay mail for: Leave Empty (Or specify whitelisted relay IPs)
		Keep number of DNS-queries minimal (Dial-on-Demand)? No
		Delivery method for local mail: mbox format in /var/mail/
		Split Configuration into small files? Yes (Very Important)
This should result in configuration file /etc/exim4/update-exim4.conf.conf
		dc_eximconfig_configtype='internet'
		dc_other_hostnames='relay.example.org'
		dc_local_interfaces='127.0.0.1 ; 172.16.75.12'
		dc_readhost='relay.example.org'
		dc_relay_domains='*'
		dc_minimaldns='false'
		dc_relay_nets=''
		CFILEMODE='644'
		dc_use_split_config='true'
		dc_hide_mailname='true'
		dc_mailname_in_oh='true'
		dc_localdelivery='maildir_home'

Case 2: Delivery with Smarthost (eg: To Use ISP's SMTP server to relay all your mails):

		mail sent by smarthost; received via SMTP or fetchmail
		IP address of hostname of the outgoing smarthost: 1.2.3.4
		Hide local mail name in outgoing mail? Yes
		Visible domain name for local users: relay.example.org
This should result in configuration file /etc/exim4/update-exim4.conf.conf with minor differences from file above;
		dc_eximconfig_configtype='smarthost'
		dc_smarthost='172.16.75.17'

Generate Self-signed Certificate

In order to use TLS (Transport Layer Security) with SMTP authentication, you must generate a self-signed certificate or purchase one from reputed CA.
	# /usr/share/doc/exim4-base/examples/exim-gencert
After filling in all the details this will generate a certificate and key files in: /etc/exim4/exim.crt , /etc/exim4/exim.key
This is the default location where exim4 searches for these files.

Add Exim4 User

To create username/passwords specifically for exim4 SMTP authentication, run the command
	# /usr/share/doc/exim4/examples/exim-adduser
	
You may also copy the file to /sbin and run it,
	# cp /usr/share/doc/exim4/examples/exim-adduser /sbin
	# exim-adduser
	

Enabling TLS

Type the following command to create a config macro file to enable TLS
	# echo "MAIN_TLS_ENABLE = yes" > /etc/exim4/conf.d/main/00_local_settings
Additional settings can be added to the file /etc/exim4/conf.d/main/00_local_settings

Enabling SMTP Authentication

Uncomment following lines in /etc/exim4/conf.d/auth/30_exim4-config_examples
	plain_server:
	   driver = plaintext
	   public_name = PLAIN
	   server_condition = "${if crypteq{$auth3}{${extract{1}{:}{${lookup{$auth2}lsearch{CONFDIR/passwd}{$value}{*:*}}}}}{1}{0}}"
	   server_set_id = $auth2
	   server_prompts = :
	   .ifndef AUTH_SERVER_ALLOW_NOTLS_PASSWORDS
	   server_advertise_condition = ${if eq{$tls_cipher}{}{}{*}}
	   .endif

	login_server:
	   driver = plaintext
	   public_name = LOGIN
	   server_prompts = "Username:: : Password::"
	   server_condition = "${if crypteq{$auth2}{${extract{1}{:}{${lookup{$auth1}lsearch{CONFDIR/passwd}{$value}{*:*}}}}}{1}{0}}"
	   server_set_id = $auth1
	   .ifndef AUTH_SERVER_ALLOW_NOTLS_PASSWORDS
	   server_advertise_condition = ${if eq{$tls_cipher}{}{}{*}}
	   .endif
	   

Updating Exim4 Configuration

Finally run this command to update exim4 configuration and restart exim4:
	# update-exim4.conf
	# /etc/init.d/exim4 restart
	
If your provider is blocking port 25 you may want to run the SMTP relay service on additional ports. To do this, modify this line in /etc/default/exim4
	SMTPLISTENEROPTIONS='-oX 587:25 -oP /var/run/exim4/exim.pid'
	
	This tells exim4 to listen on port 587 in addition to 25
	

Testing

	# telnet 172.16.75.12
	Type, EHLO SMTP
	If you see following line among other things, it means it's working.
	
	250-STARTTLS
	
A full test can be performed using an email client.
Posted by EmErgE at 1:32 PM
Categories: Linux, Security

Wednesday, June 08, 2011

Setting up IPv6 Tunnel with Hurricane Electric (Tunnelbroker.net)

Since today's World IPv6 Day, i've taken the opportunity to create a brief how-to on setting up an IPv6 Tunnel with Hurricane Electric's Tunnelbroker service.

1) Go to http://tunnelbroker.net

2) Register/Login

3) Create Regular Tunnel
	-> IPV4 Endpoint (Your Side)
	Enter Public IP Address, example: 9.33.21.35
	Selection a tunnel endpoint that's closest to you example: Los Angeles, CA, US
	
	If you have a firewall allow ICMP packets from source IP: 66.220.2.74 with, 
	# iptables -A INPUT -p icmp -s 66.220.2.74 -j ACCEPT

On the Main Page, under the tunnel you just created you get following information:

	Server IPv4 Address: 74.82.46.6
	Server IPv6 Address: 2001:1337:24:3ac::1/64
	Client IPv4 Address: 9.33.21.35
	Client IPV6 Address: 2001:1337:24:3ac::2/64

	Routed /64: 2001:db8:12:413::/64
	
	Configure your firewall to allow traffic from 74.82.46.6 endpoint.
	# iptables -A INPUT -p ip -s 74.82.46.6 -j ACCEPT

This is sufficient information to create an IPv6 Tunnel.

Setting up IPv6 Tunnel on Debian/Ubuntu:
----------------------------------------
This below is a Debian/Ubuntu specific guide. It may or maynot work on other Linux flavors.

1) Edit /etc/network/interfaces file (# vim /etc/network/interfaces)

## Add these lines below to setup a tunnel to your endpoint from information gathered above
auto mytunnel0
iface mytunnel0 inet6 v4tunnel
  address 2001:1337:24:3ac::2
  netmask 64
  endpoint 74.82.46.6
  up ip -6 route add default dev mytunnel0
  down ip -6 route del default dev mytunnel0

# This is network configuration for your default network interfaces. Leave it the way it is.
auto eth0
iface eth0 inet dhcp

# Add these lines to assign a static ipv6 address to your network interface from your very own routed /64 subnet.
iface eth0 inet6 static
  address 2001:db8:12:413::1
  netmask 64
  
############EOF################
 
That's it. if you want to load it without rebooting the server:
 # ifup mytunnel0
 # ifdown eth0 && ifup eth0
 
 or, reboot
 # reboot
 
 Setting up IPv6 Tunnel on FreeBSD/PC-BSD
 -----------------------------------------
 Using /etc/rc.conf: 
 ============
	## Edit /etc/rc.conf and add these lines according to the tunnel information above:
	ipv6_enable="YES"
	ipv6_gateway_enable="YES"
	ipv6_network_interfaces="lo0 gif0"
	ipv6_ipv4mapping="YES"
	gif_interfaces="gif0"
	gifconfig_gif0="9.33.21.35 74.82.46.6"
	ipv6_ifconfig_gif0="2001:1337:24:3ac::2 2001:1337:24:3ac::1 prefixlen 128"
	ipv6_defaultrouter="2001:1337:24:3ac::1"

	# Assuming your default network interface is re0, add this line to assign an address from /64 subnet allocated to you.
	ifconfig_fxp0_alias0="inet6 2001:db8:12:413::1 prefixlen 64"

Using script: 
============
#!/usr/local/bin/bash
# Script: /root/ipv6_tunnel.sh
ifconfig gif0 create
ifconfig gif0 tunnel 9.33.21.35 74.82.46.6
ifconfig gif0 inet6 2001:1337:24:3ac::2 2001:1337:24:3ac::1 prefixlen 128
route -n add -inet6 default 2001:470:1f04:1cf4::1
ifconfig gif0 up

ifconfig re0 inet6 2001:db8:12:413::1 prefixlen 64 alias

If you are planning to bind your services/applications on both IPv4 and IPv6 sockets, it's necessary to tune in some sysctl values.

On GNU/Linux: 
-------------
# sysctl -w net.ipv6.bindv6only=0
# echo net.ipv6.bindv6only=0 >> /etc/sysctl.conf

On FreeBSD/PC-BSD:
------------------
# sysctl -w net.inet6.ip6.v6only=0
# echo net.inet6.ip6.v6only=0 >> /etc/sysctl.conf

Testing IPv6 Connectivity: 
--------------------------
 $ ping6 ipv6.google.com

 
 
Posted by EmErgE at 2:22 PM
Categories: *BSD, General Networking, IPV6, Linux

Saturday, June 04, 2011

IspCP Installation

If you are in search of a free/open source hosting control panel IspCP might offer the solution.

Here's a guide to install IspCP (version 1.0.7 at the time of writing) on Debian Lenny:

# cd /usr/src/
# wget ispcp-omega-1.0.7.tar.bz2
# tar cjvf ispcp-omega-1.0.7.tar.bz2
# cd ispcp-omega-1.0.7

# aptitude update && aptitude safe-upgrade
# aptitude install lsb-release
# aptitude install $(cat ./docs/Debian/debian-packages-`lsb_release -cs`)
OR,
# apt-get install $(cat ./docs/Debian/debian-packages-`lsb_release -cs`)

#File: /etc/apt/sources.list
-----------------------------
   deb     http://ftp.de.debian.org/debian/         lenny         main contrib non-free
   deb     http://security.debian.org/              lenny/updates main contrib non-free

*Note*
(if you get to the proftpd screen, select 'standalone')
(if you get to the postfix screen select 'internet site'. 'mail name' should be
the server's domain. If you've set debian up correctly on install your domain
should be already shown.)
(if you get to the courier screen select 'no' to web directories)

# make install
# cp -R /tmp/ispcp/* /
# mysql_secure_installation
# cd /var/www/ispcp/engine/setup
# perl ispcp-setup
Go to http://ip.add.re.ss
# rm -fR /tmp/ispcp/

To Uninstall:

# cd /var/www/ispcp/engine/setup
# perl ispcp-uninstall
Posted by EmErgE at 12:30 PM
Categories: Linux

Blocking ZmEu scans with IPTables

With latest spike on ZmEu attacks and exploits, it is a good idea to block these scans right at the source.

These scans look like this:

  • 91.121.243.113 - - [31/May/2011:01:18:40 +0000] "GET /pma/scripts/setup.php HTTP/1.1" 404 296 "-" "ZmEu"
  • 91.121.243.113 - - [31/May/2011:01:18:39 +0000] "GET /w00tw00t.at.blackhats.romanian.anti-sec:) HTTP/1.1" 404 315 "-" "ZmEu"

They show up all over the logs and fire up IDS.

There are other solutions based on modsecurity like the one mentioned on http://linux.m2osw.com/zmeu-attack

It is also possible to block these using IPTables. Here's a script that does just that:

    
#!/bin/bash
# Filename: /root/block_zmeu_attack.sh
httpd_accesslog="/var/log/apache2/access_log"
logfile="/root/zmeu_scan_blocked.log"

for i in $(egrep -i 'w00tw00t|zmeu' ${httpd_accesslog} | awk '{print $1}' | sort -u)
do 
if [ $(iptables -nL | grep -c $i) -lt 1 ]; then
iptables -A INPUT -s ${i} -j DROP && echo "${i} blocked on $(date)" >> ${logfile}
fi 
done

Once the script is in place, it's time to add an hourly cronjob.

    # crontab -e
        @hourly /root/block_zmeu_attack.sh >/dev/null 2>&1

The list of blocked IPs will show up in the logfile (/root/zmeu_scan_blocked.log)

Posted by EmErgE at 11:56 AM
Categories: Linux

Fixing nvidia drivers issue after every kernel update on Debian/Ubuntu

I've noticed after every kernel update, nvidia drivers need to be manually compiled yet it fails to load due to incorrect modules path.

Requirements:

  • nvidia-current must be present (apt-get install nvidia-current) which puts the source in /usr/src

On every kernel update:

Install kernel headers (this can be done from console if WM isn't loading up):

  • apt-get install linux-headers-$(uname -r)

Change directory to latest version of nvidia-current package (195.36.24 at the time of writing) in /usr/src and compile the driver:

  • cd /usr/src/nvidia-current-195.36.24
  • make && make install

One time command (Symlink new drivers to X11 modules):

  • cd /usr/lib/xorg/modules/extensions
  • ln -s /usr/lib/nvidia-current/xorg/nvidia_drv.so ./nvidia_drv.so
  • ln -s /usr/lib/nvidia-current/xorg/libglx.so ./libglx.so

Restart Display Manager (kdm, gdm):

  • /etc/init.d/kdm restart
Posted by EmErgE at 11:08 AM
Categories: Linux

BIND9 Chroot

# apt-get install bind9 dnsutils
# /etc/init.d/bind9 stop
# vim /etc/default/bind9
	RESOLVCONF=no
	OPTIONS="-u bind -t /var/lib/named"
# mkdir -p /var/lib/named/{etc,dev}
# mkdir -p /var/lib/named/var/cache/bind
# mkdir -p /var/lib/named/var/run/bind/run
# mv /etc/bind /var/lib/named/etc
# ln -s /var/lib/named/etc/bind /etc/bind
# mknod /var/lib/named/dev/null c 1 3
# mknod /var/lib/named/dev/random c 1 8
# chmod 666 /var/lib/named/dev/null /var/lib/named/dev/random
# chown -R bind:bind /var/lib/named/var/*
# chown -R bind:bind /var/lib/named/etc/bind

=====(debian 4.0 [etch])=====
# vi /etc/default/syslogd
	SYSLOGD="-a /var/lib/named/dev/log"
# /etc/init.d/sysklogd restart

=====(debian 5.0 [lenny])=====
# vim /etc/rsyslog.d/bind-chroot.conf
	$AddUnixListenSocket /var/lib/named/dev/log
# /etc/init.d/rsyslog restart

# /etc/init.d/bind9 start

IPV6 NOTE:
	mkdir /var/lib/named/proc
	mount -t proc proc /var/lib/named/proc
	Modify /etc/fstab to include the mountpoint
Posted by EmErgE at 10:57 AM
Categories: Linux

Friday, June 03, 2011

Bash script to upload screenshot to imgur.com

#!/bin/sh
if [ ! -f imgurbash.sh ]; then
wget http://imgur.com/tools/imgurbash.sh
fi
result=$(uname -a | grep -i -c bsd)
if [ $result -gt 0 ]; then
$(sed  's/sed -r/sed -E/g' imgurbash.sh  > /tmp/imgurbash.tmp; mv /tmp/imgurbash.tmp imgurbash.sh)
fi
filename="screenshot-$(date +%s).png"
import -window root $filename
bash imgurbash.sh $filename

Posted by EmErgE at 12:38 PM
Categories: *BSD, Linux

Sunday, March 28, 2010

SKS OpenPGP Keyserver Installation and GnuPG Operations

This is a two part guide. First part describe installating keyserver. This is optional as there are plethora of public
keyservers out there. It can be useful however to run your own keyserver in an organization or a compnay. The Second 
part of this guides describes some of the basic gpg operatins such as generating keys and using keyserver to send, search
and import them.

	++Part 1: sks keyserver installation (Optional)++
	==================================================

Install sks from repository
	# apt-get -y install sks

Build and Initialize DB 
	# sks build 

Modify /etc/sks/sksconf

==File: /etc/sks/sksconf==
---------------------------
# Replace IP with binding IP
hostname: example.org
hkp_address: 192.168.0.100
hkp_port: 11371

Default installation lacks html pages. Download it from rainydayz.org
Rainydayz.org 
  or my modified version of the same 
  to /var/lib/sks/www/ , assign appropriate permissions and change the post url.

# mkdir /var/lib/sks/www
# cd /var/lib/sks/www
# wget Rainydayz.org
# tar xjvf sks_www.tar.bz2

Modify index.html and replace all instances of "your.site.name" with your site name or IP address.

# chown debian-sks:debian-sks *

Launch sks in the background
# sks db &

++Adding Recon++

With recon, it is possible to distribute keys among keyservers. To enable recon,
modify /etc/sks/sksconf and uncomment recon options.

==File: /etc/sks/sksconf==
----------------------------
# Replace IP with binding IP
recon_address: 192.168.0.100
recon_port: 11370

==File: /etc/sks/membership==
-----------------------------------------
# Add remote sks recon IP with recon port
172.16.0.20 11370

Ask sks admin of 172.16.0.20 to add your recon IP and port above (192.168.0.100) in remote membership file

Start Recon with,
# sks recon &

+References+
[1] http://code.google.com/p/sks-keyserver/wiki/Documentation
[2] http://www.rainydayz.org/node/10
[3] http://www.keysigning.org/sks/
[4] blog.reindel.com

	++Part 2: GnuPG Operations++
	=============================

++Key Generation++

Generate your key if you don't have one already
$ gpg --gen-key
	Your selection? 1
	What keysize do you want? (2048) [Press Enter]
	Key is valid for? (0) [Press Enter]
	Is this correct? (y/N) y
	Real name: John Doe
	Email address: john.doe@example.org
	Comment: [Press Enter]
	Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
	Enter passphrase: SomethingSecret
	Repeat passphrase: SomethingSecret
	
If you get stuck at this message,
	" Not enough random bytes available.  Please do some other work to give 
	the OS a chance to collect more entropy! (Need 284 more bytes)"
open another terminal as superuser, 
	# apt-get install rng-tools
	# rangd -r /dev/urandom
and the key generation will be completed.

++Sending Keys to Keyserver++

To send your Key to the keyserver, list out your keys first
$ gpg --list-keys 
and look for the ID which is the value after 1024/ which looks like 5E21B437
You can also use regular expression to grab key ID with:
$ gpg --list-keys | grep 1024D | sed 's/.*1024D\/\(.*\)\ .*$/\1/'
or with awk,
$ gpg --list-keys | grep 1024D | awk -F/ '{print $2}' | awk '{print $1}'

We will choose above installed sks as our keyserver and send our key using key ID
$ gpg --keyserver hkp://192.168.0.100 --send-keys 5E21B437

++Searching and Importing Key from Keyserver++

To search key with key ID or name,
$ gpg --keyserver hkp://192.168.0.100 --search-keys name
or,
$ gpg --keyserver hkp://192.168.0.100 --search-keys keyid
If search matches, output will look like this:
(1)     John Doe <johndoe@example.org>
  1024 bit DSA key 5E21B437, created: 1990-01-01
Keys 1-1 of 1 for "john".  Enter number(s), N)ext, or Q)uit > Q

Keys can be received with search and selecting the number or using: 
$ gpg --keyserver hkp://keyserver --recv-keys Key_ID

Trusted keys can be signed with,
$ gpg --sign-key Key_ID

For more information on GNU Privacy Guard visit http://www.gnupg.org/gph/en/manual.html    
  
Posted by EmErgE at 2:32 AM
Categories: General Networking, Linux

Sunday, March 21, 2010

Recovering Grub from accidental deletion

Every once in a while we may run into a situation where we accidentally delete the contents of MBR which stops grub bootloader from loading the menu and booting the system. This can happen when windows is installed on top of a *nix OS with grub installed in which case Windows deletes the MBR content and replaces it with it's own. Here is a fix.

Download and burn Knoppix (or any live-cd for that matter) into a cd or dvd.

Boot the system from live cd/dvd.

Once boot is completed, type sudo su - to become a superuser. Type grub (enter). This will result in a grub prompt. type find /boot/grub/stage1 which will output a partition with stage1 file. In our example below it's (hd0,1) which can be /dev/sda2 or /dev/hda2. Note the partition number because we will need this in the next step. Type root followed by the partition from above output. Finally type setup followed by the part before comma. In our example this is (hd0). This is the device block we will be installing grub loader to.

Note: This fix will work if the *nix partition is intact and hasn't been corrupted.

An example scenario:

# grub

grub> find /boot/grub/stage1

(hd0,1)

grub> root (hd0,1)

grub> setup (hd0)

grub> quit

# reboot

Voila!

Posted by EmErgE at 12:23 AM
Categories: Linux

Monday, March 15, 2010

qwebirc - installation and configuration with cgiirc enabled

qwebirc

qwebirc

==Installation==

=Debian/Ubuntu=
# apt-get install mercurial
# apt-get install python-twisted-names
# apt-get install python-twisted-mail
# apt-get install python-twisted-web
# apt-get install python-twisted-words

=FreeBSD/PCBSD=
# cd /usr/ports/devel/mercurial && make install clean
# cd /usr/ports/www/py-twistedWeb && make install clean
# cd /usr/ports/dns/py-twistedNames && make install clean
# cd /usr/ports/mail/py-twistedMail && make install clean
# cd /usr/ports/net-im/py-twistedWords && make install clean

$ cd ~/
$ hg clone http://hg.qwebirc.org qwebirc
$ cd qwebirc
$ hg up -C stable
$ hg pull
$ hg up

==Configuration==

Create config.py with following content:

File: config.py
--------------------------------
from qwebirc.config_options import *
IRCSERVER, IRCPORT = "irc.myserver.com", 6667
REALNAME = "http://moo.com/"
IDENT = "webchat"
WEBIRC_MODE = None
BASE_URL = "http://foo.foo.org/"
NETWORK_NAME = "FooNet"
APP_TITLE = NETWORK_NAME + " Web IRC"
FEEDBACK_FROM = "moo@moo.com"
FEEDBACK_TO = "moo@moo.com"
FEEDBACK_SMTP_HOST, FEEDBACK_SMTP_PORT = "127.0.0.1", 25
ADMIN_ENGINE_HOSTS = ["127.0.0.1"]
UPDATE_FREQ = 0.5
MAXBUFLEN = 100000
MAXSUBSCRIPTIONS = 1
MAXLINELEN = 600
DNS_TIMEOUT = 5
HTTP_AJAX_REQUEST_TIMEOUT = 30
HTTP_REQUEST_TIMEOUT = 5
HMACKEY = "mrmoo"
HMACTEMPORAL = 30
AUTHGATEDOMAIN = "webchat_test"
QTICKETKEY = "boo"
AUTH_SERVICE = "Q!TheQBot@CServe.quakenet.org"
AUTH_OK_REGEX = "^You are now logged in as [^ ]+\\.$"
import dummyauthgate as AUTHGATEPROVIDER
-----End of File----------------

Modify default values like IRCSERVER, REALNAME, IDENT, BASE_URL, NETWORK_NAME, 
FEEDBACK_FROM, FEEDBACK_TO, AUTHGATEDOMAIN, QTICKETKEY To start server (with default port 9090 and all IPs): cd ~/qwebirc ./run.py To start server on port 7777: cd ~/qwebirc ./run -p 7777 To start server on port 7777 and specific IP 1.2.3.4: cd ~/qwebirc ./run -i 1.2.3.4 -p 7777 ==Enabling CGIIRC== Modify the value of WEBIRC_MODE in config.py and add WEBIRC_PASSWORD as shown below: File: config.py (partial) ------------------------- WEBIRC_MODE = "webirc" WEBIRC_PASSWORD = "some-secret-password" ------End of File-------- If you are using UnrealIRCD add these lines in unrealircd.conf: File: unrealircd.conf (partial) ------------------------------- cgiirc { type webirc; hostname "irc.myserver.com"; password "some-secret-password"; }; ------End of File--------------- For other IRC Clients, use this link for reference: Enable Mibbit on Your IRC Server
Posted by EmErgE at 5:13 PM
Categories: *BSD, Linux

Thursday, January 07, 2010

SSH User Inactivity Check

Download This Script

#!/bin/bash
#
# SSH Inactivity Script by EmErgE @ irc.securitychat.org released under the
# terms and license of GPLv3.
#
# The bash script calculates the time difference between last logged-in date
# and current date of users using lastlog entry. In case the user hasn't
# logged in before, the modification date of user's homedir is used. By
# default users inactive for more than a month are restricted from logging in
# by adding an entry to /etc/security/limits.conf but the inactivity time
# period can be changed by editing the script. The script requires root access
# to function properly since su access is required to make an entry to
# /etc/security/limits.conf For any questions, suggestions feel free to email
# me at emerge@badfoo.net or reach me at irc.securitychat.org

cat > /tmp/conv_secs2days.pl << EOF
#! /usr/bin/perl
# Convert seconds to days, hours, minutes, seconds
\$seconds = \$ARGV[0];
@parts = gmtime(\$seconds);
printf ("%3d days %2d hours %2d minutes %2d seconds\n",@parts[7,2,1,0]);
EOF

# Change this value to 1 to lock inactive users through /etc/security/limits.conf
lock_inactive_users=0

if [ -e "inactivity_details.txt" ]; then rm inactivity_details.txt; fi
for users in /home/*
do
	user_name=$(basename "$users")
	login_date=$(lastlog -u "$user_name" | sed 1d | cut -c 43- | sed -e s/^\ //) 		#<-- get login date for user
	if test "$login_date" == "**Never logged in**" ; then 					#<-- If users hasn't logged in before
		local_date=$(ls -l "/home"| grep "$user_name" | head -n 1 | awk '{ printf "%s %s\n",$6,$7}') 	#<-- extract timestamp from user's ~/
		login_date=$(date -d "$local_date")			#<-- convert timestamp into standard form
	fi
	
	logindate_inseconds=$(date -u -d "$login_date" +%s) 		#<-- convert login date to seconds from epoch (Thu Jan 1 00:00:00 1970)
	curdate_inseconds=$(date -u +%s); 				#<-- convert current date to seconds from epoch
	DIFF=$(( $curdate_inseconds - $logindate_inseconds )); 		#<-- calculate the difference
	# diff_date=$(date -u -d@$DIFF) 				#<-- converts difference to date 
	
	if [ "$DIFF" -ge "86400" ]; then				#<-- if the difference is more than 24 hours
		cat /dev/null
		# do some stuff here for 24 hours inactivity
	fi

	if [ $DIFF -ge '2678400' ]; then				#<-- if the difference is more than 1 month
		# do some stuff here for 1 month inactivity
		
		if [[ $lock_inactive_users -gt 0 ]]; then
			grep "$user_name hard maxlogins 0" /etc/security/limits.conf > /dev/null
			if test $? -eq 0; then
				echo "$user_name's account is already locked."
			else
					echo "$user_name" hard maxlogins 0 >> /etc/security/limits.conf
					echo "$user_name userlocked."
			fi
		fi
	fi
	
	if [ $DIFF -ge '4320000' ]; then				#<-- if the difference is more than 50 days
		cat /dev/null
		# do some stuff here for 50 days inactivity
	fi

	last_logged_in=$(perl /tmp/conv_secs2days.pl $DIFF)

	## formatting output
	mylen=`expr length $user_name`
	spaces_required=`expr 15 - $mylen`
	formatted_user_name=$user_name`perl -e 'print " "x'$spaces_required';'`
	echo -e "$formatted_user_name\tlast logged in:\t$last_logged_in ago."
	echo -e "$formatted_user_name\tlast logged in:\t$last_logged_in ago." >> inactivity_details.txt
done
Posted by EmErgE at 11:12 AM
Categories: Linux

Wednesday, January 06, 2010

Random Themes (Frame Buffer Splash and SLiM)

One day randomness came to mind and I wrote a script to apply random framebuffer splash to terminal upon login. Gentoo comes with multiple themes in /etc/splash directory along with media-gfx/splash-themes-gentoo package. This is more or less general script and to prove that I've extended it to use with SLiM (Simple Login Manager) applying random themes from /usr/share/slim/themes/

Script to Apply Random FB Splash from /etc/splash (Download)
-----------------------------------------------------------------------------

### Generate random theme name from /etc/splash. Change path variable if you have a different theme location
THEME=$(MYPATH="/etc/splash/*"; 
				COUNT=$(( $(for i in ${MYPATH};do if [ -d ${i} ]; then echo $(basename ${i}); fi; done | wc -l) - 1)); 
				RAN=$(( $(expr $RANDOM % ${COUNT}) + 1)); 
				for i in ${MYPATH};do echo $(basename ${i}); done | sed -n ${RAN}p);
### Apply random theme to tty2
splash_manager -c set -t ${THEME} --tty=2
### Display info about theme applied
echo FBSplash Set to: ${THEME}

Explanation: The scripts makes use of $RANDOM shell variable and 'sed' way of displaying particular line to get a random theme from path variable and applies it to the terminal through splash_manager

Script to Apply Random SLiM Themes from /usr/share/slim/themes (Download)
------------------------------------------------------------------------------------------------

### Generate random theme name from /usr/share/slim/themes/. Change path variable if you have a different theme location
THEME=$(MYPATH="/usr/share/slim/themes/*"; 
				COUNT=$(( $(for i in ${MYPATH};do echo $(basename ${i}); done | wc -l) - 1)); 
				RAN=$(( $(expr $RANDOM % ${COUNT}) + 1)); 
				for i in ${MYPATH};do echo $(basename ${i}); done | sed -n ${RAN}p);
### Replace current_theme line in /etc/slim.conf with random theme
sed -i 's/current_theme\(\s*.*\)/current_theme '${THEME}'/' /etc/slim.conf
### Display info about theme applied
echo SLiM Theme Set To: ${THEME}

Explanation: The scripts makes use of $RANDOM shell variable and 'sed' way of displaying particular line to get a random theme from path variable and replaces current_theme line in /etc/slim.conf. SLiM will read the line and apply theme upon displaying the login manager

Note: On gentoo commands specified in /etc/conf.d/local.start are run during startup which is a good location to call the above scripts. On debian it's /etc/rc.local

Posted by EmErgE at 10:38 PM
Categories: Linux

IPtables Rules to block SSH Bruteforce and Tor exit nodes

I was going through some of the old files and came across IPTables Rules to block SSH Bruteforce and Tor exit nodes. These rules are helpful in protecting your VPS/Dedicated Servers from related attacks and IP Spoofing.

IPTables Rules to limit SSH bruteforce (Download)
------------------------------------------------------------

iptables -A INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -i eth0 -m state --state NEW -m recent --update --seconds 60 --hitcount 7 --rttl --name SSH -j DROP

Explanation: The first lines assigns a name SSH to the packets with destination port 22. If the packet count exceeds 7 hits per 60 second for an ip address further connections are dropped. If your sshd is listening to a port other than 22 update above rules to reflect changes.

IPTables Rules to block Tor exit nodes (Download)
-------------------------------------------------------------

#!/bin/bash
wget -P/tmp http://anonymizer.blutmagie.de:2505/ip_list_exit.php/Tor_ip_list_EXIT.csv
if [ -f /tmp/Tor_ip_list_EXIT.csv ]; then
	for BAD_IP in `cat /tmp/Tor_ip_list_EXIT.csv`
	do
		iptables -A INPUT -s "$BAD_IP" -j DROP
	done
else
	echo "Can't read /tmp/Tor_ip_list_EXIT.csv"
fi

Explanation: The above commands sequence downloads the tor exit node list from blutmagie.de and adds IPTables rules to drop the connection with each IP address as source.

Posted by EmErgE at 3:32 PM
Categories: General Networking, Linux, Security

Monday, January 04, 2010

MultiISO LiveDVD

EmErgE's MultiISO LiveDVD

Quoting the description from http://badfoo.net/emerge: "MultiISO LiveDVD is an integrated Live DVD technology which combines some of the very popular Live CD ISOs already available on the internet. It can be used for security reconnaissance, vulnerability identification, penetration testing, system rescue, media center and multimedia, system recovery, etc. It's a all-in-one multipurpose LiveDVD put together. There's something in it for everyone. I hope you enjoy it."

Click to See Screenshot

Recently, after months of testing, I have released version 2.0 of MultiISO LiveDVD which can be directly downloaded here or through torrent here. BSDGurl and duder have been kind enough as always and helping me out with testing and setting up torrent link.

If you are interested in mirroring the ISO (4.33gb!) let me know. I usually hang out on irc.securitychat.org

For more information check out http://badfoo.net/emerge

Posted by EmErgE at 9:44 AM
Categories: Linux