Example #1
0
    def test_sniff_loop(self):
        def cbk(ts, pkt, *args):
            assert pkt.ip.src == "1.2.3.6"
            assert pkt.tcp.srcport == 99
            assert ts > 0
            assert len(args) == 2
            if args[0] > args[1]:
                raise UMPASniffingException("test")

        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.6"), TCP(srcport=99)),
                        2)
        th.start()
        umit.umpa.sniffing.sniff_loop(1,
                                      filter="src 1.2.3.6",
                                      device='any',
                                      callback=cbk,
                                      callback_args=[1, 2])
        th.join()

        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.6"), TCP(srcport=99)))
        th.start()
        py.test.raises(UMPASniffingException,
                       umit.umpa.sniffing.sniff_loop,
                       1,
                       filter="src 1.2.3.6",
                       device='any',
                       callback=cbk,
                       callback_args=[2, 1])
        th.join()

        py.test.raises(UMPASniffingException, umit.umpa.sniffing.sniff_loop, 1)
Example #2
0
    def test_get_raw(self):
        py.test.skip('auto fields for IP have to implemented '
                     'first (like Identification)')
        # TODO more tests would be nice
        # this test pre/post raw methods as well
        ip = IP(src='127.0.0.1', dst='127.0.0.1')

        assert ip._raw(0, 0, [ip], 0) == \
                (0x450000149aa900004000e23e7f0000017f000001, 160)
Example #3
0
    def test_get_raw(self):
        py.test.skip('auto fields for IP have to implemented '
                    'first (like Identification)')
        # TODO more tests would be nice
        # this test pre/post raw methods as well
        ip = IP(src='127.0.0.1', dst='127.0.0.1')

        assert ip._raw(0, 0, [ip], 0) == \
                (0x450000149aa900004000e23e7f0000017f000001, 160)
Example #4
0
    def test_sent_size(self):
        if os.name == 'posix' and os.geteuid() != 0:
            py.test.skip('root-privileges are needed')

        p1 = Packet(IP(), TCP())
        p2 = Packet(IP(), TCP())

        s = Socket()
        size = s.send(p1, p2)
        assert size == [40, 40]
Example #5
0
    def test_proto_access_edit(self):
        p = Packet(IP(src="1.2.3.4"), TCP())
        assert p.ip.src == "1.2.3.4"
        p.ip.src = "10.0.0.1"
        assert p.ip.src == "10.0.0.1"

        ip = IP(src="127.0.0.1")
        p = Packet(ip)
        p.ip.src = "10.0.0.1"
        assert p.ip.src == "10.0.0.1"
        assert ip.src == "10.0.0.1"
Example #6
0
    def test_send_size_L2(self):
        if os.name == 'posix' and os.geteuid() != 0:
            py.test.skip('root-privileges are needed')

        p1 = Packet(Ethernet(src='00:11:22:33:44:55', dst='00:11:22:33:44:55'),
                    IP(src="127.0.0.1", dst="127.0.0.1"),
                    TCP(srcport=1234, dstport=4321), Payload('xyz'))
        p2 = Packet(Ethernet(src='00:11:22:33:44:55', dst='00:11:22:33:44:55'),
                    IP(src="127.0.0.1", dst="127.0.0.1"),
                    TCP(srcport=1234, dstport=4321), Payload('xyz'))

        s = SocketL2(iface='lo')
        size = s.send(p1, p2)

        assert size == [57, 57]
Example #7
0
    def test_add_new_protocols__strict(self):
        py.test.raises(UMPAStrictException, Packet, TCP(), IP())
        py.test.raises(UMPAStrictException, Packet, TCP(), IP(), strict=True)
        py.test.raises(UMPAStrictException, Packet, TCP(), Payload(), IP())
        py.test.raises(UMPAStrictException, Packet, TCP(), IP(), Payload())
        py.test.raises(UMPAStrictException, Packet, Payload(), TCP())
        py.test.raises(UMPAStrictException, Packet, UDP(), TCP())

        p = Packet(TCP())
        py.test.raises(UMPAStrictException, p.include, IP())
        py.test.raises(UMPAStrictException, p.include, UDP())

        p = Packet(strict=False)
        p.strict = True
        py.test.raises(UMPAStrictException, p.include, UDP(), TCP())
Example #8
0
    def test_get_raw__ip(self):
        p = Packet()
        p.include(
            IP(src="127.0.0.1", dst="127.0.0.1", _id=1000, _checksum=0x7900))

        if sys.platform.find('linux') != -1:
            ttl = _consts.TTL_LINUX
        elif sys.platform.find('darwin') != -1:
            ttl = _consts.TTL_MACOS
        elif sys.platform.find('win') != -1:
            ttl = _consts.TTL_WINDOWS
        elif sys.platform.find('freebsd') != -1:
            ttl = _consts.TTL_FREEBSD
        elif sys.platform.find('os2') != -1:
            ttl = _consts.TTL_OS2
        elif sys.platform.find('sunos') != -1:
            ttl = _consts.TTL_SUNOS
        elif sys.platform.find('aix') != -1:
            ttl = _consts.TTL_AIX
        elif sys.platform.find('irix') != -1:
            ttl = _consts.TTL_IRIX
        elif sys.platform.find('solaris') != -1:
            ttl = _consts.TTL_SOLARIS
        elif sys.platform.find('ultrix') != -1:
            ttl = _consts.TTL_ULTRIX
        elif sys.platform.find('dec') != -1:
            ttl = _consts.TTL_DEC
        else:
            ttl = _consts.TTL_LINUX

        expected = ("\x45\x00\x00\x14\x03\xe8\x00\x00"
                    "%c\x00\x79\x00\x7f\x00\x00\x01"
                    "\x7f\x00\x00\x01") % chr(ttl)
        assert expected == p.get_raw()
Example #9
0
 def test_dump(self):
     amount = 5
     dump_file = tempfile.NamedTemporaryFile(mode="w")
     th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"),
                                 TCP(srcport=99)), amount)
     th.start()
     try:
         p = pypcap.open_pcap("any", to_ms=100)
         p.setfilter("src host 1.2.3.4 and src port 99")
         d = pypcap.dumper()
         d.open(p, dump_file.name)
         pkts = []
         for i in xrange(amount):
             pkts.append(p.next())
             d.dump()
     except UMPASniffingException:
         py.test.skip("no suitable devices for sniffing found. "
                     "propably not sufficent priviliges.")
     finally:
         th.join()
     d.close()
     p = pypcap.open_pcap(dump_file.name)
     p.setfilter("src host 1.2.3.4 and src port 99")
     for i, pkt in enumerate(p):
         assert pkt[0] == pkts[i][0]
         # not sure if the below should be equivalent
         assert str(pkt[1]) == str(pkts[i][1])
Example #10
0
    def test_to_file(self):
        dump_file = tempfile.NamedTemporaryFile(mode="w")
        amount = 5

        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"), TCP(srcport=99)),
                        amount)
        th.start()
        try:
            umit.umpa.sniffing.to_file(dump_file.name, amount,
                                       "src host 1.2.3.4 and src port 99",
                                       "any")
        except UMPASniffingException:
            py.test.skip("no suitable devices for sniffing found. "
                         "propably not sufficent priviliges.")
        finally:
            th.join()

        result = umit.umpa.sniffing.from_file(dump_file.name)
        assert len(result) == amount
        for packet in result:
            assert packet.ip.src == "1.2.3.4"
            assert packet.tcp.srcport == 99

        result = umit.umpa.sniffing.from_file(dump_file.name, 2)
        assert len(result) == 2
        for packet in result:
            assert packet.ip.src == "1.2.3.4"
            assert packet.tcp.srcport == 99
Example #11
0
    def test_get_raw(self):
        # TODO more tests would be nice
        # this test pre/post raw methods as well
        ip = IP(src='127.0.0.1', dst='127.0.0.1')
        tcp = TCP(srcport=0, dstport=10)

        assert tcp._raw(0, 0, [ip, tcp], 0) == \
                (0xa000000000000000150000200afd70000, 160)
Example #12
0
    def test_pre_raw(self):
        p = PseudoHeader(0, 40)
        p._pre_raw(0, 0, [], 0)
        assert p.src == "127.0.0.1"
        assert p.dst == "127.0.0.1"

        p._pre_raw(0, 0, [IP(src="1.2.3.4")], 0)
        assert p.src == "1.2.3.4"
        assert p.dst == "127.0.0.1"

        p._pre_raw(0, 0, [IP(src="1.2.3.4", dst="4.3.2.1"),
                          TCP(srcport=123)], 0)
        assert p.src == "1.2.3.4"
        assert p.dst == "4.3.2.1"

        p._pre_raw(0, 0, [TCP(srcport=123)], 0)
        assert p.src == "127.0.0.1"
        assert p.dst == "127.0.0.1"
Example #13
0
    def test_get_destination(self):
        p = Packet(Ethernet(dst='00:11:22:33:44:55'), IP(dst='1.2.3.4'),
                   UDP(dstport=1234), Payload('UMPA'))

        py.test.raises(UMPAException, p._get_destination, 1)
        assert p._get_destination(2) == '00:11:22:33:44:55'
        assert p._get_destination(3) == '1.2.3.4'
        py.test.raises(UMPAAttributeException, p._get_destination, 4)
        py.test.raises(UMPAAttributeException, p._get_destination, 5)
        py.test.raises(UMPAException, p._get_destination, 6)
Example #14
0
    def test_sniff(self):
        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"), TCP(srcport=99)))
        th.start()
        result = umit.umpa.sniffing.sniff(1,
                                          device='any',
                                          filter="src port 99")
        th.join()

        assert len(result) == 1
        assert result[0].ip.src == '1.2.3.4'
        assert result[0].tcp.srcport == 99
Example #15
0
    def test_sniff_next(self):
        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"), TCP(srcport=99)))
        th.start()
        result = umit.umpa.sniffing.sniff_next(device='any',
                                               filter="src port 99")
        th.join()

        assert result.ip.src == '1.2.3.4'
        assert result.tcp.srcport == 99

        # send more, sniff one
        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"), TCP(srcport=99)),
                        5)
        th.start()
        result = umit.umpa.sniffing.sniff_next(device='any',
                                               filter="src port 99")
        th.join()

        assert result.ip.src == '1.2.3.4'
        assert result.tcp.srcport == 99
Example #16
0
    def test_get_raw_with_payload(self):
        ip = IP(src='1.2.3.4', dst='5.6.7.8')
        udp = UDP(srcport=9, dstport=10)
        payload = Payload('12345678')

        # the next two lines are normally done by Packet.get_raw()
        payload.get_raw([ip, udp, payload], 8*len(payload.data))
        udp.__dict__['payload'] = payload

        assert udp._raw(0, 0, [ip, udp, payload], 8*len(payload.data)) == \
                                                       (0x9000a00101ed3L, 64)
Example #17
0
    def test_protos_order(self):
        order = (IP, UDP, Payload)

        p = Packet(*[x() for x in order])
        for i in xrange(len(order)):
            assert isinstance(p.protos[i], order[i])

        p = Packet(IP())
        p.include(UDP(), Payload())
        for i in xrange(len(order)):
            assert isinstance(p.protos[i], order[i])
Example #18
0
    def test_loop_and_filter(self):
        # XXX it would rather looped than failing
        def cbk(timestamp, pkt, *args):
            assert args[0] == "foobar" # stupid isn't it? :)

        try:
            p = pypcap.open_pcap("any", to_ms=100)
            p.setfilter("src host 1.2.3.4 and src port 99")
            th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"),
                                        TCP(srcport=99)))
            th.start()
            p.loop(1, cbk, "foobar")
            th.join()

            th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"),
                                        TCP(srcport=99)), 5)
            th.start()
            p.loop(5, cbk, "foobar")
            th.join()
        except UMPASniffingException:
            py.test.skip("no suitable devices for sniffing found. "
                        "propably not sufficent priviliges.")
Example #19
0
    def test_sndout(self):
        packet = umit.umpa.Packet(IP(src="1.2.3.4", dst="67.205.14.183"),
                                  TCP(srcport=81, dstport=80))
        th = SendPacket(packet)
        th.start()
        received = umit.umpa.sniffing.sniff_next(filter="dst 67.205.14.183",
                                                 device="any")
        th.join()

        assert received.ip.src == packet.ip.src
        assert received.ip.dst == packet.ip.dst
        assert received.tcp.srcport == packet.tcp.srcport
        assert received.tcp.dstport == packet.tcp.dstport
Example #20
0
    def test_get_raw(self):
        if sys.platform.find('linux') != -1:
            ttl = _consts.TTL_LINUX
        elif sys.platform.find('darwin') != -1:
            ttl = _consts.TTL_MACOS
        elif sys.platform.find('win') != -1:
            ttl = _consts.TTL_WINDOWS
        elif sys.platform.find('freebsd') != -1:
            ttl = _consts.TTL_FREEBSD
        elif sys.platform.find('os2') != -1:
            ttl = _consts.TTL_OS2
        elif sys.platform.find('sunos') != -1:
            ttl = _consts.TTL_SUNOS
        elif sys.platform.find('aix') != -1:
            ttl = _consts.TTL_AIX
        elif sys.platform.find('irix') != -1:
            ttl = _consts.TTL_IRIX
        elif sys.platform.find('solaris') != -1:
            ttl = _consts.TTL_SOLARIS
        elif sys.platform.find('ultrix') != -1:
            ttl = _consts.TTL_ULTRIX
        elif sys.platform.find('dec') != -1:
            ttl = _consts.TTL_DEC
        else:
            ttl = _consts.TTL_LINUX

        expected = ("\x45\x00\x00\x28\x03\xe8\x00\x00"
                    "%c\x06\x79\x00\x7f\x00\x00\x01"
                    "\x7f\x00\x00\x01") % chr(ttl)

        p = Packet()
        p.include(
            IP(src="127.0.0.1", dst="127.0.0.1", _id=1000, _checksum=0x7900))
        p.include(TCP(srcport=123, dstport=321, flags='psh'))

        expected += ("\x00\x7b\x01\x41\x00\x00\x00\x00"
                     "\x00\x00\x00\x01\x50\x08\x02\x00"
                     "\xae\x1d\x00\x00")
        assert expected == p.get_raw()

        p.include(Payload(data="UMPA"))

        expected = ("\x45\x00\x00\x2c\x03\xe8\x00\x00"
                    "%c\x06\x79\x00\x7f\x00\x00\x01"
                    "\x7f\x00\x00\x01"
                    "\x00\x7b\x01\x41\x00\x00\x00\x00"
                    "\x00\x00\x00\x01\x50\x08\x02\x00"
                    "\x08\x8b\x00\x00") % chr(ttl)

        expected += "\x55\x4d\x50\x41"
        assert expected == p.get_raw()
Example #21
0
    def test_sndrcv_loopback(self):
        packet = umit.umpa.Packet(IP(src="1.2.3.4", dst="127.0.0.1"),
                                  TCP(srcport=99), Payload(data="foo bar"))
        th = SendPacket(packet)
        th.start()
        received = umit.umpa.sniffing.sniff_next(filter="src 1.2.3.4",
                                                 device="lo")
        th.join()

        assert received.ip.src == packet.ip.src
        assert received.ip.dst == packet.ip.dst
        assert received.tcp.srcport == packet.tcp.srcport
        assert received.tcp.dstport == packet.tcp.dstport
        assert received.payload.data == packet.payload.data
Example #22
0
 def test_next(self):
     # can't test iterable of the object
     # because pypcap doesn't raise StopIteration
     amount = 5
     th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.4"),
                                 TCP(srcport=99)), amount)
     th.start()
     try:
         p = pypcap.open_pcap("any", to_ms=100)
         p.setfilter("src host 1.2.3.4 and src port 99")
         for i in xrange(amount):
             packet = p.next()
     except UMPASniffingException:
         py.test.skip("no suitable devices for sniffing found. "
                     "propably not sufficent priviliges.")
     finally:
         th.join()
Example #23
0
    def test_send_sniff_tcp_L2(self):
        if os.name == 'posix' and os.geteuid() != 0:
            py.test.skip('root-privileges are needed')

        p = Packet(Ethernet(src='00:11:22:33:44:55', dst='00:11:22:33:44:55'),
                   IP(src="127.0.0.1", dst="127.0.0.1"),
                   TCP(srcport=1234, dstport=4321), Payload('xyz'))

        th = SendPacketL2(p, iface='lo')
        th.start()
        result = umit.umpa.sniffing.sniff(1,
                                          device='lo',
                                          filter="src port 1234")
        th.join()

        assert len(result) == 1
        assert result[0].ethernet.src == '00:11:22:33:44:55'
        assert result[0].ip.src == '127.0.0.1'
        assert result[0].tcp.srcport == 1234
        assert result[0].tcp.dstport == 4321
Example #24
0
    def test_from_file_loop(self):
        global idx
        idx = 0

        def cbk(ts, pkt, *args):
            global idx
            assert pkt.ip.src == "1.2.3.6"
            assert pkt.tcp.srcport == 99
            assert ts > 0
            assert len(args) == 1
            idx += 1

        dump_file = tempfile.NamedTemporaryFile(mode="w")
        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.6"), TCP(srcport=99)),
                        3)
        th.start()
        umit.umpa.sniffing.sniff(3,
                                 device="any",
                                 dump=dump_file.name,
                                 filter="src host 1.2.3.6 and src port 99")
        th.join()

        idx = 0
        amount = 3
        umit.umpa.sniffing.from_file_loop(dump_file.name,
                                          callback=cbk,
                                          callback_args=[
                                              amount,
                                          ])
        assert idx == amount

        idx = 0
        amount = 2
        umit.umpa.sniffing.from_file_loop(dump_file.name,
                                          2,
                                          callback=cbk,
                                          callback_args=[
                                              amount,
                                          ])
        assert idx == amount
Example #25
0
    def test_from_file(self):
        dump_file = tempfile.NamedTemporaryFile(mode="w")
        th = SendPacket(umit.umpa.Packet(IP(src="1.2.3.6"), TCP(srcport=99)),
                        3)
        th.start()
        umit.umpa.sniffing.sniff(3,
                                 device="any",
                                 dump=dump_file.name,
                                 filter="src host 1.2.3.6 and src port 99")
        th.join()

        result = umit.umpa.sniffing.from_file(dump_file.name)

        assert len(result) == 3
        for packet in result:
            assert packet.ip.src == "1.2.3.6"
            assert packet.tcp.srcport == 99

        result = umit.umpa.sniffing.from_file(dump_file.name, 2)
        assert len(result) == 2
        for packet in result:
            assert packet.ip.src == "1.2.3.6"
            assert packet.tcp.srcport == 99
Example #26
0
#
# obviously it's not necessary in real usecase
class SendPacket(threading.Thread):
    def __init__(self, packet, amount=1):
        super(SendPacket, self).__init__()
        self._packet = packet
        self._amount = amount

    def run(self):
        s = umit.umpa.Socket()
        for i in xrange(self._amount):
            time.sleep(2)
            s.send(self._packet)


packet = umit.umpa.Packet(IP(src="1.2.3.4", dst="127.0.0.1"), TCP(srcport=99),
                          Payload(data="sniff me"))

# run thread and send 2 packets
th = SendPacket(packet, 2)
th.start()

# capture 2 packets and resend them with reverse src/dst ports
models.react(2, filter="host 1.2.3.4 and port 99", device="any", revports=True)

# collect terminated thread
th.join()

# do the same but resend it to a new destination
th = SendPacket(packet, 2)
th.start()
Example #27
0
    def test_get_raw(self):
        ip = IP(src='1.2.3.4', dst='5.6.7.8')
        udp = UDP(srcport=9, dstport=10)

        assert udp._raw(0, 0, [ip, udp], 0) == (0x9000A0008EFB7, 64)
Example #28
0
import umit.umpa
import umit.umpa.utils.security

from umit.umpa.protocols import IP, TCP, Payload

# NOTE:
# to create RAW_SOCKET we need SUID, but for normal usage it's not
# necessary. we recommend to use umit.umpa.utils.security to make our programs
# more safety. also dropping priviliges should be done at the same beginning
# of the application

# dropping unnecessary priviliges
umit.umpa.utils.security.drop_priviliges()

# create new IP object
ip = IP()
# setting some fields
ip.src = "127.0.0.1"
ip.dst = "67.205.14.183"

# the same for TCP
tcp = TCP()
# setting some fields
tcp.srcport = 2958
tcp.dstport = 0

# also, SYN flag will be set up. here SYN
tcp.set_flags('flags', syn=True)

# create payload object and set the data while calling constructor
payload = Payload(data="something here")
Example #29
0
 def test_proto_access(self):
     p = Packet(IP(), TCP())
     assert isinstance(p.protos[0], IP)
     assert isinstance(p.protos[1], TCP)
     assert isinstance(p.ip, IP)
     assert isinstance(p.tcp, TCP)
Example #30
0
import umit.umpa
import umit.umpa.utils.security

from umit.umpa.protocols import IP, UDP

# NOTE:
# to create RAW_SOCKET we need SUID, but for normal usage it's not
# necessary. we recommend to use umit.umpa.utils.security to make our programs
# more safety. also dropping priviliges should be done at the same beginning
# of the application

# dropping unnecessary priviliges
umit.umpa.utils.security.drop_priviliges()

# create new IP object
ip = IP()
# setting some fields
ip.src = "127.0.0.1"
ip.dst = "67.205.14.183"

# create new UDP object
udp = UDP()
# setting some fields
udp.srcport = 0
udp.dstport = 7

# create a new packet and include protocols
packet = umit.umpa.Packet(ip, udp)

# creating new socket connection
# NOTE: we need to raise our priviliges.
Example #31
0
class TestExtensionXML(object):
    example_xml = """<?xml version="1.0" ?>
<UMPA>
        <packet id="0" strict="True">
                <protocol class="umit.umpa.protocols.IP.IP">
                        <_version type="int">
                                4
                        </_version>
                        <_hdr_len type="NoneType">
                                None
                        </_hdr_len>
                        <tos type="bits">
                                <precedence0 type="bool">
                                        False
                                </precedence0>
                                <precedence1 type="bool">
                                        False
                                </precedence1>
                                <precedence2 type="bool">
                                        False
                                </precedence2>
                                <delay type="bool">
                                        False
                                </delay>
                                <throughput type="bool">
                                        False
                                </throughput>
                                <reliability type="bool">
                                        False
                                </reliability>
                                <reserved0 type="bool">
                                        False
                                </reserved0>
                                <reserved1 type="bool">
                                        False
                                </reserved1>
                        </tos>
                        <_len type="NoneType">
                                None
                        </_len>
                        <_id type="int">
                                0
                        </_id>
                        <flags type="bits">
                                <rb type="bool">
                                        False
                                </rb>
                                <df type="bool">
                                        False
                                </df>
                                <mf type="bool">
                                        False
                                </mf>
                        </flags>
                        <_frag_offset type="int">
                                0
                        </_frag_offset>
                        <ttl type="NoneType">
                                None
                        </ttl>
                        <_proto type="NoneType">
                                None
                        </_proto>
                        <_checksum type="int">
                                0
                        </_checksum>
                        <src type="str">
                                127.0.0.1
                        </src>
                        <dst type="str">
                                67.205.14.183
                        </dst>
                        <options type="int">
                                0
                        </options>
                        <_padding type="int">
                                0
                        </_padding>
                </protocol>
                <protocol class="umit.umpa.protocols.TCP.TCP">
                        <srcport type="int">
                                2958
                        </srcport>
                        <dstport type="int">
                                0
                        </dstport>
                        <_seq type="NoneType">
                                None
                        </_seq>
                        <_ack type="NoneType">
                                None
                        </_ack>
                        <_hdr_len type="NoneType">
                                None
                        </_hdr_len>
                        <_reserved type="int">
                                0
                        </_reserved>
                        <flags type="bits">
                                <urg type="bool">
                                        False
                                </urg>
                                <ack type="bool">
                                        False
                                </ack>
                                <psh type="bool">
                                        False
                                </psh>
                                <rst type="bool">
                                        False
                                </rst>
                                <syn type="bool">
                                        True
                                </syn>
                                <fin type="bool">
                                        False
                                </fin>
                        </flags>
                        <_window_size type="NoneType">
                                None
                        </_window_size>
                        <_checksum type="NoneType">
                                None
                        </_checksum>
                        <_urgent_pointer type="NoneType">
                                None
                        </_urgent_pointer>
                        <options type="int">
                                0
                        </options>
                        <_padding type="int">
                                0
                        </_padding>
                </protocol>
                <protocol class="umit.umpa.protocols.Payload.Payload">
                        <data type="str">
                                this is umit.umpa!
                        </data>
                </protocol>
        </packet>
</UMPA>
"""
    example_xml2 = """        <packet id="1" strict="True">
                <protocol class="umit.umpa.protocols.TCP.TCP">
                        <srcport type="int">
                                123
                        </srcport>
                        <dstport type="int">
                                321
                        </dstport>
                        <_seq type="NoneType">
                                None
                        </_seq>
                        <_ack type="NoneType">
                                None
                        </_ack>
                        <_hdr_len type="NoneType">
                                None
                        </_hdr_len>
                        <_reserved type="int">
                                0
                        </_reserved>
                        <flags type="bits">
                                <urg type="bool">
                                        False
                                </urg>
                                <ack type="bool">
                                        False
                                </ack>
                                <psh type="bool">
                                        False
                                </psh>
                                <rst type="bool">
                                        False
                                </rst>
                                <syn type="bool">
                                        False
                                </syn>
                                <fin type="bool">
                                        False
                                </fin>
                        </flags>
                        <_window_size type="NoneType">
                                None
                        </_window_size>
                        <_checksum type="NoneType">
                                None
                        </_checksum>
                        <_urgent_pointer type="NoneType">
                                None
                        </_urgent_pointer>
                        <options type="int">
                                0
                        </options>
                        <_padding type="int">
                                0
                        </_padding>
                </protocol>
                <protocol class="umit.umpa.protocols.Payload.Payload">
                        <data type="str">
                                another umit.umpa packet!
                        </data>
                </protocol>
        </packet>
</UMPA>
"""

    ip = IP()
    ip.src = "127.0.0.1"
    ip.dst = "67.205.14.183"

    # TCP header
    tcp = TCP()
    tcp.srcport = 2958
    tcp.dstport = 0
    tcp.set_flags('flags', syn=True)

    # Payload
    data = Payload()
    data.data = "this is umit.umpa!"

    # packet
    example_packet = umit.umpa.Packet(ip, tcp, data)

    tcp2 = TCP()
    tcp2.srcport = 123
    tcp2.dstport = 321
    tcp2.set_flags('flags', syn=False)
    data2 = Payload()
    data2.data = "another umit.umpa packet!"
    example_packet2 = umit.umpa.Packet(tcp2, data2, strict=True)

    def test_packet_attrs(self):
        assert hasattr(umit.umpa.Packet, 'save_xml')
        assert hasattr(umit.umpa.Packet, 'load_xml')

    def test_xml_load(self):
        f = StringIO()
        f.write(self.example_xml)
        f.seek(0)

        packets = XML.load(f)
        for p in packets:
            for i, proto in enumerate(p.protos):
                for fieldname in proto.get_fields_keys():
                    assert proto.get_field(fieldname).fillout() == \
            self.example_packet.protos[i].get_field(fieldname).fillout()

    def test_xml_load_multiple(self):
        l_xml = (self.example_xml, self.example_xml2)
        l_packet = (self.example_packet, self.example_packet2)
        f = StringIO()
        f.write(l_xml[0][:-8])  # </UMPA>\n
        f.write(l_xml[1])
        f.seek(0)

        packets = XML.load(f)
        for j, p in enumerate(packets):
            for i, proto in enumerate(p.protos):
                for fieldname in proto.get_fields_keys():
                    assert proto.get_field(fieldname).fillout() == \
            l_packet[j].protos[i].get_field(fieldname).fillout()

    def test_xml_load_proto_only(self):
        f = StringIO()
        f.write(self.example_xml)
        f.seek(0)

        protos = XML.load(f, proto_only=True)
        for i, p in enumerate((IP, TCP, Payload)):
            assert isinstance(protos[i], p)

    def test_xml_save(self):
        output = StringIO()
        XML.save(output, (self.example_packet, ))
        a = output.getvalue()
        b = self.example_xml.replace('        ', '\t')
        assert a == b

    def test_xml_save_filename(self):
        if os.name != 'posix':
            py.test.skip('only for POSIX platforms')
        output = tempfile.NamedTemporaryFile(mode='w+t')
        XML.save(output.name, (self.example_packet, ))
        a = output.read()
        b = self.example_xml.replace('        ', '\t')
        assert a == b
        output.close()

    def test_xml_save_multiple(self):
        output = StringIO()
        XML.save(output, (self.example_packet, self.example_packet2))
        a = output.getvalue()
        b = self.example_xml[:-8]  # </UMPA>\n
        b += self.example_xml2
        b = b.replace('        ', '\t')
        assert a == b
Example #32
0
#!/usr/bin/env python

from umit.umpa.protocols import IP
from umit.umpa.protocols import TCP
from umit.umpa.protocols import UDP
from umit.umpa.protocols import ICMP
from umit.umpa.protocols import Payload
from umit.umpa import Packet
from umit.umpa import Socket
from umit.umpa._sockets import INET
from umit.umpa.utils.security import super_priviliges

ip = IP(src='127.0.0.1', dst='127.0.0.1')
#print "Value Of fielf key for Ipv6 is Here"
#print(ip)
#print(list(ip.get_fields_keys()))
#print ICMP(type=8)

tcp = TCP()
tcp.srcport = 295
tcp.dstport = 255
tcp.set_flags('flags', syn=True)
#payload = Payload()
#payload.data = "this is umpa!"
first_packet = Packet(ip, tcp)
#first_packet.include(payload)
#print "Structure Of Ipv4 Packet"

#print first_packet
#print "_____________________"
sock = super_priviliges(INET)