Skip to content

Instantly share code, notes, and snippets.

@farukyildiz
Last active September 9, 2021 09:42
Show Gist options
  • Save farukyildiz/bd9ac54aaac9be92624dde2ee0e55edc to your computer and use it in GitHub Desktop.
Save farukyildiz/bd9ac54aaac9be92624dde2ee0e55edc to your computer and use it in GitHub Desktop.
Snort alert_unixsoc - listen socket with C code
# cd /usr/ports/security/snort
# make install
# cd /usr/ports/security/snort/work/snort-2.9.9.0/src/
# clang -I /usr/local/include/ -I sfutil/ -I output-plugins/ -I . -I preprocessors/ -I ../ -I detection-plugins/ -I target-based/ -o snort_listen_unix_socket snort_listen_unix_socket.c
# sysctl net.local.dgram.recvspace = 100000
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include "snort.h"
#include "spo_alert_unixsock.h"
#undef inet_ntoa
char *inet_ntoa(struct in_addr in);
#define UNSOCK_FILE "/var/log/snort/snort_alert"
int sockfd;
void
sig_term (int sig)
{
printf ("Exiting!\n");
close (sockfd);
unlink (UNSOCK_FILE);
exit (1);
}
int
main (void)
{
struct sockaddr_un snortaddr;
struct sockaddr_un bogus;
Alertpkt alert;
Packet *p;
int recv;
socklen_t len = sizeof (struct sockaddr_un);
if ((sockfd = socket (AF_UNIX, SOCK_DGRAM, 0)) < 0)
{
perror ("socket");
exit (1);
}
bzero (&snortaddr, sizeof (snortaddr));
snortaddr.sun_family = AF_UNIX;
strcpy (snortaddr.sun_path, UNSOCK_FILE);
if (bind (sockfd, (struct sockaddr *) &snortaddr, sizeof (snortaddr)) < 0)
{
perror ("bind");
exit (1);
}
signal(SIGINT, sig_term);
while ((recv = recvfrom (sockfd, (void *) &alert, sizeof (alert), 0, (struct sockaddr *) &bogus, &len)) > 0)
{
if (!(alert.val & NOPACKET_STRUCT))
{
if ((p = calloc (1, sizeof (Packet))) == NULL)
{
perror ("calloc");
exit (1);
}
p->pkt = alert.pkt;
p->pkth = &alert.pkth;
if (alert.dlthdr)
p->eh = (EtherHdr *) (alert.pkt + alert.dlthdr);
if (alert.nethdr)
{
p->iph = (IPHdr *) (alert.pkt + alert.nethdr);
if (alert.transhdr)
{
switch (p->iph->ip_proto)
{
case IPPROTO_TCP:
p->tcph = (TCPHdr *) (alert.pkt + alert.transhdr);
break;
case IPPROTO_UDP:
p->udph = (UDPHdr *) (alert.pkt + alert.transhdr);
break;
case IPPROTO_ICMP:
p->icmph = (ICMPHdr *) (alert.pkt + alert.transhdr);
break;
default:
printf ("My, that's interesting.\n");
}
}
}
if (!(alert.val & NOPACKET_STRUCT))
{
if (p->iph)
{
printf ("%s - event_id: [%d] - sig_id: [%d]", alert.alertmsg, alert.event.event_id, alert.event.sig_id);
printf("\n");
printf ("%s -> %s", inet_ntoa (p->iph->ip_src), inet_ntoa (p->iph->ip_dst));
printf("\n\n");
}
}
if (alert.data)
p->data = alert.pkt + alert.data;
}
}
perror ("recvfrom");
close (sockfd);
unlink (UNSOCK_FILE);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment