#!/usr/bin/env python2

#       gtp-scan.py
#       
#       Copyright 2011 Daniel Mende <mail@c0decafe.de>
#

#       Redistribution and use in source and binary forms, with or without
#       modification, are permitted provided that the following conditions are
#       met:
#       
#       * Redistributions of source code must retain the above copyright
#         notice, this list of conditions and the following disclaimer.
#       * Redistributions in binary form must reproduce the above
#         copyright notice, this list of conditions and the following disclaimer
#         in the documentation and/or other materials provided with the
#         distribution.
#       * Neither the name of the  nor the names of its
#         contributors may be used to endorse or promote products derived from
#         this software without specific prior written permission.
#       
#       THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#       "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#       LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#       A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#       OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#       SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#       LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#       DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#       THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#       (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#       OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import os
import sys
import signal
import socket
import struct
import threading
import time
import IPy
from optparse import OptionParser

VERSION="0.7"

parser = OptionParser(usage="usage: %s [options] address[/net]" % os.path.basename(sys.argv[0]), version=VERSION)
parser.add_option("-w", type="int", help="Time to wait for cooldown", metavar="SEC", dest="wait", default=10)
parser.add_option("-s", help="Use SCTP for transport, instead of UDP", action="store_true", dest="sctp", default=False)
(options, args) = parser.parse_args()
if len(args) != 1:
    parser.error("incorrect number of arguments")

GTP_C_PORT = 2123
GTP_U_PORT = 2152
GTP_P_PORT = 3386

echo_req_v2 = struct.pack("!BBH3sx", 0x50, 1, 4, "\xff")
echo_req_v1 = struct.pack("!BBH3sxHBB", 0x32, 1, 4, "\x00", 3133, 0, 0)

if options.sctp:
    print "### When using SCTP for scanning, you should"
    print "### echo 1 > /proc/sys/net/sctp/max_init_retransmits"
    print "### otherwise the scan will take forever and even skip hosts"
    print "### when the sctp init queue fills up"
    print ""

class listener(threading.Thread):
    def __init__(self, sock, proto):
        threading.Thread.__init__(self)
        self.sock = sock
        self.running = True
        self.proto = proto

    def str_flags(self, c):
        out = "XXX"
        for i in xrange(3,8):
            if i == 4:
                out += " "
            out += "%d" % (((c << i) & 0x80) >> 7)
        return out
    
    def run(self):
        while self.running:
            try:
                (data, (ip, port)) = self.sock.recvfrom(4096)
            except Exception, e:
                pass
            else:
                if port == GTP_C_PORT:
                    port_str = "(gtp-c)"
                elif port == GTP_U_PORT:
                    port_str = "(gtp-u)"
                elif port == GTP_P_PORT:
                    port_str = "(gtp')"
                else:
                    port_str = ""
                out = "### %s up, from %s/%i%s sent %s\n" % (ip, self.proto, port, port_str, data.encode("hex"))
                try:
                    (v, t, l, d) = struct.unpack("!BBH3sx", data[:8])
                    f = v & 0x1f
                    v = v >> 5
                    if v == 0x01:
                        if l == len(data[8:]):
                            d = data[8:]
                            out += "\t*** VALID LEN IN GTP:"
                    elif v == 0x02:
                        if l == len(data[4:]):
                            d = data[4:]
                            out += "\t*** VALID LEN IN GTP:"
                    out += "\tversion = %i flags = %s type = %i len = %i data = %s\n" % (v, self.str_flags(f), t, l, d.encode("hex"))
                    if t == 0x03:
                        out += "\t*** VERSION NOT SUPPORTED\n"
                    elif t == 0x02:
                        out += "\t*** ECHO RESPONSE\n"
                    else:
                        out += "\t*** UNKOWN TYPE\n"
                except Exception, e:
                    #print "%s" % e
                    pass
                print out

    def quit(self):
        self.running = False

try:
    ip = IPy.IP(args[0])
except Exception, e:
    parser.error("invalid argument %s: %s" % (args[0], e))
    sys.exit(1)

if options.sctp:
    sSU = socket.socket(socket.AF_INET, socket.SOCK_SEQPACKET)
    sSU.settimeout(1.0)
    sSU.bind(('', GTP_U_PORT))
    sSC = socket.socket(socket.AF_INET, socket.SOCK_SEQPACKET)
    sSC.settimeout(1.0)
    sSC.bind(('', GTP_C_PORT))
    sSP = socket.socket(socket.AF_INET, socket.SOCK_SEQPACKET)
    sSP.settimeout(1.0)
    sSP.bind(('', GTP_P_PORT))
else:
    sUU = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sUU.settimeout(1.0)
    sUU.bind(('', GTP_U_PORT))
    sUC = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sUC.settimeout(1.0)
    sUC.bind(('', GTP_C_PORT))
    sUP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sUP.settimeout(1.0)
    sUP.bind(('', GTP_P_PORT))

if options.sctp:
    lSU = listener(sSU, "sctp")
    lSU.start()
    lSC = listener(sSC, "sctp")
    lSC.start()
    lSP = listener(sSP, "sctp")
    lSP.start()
else:
    lUU = listener(sUU, "udp")
    lUU.start()
    lUC = listener(sUC, "udp")
    lUC.start()
    lUP = listener(sUP, "udp")
    lUP.start()

def exit(signal, data):
    if options.sctp:
        lSU.quit()
        lSC.quit()
        lSP.quit()
        sSU.close()
        sSC.close()
        sSP.close()
    else:
        lUU.quit()
        lUC.quit()
        lUP.quit()
        sUU.close()
        sUC.close()
        sUP.close()
    sys.exit(0)

signal.signal(signal.SIGINT, exit)
print "gtp-scan v%s\t\tCopyright 2011 Daniel Mende <mail@c0decafe.de>" % VERSION
print "starting scan of " + args[0]
for i in ip:
    if options.sctp:
        exception = True
        while exception:
            if type(exception) != bool:
                print "caught socket exception, will sleep for 1sec and try host %s again..." % i
                time.sleep(1)
            exception = False
            try:
                sSU.sendto(echo_req_v1, (str(i), GTP_U_PORT))
            except Exception, e:
                exception = e
            try:
                sSU.sendto(echo_req_v2, (str(i), GTP_U_PORT))
            except Exception, e:
                exception = e
            try:
                sSC.sendto(echo_req_v1, (str(i), GTP_C_PORT))
            except Exception, e:
                exception = e
            try:
                sSC.sendto(echo_req_v2, (str(i), GTP_C_PORT))
            except Exception, e:
                exception = e
            try:
                sSP.sendto(echo_req_v1, (str(i), GTP_P_PORT))
            except Exception, e:
                exception = e
            try:
                sSP.sendto(echo_req_v2, (str(i), GTP_P_PORT))
            except Exception, e:
                exception = e
    else:
        try:
            sUU.sendto(echo_req_v1, (str(i), GTP_U_PORT))
        except:
            pass
        try:
            sUU.sendto(echo_req_v2, (str(i), GTP_U_PORT))
        except:
            pass
        try:
            sUC.sendto(echo_req_v1, (str(i), GTP_C_PORT))
        except:
            pass
        try:
            sUC.sendto(echo_req_v2, (str(i), GTP_C_PORT))
        except:
            pass
        try:
            sUP.sendto(echo_req_v1, (str(i), GTP_P_PORT))
        except:
            pass
        try:
            sUP.sendto(echo_req_v2, (str(i), GTP_P_PORT))
        except:
            pass
print "cooling down for %d sec..." % options.wait
time.sleep(options.wait)
print "done"
exit(None, None)
