aboutsummaryrefslogtreecommitdiff
path: root/tests/nixos/ca-fd-leak/smuggler.c
blob: 82acf37e68ee4af2b869e65efc50064daa6bcec7 (plain)
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
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <assert.h>

int main(int argc, char **argv) {

    assert(argc == 2);

    int sock = socket(AF_UNIX, SOCK_STREAM, 0);

    // Bind to the socket.
    struct sockaddr_un data;
    data.sun_family = AF_UNIX;
    data.sun_path[0] = 0;
    strcpy(data.sun_path + 1, argv[1]);
    int res = bind(sock, (const struct sockaddr *)&data,
        offsetof(struct sockaddr_un, sun_path)
        + strlen(argv[1])
        + 1);
    if (res < 0) perror("bind");

    res = listen(sock, 1);
    if (res < 0) perror("listen");

    int smuggling_fd = -1;

    // Accept the connection a first time to receive the file descriptor.
    fprintf(stderr, "%s\n", "Waiting for the first connection");
    int a = accept(sock, 0, 0);
    if (a < 0) perror("accept");

    struct msghdr msg = {0};
    msg.msg_control = malloc(128);
    msg.msg_controllen = 128;

    // Receive the file descriptor as sent by the smuggler.
    recvmsg(a, &msg, 0);

    struct cmsghdr *hdr = CMSG_FIRSTHDR(&msg);
    while (hdr) {
        if (hdr->cmsg_level == SOL_SOCKET
          && hdr->cmsg_type == SCM_RIGHTS) {

            // Grab the copy of the file descriptor.
            memcpy((void *)&smuggling_fd, CMSG_DATA(hdr), sizeof(int));
        }

        hdr = CMSG_NXTHDR(&msg, hdr);
    }
    fprintf(stderr, "%s\n", "Got the file descriptor. Now waiting for the second connection");
    close(a);

    // Wait for a second connection, which will tell us that the build is
    // done
    a = accept(sock, 0, 0);
    fprintf(stderr, "%s\n", "Got a second connection, rewriting the file");
    // Write a new content to the file
    if (ftruncate(smuggling_fd, 0)) perror("ftruncate");
    char * new_content = "Pwned\n";
    int written_bytes = write(smuggling_fd, new_content, strlen(new_content));
    if (written_bytes != strlen(new_content)) perror("write");
}