Skip to content

Instantly share code, notes, and snippets.

@pstengel
Created June 27, 2012 13:48
Show Gist options
  • Save pstengel/3004163 to your computer and use it in GitHub Desktop.
Save pstengel/3004163 to your computer and use it in GitHub Desktop.
NETLINK proc_exec connector
#include <stdio.h>
#include <sys/socket.h>
#include <linux/netlink.h>
#include <linux/connector.h>
#include <linux/cn_proc.h>
#include <stdlib.h>
#include <errno.h>
struct __attribute__ ((aligned(NLMSG_ALIGNTO))) nlcn_msg {
struct nlmsghdr nl_hdr;
struct __attribute__ ((__packed__)) {
struct cn_msg cn_msg;
enum proc_cn_mcast_op cn_mcast;
};
};
struct __attribute__ ((aligned(NLMSG_ALIGNTO))) nlcn_proc_event {
struct nlmsghdr nl_hdr;
struct __attribute__ ((__packed__)) {
struct cn_msg cn_msg;
struct proc_event event;
};
};
static const struct nlcn_msg nilmsg;
static const struct nlcn_proc_event nilevent;
int main(int argc, const char *argv[])
{
int nl_sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_CONNECTOR);
struct sockaddr_nl sa_nl;
if (nl_sock == -1) {
perror("Problem opening NETLINK socket!");
exit(-1);
}
sa_nl.nl_family = AF_NETLINK;
sa_nl.nl_groups = CN_IDX_PROC;
sa_nl.nl_pid = getpid();
if (bind(nl_sock, (struct sockaddr*)&sa_nl, sizeof(sa_nl)) != 0) {
perror("Problem binding NETLINK socket!");
close(nl_sock);
exit(-1);
}
struct nlcn_msg msg = nilmsg;
msg.nl_hdr.nlmsg_len = sizeof(struct nlcn_msg);
msg.nl_hdr.nlmsg_type = NLMSG_DONE;
msg.cn_msg.id.idx = CN_IDX_PROC;
msg.cn_msg.id.val = CN_VAL_PROC;
msg.cn_msg.len = sizeof(enum proc_cn_mcast_op);
msg.cn_mcast = PROC_CN_MCAST_LISTEN;
if (send(nl_sock, &msg, sizeof(msg), 0) == -1) {
perror("Problem sending NETLINK registration message!");
close(nl_sock);
exit(-1);
}
int rc = 0;
struct nlcn_proc_event ev = nilevent;
while(1) {
rc = recv(nl_sock, &ev, sizeof(ev), 0);
if (rc == 0) {
exit(0);
}
else if (rc == -1) {
if (errno == EINTR) continue;
perror("Problem during NETLINK recv()!");
close(nl_sock);
exit(-1);
}
if (ev.event.what == PROC_EVENT_UID) {
printf("id change: pid=%d tgid=%d\n",
ev.event.event_data.id.process_pid,
ev.event.event_data.id.process_tgid);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment