#!/usr/bin/env python
#-*- coding:utf-8 -*-
#
# decode_bigip - Decodes F5 BIG-IP Cookies
# http://www.sertankolat.com/2011/12/f5-big-ip-cookie-tespiti-ve-desifreleme.html
#
# Copyright (c)2008-2011  Sertan Kolat - sertan@olympos.org
#
# version 2
#

import re, sys, socket, struct
from string import lstrip

if len(sys.argv)<2:
	print 'Usage: ./decode_bigip.py COOKIE'
	sys.exit(2)

# Cookie matchers
cookie1 = re.compile(r"([0-9]+)\.([0-9]+)\.(0{4})").findall(' '.join(sys.argv))
cookie2 = re.compile(r"rd([0-9]+)o([0-9a-f]+)o([0-9]+)").findall(' '.join(sys.argv))
cookie3 = re.compile(r"vi([0-9a-f]{32})\.([0-9]+)").findall(' '.join(sys.argv))

if cookie1 or cookie2 or cookie3:
	for c in cookie1:
		ip = socket.inet_ntoa(struct.pack('<L', int(c[0])))
		port = struct.unpack('<H', struct.pack('>H', int(c[1])))[0]
		print 'Found IPv4 Cookie: %s\nDecoded IP/port: %s:%s\n' % ('.'.join(c), str(ip), str(port))
	for c in cookie2:
		ip = socket.inet_ntoa(struct.pack('>L', int(c[1][-8:],16)))
		print 'Found IPv4 Cookie with root domain: rd%s\nRoot domain ID: %s\nDecoded IP/port: %s:%s\n' % ('o'.join(c), str(c[0]), str(ip), str(c[2]))
	for c in cookie3:
		ip = re.sub(r'::+', '::', \
					':'.join([lstrip(o, '0') for i, o in enumerate(re.findall("([a-f0-9]{4})", c[0]))]))
		port = struct.unpack('<H', struct.pack('>H', int(c[1])))[0]
		print 'Found IPv6 Cookie: vi%s\nDecoded IPv6/port: [%s]:%s\n' % ('.'.join(c), ip, str(port))
else:
	print 'Unable to find a valid F5 BIG-IP Cookie value'

