How to read offline pcap file using libnids? - libnids

void main( )
{
char filename[] = "dns.pcap";
nids_params.filename = filename ;
nids_params.device = NULL;
if (!nids_init())
{
printf("%s\n", nids_errbuf);
exit(1);
}
nids_register_udp(udp_callback);
nids_run();
}
My application need to read local pcap file for debuging more easily. My code is wrong , it still read data from eth0.How to read pcapfile using libnids?

Related

How to create a snort content rule

I am new into using snort and I don't know how to properly create rules.
I want someone to explain me how to create a rule for detection of a specific content. For example: I want to generate an alert when I search on Google the word 'terrorism'.
I tried to create the rule with what I've seen on Youtube or Google, as examples, but none of them works and I don't know what to try anymore. For instance, I am using Snort 2.9.9
alert tcp $HOME_NET any -> $EXTERNAL_NET any (msg:"terrorism content found"; content:"terrorism"; nocase; sid:1000000;)
I don't have any errors from the local.rules file, but I got the line 'include $RULE_PATH/snort.rules' commented because of some problems with PulledPork.
I expect to have an alert in the CLI, but there is no output.
I know that this is already too late but here's the answer for future reference.
The packets are probably being sent using HTTPS connection (which is why they are encrypted).
This might be a reason why there are no alerts.
Please refer here for a detailed explanation.
rules are ready, u just replace, alert with sdrop:
find /home/www \( -type d -name .git -prune \) -o -type f -print0 | xargs -0 sed -i 's/subdomainA\.example\.com/subdomainB.example.com/g'
and you can use include in config file
O.K
Answer is here: http://manpages.ubuntu.com/manpages/xenial/man8/u2spewfoo.8.html
Download Snort source, Make logs costume, write ur code to get log stream in control
Then Build source and run
Be successful :)
It is possible to send alert messages and some packet relevant data
from snort through a unix socket, to perform additional separate
processing of alert data.
Snort has to be built with spo_unsock.c/h output plugin is built in and
-A unsock (or its equivalent through the config file) is
used. The unix socket file should be created in /dev/snort_alert. Your
‘client’ code should act as ‘server’ listening to this unix socket.
Snort will be sending you Alertpkt structures which contain alert
message, event id. Original datagram, libpcap pkthdr, and offsets to
datalink, netlayer, and transport layer headers.
Below is an example how unix sockets could be used. If you have any
comments bug reports, and feature requests, please contact
snort-devel#lists.sourceforge.net or drop me an email to fygrave at
tigerteam dot net.
-Fyodor
[for copyright notice, see snort distribution code]
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include
#include "snort.h"
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)
{
/* do validation of recv if you care */
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");
} /* case */
} /* thanshdr */
} /* nethdr */
if (alert.data)
p->data = alert.pkt + alert.data;
/* now do whatever you want with these packet structures */
} /* if (!NOPACKET_STRUCT) */
printf ("%s [%d]\n", alert.alertmsg, alert.event.event_id);
if (!(alert.val & NOPACKET_STRUCT))
if (p->iph && (p->tcph || p->udph || p->icmph))
{
switch (p->iph->ip_proto)
{
case IPPROTO_TCP:
printf ("TCP from: %s:%d ",
inet_ntoa (p->iph->ip_src),
ntohs (p->tcph->th_sport));
printf ("to: %s:%d\n", inet_ntoa (p->iph->ip_dst),
ntohs (p->tcph->th_dport));
break;
case IPPROTO_UDP:
printf ("UDP from: %s:%d ",
inet_ntoa (p->iph->ip_src),
ntohs (p->udph->uh_sport));
printf ("to: %s:%d\n", inet_ntoa (p->iph->ip_dst),
ntohs (p->udph->uh_dport));
break;
case IPPROTO_ICMP:
printf ("ICMP type: %d code: %d from: %s ",
p->icmph->type,
p->icmph->code, inet_ntoa (p->iph->ip_src));
printf ("to: %s\n", inet_ntoa (p->iph->ip_dst));
break;
}
}
}
perror (“recvfrom”);
close (sockfd);
unlink (UNSOCK_FILE);
return 0;
}

What to do after shutdown(sock, SD_SEND)

I want to send several files from Server to the Client but I'm having a problem.
Server sendfile code:
while ((len = fread(Buffer,1,sizeof(Buffer), fs)) > 0)
{
if((resultEnviar = send(ClientSocket,Buffer,len,0)) < 0){
printf("ERROR: Failed to send file %s.\n", nombreArchivoADescargar.c_str());
break;
}
sumEnviada+=resultEnviar;
}
fclose(fs);
Client receiveFile code:
//shutdown(sock, SD_SEND); ???????
do{
recvVal = recv(sock, Buffer2, sizeof(Buffer2), 0);
if (recvVal <= 0){
printf("Can't read from socket");
recvVal =0;
fclose(fp);
continue;
}else{
int off =0;
do{
int write_sz = fwrite(Buffer2, 1, recvVal, fp);
if (write_sz < 0){
printf("Can't write to file");
fclose(fp);
break;};
if (write_sz == 0) {cout<<endl<<"Nada que copiar"<<endl; break;}
off += write_sz;
}while(off<recvVal);
bzero(Buffer2, 1024);
contador+=off;
}
}while (contador<LongitudArchivo);
cout<<endl<<"Numero de bytes recibidos: "<<contador<<endl<<endl;
printf("Ok received from client!\n");
fclose(fp);
If I don't use the SHUTDOWN(sock, SD_SEND) I don't receive all the expected bytes but if I use it I don't know how to send more files (how to wake up the send part of the socket).
Thanks!
I don't see what shutdown() has to do with it. You should receive all the bytes either way. If you want to send multiple files, you will have to send the length ahead of each one and read exactly that many following bytes from the socket into each target file.
NB If recv() returns zero you should close the socket and break. If it returns -1 you should log the errno, e.g. via perror(), close the socket, and break.

How to use expat-parser with Russian charsets?

I tried to use expat for XML parsing, and I have Russian symbols in XML file, this symbols incorrectly interpret by expat.
I got expired_str: Русский текст
Instead of: Русский текст
Here is my cutted code:
static int xmlParseStartup(char *buffer, int n, START_UP_T *startUp_sp)
{
void *buff;
XML_Parser parser_p = XML_ParserCreate("UTF-8");
if (!parser_p)
{
DEBUG("Unable to create parser!\n");
return RES_ERR;
}
XML_SetUserData(parser_p, (void *)startUp_sp);
XML_SetElementHandler(parser_p, startElement, endElement);
buff = XML_GetBuffer(parser_p, n);
memcpy(buff, buffer, n);
if (XML_STATUS_ERROR == XML_ParseBuffer(parser_p, n, TRUE))
{
DEBUG("%s at line %" XML_FMT_INT_MOD "u\n",
XML_ErrorString(XML_GetErrorCode(parser_p)),
XML_GetCurrentLineNumber(parser_p));
return RES_ERR;
}
return RES_OK;
}
static void XMLCALL startElement(void *userData,
const char *name,
const char **atts)
{
int i;
START_UP_T *startUp_sp = (START_UP_T *)userData;
for (i = 0; i < startUp_sp->depthPtr; i++)
{
fprintf(stderr, ".");
}
DEBUG("[%d]name: %s\n", startUp_sp->depthPtr, name);
if (0 == strcmp(name, "response"))
{
if (0 == strcmp(atts[i], "result"))
{
startUp_sp->result = atoi(atts[3]);
DEBUG("RESULT: %d\n", startUp_sp->result);
}
else if (0 == strcmp(atts[i], "status_str"))
{
strcpy(startUp_sp->expired_str, atts[3]);
DEBUG("EXPIRED_STR: %s\n", startUp_sp->expired_str);
}
else if (0 == strcmp(atts[i], "status_width"))
{
startUp_sp->status_width = atoi(atts[3]);
}
}
startUp_sp->depthPtr += 1;
}
static void XMLCALL endElement(void *userData,
const char *name)
{
START_UP_T *startUp_sp = (START_UP_T *)userData;
startUp_sp->depthPtr -= 1;
}
XML file:
<?xml version="1.0" encoding="UTF-8"?>
<startup>
<response name="result" value="0"/>
<response name="status_str" value="Русский текст"/>
<response name="status_width" value="120"/>
</startup>
You get a cp1251 representation of the UTF-8 char*-typed string, so the expat actually works fine - it is the console output you're having problems with.
If it is not the case, check for the utf8 marker at the beginning of the xml file (239, 187, 191 bytes in ASCII codes, or "п>ї" without quotes in CP-1251).
One more: You should check the actual encoding of the .xml file, looks like it is not what you think it is (utf-8). What editor do you use to create the file ?
The CP1251 representation of UTF-8 "Русский текст" string is "Р С_С_С_РєРёР№ С'РчРєС_С'".

Unzip files downloaded from server

Hi I am developing an application to download an attachment from server and read those files using Blackberry 10 Cascades(QNX Momentics IDE) . I have downloaded the attachment but the attachment is a .Zip file. How can I unzip the folder? Does anyone have samples please share?
you can use quazip library for unzipping the archive, here quazip porting for Blackberry 10 cascades
https://github.com/hakimrie/quazip
here sample function to unzip a file using quazip to extract a file into /data/ folder
bool ZipUtils::extractArchive(QString m_filename) {
// check if file exists
QFile file(m_filename);
if (!file.exists()){
qDebug() << "file is not exists gan";
return false;
}
bool result = true;
QuaZip *m_zip = new QuaZip(m_filename);
QString dataFolder = QDir::homePath();
QString bookname = m_filename.split("/").last().split(".").first();
QString dest = dataFolder + "/" + bookname;
QDir dir(dest);
if (!dir.exists()) {
// create destination folder
dir.mkpath(".");
}
qDebug() << "destination folder: " + dest;
m_zip->open(QuaZip::mdUnzip);
if (!m_zip) {
return false;
}
QuaZipFile *currentFile = new QuaZipFile(m_zip);
int entries = m_zip->getEntriesCount();
int current = 0;
for (bool more = m_zip->goToFirstFile(); more; more =
m_zip->goToNextFile()) {
++current;
// if the entry is a path ignore it. Path existence is ensured separately.
if (m_zip->getCurrentFileName().split("/").last() == "")
continue;
QString outfilename = dest + "/" + m_zip->getCurrentFileName();
QFile outputFile(outfilename);
// make sure the output path exists
if (!QDir().mkpath(QFileInfo(outfilename).absolutePath())) {
result = false;
//emit logItem(tr("Creating output path failed"), LOGERROR);
qDebug() << "[ZipUtil] creating output path failed for:"
<< outfilename;
break;
}
if (!outputFile.open(QFile::WriteOnly)) {
result = false;
//emit logItem(tr("Creating output file failed"), LOGERROR);
qDebug() << "[ZipUtil] creating output file failed:" << outfilename;
break;
}
currentFile->open(QIODevice::ReadOnly);
outputFile.write(currentFile->readAll());
if (currentFile->getZipError() != UNZ_OK) {
result = false;
//emit logItem(tr("Error during Zip operation"), LOGERROR);
qDebug() << "[ZipUtil] QuaZip error:" << currentFile->getZipError()
<< "on file" << currentFile->getFileName();
break;
}
currentFile->close();
outputFile.close();
//emit logProgress(current, entries);
}
return result;
}
please make sure to update your pro file to include quazip library (assume your project & quazip project in the same workspace/folder):
INCLUDEPATH += ../src ../../quazip/src/
SOURCES += ../src/*.cpp
HEADERS += ../src/*.hpp ../src/*.h
LIBS += -lbbsystem
LIBS += -lbbdata
LIBS += -lz
lupdate_inclusion {
SOURCES += ../assets/*.qml
}
device {
CONFIG(release, debug|release) {
DESTDIR = o.le-v7
LIBS += -Bstatic -L../../quazip/arm/o.le-v7 -lquazip -Bdynamic
}
CONFIG(debug, debug|release) {
DESTDIR = o.le-v7-g
LIBS += -Bstatic -L../../quazip/arm/o.le-v7-g -lquazip -Bdynamic
}
}
simulator {
CONFIG(release, debug|release) {
DESTDIR = o
LIBS += -Bstatic -L../../quazip/x86/o-g/ -lquazip -Bdynamic
}
CONFIG(debug, debug|release) {
DESTDIR = o-g
LIBS += -Bstatic -L../../quazip/x86/o-g/ -lquazip -Bdynamic
}
}
I used the PKZIP 2.0 compatible archive handler from the OSDaB Project, it does the job quite nicely. They provide Zip and UnZip classes. You also need to include linkage to the installed compression library by adding -lz to the LIBS variable in your .pro file:
LIBS += -lz
Sample code:
UnZip unzip;
UnZip::ErrorCode ec = unzip.openArchive(fileName);
if (ec != UnZip::Ok) {
emit errorString(fileName + " could not open archive.");
} else {
QList<UnZip::ZipEntry> fileNames = unzip.entryList();
ec = unzip.extractAll(dirName);
if (ec != UnZip::Ok) {
emit errorString(
newFileName + " could not extract data to "
+ dirName);
} else {
UnZip::ZipEntry file;
foreach(file, fileNames) {
// do something with file if needed.
}
}
}

How to get metadata info from Flac file using LibFlac

I am decoding Flac files in to wave files . After decoding file , I am getting stream info by this code
void metadata_callback(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
{
(void)decoder, (void)client_data;
/* print some stats */
if(metadata->type == FLAC__METADATA_TYPE_STREAMINFO) {
/* save for later */
total_samples = metadata->data.stream_info.total_samples;
sample_rate = metadata->data.stream_info.sample_rate;
channels = metadata->data.stream_info.channels;
bps = metadata->data.stream_info.bits_per_sample;
fprintf(stderr, "sample rate : %u Hz\n", sample_rate);
fprintf(stderr, "channels : %u\n", channels);
fprintf(stderr, "bits per sample: %u\n", bps);
#ifdef _MSC_VER
fprintf(stderr, "total samples : %I64u\n", total_samples);
#else
fprintf(stderr, "total samples : %llu\n", total_samples);
#endif
}
Now I want to fetch metadata such as album name, picture ,artist name.
For this I tried this code
FLAC__StreamMetadata *tags;
FLAC__bool success = FLAC__metadata_get_tags(infilePath, &tags);
if (success) {
printf("Got stream information");
printf("metadata %u",tags->data.vorbis_comment.num_comments);
}else {
printf("Failed to get stream information");
}
But I am getting Zero i.e 0 on console. Please help .