Understand cookies in http! C/C++ implements HTTP cookies on the network

HTTP Sniffing is a network monitoring technology that intercepts and analyzes HTTP packets transmitted on the network to obtain sensitive information or carry out attacks. Among them, a sniffer (Sniffer) is a tool used to sniff HTTP traffic.

In HTTP sniffing, cookies are a commonly used sensitive information. A cookie is a small piece of data sent by the server to the user’s browser and stored locally. It is usually used to track user session status, save user login information, etc. Therefore, cookies are of high value to attackers.

When attackers perform HTTP sniffing, they can intercept and analyze HTTP packets transmitted on the network through the sniffer. When analyzing packets, an attacker can look for request and response packets that contain cookie information. Attackers can use various techniques to extract and analyze cookies, such as using packet capture tools (such as Wireshark) or writing custom scripts to extract and analyze packets.

Once an attacker obtains a user’s cookie, they can take different actions. A common approach is to use a “session hijacking” attack, by using a obtained cookie to impersonate the user’s identity and interact with the server. Attackers can use this to access users’ personal data, perform sensitive operations, or steal users’ identity information.

Understanding HTTP sniffing cookies?

HTTP sniffing refers to the process of intercepting and analyzing HTTP requests and responses on the network, and cookies are an important part of HTTP responses. To understand HTTP sniffing cookies, you need to first understand the following concepts:

  • HTTP request and response: HTTP (Hypertext Transfer
    Protocol) is the most widely used protocol on the Internet and is used for communication between clients and servers. HTTP requests are initiated by the client and include request methods (such as
    GET, POST, etc.), request URL, HTTP protocol version and other information. The HTTP response is returned by the server and contains the HTTP
    Protocol version, status code, message and requested resources, etc.
  • Cookie: A cookie is a text file stored on the client that is used to save some of the user’s personal information and access preferences. The server can set the
    Cookie to realize client identification and tracking.
  • Set-Cookie and Cookie: There are two cookie-related fields in the HTTP response header, namely Set-Cookie and
    Cookies. Set-Cookie is sent by the server to create a new Cookie on the client. Cookies are sent by the client and are included in the HTTP
    In the header of the request, it indicates the cookie set by the server that has been stored by the client.

When performing HTTP sniffing, you can understand the interaction between the client and the server by analyzing the Cookie field in the HTTP request and response. For example, the server may set a cookie containing the user ID. The client will send this cookie to the server in subsequent requests, and the server uses this cookie to identify the user. This way, even if the user deletes the cookie in the browser, the server can still obtain this information through HTTP sniffing.

It should be noted that HTTP sniffing may cause privacy and security issues, so it should be used with caution in practical applications. Usually, the browser will provide settings to allow or disable the storage of cookies, and users can choose according to their own needs.

What are cookies in web development?

Cookies are tiny bits of data that the backend can store in the user’s browser. User tracking, personalization and most importantly authentication are the most common use cases for cookies.

Cookies have many privacy issues and have been heavily regulated for years.

In this article, you will learn how to create and use HTTP cookies on the front-end and back-end.

  • Set up backend

An example of a backend is Flask in Python. If you want to continue, create a new Python virtual environment, move into it, and install Flask:

mkdir cookies & amp; & amp; cd $_

python3 -m venv venv
source venv/bin/activate

pip install Flask

Create a new file called flask_app.py in the project folder and experiment locally with my example.

from flask import Flask, make_response

app = Flask(__name__)


@app.route("/index/", methods=["GET"])
def index():
    response = make_response("Here, take some cookies!")
    response.headers["Set-Cookie"] = "myfirstcookie=somecookievalue"
    return response

The backend mentioned here means that cookies can be created in the following ways:

Actual application code on the backend (Python, JavaScript, PHP, Java)

Web server (Nginx, Apache) that responds to requests

To do this, the backend sets an HTTP header called Set Cookie in the response, which has a corresponding string consisting of key/value pairs, and optional attributes:

Set-Cookie: myfirstcookie=somecookievalue

When and where these cookies are created depends on the requirements.

So, cookies are simple strings. Consider this example from Python with Flask. Create a Python file named flask_app.py in the project folder using the following code:

Then run the application:

FLASK_ENV=development FLASK_APP=flask_app.py flask run

When the application is running and the user accesses http://127.0.0.1:5000/ The index/backend sets a response header called Set-Cookie using a key/value pair. (127.0.0.1:5000 is the default listening address/port for Flask applications under development).

The Set Cookie header is the key to understanding how cookies are created:

response.headers["Set-Cookie"] = "myfirstcookie=somecookievalue"
  • How to view cookies?

On the command line, you can also use curl to see what cookies are set by the backend:

curl -I http://127.0.0.1:5000/index/

How do cookies work?

In the HTTP protocol, a cookie is a text file saved on the user’s browser. When the user visits a website, it is sent to the browser by the website’s server and saved locally. When the user visits the same website again, the browser will carry the cookie and send it to the server. The purpose of cookies is mainly to save some session information of users so that they can be used the next time they come to this website again and improve user experience.

Cookies contain some user-related information, such as user ID, password, visited web pages, length of stay, etc., and are used to identify users. Cookie names are usually named in the format of “user@domain”, where “user” represents the user ID and “domain” represents the website domain name.

  • Here’s how cookies work:
1. When a user visits a website, the website's server will send a cookie to the user's browser.
2. The browser will store the cookie locally and carry and send the cookie to the server the next time you visit the same website.
3. After the server receives the cookie, it can determine the user's identity based on the information in it and perform corresponding operations as needed, such as displaying personalized content or automatic login.

However, Cookies also raise some security and privacy issues, such as cross-site scripting attacks (XSS) and privacy leaks. To ensure the safe use of cookies, website developers need to take certain measures, such as setting the HttpOnly flag to protect cookies from being accessed by scripts, or using a secure transmission protocol (such as HTTPS) to encrypt cookies. At the same time, users can also manage and control cookies through browser settings, such as choosing to allow or reject certain cookies, or clearing all cookies.

C/C++ implements HTTP cookies on the network

...
void pcap_fatal(const char *failed_in, const char *errbuf);
char is_ip(const struct pcap_pkthdr *header, const u_char *packet);
char is_tcp(const struct pcap_pkthdr *header, const u_char *packet);
char is_http(const struct pcap_pkthdr *header, const u_char *packet);
void *get_tcp_payload_addr(const struct pcap_pkthdr *header, const u_char *packet);
u_int get_tcp_payload_size(const struct pcap_pkthdr *header, const u_char *packet);
...
typedef struct
{<!-- -->
    char *interface;
    char filter_exp[15];
} Arguments;

struct HTTP_cookie
{<!-- -->
    char *id;
    char *val;
    struct HTTP_cookie *next;
};

typedef struct HTTP_cookie HTTP_cookie;

typedef struct
{<!-- -->
    char *ip_src;
    char *host_dst;
    char *resource;
    char *request_type;
    HTTP_cookie *cookies;
} Host_cookies;

/* ---------- Prototypes ---------- */

error_t parse_opt(int key, char *arg, struct argp_state *state);
void signal_handler(int signal);

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);

void display_raw_data(Host_cookies *host_cookies);
void display_csv_data(Host_cookies *host_cookies);
...
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{<!-- -->
...

    /* While there are cookies */
    while (tok_cookie != NULL)
    {<!-- -->
        current_cookie = (HTTP_cookie *) malloc(sizeof(HTTP_cookie));

        if (current_cookie == NULL)
        {<!-- -->
            fprintf(stderr, "[x] Out of memory\
");
            pcap_close(handle);
            exit(EXIT_FAILURE);
        }

        current_cookie->id = strtok_r(tok_cookie, "=", & amp;saveptr2);
        current_cookie->val = strtok_r(NULL, "=", & amp;saveptr2);
        current_cookie->next = NULL;

        if (previous_cookie == NULL)
            host_cookies.cookies = current_cookie;
        else
            previous_cookie->next = current_cookie;

        previous_cookie = current_cookie;
        tok_cookie = strtok_r(NULL, " ;", & amp;saveptr);
    }

    ip_src.s_addr = ip->ip_src_addr;
    host_cookies.ip_src = inet_ntoa(ip_src);

    host_cookies.host_dst = strstr(http_payload, "Host:");
    host_cookies.host_dst + = 6;
    host_cookies.host_dst = strtok(host_cookies.host_dst, "\r\t\r\t");

...

    if (host_cookies.cookies != NULL)
        display_data( & amp;host_cookies);
}
char is_http(const struct pcap_pkthdr *header, const u_char *packet)
{<!-- -->
...

    http_payload_addr = get_tcp_payload_addr(header, packet);
    http_payload_size = get_tcp_payload_size(header, packet);

    memcpy(http_payload, http_payload_addr, http_payload_size);

    if ((strstr(http_payload, " HTTP/")) == NULL)
        return 0;
    else
        return 1;
}
...
static struct argp_option options[] = {<!-- -->
    {<!-- -->"interface", 'i', "INTERFACE", 0, "Network interface to use"},
    {<!-- -->"port", 'p', "PORT", 0, "Network port to listen (default: 80)"},
    {<!-- -->"csv", 'C', 0, 0, "Display the cookies as CSV data"},
    {<!-- -->0}
};
...
int main (int argc, char ** argv)
{<!-- -->
...

    argp_parse( & amp;argp, argc, argv, 0, 0, & amp;arguments);

    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    if (arguments.interface == NULL)
    {<!-- -->
        dev = pcap_lookupdev(errbuf);

        if (dev == NULL)
        {<!-- -->
            fprintf(stderr, "[x] Couldn't find the default network adapter: %s\
", errbuf);
            exit(EXIT_FAILURE);
        }
    }
    else
        dev = arguments.interface;

    printf("[*] Device : %s\
", dev);

    if (pcap_lookupnet(dev, & amp;net, & amp;mask, errbuf) == -1)
    {<!-- -->
        fprintf(stderr, "[!] Couldn't get the netmask for device %s: %s\
", dev, errbuf);
        net = mask = 0;
    }

    handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);

    if (handle == NULL)
    {<!-- -->
        fprintf(stderr, "[x] Couldn't open device %s: %s\
", dev, errbuf);
        exit(EXIT_FAILURE);
    }

    if ((pcap_compile(handle, & amp;fp, arguments.filter_exp, 0, net)) == -1)
    {<!-- -->
        fprintf(stderr, "[x] Couldn't parse filter %s: %s\
", arguments.filter_exp, pcap_geterr(handle));
        pcap_close(handle);
        exit(EXIT_FAILURE);
    }

    if ((pcap_setfilter(handle, & amp;fp)) == -1)
    {<!-- -->
        fprintf(stderr, "[x] Couldn't install filter %s: %s\
", arguments.filter_exp, pcap_geterr(handle));
        pcap_close(handle);
        exit(EXIT_FAILURE);
    }

    printf("[*] Filter : %s\
", arguments.filter_exp);
    printf("[*] Start sniffing ...\
");

    if ((pcap_loop(handle, -1, got_packet, NULL) == -1))
    {<!-- -->
        fprintf(stderr, "[x] Error while reading the packets\
");
        pcap_close(handle);
        exit(EXIT_FAILURE);
    }
...
}

If you need the complete source code, please add the WeChat number (c17865354792)


The following is an example of the default output:

Host: www.html-kit.com
IP sources: 192.168.20.22
Resource: /tools/cookietester/
Request type: GET

TestCookie_Name_202310045556 = TestCookie_Value_155556
TestCookie_Name_202310045620 = TestCookie_Value_155620

With option -C, each output line will follow the following structure:

host;ip_source;resource_requested;request_type;cookie_1_name;cookie_1_value;cookie_2_name;cookie_2_value;...

Here is an example:

www.html-kit.com;192.168.20.22;/tools/cookietester/;GET;TestCookie_Name_202310045556;TestCookie_Value_155556;TestCookie_Name_202310045620;TestCookie_Value_155620

Summary

To prevent HTTP sniffing and cookie theft, some security measures can be implemented. For example, using the HTTPS protocol to encrypt network transmission data can prevent sniffers from intercepting sensitive information. In addition, using a secure password policy, promptly clearing sensitive information in cookies, and limiting cookie storage time and access permissions can also improve security. In addition, using common security measures such as multi-factor authentication and regular password changes can also reduce the possibility of an attacker obtaining a cookie.

Welcome to follow WeChat official account【Programmer Coding

Reference: RFC 6265