Thursday, September 22, 2011
MaraDNS - Running Authorative and Recursive DNS server
MaraDNS - Authorative DNS server Configuration
++++++++++++++++++++++++++++++++++++++++++++++
# apt-get install maradns
If you are using the default configuration file sometimes it's helpful to see the non-commented lines
# cat /etc/maradns/mararc | awk '/^[^#]/ { print $0 '}
-----------------------------------
Running an Authorative DNS Server
-----------------------------------
Now let's modify the mararc config file by adding/modifying the lines below:
# vim /etc/maradns/mararc
csv2 = {}
csv2["example.org."] = "db.example.org"
csv2["helloworld.net."] = "db.helloworld.net"
bind_address = "50.3.1.8"
chroot_dir = "/etc/maradns"
It's time to create the corresponding zone files.
# vim /etc/maradns/db.example.org
example.org NS ns1.example.org ~
example.org 1.2.3.4 ~
www.example.org 1.2.3.4 ~
example.org MX 10 mail.example.org ~
ns1.example.org 50.3.1.8 ~
mail.example.org 50.3.1.8 ~
irc.example.org 1.3.3.7 ~
Notice the lack of SOA records which are generate automagically.
Another way is to use the shortcut % which represents the domain as defined on mararc.
# vim /etc/maradns/db.helloworld.net
% NS ns1.% ~
% 1.2.3.4 ~
www.% 1.2.3.4 ~
% MX 10 mail.% ~
ns1.% 50.3.1.8 ~
mail.% 50.3.1.8 ~
irc.% 1.3.3.7 ~
This is exactly the same as above zone file except all '%' symbols in this file are
replaced by 'helloworld.net.'
Finally restart the service:
# /etc/init.d/maradns restart
and check the log,
# cat /var/log/syslog | grep maradns
to make sure there are no errors.
Test using 'askmara':
$ askmara Awww.example.org. 50.3.1.8
# Querying the server with the IP 50.3.1.8
# Question: Awww.example.org.
www.example.org. +86400 a 1.2.3.4
# NS replies:
#example.org. +86400 ns ns1.example.org.
# AR replies:
#ns1.example.org. +86400 a 50.3.1.8
Test using 'dig':
$ dig A www.example.org @50.3.1.8
;; ANSWER SECTION:
www.example.org. 86400 IN A 1.2.3.4
;; AUTHORITY SECTION:
example.org. 86400 IN NS ns1.example.org.
-------------------------------
Running a Recursive DNS Server
-------------------------------
In addition to authorative server, maradns can also funcation as a recursive DNS server.
To run a recursive server, add/modify lines in the config file.
# vim /etc/maradns/mararc
bind_address = "50.3.1.8"
chroot_dir = "/etc/maradns"
# Uncomment this line if commented.
ipv4_alias = {}
# Here you define the forwarders which in most cases are the providers DNS server IPs
# or Public DNS Servers. We're using Google DNS for this purpse
upstream_servers = {}
upstream_servers["."] = "8.8.8.8 8.8.4.4"
# Hosts allowed to perform recursive queries
recursive_acl = "192.168.51.0/24"
That's it. Verify it works:
$ dig A google.com @50.3.1.8
Since the modifcation of config file for both authorative and recursive purpose do
not conflict with one another, it is possible to run them both at the same time
through a single config file.
More Info:
* Example files: /usr/share/doc/maradns/en/examples
* Manual: man maradns
* Manual: man askmara
* Web: http://www.maradns.org
Coding Standards and Style Guides
List of coding standard and style guides to assist programmers in writing better code:
General:
BASH: http://wiki.bash-hackers.org/scripting/style
C: http://www.jetcafe.org/jim/c-style.html
C++: http://www.possibility.com/Cpp/CppCodingStandard.html
CSS: http://www.louddog.com/2008/create-maintainable-code-with-a-css-styleguide/
Django: https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/
Erlang: http://www.erlang.se/doc/programming_rules.shtml
Haskell: http://www.haskell.org/haskellwiki/Programming_guidelines
HTML5: http://coding.smashingmagazine.com/2009/08/04/designing-a-html-5-layout-from-scratch/
Java: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Javascript: http://javascript.crockford.com/code.html
LaTeX: http://www.clt.mq.edu.au/~rdale/resources/writingnotes/latexstyle.html
Lisp: http://mumble.net/~campbell/scheme/style.txt
Matlab: http://www.cs.cornell.edu/courses/cs99/2002fa/matlabstyle.html
.Net Framework (including C#): http://blogs.msdn.com/b/brada/archive/2005/01/26/361363.aspx
node.js: http://nodeguide.com/style.html
Objective-C: http://cocoadevcentral.com/articles/000082.php
Perl: http://perldoc.perl.org/perlstyle.html
PHP: http://pear.php.net/manual/en/standards.php
Postscript: http://www.ghostscript.com/doc/current/Ps-style.htm
Python: http://www.python.org/dev/peps/pep-0008/
Ruby: https://github.com/chneukirchen/styleguide/blob/436e8c1bbeb6ffde8bcfbcf72af449c5f8a741f3/RUBY-STYLE
Visual Basic: http://msdn.microsoft.com/en-us/library/aa240822(v=vs.60).aspx
XML: http://google-styleguide.googlecode.com/svn/trunk/xmlstyle.html
Misc:
Drupal: http://drupal.org/coding-standards
Joomla: http://docs.joomla.org/Coding_style_and_standards
Mozilla: https://developer.mozilla.org/En/Mozilla_Coding_Style_Guide
Wikipedia: http://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style
Wordpress: http://codex.wordpress.org/WordPress_Coding_Standards
Tuesday, September 06, 2011
Configuring IPv6 BGP Tunnel with Hurricane Electric (tunnelbroker.net)
Prerequisites: * Cisco IOS with IPv6 support * Internet Routable IPv4 address * AS number exclusively assigned to you by your RIR Throughout the guide, following assumptions are made: * Public IP of your Cisco Router is: 9.33.21.35 * Your ASN is: 31337 * Your RIR delegated IPv6 Prefix is: 1337:C0DE::/32 * 1337:C0DE:0A:49::74 an example IPv6 we'll assign to our router 1) Go to http://tunnelbroker.net 2) Register/Login 3) Create BGP Tunnel -> IPV4 Endpoint (Your Side) Enter Public IP Address, example: 9.33.21.35 Prefixes announced: 1337:C0DE::/32 Selection a tunnel endpoint that's closest to you (eg: Fremont, CA, US 64.71.128.83) Click on Create BGP Tunnel On the Main Page, under the tunnel you just created you get following information: IPv6 Tunnel Endpoints Server IPv4 Address: 64.71.128.83 Server IPv6 Address: 2001:1337:28:bad::1/64 Client IPv4 Address: 9.33.21.22 Client IPV6 Address: 2001:1337:28:bad::2/64 BGP Details Prefixes: 1337:C0DE::/32 Your ASN: 31337 Our ASN: 6262 Peer Address: 2001:1337:28:bad::1/64 This is sufficient information to create an IPv6 BGP Tunnel. Hurricane Electric/Tunnel Broker requires Letter of Authorization that you are the sole owner of your AS and the IPv6 Prefix. You will receive instructions through email to submit this authorization letter through email. 4) It's now time to configure the Cisco IOS. Login in to your Cisco IOS and enter the router configuration mode: First thing is to make sure IPv6 support is enabled on your router. To check, enter the command to enable ipv6 on the router router(config)# ipv6 unicast-routing If it gives an error such as: % Invalid input detected at '^' marker. then you may need to upgrade the firmware on the router or find another one that supports Ipv6 We configure the rest of the router according to the information above: interface Tunnel0 description Hurricane Electric IPV6 Tunnel Broker no ip address ipv6 address 2001:1337:28:bad::2/64 ipv6 enable tunnel source 9.33.21.22 tunnel destination 64.71.128.83 tunnel mode ipv6ip ! router bgp 31337 no bgp default ipv4-unicast bgp log-neighbor-changes neighbor 2001:1337:28:bad::1 remote-as 6262 neighbor 2001:1337:28:bad::1 update-source Tunnel0 ! address-family ipv6 neighbor 2001:1337:28:bad::1 activate neighbor 2001:1337:28:bad::1 remove-private-as neighbor 2001:1337:28:bad::1 route-map he-ipv6-in in neighbor 2001:1337:28:bad::1 route-map he-ipv6-out out network 1337:C0DE::/32 aggregate-address 1337:C0DE::/32 summary-only redistribute connected metric 1 no synchronization exit-address-family ! ipv6 route ::/0 Tunnel0 ! ipv6 prefix-list ipv6-general-prefix seq 5 deny ::/0 ipv6 prefix-list ipv6-general-prefix seq 10 permit ::/0 le 64 ! ipv6 prefix-list myprivate-prefix seq 5 permit 1337:C0DE::/32 le 64 ! route-map he-ipv6-out permit 10 match ipv6 address prefix-list myprivate-prefix set as-path prepend 31337 31337 31337 ! route-map he-ipv6-in permit 10 match ipv6 address prefix-list ipv6-general-prefix set as-path prepend 6262 6262 6262 ! This should look familiar if you have configured BGP before.
Notice the line "address-family ipv6" is configured from within the "router bgp" prompt.
This basically enables BGP for IPv6 addresses only.
The other lines are responsible for:
1) Setting up the default ipv6 route through the tunnel interface
2) Publishing aggregate routes with our delegated prefix-only to remote peer. The final step is to enable the IPv6 on the external router interface. ! interface GigabitEthernet0/0 ip address 9.33.21.35 255.255.255.0 ipv6 address 1337:C0DE:0A:49::74/64 ipv6 enable ipv6 nd ra suppress ! Notice, I've added the "ip address" line to show the interface with preconfigured IPv4 address we are using as tunnel endpoint. To verify the tunnel is working and the routes are established, use commands below: router# sh bgp ipv6 router# sh ipv6 routes If these commands produce a long list of IPv6 routes then you have successfully configured your Cisco IOS with BGP and IPv6. If you don't see the IPv6 routes, check the configuration for any errors and verify tunnelbroker.net has received your letter of authorization (shows up as "LoA on file" on the website's tunnel details page).
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
# dpkg-reconfigure exim4-config
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)
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
dc_eximconfig_configtype='smarthost' dc_smarthost='172.16.75.17'
Generate Self-signed Certificate
# /usr/share/doc/exim4-base/examples/exim-gencert
Add Exim4 User
# /usr/share/doc/exim4/examples/exim-adduser
# cp /usr/share/doc/exim4/examples/exim-adduser /sbin # exim-adduser
Enabling TLS
# echo "MAIN_TLS_ENABLE = yes" > /etc/exim4/conf.d/main/00_local_settings
Enabling SMTP Authentication
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
# update-exim4.conf # /etc/init.d/exim4 restart
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
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
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
Cisco Router Password Recovery
Configure Putty to following details: Serial Line: COM5 Speed: 9600 Speed (baud):9600 Data bits: 8 Stop bits: 1 Parity: None Flow Control: None Power up the router. Press Ctrl + Pause Break key combinations while it's booting up. This will present a ROMmon mode. rommon 2 > confreg 0x2142 rommon 2 > reset After the router finishes loading, Router> sh ver | begin ^Configuration Configuration register is 0x2142 Router> enable Router> copy startup-config running-config Router> config t Router(config)# enable secret mysecretpassword Router(config)# config-register 0x2102 Router(config)# exit Router# copy running-config startup-config Destination filename [startup-config]? (Press Enter) Router# reload Proceed with reload? [confirm] (Press Enter) Once the router finishes booting up: Router>sh ver | begin ^Configuration Configuration register is 0x2102 Congratulations!
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)
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
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
Friday, June 03, 2011
Cisco VPN Server
aaa new-model aaa authentication login default local aaa authentication login MYVPNXAUTH local aaa authorization exec default local aaa authorization network MYVPNAUTHGROUP local ! username admin privilege 15 password 0 MYPASSWORD ! crypto isakmp policy 10 encr aes hash md5 authentication pre-share group 2 ! crypto isakmp client configuration group TUNNELGROUP key MYVPNKEY pool MYPOOL acl 100 netmask 255.255.255.0 crypto isakmp profile MYIKEPROFILE match identity group TUNNELGROUP client authentication list MYVPNXAUTH isakmp authorization list MYVPNAUTHGROUP client configuration address respond virtual-template 1 ! crypto ipsec transform-set MYSET esp-aes esp-sha-hmac ! crypto ipsec profile MYIPSECPROFILE set transform-set MYSET set isakmp-profile MYIKEPROFILE ! interface Virtual-Template1 type tunnel ip unnumbered FastEthernet4 tunnel mode ipsec ipv4 tunnel protection ipsec profile MYIPSECPROFILE ! ip local pool MYPOOL 192.168.1.50 192.168.1.60 ! access-list 100 permit ip 192.168.1.0 0.0.0.255 any access-list 110 deny ip 192.168.1.0 0.0.0.255 192.168.1.0 0.0.0.255 access-list 110 permit ip 192.168.1.0 0.0.0.255 any ! route-map nonat permit 10 match ip address 110 ! interface FastEthernet4 ip address 172.16.12.13 255.255.255.0 ip nat outside ! interface Vlan1 ip address 192.168.1.1 255.255.255.0 ip nat inside ! ip route 0.0.0.0 0.0.0.0 172.16.12.1 ! ip nat inside source route-map nonat interface FastEthernet4 overload
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
FreeBSD Jail + IPFW + NAT
Running a NATed jail under FreeBSD is quite helpful when you don't have a public internet routable ip address avilable except that of host's. With the combination of ipfw and nat it is possibe to share the same address space and ports as the host and forward certain ports to jail services.
BSDGurls' has written a handy ezjail guide available at http://bsdgurl.net/text/ezjail-guide.txt. With her permission, I'm adopting the first part of this tutorial from the same.
Setting Up Ezjail:
Install sources: # sysinstall Select all sources from Configure -> Distributions -> src and install them Buildworld: # cd /usr/src # make buildworld Compile ezjail port: # cd /usr/ports/sysutils/ezjail && make install clean Prepare Base System: # ezjail-admin update -p -i Create Your Jail (Replace mydomain.org and ip address) # ezjail-admin create -r /usr/jails/mydomain.org mydomain.org 1.2.3.4 Add alias IP to interface (example: em0) and turn on ezjail service: # echo 'ifconfig_em0_alias0="inet 1.2.3.4 netmask 255.255.255.255"' >> /etc/rc.conf # echo 'jail_socket_unixiproute_only="NO"' >> /etc/rc.conf # echo 'ezjail_enable="YES"' >> /etc/rc.conf Configure syslogd to listen on both host and jail # echo 'syslogd_flags="-ss"' >> /etc/rc.conf Copy resolv.conf from host to jail: # cp /etc/resolv.conf /usr/jails/mydomain.org/etc/ Start Jail: # /usr/local/etc/rc.d/ezjail.sh start Some Userful Jail commands: jls => list jails jexec 1 /bin/sh => connects to jail console /usr/local/etc/rc.d/ezjail.sh restart => restarts all jails ezjail-admin delete -w mydomain.org => deletes mydomain.org jail Okay now that's done, we will setup ipfw and nat. We will now create a basic IPFW rules file. For Advanced example, take a look at BSDGurl's IPFW Guide Page: http://bsdgurl.net/text/ipfw-guide.txt # ee /usr/local/etc/myfirewall.rules Example Contents of file /usr/local/etc/myfirewall.rules -----------------START------------- # Example Interface: em0 # List of Ports: # Host SSH: 4567 # HOST WEBERVER: 8080,4443 # JAIL SSH: 7890 # JAIL WEB SERVER: 80, 443 # JAIL DNS SERVER: 53 IPF="ipfw -q add" ipfw -q -f flush # Replace with your interface PIF="em0" # Host IP inet="172.16.83.84" # Jail IP jail="1.2.3.4" $IPF 10 allow all from any to any via lo0 $IPF 15 allow all from any to 127.0.0.0/8 $IPF 20 deny all from any to 127.0.0.0/8 $IPF 25 deny all from 127.0.0.0/8 to any $IPF 40 deny tcp from any to any frag $IPF 41 allow tcp from any to me 4567 established # Allow out NATed traffic from Jail. This is DNATed traffic. $IPF 45 divert natd ip from $jail to not me out via $PIF $IPF 46 skipto 10000 ip from any to any diverted # Allow remaining all outgoing traffic $IPF 110 allow all from me to any out # Allow NATed traffic to Jail. This is SNATed traffic. natd (NAT daemon) will take care of these. $IPF 150 divert natd ip from not me to any in via $PIF $IPF 160 skipto 10000 ip from any to any diverted # Allow ICMP from friendly subnet and deny the rest $IPF 165 allow icmp from 172.16.83.0/83 to me $IPF 166 deny icmp from any to any # Allow inbound ports to host services with maximum 2 concurrent connections # We will not add Jail services ports here. They are specified in natd config file. $IPF 171 allow tcp from any to $inet 4567 in via $PIF setup limit src-addr 2 $IPF 172 allow tcp from any to $inet 8080 in via $PIF setup limit src-addr 2 $IPF 173 allow tcp from any to $inet 4443 in via $PIF setup limit src-addr 2 # Log an deny the traffic $IPF 500 deny log logamount 10000 ip from any to any # This is where all diverted NAT traffic are skipped to after being processed. $IPF 10000 allow ip from any to any -----------------STOP------------- Verify your ipfw firewall is enabled in /etc/rc.conf: firewall_enable="YES" firewall_script="/usr/local/etc/myfirewall.rules" Specify ports to be redirected in natd rules file /usr/local/etc/natd.rules (More Info: http://freebsd.rogness.net/redirect.cgi?basic/nat.html) # ee /usr/local/etc/natd.rules Example Contents of file /usr/local/etc/natd.rules (Fomat: jail_ip:jail_port host_ip:host_port) -----------------START------------- redirect_port tcp 1.2.3.4:4567 4567 redirect_port tcp 1.2.3.4:80 80 redirect_port tcp 1.2.3.4:443 443 -----------------STOP------------- Enable natd service: # echo 'natd_enable="YES"' >> /etc/rc.conf # echo 'natd_interface="em0"' >> /etc/rc.conf # echo 'natd_flags="-config /usr/local/etc/natd.rules"' >> /etc/rc.conf Test to verify both host and jail services are accessible. If you wish to ping from within jail run this command: echo security.jail.allow_raw_sockets=1 >> /etc/sysctl.conf
Guessing Game v1.0
This brings back memories. It's a python recreation of old guessing game in qbasic. Computer guesses random number from 1 to 10. You have 3 chaces to guess it right. (Download)
#!/usr/bin/env python
import sys
from random import randint
play=1
while (play):
chances = 3
computer=randint(1,10)
print "++Guessing Game v0.1 by EmErgE++"
print "I've guessed a number between 1 to 10. You have 3 chances to guess."
while (chances):
myguess=int(raw_input("Enter your guess:"))
if myguess < computer:
print "Your guess is less than mine."
elif myguess > computer:
print "Your is greater than mine."
else:
print "Bravo! We both guessed",computer," XDD"
break
chances = chances - 1
else:
print "Oops, your chances are over! I guessed ",computer
cont=raw_input("Do You want to play again? (y/n)")
if cont=="n":
play=0
else:
print "Game Over."
jQuery + PHP Multiple File Upload v1.0 by EmErgE
<?php
## Jquery + PHP Multiple File Upload Script v1.0 by EmErgE released under GNU General Public License Version 2.0
## This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; version 2 of the License.
session_start();
if (!isset($_SESSION['imagelist'])) $_SESSION['imagelist'] = array();
$errormsg = "";
define ('MAX_FILE_SIZE', 1024000);
define('UPLOAD_DIR', 'uploads/');
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0755);
}
touch(UPLOAD_DIR."index.html");
$image_extensions_allowed = array('jpg', 'jpeg', 'png', 'gif','bmp');
$mime_allowed = array('image/jpg', 'image/jpeg', 'image/pjpeg','image/png', 'image/gif','image/bmp');
if (isset($_POST['Send'])) {
while(list($key,$value) = each($_FILES[fileX][name]))
{
if(!empty($value)){
$filename = basename($value);
$filename=str_replace(" ","_",$filename);
$ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
if( ($_FILES[fileX][size][$key] > 0) && ( $_FILES[fileX][size][$key] <= MAX_FILE_SIZE ) && ( in_array($_FILES[fileX][type][$key],$mime_allowed) ) && (in_array($ext, $image_extensions_allowed)) )
{
$file_info = getimagesize($_FILES[fileX][tmp_name][$key]);
if(!empty($file_info)) {
$add = UPLOAD_DIR."$filename";
if (!move_uploaded_file($_FILES[fileX][tmp_name][$key], $add)) unlink($_FILES[fileX][tmp_name][$key]);
chmod("$add",0777);
$_SESSION['imagelist'][] = "$add";
} else $errormsg .="Empty File Information. ";
} else $errormsg .="Unknown Extension. ";
} //else $errormsg .="Empty File. ";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr"><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<head>
<title>Jquery + PHP Multiple File Upload Script v1.0 by EmErgE v1.0 released under GPLv2</title>
<style type="text/css">
.remove:hover{
background: #DDD;
}
.remove{
color: #F00;
font-size: 15px;
font-weight: bold;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var MaxNumber = 3;
$("input.upload").change(function(){
validateFile(this, MaxNumber);
});
function validateFile(myelement, maxAllowed) {
if($('input.upload').size() > maxAllowed) {
$("#errormsg").html("Files count exceeded Maximum Allowed Number of "+maxAllowed);return true;
}
$(myelement).hide();
$(myelement).parent().prepend('<input type="file" class="upload" name="fileX[]" />').find("input").change(function() {validateFile(this, maxAllowed)});
var elementval = myelement.value;
if(elementval != '') {
$("#queue").append('<div>'+elementval+' <a class="remove">X</a></div>').find("a").click(function(){
$(this).parent().remove();
$(myelement).remove();
return true;
});
}
};
});
</script>
</head>
<body>
<?php if(!empty($errormsg)) { echo "<span style='color: f00'>$errormsg</span>"; } ?>
<span id="errormsg" style="color: #f00"></span>
Upload Image - Maximum Number of Files: 3 & Maximum Size: 1Mb
<form method=post action="<?php $_SERVER['PHP_SELF']; ?>" enctype='multipart/form-data' id="myform">
<input type="file" class="upload" name="fileX[]" />
<input type="hidden" name="MAX_FILE_SIZE" value="1048000" />
<input type=submit name="Send" value="Upload">
</form>
<div id="queue" class="queue"></div>
<?php
if (!empty($_SESSION['imagelist'][0])) {
echo "Thank You For Uploading:<br>";
foreach ($_SESSION['imagelist'] as &$value) {
echo "<img src='$value' />";
}
}
?>
</body>
</html>
Routers: From a Psychological Standpoint
If I was little and somebody asked what I wanted to be when I grew up, I'd say a Router, not a cheap "Made in China" Huawei Router, but a decent Cisco made Router because routers are amazing creation of humankind and research. They always know best, even if they don't they give their best shot by utilizing routing protocols such as RIP, IGRP, OSPF, BGP, EIGRP. Giving up is merely word in a router's dictionary. They perform undaunted task of finding best possible route for packets that are lost and confused. As long as a datagram lives in the same subnet, router will show them the way for they do not know their destiny. Combined with access-lists they block evil in a blink of an eye. They know best not to forward broadcast packets. In a society full of crime and war, routers prevent collision by splitting collision domains. To a wanderer, router is a gateway of light and hope. Distributed Denial of Service (DDoS) is router's greatest enemy. Nevertheless, a router fights back against such repulsive behaviors with courage and dignity in the form of null routing. Routers and switches go hand in hand in forming a stable network and uninterrupted services. Router is a great teamplayer with other network devices like repeaters, bridges and hubs.
To sum up, routers make information sharing easy and painless as possible and guide otherwise chaotic networks to best possible optimized direction. It is routers that have brought millions of lives together and it is only fair that we continue studying and implementing them to create a bigger, better global network we are so fond of.
Thumbnail Generator
<?php
/*
Thumbnail Generator by EmErgE :: irc.securitychat.org
This php code will generate specific number of vertical and horizontal tables
with specifi number of columns and rows per cell. This can be used to generate
image thumbnails by replacing the * with <img> tag.
Sample Output 1:
Column per cell: 5
Rows Per cell: 5
Horizontal Tables: 2
Vertical Tables: 3
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
|*_|*_|*_|*_|*_| |*_|*_|*_|*_|*_|
Sample Output 2:
Column per cell: 2
Rows Per cell: 2
Horizontal Tables: 8
Vertical Tables: 4
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
|*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_| |*_|*_|
*/
$columns_per_cell=2;
$rows_per_cell=2;
$horizontal_tables =3;
$vertical_tables = 3;
$columncount = $columns_per_cell * $horizontal_tables;
$rowcount = $rows_per_cell * $vertical_tables;
$endvalue = $columncount * ($vertical_tables-1);
$colors=array("red","green","blue","green","orange","gray","brown");
for ($i=0; $i<=$endvalue; $i=$i+$columncount) {
for ($k = 1; $k <= $rows_per_cell; $k++) {
$mycolorindex = array_rand($colors);
$mycolor = $colors[$mycolorindex];
echo "<font color='".$mycolor."'>";
for ($j=$i; $j <= ($i+$columncount-1); $j++){
if(!($j%$columns_per_cell)) echo " |";
echo "*_|";
}
echo "</font>";
echo '<br>';
}
echo "<br> ";
}
echo '<br>';
?>
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
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!
Friday, March 19, 2010
glusterfs installation (storage brick replication)
In this guide we will use gluster2 to replicate stroage bricks between two nodes both of which will act as both server and client. #File: /etc/hosts 192.168.0.100 node1.example.org node2 192.168.0.101 node2.example.org node2 # aptitude install sshfs build-essential flex bison byacc libdb libdb-dev # cd /usr/src # wget http://ftp.zresearch.com/pub/gluster/glusterfs/3.0/3.0.0/glusterfs-3.0.0.tar.gz # tar xzvf glusterfs-3.0.0.tar.gz # cd glusterfs-3.0.0 # ./configure --prefix=/usr > /dev/null # make && make install # ldconfig # mkdir /data # mkdir /data/export # mkdir /data/export-ns # mkdir /etc/glusterfs # mkdir /srv #File: /etc/glusterfs/glusterfsd.vol volume posix type storage/posix option directory /data/export end-volume volume locks type features/locks subvolumes posix end-volume volume brick type performance/io-threads option thread-count 8 subvolumes locks end-volume volume server type protocol/server option transport-type tcp option auth.addr.brick.allow 192.168.0.* subvolumes brick end-volume # update-rc.d glusterfsd defaults # /etc/init.d/glusterfsd start # cd /usr/src/ # wget ftp://ftp.zresearch.com/pub/gluster/glusterfs/fuse/fuse-2.7.4glfs11.tar.gz # tar xzvf fuse-2.7.4glfs11.tar.gz # cd fuse-2.7.4glfs11 # ./configure # make && make install #File: /etc/glusterfs/glusterfs.vol volume remote1 type protocol/client option transport-type tcp option remote-host node1 option remote-subvolume brick end-volume volume remote2 type protocol/client option transport-type tcp option remote-host node2 option remote-subvolume brick end-volume volume replicate type cluster/replicate subvolumes remote1 remote2 end-volume volume writebehind type performance/write-behind option window-size 1MB subvolumes replicate end-volume volume cache type performance/io-cache option cache-size 512MB subvolumes writebehind end-volume # glusterfs -f /etc/glusterfs/glusterfs.vol /srv #File: /etc/fstab /etc/glusterfs/glsuterfs.vol /srv glusterfs defaults 0 0 NOTE: This guide was largely adopted from HowtoForge GlusterFS on Debian
Monday, March 15, 2010
qwebirc - installation and configuration with cgiirc enabled
==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
Wednesday, March 03, 2010
Cisco Site-To-Site IPSEC VPN Tunnel
Our site-to-site VPN Tunnel will share 192.168.7.0/24 and 10.11.12.0/24 with each other. For this to work, 172.16.1.10 and 192.168.10.10 should be publicly reachable though static NAT translation on Gateway routers (ip nat inside source static 1.1.1.1 192.168.1.1) where 1.1.1.1 is Public IP and 192.168.1.10 is private ip. All traffic directed to 1.1.1.1 will be translated and forwarded to 192.168.1.10
NAT Traversal is automagic if both end devices support it. Cisco routers do. I have included requied commands for both sites.
SITE-A-Configuration -------------------- hostname SITEA ! ip cef ip name-server 172.16.1.1 ! crypto isakmp policy 10 encr aes hash md5 authentication pre-share group 2 crypto isakmp key MYVPNKEY address 192.168.10.10 no-xauth ! crypto ipsec transform-set MYSET esp-aes esp-sha-hmac ! crypto map MYMAP 10 ipsec-isakmp set peer 192.168.10.10 set transform-set MYSET match address NONAT ! interface FastEthernet4 description ## Publicly reachable Outside End Point IP ## ip address 172.16.1.10 255.255.255.0 ip nat outside crypto map MYMAP ! interface Vlan1 description ## Internal Overloaded IP# ip address 192.168.7.1 255.255.255.0 ip nat inside ! ip default-gateway 172.16.1.1 ip route 0.0.0.0 0.0.0.0 172.16.1.1 ! ip nat inside source route-map allowed-out interface FastEthernet4 overload ip dns server ! ip access-list extended NONAT permit ip 192.168.7.0 0.0.0.255 10.11.12.0 0.0.0.255 ! access-list 150 deny ip 192.168.7.0 0.0.0.255 10.11.12.0 0.0.0.255 access-list 150 permit ip 192.168.7.0 0.0.0.255 any route-map allowed-out permit 10 match ip address 150 SITE-B-Configuration -------------------- hostname SITEB ! ip cef ip name-server 192.168.10.1 ! crypto isakmp policy 10 encr aes hash md5 authentication pre-share group 2 crypto isakmp key MYVPNKEY address 172.16.1.10 no-xauth ! crypto ipsec transform-set MYSET esp-aes esp-sha-hmac ! crypto map MYMAP 10 ipsec-isakmp set peer 172.16.1.10 set transform-set MYSET match address NONAT ! interface FastEthernet4 description ## Publicly reachable Outside End Point IP ## ip address 192.168.10.10 255.255.255.0 ip nat outside crypto map MYMAP ! interface Vlan1 description ## Internal Overloaded IP# ip address 10.11.12.1 255.255.255.0 ip nat inside ! ip default-gateway 192.168.10.1 ip route 0.0.0.0 0.0.0.0 192.168.10.1 ! ip nat inside source route-map allowed-out interface FastEthernet4 overload ip dns server ! ip access-list extended NONAT permit ip 10.11.12.0 0.0.0.255 192.168.7.0 0.0.0.255 ! access-list 150 deny ip 10.11.12.0 0.0.0.255 192.168.7.0 0.0.0.255 access-list 150 permit ip 10.11.12.0 0.0.0.255 any route-map allowed-out permit 10 match ip address 150 !
Saturday, January 23, 2010
Practical Subnetting made easy
First off, remember the series of numbers and their order: 128, 192, 224, 240, 248, 252, 254, 255 Also remember, /24 = Class C (255.255.255.0) /16 = Class B (255.255.0.0) /8 = Class A (255.0.0) class A is between 0.0.0.0 127.255.255.255 class B is between 128.0.0.0 191.255.255.255 class C is between 192.0.0.0 223.255.255.255 Interestingly the starting numbers of each class is similar to above series of numbers. Another way to remember is: class A 0 to 127 class B 128 to 191 class C 192 to 223 * The numbers 127 and 192 are easy to rememner since 127.0.0.1 is loopback address and 192.168.0.0/16 is one of the private IP range Now let's do an example: Example 1) (Type: Class C) 192.168.1.104 with prefix /27 ==> We have /27 which falls under class C /24 (255.255.255.0) Calculating Number of Subnets: ------------------------------ 27 - 24 = 3 [Here we subtract the prefix from closest-match class prefix] 2^3 = 8 [Here we calculate the result as power of 2] Therefore, Number of Subnets = 8 Calculating Number of hosts: ---------------------------- (8 - 3) = 5 [where 8 is the number of bits in each octet and is constant] Therefore, number of hosts = 2^5 - 2 = 32 -2 = 30 (We subtract 2 because each subnet has 1 network and 1 broadcast address) Calculating Subnet Mask ------------------------- From above table, third number on the series ( 128, 192, 224) is 224. Since this is Class C prefix, (255.255.255.0) Subnet Mask for /27 subnet is 255.255.255.224 Subnet mask can also be obtained from simple math. Take 3 (27 - 24). Since there are 8 bits in each octet, the first three bits become 1 which gives us, 2^7 + 2^6 + 2^5 + 0 + 0 + 0 + 0 + 0 = 128 + 64 + 32 = 224 Calculating Each Subnets ------------------------ We have already obtained Number of hosts = 30 Including Network and broadcast, we have 32 We can now find out each subnet by adding 32 (which is the number of hosts including network and broadcast) starting from 0. So our networks are: 192.168.1.0/27 192.168.1.32/27 192.168.1.64/27 192.168.1.96/27 __Our IP Falls In This Subnet__ 192.168.1.128/27 192.168.1.160/27 192.168.1.192/27 192.168.1.224/27 You don't have to compute each subnet. To quickly identify which subnet IP belongs to, divide last octet (for class C) by subnet number 32 104/32 = 3 (discard the value after decimal point) Network Address can be calculated as: 3 * 32 = 96 That gives us 192.168.1.96/27 Broadcast Address, Minimum and Maximum Hosts: --------------------------------------------- Broadcast address is always the last address in a subnet which is also the last number before next subnet starts. In this case broadcast address is 192.168.1.127 The minimum available IP of host is the first IP after subnet's network address. In this case minimum host is 192.168.1.97 The maximum available IP of host is the IP before broadcast address. In this case maximum host is 192.168.1.126 Summary ------- Network Address: 192.168.1.96/27 Subnet Mask: 255.255.255.224 Broadcast Address: 192.168.1.127 Minimum Host IP: 192.168.1.97 Maximum Host IP: 192.168.1.126 Next Subnet: 192.168.1.128/27 Let's do another example: Example 2) (Type: Class B) 151.33.63.124 with prefix /18 ==> We have /18 which falls under class B /16 (255.255.0.0) Calculating Number of Subnets: ------------------------------ 18 - 16 = 2 [Here we subtract the prefix from closest-match class prefix] 2^2 = 4 [Here we calculate the result as power of 2] Therefore, Number of Subnets = 4 Calculating Number of hosts: ---------------------------- (8 - 2) = 6 [where 8 is the number of bits in each octet and is constant] Therefore, number of hosts = 2^6 - 2 = 64 -2 = 62 (We subtract 2 because each subnet has 1 network and 1 broadcast address) Calculating Subnet Mask ------------------------- From above table, second number on the series ( 128, 192) is 192. Since this is Class B prefix, (255.255.0.0) Subnet Mask for /18 subnet is 255.255.192.0 Subnet mask can also be obtained from simple math. Take 2 (18 - 16). Since there are 8 bits in each octet, the first three bits become 1 which gives us, 2^7 + 2^6 + 0 + 0 + 0 + 0 + 0 + 0 = 128 + 64 = 192 Calculating Each Subnets ------------------------ We have already obtained Number of hosts = 62 Including Network and broadcast, we have 64 We can now find out each subnet by adding 64 (which is the number of hosts including network and broadcast) starting from 0. So our equal hosts networks are: 151.33.0.0/18 __Our IP Falls In This Subnet__ 151.33.64.0/18 151.33.128.0/18 151.33.192.0/18 You don't have to compute each subnet. To quickly identify which subnet IP belongs to, divide last octet (for class C) by subnet number 32 124/64 = 0 (discard the value after decimal point) Network Address can be calculated as: 0 * 64 = I'll leave you to it. That gives us 151.33.0.0/18 Broadcast Address, Minimum and Maximum Hosts: --------------------------------------------- Broadcast address is always the last address in a subnet which is also the last number before next subnet starts. In this case broadcast address is 151.33.63.255 The minimum available IP of host is the first IP after subnet's network address. In this case minimum host is 151.33.0.1 The maximum available IP of host is the IP before broadcast address. In this case maximum host is 151.33.63.254 Summary ------- Network Address: 151.33.0.0/18 Subnet Mask: 255.255.192.0 Broadcast Address: 151.33.63.255 Minimum Host IP: 151.33.0.0 Maximum Host IP: 151.33.63.254 Next Subnet: 192.168.64.0/18 [Reference] Subnet Cheat Sheet: http://support.tranzeo.com/guides/network/Subnet%20Cheat%20Sheet.pdf
Thursday, January 14, 2010
Image Streaming with jQuery
<!-- Most IP based security cameras come equipped with management
software, web interface and rtsp protocol to stream videos. They
also provide image url which is constantly updated as new video
capture is available. Following HTML + jQuery code uses such url
to stream live images from security cameras without management
software. This is a sample code for D-Link based security cameras.
You would need: IP Address, image url and username, password.
Feel free to reuse the code below.
Code Reference: http://savitechnologies.com/?p=107
Modified by: EmErgE :: irc.securitychat.org -->
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
setInterval('reloadImages()',2000);
});
function reloadImages() {
$('#camera1').attr('src','http://user:password@192.168.100.200/cgi-bin/video.jpg?' + Math.random());
$('#camera2').attr('src','http://user:password@192.168.100.201/cgi-bin/video.jpg?' + Math.random());
$('#camera3').attr('src','http://user:password@192.168.100.202/cgi-bin/video.jpg?' + Math.random());
$('#camera4').attr('src','http://user:password@192.168.100.203/cgi-bin/video.jpg?' + Math.random());
}
</script>
</head>
<body>
<!-- Row 1 Column 1 -->
<div style="float: left">
<img id="camera1" src="http://user:password@192.168.100.200/cgi-bin/video.jpg" border=1/>
</div>
<!-- Row 1 Column 2 -->
<div>
<img id="camera2" src="http://user:password@192.168.100.201/cgi-bin/video.jpg" border=1/>
</div>
<!-- Row 2 Column 1 -->
<div style="clear: both; float: left">
<img id="camera3" src="http://user:password@192.168.100.202/cgi-bin/video.jpg" border=1/>
</div>
<!-- Row 2 Column 2 -->
<div>
<img id="camera4" src="http://user:password@192.168.100.203/cgi-bin/video.jpg" border=1/>
</div>
</body>
</html>
Sunday, January 10, 2010
Basic Cisco Router Configuration with NAT and DHCP
hostname myrouter enable password @bcD987 enable secret @bcD987 service password-encryption int fa4 ip address 1.2.3.4 255.255.255.0 ip nat outside no shut int vlan 1 ip address 192.168.5.1 255.255.255.0 ip nat inside no shut line vty 0 4 password @bcD987 login line con 0 password @bcD987 login access-list 100 permit 192.168.5.0 0.0.0.255 ip nat inside source list 100 interface FastEthernet 4 overload ip name-server 1.2.3.4 ip name-server 5.6.7.8 ip dns server ip http server ip http secure-server ip default-gateway 1.2.3.1 ip route 0.0.0.0 0.0.0.0 1.2.3.1 username myuser privilege 15 password 0 gh!JK678 ip dhcp excluded-address 192.168.5.1 ip dhcp pool mydhcppool network 192.168.5.0 255.255.255.0 default-router 192.168.5.1 domain-name mydomain.org dns-server 192.168.5.1 5.6.7.8 netbios-name-server 192.168.5.1 netbios-node-type h-node
Thursday, January 07, 2010
SSH User Inactivity Check
#!/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
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
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.
Monday, January 04, 2010
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."
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
Friday, January 01, 2010
In the beginning was a dot of infinite mass and density
And from that day on I became what is known to the rest of the humankind as Evolution.
I finally decided to write a blog because i've had a lot of thoughts in my head and the only way to stop them is to write them down. Besides, what better day to start than the first day of a brand new year.