Sending spoofed syslog messages in Perl - perl

TL;DR I am trying to send syslog messages I have already created to a syslog server using spoofed source IPs but I'm making it really hard for myself and could do with a succinct approach
Most questions about syslog do not include the spoofed IP problem hence I am asking afresh.
I am writing (well updating) a script I wrote a long time ago that generates spoofed syslog messages (using UDP). It currently uses Net::RawIP which is terrible for portability and also the code for the transmission I wrote ages ago has decided to stop working in Perl 5 (I haven't used this for ages and I am refreshing it). I have been meaning to get rid of Net::RawIP for ages but its the only one I know how to use!
Given I have to fix it and I have a little time at the moment I probably want to move to use the Socket capability, which is what I have been playing with - using code from SO or gists or other places I can find - rather than something like IO::Socket as I need the spoofed IPs permission given a low level ability to write to sockets.
However, I have tied myself in knots with this, what I have right now forms the packets from scratch and then creates a socket and sends it, but in the processes wraps a superflous IPv4 header (I can see using wireshark) and without starting afresh I think its stuck like that as it has a fundamental flaw, hence I'm not sharing old code.
Basically, I can keep playing with the overly complicated code I have or ask for help simplify it, as I am beyond my knowledge of sockets and many hours of googling haven't helped much. What I keep finding is code that will work but it not compliant in some way - probably not an issue for what they are usually for which is for DDOS or syn attacks or whatever.
Key requirements of this are (which every attempt I have done has failed in some form!):
must come from a spoofed source IP and go to a known destination IP
(hence I'm using UDP) (both of which I have in config variables) so that the syslog server things many different devices generated the logs
must come from a set port and go to a set port (both of which I have in my
existing config variables)
must contain a message I have already formed which includes all the syslog content (the PRI and the syslog message content)
must be fully complaint with checksums and packet lengths etc when received
be as portable as possible (I'll probably embed it in my main script to keep it all in one file I can share with others).
I just feel there must be a simple and easy way to do this as everything I have is overly flexible and complicated and a nightmare to unwind.
NB This is shared in Sourceforge as "must syslog" and so you can see what I used to do but be aware its stopped working so it wont work if you run it currently! Once I fix this I'll upload a new version.
Cheers, --Chris

Actually I just had a breakthrough, I have linked the sources in the code but I found a test harness that is pretty basic and some UDP checksum code that with a bit of playing worked together and wireshark confirms its all correct
Posted in case someone else needs it as its taken me a good couple of days to get to this
#!/usr/bin/perl
use Socket;
use List::Util qw(sum);
sub udp_checksum {
# thanks to ikegami in post https://stackoverflow.com/questions/46181281/udp-checksum-function-in-perl
my $packed_src_addr = shift; # As 4-char string, e.g. as returned by inet_aton.
my $packed_dst_addr = shift; # As 4-char string, e.g. as returned by inet_aton.
my $udp_packet = shift; # UDP header and data as a string.
my $sum = sum(
IPPROTO_UDP,
length($udp_packet),
map({ unpack('n*', $_) }
$packed_src_addr,
$packed_dst_addr,
$udp_packet."\0", # Extra byte ignored if length($udp_packet) is even.
),
);
while (my $hi = $sum >> 16) {
$sum = ($sum & 0xFFFF) + $hi;
}
return ~$sum & 0xFFFF;
}
#this was found and adapted from http://rhosted.blogspot.com/2009/08/creating-udp-packetip-spoofing-through.html
$src_host = $ARGV[0];
$dst_host = $ARGV[1];
$src_port = 33333;
$dest_port = 514;
$cksum = 0; #initialise, we will sort this later
#$udp_len is the udp packet length in the udp header. Its just 8 plus the length of the data
#for this test harness we will set the data here too
$data = "<132> %FWSM-3-106010: Deny inbound tcp src outside:215.251.218.222/11839 dst inside:192.168.1.1/369";
$udp_len = 8+length($data);
$udp_proto = 17; #17 is the code for udp
#Prepare the udp packet, needed for the checksum to happen, then get the checksum (horrifically complicated, just google it)
$udp_packet = pack("nnnna*", $src_port,$dest_port,$udp_len, $cksum, $data);
$cksum = udp_checksum(inet_aton($src_host),inet_aton($dst_host),$udp_packet);
$zero_cksum = 0;
#test harness checks about host IPs
my $dst_host = (gethostbyname($dst_host))[4]; my $src_host = (gethostbyname($src_host))[4];
# Now lets construct the IP packet
my $ip_ver = 4;
my $ip_len = 5;
my $ip_ver_len = $ip_ver . $ip_len;
my $ip_tos = 00;
my ($ip_tot_len) = $udp_len + 20;
my $ip_frag_id = 19245;
my $ip_frag_flag = "010";
my $ip_frag_oset = "0000000000000";
my $ip_fl_fr = $ip_frag_flag . $ip_frag_oset;
my $ip_ttl = 30;
#H2H2nnB16C2na4a4 for the IP Header part#nnnna* for the UDP Header part.
#To understand these, see the manual of pack function and IP and UDP Header formats
#IP checksum ($zero_cksum is calculated by the kernel. Dont worry about it.)
my ($pkt) = pack('H2H2nnB16C2na4a4nnnna*',
$ip_ver_len,$ip_tos,$ip_tot_len,$ip_frag_id,
$ip_fl_fr,$ip_ttl,$udp_proto,$zero_cksum,$src_host,
$dst_host,$src_port,$dest_port,$udp_len, $cksum, $data);
#bit that makes the socket and sends the packet
socket(RAW, AF_INET, SOCK_RAW, 255) || die $!; setsockopt(RAW, 0, 1, 1);
my ($destination) = pack('Sna4x8', AF_INET, $dest_port, $dst_host);
send(RAW,$pkt,0,$destination);

Related

PERL - Net::Websocket::Server with external periodic event

In my server program I need to have ability to iterate every 5 minutes through all opened connections and see which is really "active" or not.
I know that the best approach is to use "heart beat", but then, the server need to have somehow ability to check weather the connection is "off" in order to delete the associated "user parameters" that is attached to the connection.
My first approach was to use "Async" module, but this works in a separate process - so I cannot delete any element from the main process unless I use a technique to invoke a subroutine from the main process called from the child process (I don't know how, any help will be warmly welcomed).
Another possibility using Async is create a static client that is all the time on (also in the server) and sending "commands" to the server, but to me it looks "too exaggerating" to create such "wasting memory" client in the server, and also "eat" CPU time (I think much more than simple event like equivalent to "setTimeout" in JS).
Yet another approach is to use EV: But when I call EV::run it will NOT RUN anything ELSE than this "periodic event" - means that it will not reach the next line where the ->Start for the server is.
Placing it after the ->Start will make this event useless too: As the server works the program will not go behind the ->Start line.
Using EV::run EV::RUN_NOWAIT; will make the server work, but the EV will somehow not work, for a strange reason (Anyone know how can I still make it work?)
I prefer to not use Net::Websocket::EV, because as per their script, it doesn't do the handshake automatically, and many things (as well as SSL connection that I have) I will need to do manually and for me it is change a lot in my program.
PROBLEM SUMMARY:
How to make the code in EV run every 5 minutes, together with the server?
my %CON; # Connections (And user data) hash
my $__ConChk=EV::periodic 0, 300, 0, sub {
my #l=keys %CON;
for(my $i=0 ; $i<#l ; $i++) {
if($CON{$l[$i]}{"T"}+3600<time()) { # I give one hour time to be completely offline (for different reasons)
$CON{$l[$i]}{"C"}->disconnect(); delete $CON{$l[$i]};
}
}
};
EV::run EV::RUN_NOWAIT; # This is not working - Seems to be ignored!
Net::WebSocket::Server->new(
listen => $ssl, # Earlier preset
silence_max=>60, # Time to just shut the connection off, but don't delete user data
on_connect => sub {
my($serv,$conn)=#_;
my $cid; # Connection ID (for the hash)
$conn->on(
handshake => sub {
my($conn,$handshake)=#_;
# Create user data in $CON{$cid}
},
binary => sub {
$CON{$cid}{"T"}=time();
# Handling of single incomming message (command)
},
disconnect => sub {
# Do NOT DELETE THE ENTRY!! Maybe the connection drop due to instability!!
}
);
}
)->start; # This will run - but ignoring EV::run - what to do....?
undef $__ConChk;

ZMQ socket - disconnect when all request are served

I am trying to implement ZMQ REQ/REP model in Java
I have a Server-role, running on post 5564, which acts as Replier
ZMQ.Socket repSock = context.socket(ZMQ.REP);
I have a Client-role, running on post 5563
ZMQ.Socket syncclient = context.socket(ZMQ.REQ);
I have a proxy-server in middle, which passes request and response
ZMQ.proxy(reqSocket, repSocket, null);
Good thing about having a proxy is I can add multiple Servers
repSocket.connect("tcp://" + addr.getHostAddress() + ":" + port);
Which is working fine .
Now, when I remove a Server node from Proxy
repSocket.disconnect("tcp://" + addr.getHostAddress() + ":" + port);
Client gets stuck, as an request has being made and the REQ-socket waits for a response.
So the process stucks at syncclient.recvStr()
for (int request_nbr = 0; request_nbr < (request_nbr + 1); request_nbr++) {
syncclient.send(str.getBytes(),0);
System.out.println("Send Dataaaa....... " );
String data = syncclient.recvStr(Charset.defaultCharset());
System.out.println(" here.. " +data);
request_nbr++;
}
I searched and couldn't find a way to track the REQ-socket
I need any one of 2 things:
A way to keep track on a Socket-instance, which I am about to disconnect, wait till all messages are processed, so that syncclient.recvStr() will not be blocked
A way to reset the syncclient-socket, so that I can keep getting REQ/REP respond without an interruption
In real-world scenarios, rather avoid using a blocking-mode of the ZeroMQ .send() / .recv() methods and better use .poll().
While this may require a bit more SLOCs of code, the results are leaving you in a control, whereas a blocking SLOC takes all the control from your code and you cannot do much about that until ( if at all ) a next message gets delivered. That's a very wrong design practice and except the most simplistic schoolbook examples, that are actually sort of anti-patterns for the real-world.
So, do not expect Question 2 to become somehow magically solved, this is not a part of ZeroMQ API ( for many rather aloud evangelisated reasons ). Better decide between .setsockopt( ZMQ.REQ_RELAXED, 1 ), if API version and context of use permits, or do not use the trivial REQ/REP pattern at all ( due it's known risk of falling into an unsalvageable mutual dead-lock ( ref. other my posts on this very subject, where this phenomenon was both illustrated and countless times explained ) ).
In a similar manner, asking Question 1 seems reasonable in cases you have never read the ZeroMQ specifications and/or documentation and ZeroMQ "Best Practices". Having spent some time in this, your options would be crystal-clear. There are none such tools for doing this built-in. One can add some add-on, if in a need to add any similar non-core logic for her/his own need. The only setting that indirectly influences the behaviour on aSocket.close() is available in .setsockopt( ZMQ.LINGER, 0 ), which may help to prevent a system from a transition into an effective hangup-state, once aSocket waits infinitely for a state that will never happen in cases, when a message-queue is still non-empty ( messages still waiting for getting delivered ).
Going into Distributed-Systems design is like entering a new world. No sequences are guarranteed ( non-serial code execution paths happen ). No means of any local control of remote entities, their states, their failures, their presence at all, their actual ZeroMQ API version.
Indeed a challenging world to enter into.
N.b.:
You might already know, that one can .connect() aSocket-instance ( better an Access Point to aSocket-instance ) to more than one remote ends without using the proxy. With some additional .setsockopt() tuning ZMQ.IMMEDIATE to a value of 1, will help better manage the round-robin distribution policy, irrespective of the transport-classes used for the actual message delivery ( { tcp:// | ipc:// | vmci:// | pgm:// | epgm:// | inproc:// } ). All that at your fingertips.

AutoIT TCP Protocol

Witam.
I'm trying to send in a scripting language AutoIT using the TCP Send to type Hex Socket data.
I do this in the following way:
_AutoItObject_StartUp()
Global $oTCP = _Class_TCPClient($ip,$port)
Previously, $ip and $port is entered manually.
TCPStartup() is included in _Class_TCPClient.
Class_TCPClient - constructor.
$oTCP.Connect()
Local $string = _HexToString(0xBB01C8007F010140)
Local $ret = $oTCP.Send($string)
But it does not work.
When you preview frames using Wireshark data field looks quite different.
The target script which is communication protocol for device from company where I'm working.
You can try the BinaryToString function.
Do not forget to use quotes: BinaryToString("0x...")
I have tried it and in my opinion this is the best option to send this frame.
The problem is whenever i change frame, then it sends the same data.

parallely execution of perl language

I have a perl program that read the packets of a flow from a pcap file, but it takes a lot of time,I want to make it parallel,but I don't know is it possible or not?if yes can I do it with MPI?and another question, the best way for making this code parallel,here is the piece of my code ( I think I should work on this part for paralleling, but I don't know the best way!)
while (!eof($inFileH))
{
#inFileH is the handler of the pcap file
#in each while I read one packet
$ts_sec = readBytes($inFileH,4);
$ts_usec = readBytes($inFileH,4);
$incl_len = readBytes($inFileH,4);
$orig_len = readBytes($inFileH,4);
if ($totalLen == 0) # it is the 1st packet
{
$startTime = $ts_sec + $ts_usec/1000000;
}
$timeStamp = $ts_sec + $ts_usec/1000000 - $startTime;
$totalLen += $orig_len;
$#packet = -1; n # initing the array
for (my $i=0 ; $i<$incl_len ; $i++) #read all included octects of the current packet
{
read $inFileH, $packet[$i], 1;
$packet[$i] = ord($packet[$i]);
}
#and after that I will work on the "packet" and analyze it
so how should I send the file content for other processors to work on it in parallel.....
First you need to determine the bottleneck. If it is really CPU usage (i.e. CPU usage is at 100% while you are running the script), you need to figure out where the processing spends its time.
This may well be in the way that you are parsing the input. There may be obvious ways to speed this up. For instance, if you use complex regular expressions, and focus exclusively on matching input correctly, there may be ways to make the matching a lot faster by rewriting the expressions or doing simpler matches before trying more complex ones.
If you can't reduce CPU usage far enough in this way, and you really want to parallelize, see if you can employ the mechanism with which Perl was born: Unix pipes. You can write Perl scripts that pass data through to each other in a pipeline, or you can do the creation of the processes and pipes within Perl itself (see perlopentut, and if that isn't enough, perlipc).
As a general rule, I would consider these options first before trying other mechanisms, but it really depends of the details of what you're trying to do and the context in which you need to do it.

R socketConnection/make.socket(): any way to keep listen()ing?

[Disclaimer: my knowledge of sockets is very rusty, and I'm just getting into R, so if I missed something completely obvious, please point it out!]
If I understand the (sparsely-documented) R functions for creating and managing sockets, namely socketConnection and make.socket, it appears that when creating a server socket (server=TRUE), the moral equivalent of the following is carried out:
s = socket(yada yada);
listen(s, ...);
s2 = accept(s, ...);
close(s, ...);
and now I can work with s2 but can't loop to deal with a backlog of incoming connections to s. Is this more-or-less right? Is there any way to keep listening and continue to deal with additional incoming connections after handling the first?
I'd like to know the answer to this one too! ...but in the meantime I can at least suggest a work-around with some limitations:
If you can know HOW MANY clients will connect, then the following should work.
On the server:
n=2 # Number of clients
port=22131
slist=vector('list',n)
# Connect to all clients
for(i in 1:n) slist[i] <- socketConnection('localhost', port=port, server=TRUE)
# Wait for a client to send data, returns the client index
repeat {
avail <- which( socketSelect(slist) )[[1]]
# ...then read and process data, rinse, repeat...
}
On each client:
port=22131
# Connect to server
s <- socketConnection('localhost', port=port)
# ...then send data...
writeLines(c('foo', 'bar'), s)
No, you can touch the back-log on s1.
Window 1:
$ R
s1 = socketConnection(server=T,port=12345)
s2 = socketConnection(server=T, port=98765)
Window 2:
$ nc localhost 12345
If ever I should leave you, it wouldn't be in springtime
Knowing how in spring I'm bewitched by you so
oh no not in springtime, summer, winter, or fall
no never could I leave you at all
Window 3:
$ nc localhost 98765
for Hitler and Germany
Deutschland is happy and gay
we're marching to a faster pace
look out, here comes the Master Race!
Window 1:
readLines(s1,1)
# "if ever I should leave you, it wouldn't be in springtime"
readLines(s2,1)
# "for Hitler and Germany"
readLines(s1,1)
# "knowing how in spring I'm bewitched by you so"