def get_gateway_ip():
    table = []
    route = os.popen("route")
    i = 0
    for r in route:
        r = " ".join(re.split("\s+", r, flags=re.UNICODE))
        table.append(r)

    l = len(table)
    for i in range(l):
        table[i] = table[i].strip()
        table[i] = table[i].split(" ")

        #print(table[i])
        #lst.split(" ")
    for i in range(l - 2):
        if table[i + 2][7] == "wlp2s0" and table[i + 2][1] != "*":
            gateway_ip = table[i + 2][1]
            gateway_ip = str(gateway_ip)
            print("gateway_ip : " + gateway_ip)

    gateway = arpreq.arpreq(gateway_ip)
    print("gateway : " + gateway)
    gateway = str(gateway)
    #print(table)
    tshark(gateway, gateway_ip)
Example #2
0
def index():
    ip = request.remote_addr
    try:
        mac = arpreq.arpreq(ip)
    except OSError as e:
        content = render_template("error.html",
                                  message=_("An error occurred while resolving "
                                            "IP address into a MAC address."))
        return content, 500
    if mac is None:
        content = render_template("error.html",
                                  error=_("No MAC address could be found for "
                                          "your IP address {}".format(ip)))
        return content, 500
    mac_groups = get_groups(mac)
    latest_auth_attempt = get_latest_auth_attempt(mac)
    if latest_auth_attempt:
        last_auth_groups, last_auth_date = latest_auth_attempt
    else:
        last_auth_groups, last_auth_date = [], None
    reasons = [messages[group] for group in mac_groups if group in messages]
    show_mac = False
    if not mac_groups:
        reasons.append(messages['unknown'])
        show_mac = True
    if 'unknown' in last_auth_groups and mac_groups:
        reasons.append(messages['wrong_port'])
    return render_template(
        "status.html", reasons=reasons,
        mac=mac,
        show_mac=show_mac,
    )
Example #3
0
def scan_network_ips(ip_range):
    nm = nmap.PortScanner()
    scans = nm.scan(hosts=ip_range, arguments='-sn')
    res = {}
    for ip, data in scans.get('scan', {}).items():
        mac = arpreq.arpreq(ip)
        data.setdefault('vendor', {}).setdefault('mac', mac)
        res[ip] = data
    return res
Example #4
0
def index():
    ip = request.remote_addr
    try:
        mac = arpreq.arpreq(ip)
    except OSError as e:
        logger.exception("Could not resolve IP {} into MAC: {}".format(ip, e))
        content = render_template("error.html",
                                  message=_("An unexpected error occurred "
                                            "while resolving your IP address "
                                            "into a MAC address."))
        return content, 500
    if mac is None:
        content = render_template("error.html",
                                  error=_("No MAC address could be found for "
                                          "your IP address {}".format(ip)))
        return content, 500

    with contextlib.closing(
            engine.connect()) as connection, connection.begin():
        mac_groups = list(get_groups(connection, mac))

        if not mac_groups:
            return render_template("status.html",
                                   reasons=[messages['unknown']],
                                   mac=mac,
                                   show_mac=True)

        latest_auth_attempt = get_latest_auth_attempt(connection, mac)
        if not latest_auth_attempt:
            content = render_template("error.html",
                                      error=_(
                                          "No authentication attempt found "
                                          "for your MAC address."))
            return content, 500

        nas_ip_address, nas_port_id, *ignore = latest_auth_attempt

        port_groups = [
            group for nai, npi, group in mac_groups
            if nas_ip_address == nai and nas_port_id == npi
        ]

        if not port_groups:
            return render_template("status.html",
                                   mac=mac,
                                   show_mac=False,
                                   reasons=[messages['wrong_port']])

        reasons = [
            messages[group] for group in port_groups if group in messages
        ]

        return render_template("status.html",
                               reasons=reasons,
                               mac=mac,
                               show_mac=False)
Example #5
0
    def whos_home(self):

        home_list = [(time.time(), 0)] * self.devices

        for ip in range(0, self.devices):
            test = arpreq.arpreq('192.168.0.' + str(ip + 51))
            if test is not None:
                home_list[ip] = time.time(), 1

        return home_list
Example #6
0
def get_realm_id():
    """Return a unique identifier for the Internet Service Provider
    """
    isp_id = get_essid()
    if not isp_id:
        # Then the network probably isn't wifi. Check ethernet :
        import arpreq
        #isp_id = arpreq.arpreq(get_ip_address(get_active_interface()))
        isp_id = arpreq.arpreq(get_gateway_address())
    return isp_id
Example #7
0
def get_attendance():
    mac_list = []
    for i in range(1, 255):
        request_mac = arpreq.arpreq(f'192.168.0.{i}')
        if request_mac:
            student_with_mac = Student.objects.filter(
                mac=str(request_mac).strip())
            if student_with_mac.exists():
                record = Record(student=student_with_mac.first())
                record.save()
Example #8
0
def getDevStatus():
    data = []
    lease = []
    with open('/var/lib/misc/dnsmasq.leases') as f:
        data = f.readlines()
        for line in data:
            if arpreq.arpreq(line.strip('\n').split()[2]):
                lease.append(line.strip('\n').split() + [True])
            else:
                lease.append(line.strip('\n').split() + [False])
    sendresponse(json.dumps(lease))
Example #9
0
 def __init__(self, target_ip, target_mac, gateway_ip=None):
     self.logger = logging.getLogger(__name__)
     if gateway_ip is None:
         gateway_ip = netifaces.gateways()['default'][AF_INET][1]
     self.gateway_ip = gateway_ip
     self.gateway_mac = arpreq.arpreq(gateway_ip)
     if self.gateway_mac is None:
         raise IOError("Unable to get gateway MAC address")
     self.target_ip = target_ip
     self.target_mac = target_mac
     self.__running = True
     atexit.register(self.stop)
Example #10
0
def mark_attendance(request):
    if request.method == 'POST':
        print(f"roll_no: {request.POST.get('id')}")
    else:
        print('*************')
    request_mac = arpreq.arpreq(get_client_ip(request))
    student_with_mac = Student.objects.filter(mac=request_mac)
    if (student_with_mac):
        record = Record(student=student_with_mac.first())
        record.save()
    else:
        print('Not a student')
    print(' ')
    return HttpResponse(status=200)
Example #11
0
    def ping_sweep_async(self, network=None, callback=None):
        if network is None:
            network = self.get_current_network()

        self.logger.debug(network)
        with ThreadPoolExecutor(max_workers=THREAD_LIMIT) as executor:
            futures = []
            for ip in network:
                future = executor.submit(self.ping_host, str(ip))
                futures.append(future)

            for future in futures:
                result = future.result()
                if result is not None and callback:
                    callback((result, arpreq.arpreq(result)))
Example #12
0
    def add_server(self, ip, port, id=None):
        print("Adding server at %s:%d" % (ip, port))
        structip = ip2int(ip)
        mac = arpreq.arpreq(ip)
        if mac is None:
            print("COULD NOT FIND MAC ADDRESS FOR IP %s" % ip)
        macstr = mac.replace(':', '').decode('hex')
        print("Found mac address: {}, {}".format(mac, macstr))
        server = DstAddr(macstr, structip, ct.c_uint16(socket.htons(port)))

        if id is None:
            id = self.n_servers

        self.n_servers = max(self.n_servers, id + 1)

        self.b['dst_servers'][id] = server
        self.b['n_dst_servers'][0] = ct.c_uint(self.n_servers)
Example #13
0
    def handle_beacon(self, fd, event):
        """
        Reads response from nodes

        Creates :class:`Peer` objects and tracks them in `self.peers`. Finally
        sends messages through pipe to main application thread.

        :param fd: not used
        :param event: not used
        """
        log.debug("Waiting for a beacon.")
        try:
            data, host = self._next_packet()
        except ReceiveTimeout:
            msg_parts = [b"RECEIVE_TIMEOUT"]
            try:
                self._send_to_pipe_multipart(msg_parts)
            except Exception:
                return
            return
        if data == PING_MESSAGE:
            log.debug("Ignoring ping message received from network from %s.", host)
            return
        log.debug("Received a beacon from %s.", host)
        ip_address, device_id = decode_discovery_response(data)
        # if host != ip_address:
        # print("Host {} != ip_address {}".format(host, ip_address))
        log.debug("Getting hardware address of %s.", ip_address)
        hw_address = arpreq(ip_address)
        if is_py3 and not isinstance(hw_address, bytes):
            hw_address = bytes(hw_address, "utf-8")
        if hw_address is None:
            log.error("Unable to get HW adress of %s.", ip_address)
            msg_parts = [b"ERROR", device_id, ip_address]
            try:
                self._send_to_pipe_multipart(msg_parts)
            except Exception:
                return
        # print("Host {} has MAC address {}".format(ip_address, hw_address))
        if hw_address in self.peers:
            log.debug("Peer %s seen before.", hw_address)
            return self.process_seen_peer(hw_address, device_id, ip_address)
        else:
            log.debug("Never seen %s before.", hw_address)
            return self.process_new_peer(hw_address, device_id, ip_address)
Example #14
0
def arpRequest(dict_arp_table):
    dict_mac = {}
    for ips in range(255):
        mac = arpreq.arpreq(ipaddress.IPv4Address(u'192.168.10.' + str(ips)))
        if mac is not None:
            dict_arp_table[str('192.168.10.' + str(ips))].append(mac)
            dict_arp_table[str('192.168.10.' + str(ips))].append("Normal")
            if str(mac) in dict_mac:
                for key in dict_arp_table.keys():
                    if dict_arp_table[key][0] == str(mac):
                        dict_arp_table[key][1] = "Abnormal"
                        print(
                            "Alert !! Duplicate entry found in ARP Table, Duplicate Mac: "
                            + mac + " with IP: " + key)
                dict_mac[str(mac)] += 1

            else:
                dict_mac[str(mac)] = 1
    def ap_lookup(self, client_ip):
        requesting_mac = arpreq.arpreq(client_ip)
        if not self.cur.execute(
                "SELECT *, CAST(non_member_perdiem AS CHAR) AS non_member_perdiem,CAST(non_member_rate AS CHAR) AS non_member_rate,CAST(member_rate AS CHAR) AS member_rate FROM civicrm_mstk_access_points WHERE mac_address = %s",
            (requesting_mac, )):
            self.debug_message(
                self.log_level, 0,
                "UNAUTHORIZED AP REQUEST: by ip address %s with mac address %s"
                % (client_ip, requesting_mac))
            return {'error_code': 'x10'}
        else:
            requesting_ap = self.cur.fetchone()

        if requesting_ap['ip_address'] == client_ip:
            # Ok, this is a legit ap.
            if str(requesting_ap['maintenance_mode']) == "1":
                error_code = 'x20'
                requesting_ap.update({"error_code": str(error_code)})
            else:
                # adding door comands if this is under an access control device
                try:
                    requesting_ap.update({"dev": str(requesting_ap['dev'])})
                    requesting_ap.update({"cmd": str(requesting_ap['cmd'])})
                except:
                    pass
                # adding a parent if present
                try:
                    requesting_ap.update(
                        {"parent_ap": str(requesting_ap['parent_id'])})
                except:
                    # no parent
                    pass

                error_code = 'x00'
                requesting_ap.update({"error_code": str(error_code)})

            return requesting_ap
        else:
            self.debug_message(
                self.log_level, 0,
                "UNAUTHORIZED AP REQUEST: ip/mac don't agree. ip %s, mac %s" %
                (client_ip, requesting_mac))
            return {'error_code': 'x10'}
Example #16
0
def getRandomIps(count=1):
    # Get all the possible hosts in the network
    myip = _getIp()
    myip = myip + _getSubnetMaskFromIp(myip)  # 192.168.0.4/24

    hosts = [
        ip.exploded
        for ip in ipaddress.IPv4Network(myip, strict=False).hosts()
    ]
    random.shuffle(hosts)  # Shuffle the list
    print("Discovering {} addresses to use...".format(count))
    addresses = set()
    # Keep looping until we run out of ip addresses or have found enough
    for ip in hosts:
        if ip not in addresses:
            if not arpreq.arpreq(ip):
                addresses.add(ip)
                print(".", end="", flush=True)
        if len(addresses) == count:
            break
    return list(addresses)
Example #17
0
	def pinger(self, host_num):
		ni.ifaddresses(interface)
		ip = ni.ifaddresses(interface)[ni.AF_INET][0]['addr']

		hostadrr = ip.split('.')[:-1]
		hostadrr = '.'.join(hostadrr) + '.' + repr(host_num)

		line = subprocess.getoutput("ping -n -c 1 %s 2> /dev/null" % hostadrr)
		time.sleep(2)

		while True:
			if line.find(hostadrr) and line.find("bytes from") > -1:  # Host Active
				is_active = []
				is_active.append(hostadrr)
				alive_host = is_active.pop()

				print("Host %s is \033[92m Active \033[0m" % alive_host)
				with open('result_ping.txt', 'a+') as the_file:
    					the_file.write(alive_host + ' -- ' + arpreq.arpreq(alive_host))
    					the_file.write("\n")
				break
			else:
				exit(0)
Example #18
0
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
serverPort = 20170
server_socket.bind(('', serverPort))
server_socket.listen(1)

read_list = [server_socket]
while (1):

    try:
        readable, writable, errored = select.select(read_list, [], [])
        for s in readable:
            if s is server_socket:
                client_socket, address = server_socket.accept()
                read_list.append(client_socket)
                print "Connection from", address, arpreq.arpreq(str(
                    address[0]))

            else:
                data = s.recv(1024)

                #print data
                if data:
                    #s.send(data)

                    try:
                        data = data.split('\n')[0]

                        if "|" in data:
                            raw_data = data.split('|')
                        elif "%7C" in data:
                            raw_data = data.split('%7C')
import arpreq

mac_list = []
for i in range(1, 255):
    request_mac = arpreq.arpreq(f'192.168.0.{i}')
    # print(f'192.168.0.{i} ' + str(request_mac))
    if request_mac:
        mac_list.append(f'192.168.0.{i} ' + str(request_mac))
Example #20
0
def test_cached_entries():
    for ip, mac in get_arp_cache():
        assert arpreq(ip) == mac
Example #21
0
def test_localhost(value):
    assert arpreq(value) == '00:00:00:00:00:00'
Example #22
0
def test_cached_entries():
    for ip, mac in get_arp_cache():
        assert arpreq(ip) == mac
Example #23
0
def test_gateways():
    for gateway in get_gateways():
        ping(gateway)
        assert arpreq(gateway) is not None
print('version of device: {}'.format(response_show_versio_json['version']))

#Get hostname
url_hostname = 'https://192.168.4.164/api/config/settings/host-name'
Response_Show_Hostname = requests.get(
    url_hostname,
    headers={'Authorization': 'Token ' + token_json['token']},
    verify=False,
    timeout=30)
Response_Show_Hostname = Response_Show_Hostname.content.decode()
Response_Show_Hostname_json = json.loads(Response_Show_Hostname)
print('Hostname: {}'.format(Response_Show_Hostname_json['data']['value']))
print('===================================================')
# ar = ArpRequest('192.168.50.1', 'enp0s25')
# print(ar.request)
print(arpreq.arpreq('192.168.50.1'))
"""


data_interface= {
            "name": "ETH1",
            "error": None,
            "is_used_in_dhcp": False,
            "is_used_in_ha": False,
            "mac": "00:0C:29:6C:4D:D0",
            "name_sort": "eth00000000",
            "description": None,
            "alias": "ETH1",
            "ip_list": [
                {
                    "ip": "192.168.20.164",
Example #25
0
def test_illegal_type(value):
    with pytest.raises(TypeError):
        arpreq(value)
Example #26
0
addr = ip_info[0]["addr"]
netmask = ip_info[0]["netmask"]
network = ipaddress.ip_network("%s/%s" % (addr, netmask), strict=False)

start = network.network_address + 1
end = network.broadcast_address

maclookup = MacLookup()
nmap = nmap.PortScanner()

#for ipint in range(int(start), int(end)):
for ipint in range(int(start), int(start) + 1):
    ip = ipaddress.IPv4Address(ipint)
    ipstr = str(ip)
    hosts_info[ipstr] = {}
    mac = arpreq.arpreq(ip)
    vendor = None

    if mac is not None:
        vendor = maclookup.lookup(mac)
        scan_result = {}
        nmap.scan(hosts=ipstr, ports='1-1000', arguments='-sS -O')
        scan_result['os'] = nmap[ipstr]['osmatch'][0]['name']
        scan_result['open_tcp'] = [p for p in nmap[ipstr]['tcp']]
        #nmap.scan(hosts=ipstr, ports='1-1000', arguments='-sU')
        #print(nmap[ipstr]['udp'])

    hardware_info = [mac, vendor]
    hosts_info[ipstr]['hardware'] = hardware_info
    hosts_info[ipstr]['scan_result'] = scan_result
Example #27
0
def test_localhost(value):
    assert arpreq(value) == '00:00:00:00:00:00'
Example #28
0
def get_MAC(ipAddr):
    return arpreq.arpreq(ipAddr)
Example #29
0
import arpreq

config = configparser.ConfigParser()
secrets_file = 'mstk-secrets.conf'
secrets_path = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))
config.read(os.path.join(secrets_path, secrets_file))
civicrm_url = config.get('civi-connect', 'url')
civicrm_site_key = config.get('civi-connect', 'site_key')
civicrm_api_key = config.get('civi-connect', 'api_key')
civicrm = CiviCRM(civicrm_url, civicrm_site_key, civicrm_api_key, use_ssl=False, timeout=10 )
ap_ip = config.get('doord','host')
# during testing the server host and "ap" share an ip address
host = ap_ip
port = config.get('doord','port')
ap_mac =  arpreq.arpreq(ap_ip)

server = pythonmstk.MstkServer(secrets_path,secrets_file)

class TestMstkServer(unittest.TestCase):
   
   @classmethod
   def setUpClass(cls):
      contact_dict = {
        "first_name":"Testy",
       "last_name":"McTesterson",
        "contact_type":"Individual"
      }
      membership_type_dict = {
        "domain_id": "Fat Cat Fab Lab",
        "member_of_contact_id": "1",
Example #30
0
 def __verifyArp(self):
     return arpreq.arpreq(self.ip) == self.mac
Example #31
0
def test_illegal_argument(value):
    with pytest.raises(ValueError):
        arpreq(value)
Example #32
0
def test_illegal_argument(value):
    with pytest.raises(ValueError):
        arpreq(value)
Example #33
0
    def handle_beacon(self, fd, event):
        """
        Reads response from nodes

        Creates :class:`Peer` objects and tracks them in `self.peers`. Finally
        sends messages through pipe to main application thread.

        :param fd: not used
        :param event: not used
        """
        log.debug("Waiting for a beacon.")
        data, host = self.udp.recv(64)
        if data == PING_MESSAGE:
            log.debug("Ignoring ping message received from network from %s.",
                      host)
            return
        log.debug("Received a beacon from %s.", host)
        ip_address, device_name = decode_discovery_response(data)
        # if host != ip_address:
        # print("Host {} != ip_address {}".format(host, ip_address))
        log.debug("Getting hardware address of %s.", ip_address)
        hw_address = arpreq(ip_address)
        if is_py3 and not isinstance(hw_address, bytes):
            hw_address = bytes(hw_address, "utf-8")
        if hw_address is None:
            log.error("Unable to get HW adress of %s.", ip_address)
            msg_parts = [b"ERROR", device_name, ip_address]
            try:
                self._send_to_pipe_multipart(msg_parts)
            except Exception:
                return
        # print("Host {} has MAC address {}".format(ip_address, hw_address))
        if hw_address in self.peers:
            log.debug("Peer %s seen before.", hw_address)
            self.peers[hw_address].is_alive()
            if device_name != self.peers[hw_address].device_name:
                old_device_name = self.peers[hw_address].device_name
                self.peers[hw_address].device_name = device_name
                msg_parts = [
                    b"RENAMED", hw_address, old_device_name, device_name
                ]
                try:
                    self._send_to_pipe_multipart(msg_parts)
                except Exception:
                    return
            if ip_address != self.peers[hw_address].ip_address:
                old_ip_address = self.peers[hw_address].ip_address
                self.peers[hw_address].ip_address = ip_address
                msg_parts = [
                    b"ADDRESS_CHANGED", hw_address, old_ip_address, ip_address
                ]
                try:
                    self._send_to_pipe_multipart(msg_parts)
                except Exception:
                    return
        else:
            log.debug("Never seen %s before.", hw_address)
            self.peers[hw_address] = Peer(hw_address, device_name, ip_address)
            msg_parts = [b"JOINED", hw_address, device_name, ip_address]
            try:
                self._send_to_pipe_multipart(msg_parts)
            except Exception:
                return
Example #34
0
    def initHeader(self):
        """Initialize the IP header according to the IP format definition.

        """

        # Ethernet header

        # Retrieve remote MAC address
        dstMacAddr = arpreq.arpreq(self.remoteIP)
        if dstMacAddr is not None:
            dstMacAddr = dstMacAddr.replace(':', '')
            dstMacAddr = binascii.unhexlify(dstMacAddr)
        else:
            # Force ARP resolution
            p = subprocess.Popen(["/bin/ping", "-c1", self.remoteIP])
            p.wait()
            time.sleep(0.1)

            dstMacAddr = arpreq.arpreq(self.remoteIP)
            if dstMacAddr is not None:
                dstMacAddr = dstMacAddr.replace(':', '')
                dstMacAddr = binascii.unhexlify(dstMacAddr)
            else:
                raise Exception("Cannot resolve IP address to a MAC address for IP: '{}'".format(self.remoteIP))

        # Retrieve local MAC address
        srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1]

        eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr))
        eth_src = Field(name='eth.src', domain=Raw(srcMacAddr))
        eth_type = Field(name='eth.type', domain=Raw(b"\x08\x00"))


        # IP header

        ip_ver = Field(
            name='ip.version', domain=BitArray(
                value=bitarray('0100')))  # IP Version 4
        ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000')))
        ip_tos = Field(
            name='ip.tos',
            domain=Data(
                dataType=BitArray(nbBits=8),
                originalValue=bitarray('00000000'),
                svas=SVAS.PERSISTENT))
        ip_tot_len = Field(
            name='ip.len', domain=BitArray(bitarray('0000000000000000')))
        ip_id = Field(name='ip.id', domain=BitArray(nbBits=16))
        ip_flags = Field(name='ip.flags', domain=Data(dataType=BitArray(nbBits=3), originalValue=bitarray('000'), svas=SVAS.PERSISTENT))
        ip_frag_off = Field(name='ip.fragment', domain=Data(dataType=BitArray(nbBits=13), originalValue=bitarray('0000000000000'), svas=SVAS.PERSISTENT))
        ip_ttl = Field(name='ip.ttl', domain=Data(dataType=BitArray(nbBits=8), originalValue=bitarray('01000000'), svas=SVAS.PERSISTENT))
        ip_proto = Field(name='ip.proto', domain=Integer(value=self.upperProtocol, unitSize=AbstractType.UNITSIZE_8, endianness=AbstractType.ENDIAN_BIG, sign=AbstractType.SIGN_UNSIGNED))
        ip_checksum = Field(name='ip.checksum', domain=BitArray(bitarray('0000000000000000')))
        ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP))
        ip_daddr = Field(
            name='ip.dst', domain=IPv4(self.remoteIP))
        ip_payload = Field(name='ip.payload', domain=Raw())

        ip_ihl.domain = Size([ip_ver,
                              ip_ihl,
                              ip_tos,
                              ip_tot_len,
                              ip_id, ip_flags,
                              ip_frag_off,
                              ip_ttl, ip_proto,
                              ip_checksum,
                              ip_saddr,
                              ip_daddr], dataType=BitArray(nbBits=4), factor=1/float(32))
        ip_tot_len.domain = Size([ip_ver,
                                  ip_ihl,
                                  ip_tos,
                                  ip_tot_len,
                                  ip_id,
                                  ip_flags,
                                  ip_frag_off,
                                  ip_ttl,
                                  ip_proto,
                                  ip_checksum,
                                  ip_saddr,
                                  ip_daddr,
                                  ip_payload], dataType=Integer(unitSize=AbstractType.UNITSIZE_16, sign=AbstractType.SIGN_UNSIGNED), factor=1/float(8))
        ip_checksum.domain = InternetChecksum(fields=[ip_ver,
                                                      ip_ihl,
                                                      ip_tos,
                                                      ip_tot_len,
                                                      ip_id,
                                                      ip_flags,
                                                      ip_frag_off,
                                                      ip_ttl,
                                                      ip_proto,
                                                      ip_checksum,
                                                      ip_saddr,
                                                      ip_daddr], dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16))
        
        self.header = Symbol(name='Ethernet layer', fields=[eth_dst,
                                                            eth_src,
                                                            eth_type,
                                                            ip_ver,
                                                            ip_ihl,
                                                            ip_tos,
                                                            ip_tot_len,
                                                            ip_id,
                                                            ip_flags,
                                                            ip_frag_off,
                                                            ip_ttl,
                                                            ip_proto,
                                                            ip_checksum,
                                                            ip_saddr,
                                                            ip_daddr,
                                                            ip_payload])
Example #35
0
def test_illegal_type():
    with pytest.raises(TypeError):
        arpreq(None)
Example #36
0
def test_default_gateway():
    gateway = get_default_gateway()
    if not gateway:
        pytest.skip("No default gateway present.")
    assert arpreq(gateway) is not None
Example #37
0
    def initHeader(self):
        """Initialize the IP header according to the IP format definition.

        """

        # Ethernet header

        # Retrieve remote MAC address
        dstMacAddr = arpreq.arpreq(self.remoteIP)
        if dstMacAddr is not None:
            dstMacAddr = dstMacAddr.replace(':', '')
            dstMacAddr = binascii.unhexlify(dstMacAddr)
        else:
            # Force ARP resolution
            p = subprocess.Popen(["/bin/ping", "-c1", self.remoteIP])
            p.wait()
            time.sleep(0.1)

            dstMacAddr = arpreq.arpreq(self.remoteIP)
            if dstMacAddr is not None:
                dstMacAddr = dstMacAddr.replace(':', '')
                dstMacAddr = binascii.unhexlify(dstMacAddr)
            else:
                raise Exception(
                    "Cannot resolve IP address to a MAC address for IP: '{}'".
                    format(self.remoteIP))

        # Retrieve local MAC address
        srcMacAddr = self.get_interface_addr(bytes(self.interface, 'utf-8'))[1]

        eth_dst = Field(name='eth.dst', domain=Raw(dstMacAddr))
        eth_src = Field(name='eth.src', domain=Raw(srcMacAddr))
        eth_type = Field(name='eth.type', domain=Raw(b"\x08\x00"))

        # IP header

        ip_ver = Field(name='ip.version',
                       domain=BitArray(value=bitarray('0100')))  # IP Version 4
        ip_ihl = Field(name='ip.hdr_len', domain=BitArray(bitarray('0000')))
        ip_tos = Field(name='ip.tos',
                       domain=Data(dataType=BitArray(nbBits=8),
                                   originalValue=bitarray('00000000'),
                                   svas=SVAS.PERSISTENT))
        ip_tot_len = Field(name='ip.len',
                           domain=BitArray(bitarray('0000000000000000')))
        ip_id = Field(name='ip.id', domain=BitArray(nbBits=16))
        ip_flags = Field(name='ip.flags',
                         domain=Data(dataType=BitArray(nbBits=3),
                                     originalValue=bitarray('000'),
                                     svas=SVAS.PERSISTENT))
        ip_frag_off = Field(name='ip.fragment',
                            domain=Data(
                                dataType=BitArray(nbBits=13),
                                originalValue=bitarray('0000000000000'),
                                svas=SVAS.PERSISTENT))
        ip_ttl = Field(name='ip.ttl',
                       domain=Data(dataType=BitArray(nbBits=8),
                                   originalValue=bitarray('01000000'),
                                   svas=SVAS.PERSISTENT))
        ip_proto = Field(name='ip.proto',
                         domain=Integer(value=self.upperProtocol,
                                        unitSize=AbstractType.UNITSIZE_8,
                                        endianness=AbstractType.ENDIAN_BIG,
                                        sign=AbstractType.SIGN_UNSIGNED))
        ip_checksum = Field(name='ip.checksum',
                            domain=BitArray(bitarray('0000000000000000')))
        ip_saddr = Field(name='ip.src', domain=IPv4(self.localIP))
        ip_daddr = Field(name='ip.dst', domain=IPv4(self.remoteIP))
        ip_payload = Field(name='ip.payload', domain=Raw())

        ip_ihl.domain = Size([
            ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off,
            ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr
        ],
                             dataType=BitArray(nbBits=4),
                             factor=1 / float(32))
        ip_tot_len.domain = Size([
            ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags, ip_frag_off,
            ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr, ip_payload
        ],
                                 dataType=Integer(
                                     unitSize=AbstractType.UNITSIZE_16,
                                     sign=AbstractType.SIGN_UNSIGNED),
                                 factor=1 / float(8))
        ip_checksum.domain = InternetChecksum(
            fields=[
                ip_ver, ip_ihl, ip_tos, ip_tot_len, ip_id, ip_flags,
                ip_frag_off, ip_ttl, ip_proto, ip_checksum, ip_saddr, ip_daddr
            ],
            dataType=Raw(nbBytes=2, unitSize=AbstractType.UNITSIZE_16))

        self.header = Symbol(name='Ethernet layer',
                             fields=[
                                 eth_dst, eth_src, eth_type, ip_ver, ip_ihl,
                                 ip_tos, ip_tot_len, ip_id, ip_flags,
                                 ip_frag_off, ip_ttl, ip_proto, ip_checksum,
                                 ip_saddr, ip_daddr, ip_payload
                             ])