Skip to content

Instantly share code, notes, and snippets.

@Javex
Created September 29, 2015 15:16
Show Gist options
  • Save Javex/2e4ad293a1563dec3110 to your computer and use it in GitHub Desktop.
Save Javex/2e4ad293a1563dec3110 to your computer and use it in GitHub Desktop.
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
struct ucred {
pid_t pid; /* process ID of the sending process */
uid_t uid; /* user ID of the sending process */
gid_t gid; /* group ID of the sending process */
};
void main(void) {
int sock = socket(AF_UNIX, SOCK_STREAM, 0);
if(!sock)
exit(EXIT_FAILURE);
struct sockaddr_un addr = {0};
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "/tmp/socket_cred_poc.sock");
unlink("/tmp/socket_cred_poc.sock");
if(bind(sock, (struct sockaddr *) &addr, sizeof(struct sockaddr_un)) == -1) {
perror("bind");
exit(EXIT_FAILURE);
}
if(listen(sock, 5) == -1) {
fprintf(stderr, "Errno: %d, %d\n", errno, EINVAL);
perror("listen");
exit(EXIT_FAILURE);
}
while(1) {
int client_sock;
if((client_sock = accept(sock, NULL, NULL)) == -1) {
perror("accept");
exit(EXIT_FAILURE);
}
struct ucred cr;
int cr_len = sizeof cr;
if(getsockopt(client_sock, SOL_SOCKET, SO_PEERCRED, &cr, &cr_len) != 0) {
perror("getsockopt: SO_PEERCRED");
exit(EXIT_FAILURE);
}
fprintf(stderr, "PID: %d, UID: %d, GID: %d\n", cr.pid, cr.uid, cr.gid);
char buffer[4096] = {0};
ssize_t data_len = recv(client_sock, buffer, 4096 - 1, 0);
if(!data_len) {
perror("recv");
exit(EXIT_FAILURE);
}
buffer[data_len] = '\0';
fprintf(stderr, "Data read: %s\n", buffer);
close(client_sock);
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment