Proof Of Concept Script – Allowing Incoming Server Connections Through An Outbound Client Connection Only (All Through An External Public Server)

#!/usr/bin/python

import os
import random
import select
import socket
import string
import sys
import time

def rndstr(size):
	o = ""
	for x in range(0, size):
		o += random.choice(string.digits + string.ascii_uppercase + string.ascii_lowercase)
	return o

def tryclose(sockobjc):
	try:
		sockobjc.close()
	except:
		pass

def childrwe(socklist):
	buffsize = 1024
	bufflist = ["", ""]
	erroflag = 0; dataflag = 1
	while (erroflag == 0):
		if (dataflag == 0):
			for x in range(0, 2):
				if (bufflist[x]):
					y = ((x + 1) % 2)
					#print("send:",y,"data:",bufflist[x])
					try:
						socklist[y].send(bufflist[x])
						bufflist[x] = ""
					except:
						erroflag = 1
		dataflag = 0
		(readlist, writlist, errolist) = select.select(socklist, [], [], 0.01)
		for x in range(0, 2):
			if (socklist[x] in readlist):
				try:
					databuff = socklist[x].recv(buffsize)
				except:
					databuff = ""
					erroflag = 1
				if (not databuff):
					erroflag = 1
				else:
					bufflist[x] += databuff
					dataflag = 1
	tryclose(socklist[0]); tryclose(socklist[1])
	sys.exit(0)

def main():
	print("%s public [public_port] [private_port] [private_password]" % (sys.argv[0]))
	print("%s private [public_host] [private_port] [private_password] [local_port]" % (sys.argv[0]))
	print("")
	
	buffsize = 1024
	
	if (sys.argv[1] == "public"):
		clieport = int(sys.argv[2])
		servport = int(sys.argv[3])
		password = sys.argv[4]
		
		clieobjc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		clieobjc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		clieobjc.bind(("0.0.0.0", clieport))
		clieobjc.listen(1)
		clielist = []
		
		servobjc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		servobjc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		servobjc.bind(("0.0.0.0", servport))
		servobjc.listen(1)
		servlist = []
		
		childlst = []
		while (1):
			templist = [clieobjc, servobjc]
			for clieitem in clielist:
				if (clieitem[0]):
					templist.append(clieitem[0])
			for servitem in servlist:
				if (servitem[0]):
					templist.append(servitem[0])
			
			(readlist, writlist, errolist) = select.select(templist, [], [])
			
			if (clieobjc in readlist):
				(connobjc, addrobjc) = clieobjc.accept()
				uniqstri = rndstr(16)
				print(int(time.time()),"clie:","connection opened:",addrobjc,"id:",uniqstri)
				clielist.append([connobjc, None, "", addrobjc, uniqstri])
				sentflag = 0
				delelist = []
				for servitem in servlist:
					if (servitem[1] == "control"):
						print(int(time.time()),"serv:","sending notice:",servitem[2],"data:",uniqstri)
						try:
							servitem[0].send(uniqstri)
							sentflag = 1
						except:
							delelist.append(servitem)
					if (sentflag == 1):
						break
				for deleitem in delelist:
					print(int(time.time()),"serv:","connection closed:",deleitem[2])
					tryclose(deleitem[0])
					servlist.remove(deleitem)
			
			elif (servobjc in readlist):
				(connobjc, addrobjc) = servobjc.accept()
				print(int(time.time()),"serv:","connection opened:",addrobjc)
				servlist.append([connobjc, "", addrobjc])
			
			else:
				delelist = []
				for servitem in servlist:
					if (servitem[0] in readlist):
						try:
							databuff = servitem[0].recv(buffsize)
						except:
							delelist.append(servitem)
						if (not databuff):
							delelist.append(servitem)
						else:
							print(int(time.time()),"serv:","recv from:",servitem[2])
							#print(int(time.time()),"serv:","recv from:",servitem[2],"data:",databuff)
							if (databuff.strip() == password):
								print(int(time.time()),"serv:","verified auth:",servitem[2])
								servitem[1] = "control"
							else:
								for clieitem in clielist:
									if (databuff.strip() == clieitem[4]):
										print(int(time.time()),"serv:","est. middle:",clieitem[3],"*----",clieitem[4],"----*",servitem[2])
										clieitem[1] = servitem[0]
				for deleitem in delelist:
					print(int(time.time()),"serv:","connection closed:",deleitem[2])
					tryclose(deleitem[0])
					servlist.remove(deleitem)
				
				delelist = []
				for clieitem in clielist:
					if (clieitem[0] in readlist):
						try:
							databuff = clieitem[0].recv(buffsize)
						except:
							delelist.append(clieitem)
						if (not databuff):
							delelist.append(clieitem)
						else:
							print(int(time.time()),"clie:","recv from:",clieitem[3],"id:",clieitem[4])
							#print(int(time.time()),"clie:","recv from:",clieitem[3],"id:",clieitem[4],"data:",databuff)
							clieitem[2] += databuff
				for deleitem in delelist:
					print(int(time.time()),"clie:","connection closed:",deleitem[3],"id:",deleitem[4])
					tryclose(deleitem[0])
					clielist.remove(deleitem)
			
			delelist = []
			for childpid in childlst:
				try:
					os.waitpid(childpid, os.WNOHANG)
				except:
					delelist.append(childpid)
			for deleitem in delelist:
				print(int(time.time()),"fork:","child exit:",deleitem)
				childlst.remove(deleitem)
			
			for clieitem in clielist:
				if (clieitem[1]):
					childpid = os.fork()
					if (childpid == 0):
						for sockitem in clielist:
							if (sockitem[0] != clieitem[0]):
								tryclose(sockitem[0]); tryclose(sockitem[1])
						for sockitem in servlist:
							if (sockitem[0] != clieitem[1]):
								tryclose(sockitem[0])
						if (clieitem[2]):
							try:
								clieitem[1].send(clieitem[2])
							except:
								pass
						childrwe([clieitem[0], clieitem[1]])
						sys.exit(0)
					else:
						print(int(time.time()),"fork:","child start:",childpid)
						delelist = []
						for sockitem in clielist:
							if (sockitem[0] == clieitem[0]):
								delelist.append(sockitem)
						for deleitem in delelist:
							tryclose(deleitem[0]); tryclose(deleitem[1])
							clielist.remove(deleitem)
						delelist = []
						for sockitem in servlist:
							if (sockitem[0] == clieitem[1]):
								delelist.append(sockitem)
						for deleitem in delelist:
							tryclose(deleitem[0])
							servlist.remove(deleitem)
						childlst.append(childpid)
	
	if (sys.argv[1] == "private"):
		servport = int(sys.argv[3])
		password = sys.argv[4]
		loclport = int(sys.argv[5])
		
		servobjc = None
		childlst = []
		while (1):
			forkitem = None
			if (servobjc == None):
				try:
					servaddr = socket.gethostbyaddr(sys.argv[2])
					servobjc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
					servobjc.connect((servaddr[2][0], servport))
					servobjc.send(password)
				except:
					servobjc = None
			if (servobjc == None):
				time.sleep(1)
				continue
			
			(readlist, writlist, errolist) = select.select([servobjc], [], [])
			
			if (servobjc in readlist):
				try:
					databuff = servobjc.recv(buffsize)
					clieaddr = socket.gethostbyaddr(sys.argv[2])
					clieobjc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
					clieobjc.connect((clieaddr[2][0], servport))
					clieobjc.send(databuff)
					middobjc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
					middobjc.connect(("127.0.0.1", loclport))
					forkitem = [clieobjc, middobjc, databuff]
				except:
					servobjc = None
			
			delelist = []
			for childpid in childlst:
				try:
					os.waitpid(childpid, os.WNOHANG)
				except:
					delelist.append(childpid)
			for deleitem in delelist:
				childlst.remove(deleitem)
			
			if (forkitem):
				childpid = os.fork()
				if (childpid == 0):
					childrwe([forkitem[0], forkitem[1]])
					sys.exit(0)
				else:
					tryclose(forkitem[0]); tryclose(forkitem[1])
					childlst.append(childpid)

if (__name__ == "__main__"):
	main()

[user1@public-server ~]$ ./fwbust.py public 61337 51337 abcxyz

[user2@private-server ~]$ ./fwbust.py private public.server.com 51337 abcxyz 22

[user3@local ~]$ ssh -p 61337 user2@public.server.com
[user2@private-server ~]$ hostname …

Figured it out yet? 🙂

Auto Login To Cisco WiFi Curl Command

#!/bin/bash
read -p "P: " -s p
printf "$p" | openssl sha1
echo
while true
do
	echo "Attempting login..."
	curl -sL "https://wlc.company.com/login.html" -d "buttonClicked=4" -d "err_flag=0" -d "err_msg=" -d "info_flag=0" -d "info_msg=" -d "redirect_url=" -d "username=$USER" -d "password=$p" > /tmp/wifi.log 2>&1
	sleep 60
done

A Simple Server/Router Firewall

This simple firewall achieves the following:

  • Drops all layer-2 ARP traffic from being forwarded between bridged clients (WiFi)
    • Security: Prevents ARP cache poisoning attacks between clients only
    • Note: This breaks the ability for clients to learn about each others addresses to talk to each other
    • Trick: Clients could still talk to each other by setting static ARP entries to the MAC of the router with each others IP addresses
  • Router loops through the DHCP lease table and sets a static ARP entry for each IP / MAC combo found for every client
    • Security: Prevents ARP cache poisoning attacks coming from a client into the router
    • Note: This does not prevent attackers with Rogue DHCP servers from answering other clients first
  • Drops all layer-3 UDP-DHCP traffic from being broadcasted between clients (WiFi)
    • Security: Prevents rogue DHCP server traffic from being sent between clients
  • General firewalling rules
    • Allows specific inbound traffic only: lo/dhcp/ssh/related/established – drops all else
    • Allow a Destination-NAT port forwarding to a given server IP/Port
    • Allow a Source-NAT for clients of the router to get out
    • Note: Does not prevent DHCP starvation DoS attacks
  • Routing rules to direct traffic to the main VLANs
    • 192.168.0.0/18 is used for the local DHCP VLSM
    • 192.168.96.0/19 -> 192.168.64.2/24 (Part of the 192.168.64.0/18 VLSM)
    • 192.168.160.0/19 -> 192.168.128.2/24 (Part of the 192.168.128.0/18 VLSM)
    • 192.168.192.0/18 is a free VLSM block

 

LAN="br-lan"
WAN="eth0.2"
SRV="192.168.161.2:22"
ROU="192.168.96.0/19:192.168.64.2 192.168.160.0/19:192.168.128.2"


C=`/usr/sbin/ebtables -L FORWARD | grep -i '.p ARP.*.j DROP'`
if [ "$C" == "" ] ; then
	echo "Setting ebtables"
	
	/usr/sbin/ebtables -F
	
	for INTF in -i -o ; do
		/usr/sbin/ebtables -A FORWARD "$INTF" "$LAN" -p ARP -j DROP
		
		for PORT in 67 68 ; do
			for TYPE in sport dport ; do
				/usr/sbin/ebtables -A FORWARD "$INTF" "$LAN" -p ip --ip-protocol udp --ip-"$TYPE" "$PORT" -j DROP
			done
		done
	done
fi


while read E ; do
	M=`echo "$E" | awk '{ print $2 }'`
	I=`echo "$E" | awk '{ print $3 }'`
	/usr/sbin/ip neighbor change "$I" lladdr "$M" dev "$LAN" nud permanent
done < /tmp/dhcp.leases


C=`/usr/sbin/iptables -nvL | grep -i '^chain' | tail -n +4`
if [ "$C" != "" ] ; then
	echo "Setting iptables"
	
	/usr/sbin/iptables -F ; /usr/sbin/iptables -X
	/usr/sbin/iptables -t nat -F ; /usr/sbin/iptables -t nat -X
	/usr/sbin/iptables -t mangle -F ; /usr/sbin/iptables -t mangle -X
	/usr/sbin/iptables -t raw -F ; /usr/sbin/iptables -t raw -X
	
	/usr/sbin/iptables -P INPUT ACCEPT
	/usr/sbin/iptables -A INPUT -i lo -j ACCEPT
	/usr/sbin/iptables -A INPUT -p udp --dport 67 -j ACCEPT
	/usr/sbin/iptables -A INPUT -p tcp --dport 22 -j ACCEPT
	/usr/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
	/usr/sbin/iptables -A INPUT -j DROP
	
	/usr/sbin/iptables -P FORWARD ACCEPT
	/usr/sbin/iptables -P OUTPUT ACCEPT
	
	if [ "$WAN" != "" ] ; then
		if [ "$SRV" != "" ] ; then
			/usr/sbin/iptables -t nat -A PREROUTING -i "$WAN" -p tcp --dport 443 -j DNAT --to "$SRV"
		fi
		/usr/sbin/iptables -t nat -A POSTROUTING -o "$WAN" -j MASQUERADE
	fi
fi

for ROUTE in $ROU ; do
	SRC=`echo "$ROUTE" | awk -F':' '{ print $1 }'`
	DST=`echo "$ROUTE" | awk -F':' '{ print $2 }'`
	C=`/usr/sbin/ip route | grep -i "$SRC"`
	if [ "$C" == "" ] ; then
		echo "Adding route [$SRC] -> [$DST]"
		
		/usr/sbin/ip route add "$SRC" via "$DST"
	fi
done

Just some LDAP commands with auth

ldapsearch -xZW -h ldap-master -D "uid=$USER,ou=users,dc=company,dc=com" -LLL 'uid=testuser'
ldapmodify -xZW -h ldap-master -D "uid=$USER,ou=users,dc=company,dc=com" -f /tmp/mod.ldiff
ls... | while read l ; do echo "[$l]" ; c=`echo "$l" | grep -i '^userpassword:'` ; if [ "$c" != "" ] ; then d=`echo "$l" | awk '{ print $2 }' | base64 -d` ; echo "    $d" ; fi ; done

My Net Loss Proof SSH Tunnel Commands

/etc/rc.local

sysctl net.ipv4.conf.all.forwarding=1
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
while true ; do ifconfig tun0 inet 10.0.0.1 netmask 255.255.255.0 pointopoint 10.0.0.2 mtu 1500 up ; sleep 5 ; done &

[common]

S="1.2.3.4"

client

screen -S rssh
sudo ssh -w0:0 "root@$S" 'while true ; do echo `date`-$RANDOM ; sleep 5 ; done'

os x/bsd

screen -S rtun
sudo su -
ifconfig tun0 inet 10.0.0.2 netmask 255.255.255.0 pointopoint 10.0.0.1 mtu 1500 up
R=`netstat -nr | grep -i 'default[ ]*[1-9]' | awk '{ print $2 }'`
route add -host "$S" "$R"
route delete default "$R"
route add default 10.0.0.1
while true ; do c=`ifconfig tun0 2> /dev/null` ; if [ "$c" == "" ] ; then route add default "$R" ; break ; fi ; sleep 5 ; done

Thought This Was Cool (+OpenSSH Config)

Daily NSA Edit: http://www.theguardian.com/world/2013/sep/05/nsa-how-to-remain-secure-surveillance

and another one! http://prism-break.org

To choose a specific set of ciphers, hashes, and key exchanges for your OpenSSH server:

rm -fv *ec*key*

sshd_config

# Strongest
HostKey        /usr/local/etc/ssh_host_rsa_key
KexAlgorithms  diffie-hellman-group-exchange-sha256
Ciphers        aes256-cbc,aes256-ctr
MACs           hmac-sha2-512,hmac-sha2-256

# Tunneling
TCPKeepAlive     yes
PermitRootLogin  yes
PermitTunnel     point-to-point

A Quick SSH Based VPN Tunnel With Default Gateway Override

sudo su

screen -S server
ssh -o Tunnel=point-to-point -w 0:0 root@infraopslab
ifconfig tun0 10.0.0.2 pointopoint 10.0.0.1
h=$(dig +search +short "$(cat ~/client.txt)" | grep -i '^[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$' | head -n 1 | sed -e 's/[0-9]*$/0/g')
g=$(netstat -nr | grep -i '^0.0.0.0.*0.0.0.0' | awk '{ print $2 }')
route add -net "$h" netmask 255.255.255.0 gw "$g"
for s in $(cat ~/servers.txt) ; do echo "[$s]" ; i=$(dig +search +short "$s") ; route add -host "$i" gw 10.0.0.1 ; done
#route add -net 128.0.0.0 netmask 128.0.0.0 gw 10.0.0.1
#route add -net 0.0.0.0 netmask 128.0.0.0 gw 10.0.0.1

screen -S client
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -F ; iptables -X ; iptables -t nat -F ; iptables -t nat -X
iptables -t nat -A POSTROUTING -o em1 -j MASQUERADE
while true ; do ifconfig tun0 10.0.0.1 pointopoint 10.0.0.2 ; sleep 3 ; done

You should change the following references above: infraopslab and em1

while true ; do ping -c 1 google.ca ; if [ $? -ne 0 ] ; then reboot ; fi ; sleep 3 ; done
netstat -nr | grep -Eiv '^(kernel|destination|0.0.0.0.*0.0.0.0|.*0.0.0.0)' | while read l ; do d=`echo "$l" | awk '{ print $1 }'` ; g=`echo "$l" | awk '{ print $2 }'` ; n=`echo "$l" | awk '{ print $3 }'` ; echo "$d $g $n" ; for t in net host ; do route del "-$t" "$d" netmask "$n" gw "$g" > /dev/null 2>&1 ; done ; done

Bash Login Script To Auto Add Your SSH Agent/Key

~/.bashrc

FOLDIR=~/.tmp/sshagent
mkdir -p $FOLDIR/shell > /dev/null 2>&1
. $FOLDIR/shell/cmds.$(hostname -s) > /dev/null 2>&1
sshcheck=$(ssh-add -l 2>&1 | grep -i '^[0-9][0-9][0-9][0-9 ]')
if [ "$sshcheck" == "" ]
then
	mkdir -p $FOLDIR/sock > /dev/null 2>&1
	rm -frv $FOLDIR/sock/agent.$(hostname -s) > /dev/null 2>&1
	killall -9 ssh-agent > /dev/null 2>&1
	ssh-agent -a $FOLDIR/sock/agent.$(hostname -s) > $FOLDIR/shell/cmds.$(hostname -s)
	. $FOLDIR/shell/cmds.$(hostname -s) > /dev/null 2>&1
	ssh-add
fi

Description of the script above (nfs friendly):
* Attempt to run the last ssh-agent export commands and check for valid keys with the ssh-add command
* If nothing exists then kill any current ssh-agent processes and save a new set of ssh-agent export commands
* Run the current set of ssh-agent export commands and add the default ssh key with ssh-add

Scripting JS Against PHPLDAPAdmin

Just a lame script to find any attributes for a given objectClass which are not used by any other objectClasses:

var a="";
var l=document.getElementsByTagName("tr");
for (var i in l)
{
	try { var m=l[i].getElementsByTagName("a"); }
	catch(e) { var m=[]; }
	if (m.length == 1)
	{
		try { var z=l[i].innerHTML.match(/^.*Used.*by.*objectClasses.*User.*Authorization.*$/); }
		catch(e) { var z=0; }
		if (z)
		{
			var p=l[i].parentNode.getElementsByTagName("tr")[0].getElementsByTagName("a");
			a += ("\""+p[0].innerHTML+"\", ");
		}
	}
}
console.log(a);

Some Simple Automation Finally

Yesterday I got to starting a new script which could help Afilias with the automation of adding a new user to all of the systems and services they run here. There are a lot of steps involved and many systems but Python should be able to handle it since it has a great module/library collection. Anyway, sorry for all of the non-tech posts but it’s my first week here and I believe the work is kept private (for internal use only). Once I get more comfortable, I could probably publish some of my work towards any open-source projects if possible. 🙂

Still Learning! [Continued]

So yesterday I got to editing NIS passwd/group (being deprecated) files so we can add a new user and then used that information to convert it over into LDAP format. I also got into to writing a little bot that attempts to monitor some of our servers by SSH’ing into them and watching some log files and then reporting back to IRC mostly via Python. I’m excited for any new projects that come my way along with reading about new technologies that I’m unfamiliar with! I’m also noticing that some of our ticket processing steps (SOP guided) could use some more automation along with translating some older scripts to a common language in a common place 🙂

Learning New Concepts!

So yesterday I went through the process of removing/disabling a user from all of the systems/services we use here at Afilias. It’s a multi-step procedure and I could look into automating it a bit more with Python. In addition, I did some reading up on LDAP modify/search via the command line as well as Kerberos *princ commands. I have a lot to learn still but I’m trying my best to catch up 🙂

Random Last Minute File Cleanup

Just found a little script I used to rename my music files based on their ID3 tag info.

#!/bin/bash
ls | while read s
do
	i=`exiftool "$s" | sed -e 's@[/?]@_@g'`
	a=`echo "$i" | grep '^Artist [ ]*:' | sed -e 's/^[^:]*:[ ]*//'`
	t=`echo "$i" | grep '^Title [ ]*:' | sed -e 's/^[^:]*:[ ]*//'`
	n=`echo "$i" | grep '^Track [ ]*:' | sed -e 's/^[^:]*:[ ]*//' -e 's/_.*$//'`
	if [ "$n" == "" ]
	then
		n="0"
	fi
	f=`echo "$i" | grep '^File Type [ ]*:' | sed -e 's/^[^:]*:[ ]*//' -e 's/^.*_//' | tr '[A-Z]' '[a-z]'`
	z="$a - $t - $n.$f"
	if [ "$s" != "$z" ]
	then
		if [ ! -f "$z" ]
		then
			mv -fv "$s" "$z"
		fi
	fi
done