Strange goings on with port 37, (Thu, Jun 3rd)

This post was originally published on this site

Similar to Yee Ching's diary on Thursday, I noticed an oddity in the Dshield data last weekend (which I had hoped to discuss in a diary on Wednesday, but life got in the way) and thought it was worth asking around to see if anyone knows what is going on. As soon as I saw it, I reconfigured my honeypots to try to capture the traffic, but wasn't able to. I'm always very interested when I see some of the legacy ports and protocols pop up. In this case, %%port:37%% is the time protocol which operates on both TCP and UDP and is one of the many services that frequently ran on the low ports of Unix machines I administered back in the 1980s and 1990s. In recent years, most operating systems have disabled these services since they only seemed to be used for DDoS purposes. On Thursday, I took another look at the graph.

By default, we normally only show the Targets/Day and Sources/Day, but I've added in the Reports/Day and TCP Ratio for this analysis. The first thing that I noticed was the huge spike in reports. Our baseline was in the 200-500 reports/day range, but on 26 May, this jumped to around 46,000. So someone, was very actively looking, the other oddity to me was, that prior to the spike, nearly all of the probes were TCP, but from 25 May – 2 Jun, nearly all the attack traffic was UDP (the gold line on the graph above, ranges from 0 = all UDP to 100 = all TCP), which then seemed to disappear and return to the mostly TCP probes on 3 Jun when I took this snapshot. Since I was unable to capture any of the packets, I don't know if there was some strange data there that might have shed some light on the purpose of this activity. The total number of sources was still pretty small ranging from a low of 69 on 25 May to 176 on 2 Jun. Meanwhile the number of targets ranged from 156 on 25 May to almost 700 on 27 May, which is right in the range of targets we've seen for the past 10 months (there was a flurry of activity on the port last June and July that spiked regularly around 2400-2500 targets, not shown in the graph above). 

So, I'm not sure what to make of it, especially without any packets. If any of you managed to capture any of this traffic last weekend and early this past week and care to share, we'd love to have a look. Otherwise, if you have any insight into what was going on, please share below or via our contact form. I'm always very curious about these traffic oddities.

—————
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.

Fake News

This post was originally published on this site

Fake news is a false narrative that is published and promoted as if it were true. People (and organizations) create fake news to control and manipulate your thoughts and actions. Be skeptical of what you read on the Internet, use trusted sources that are vetted, check their motivations and funding.

DShield Data Analysis: Taking a Look at Port 45740 Activity, (Thu, Jun 3rd)

This post was originally published on this site

At the SANS Internet Storm Center (ISC), handlers frequently analyze data submitted from DShield participants to determine activity trends and potential attacks. A few days ago on May 31st, I observed a small anomaly for %%port:45740%% and decided to monitor it for the next 3 days or so. There was a huge spike in number of sources/day and reports/day recorded on May 31st as shown in Figure 1.

Figure 1: Port 45740 Activity (Taken June 1, 2021)

I did not receive any probes on this port on my sensors, but after digging into the DShield data, it was observed that the reported traffic to port 45740 were sent via UDP.

Over the next few days (till June 3, 2021), the number of sources/day and reports/day have dropped drastically as compared to May 31 (with reference to Figure 2). A check on Censys and Shodan did not yield any interesting findings, although there were some mentions of Distributed Hash Table (DHT) along with some IP addresses and port 45740 as a pair.

Figure 2: Port 45740 Activity (Taken June 3, 2021)

If anyone has any insights or information that could help shed light on this phenomenon, please comment down below, contact us via our contact page or e-mail us.

———–
Yee Ching Tok, ISC Handler
Personal Site
Twitter

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

PowerShell for Visual Studio Code May 2021 Update

This post was originally published on this site

We are excited to announce that an update to our PowerShell extension is now available on the Visual Studio Code Marketplace. This blog will explain what is new in this release as well as what you can expect from the extension in the coming months.

What’s new in the PowerShell Extension release

This incremental release incorporates a major update to OmniSharp, the Language Server Protocol library we use (like many other VSCode extensions). Behind the scenes there has also been a concerted effort to improve our build and release processes, with the intention of accelerating our release cadence.

Some highlights of the release include:

Since we have disabled semantic highlighting by default now, if you wish to re-enable it, use:

"[powershell]": {
    "editor.semanticHighlighting.enabled": true
}

The intention of this change is to reduce issues while the semantic highlighting backend is improved.

We now also remove - and $ from the word separators by default for PowerShell files. To add them back, use:

"[powershell]": {
    "editor.wordSeparators": "`~!@#$%^&*()-=+[{]}|;:'",.<>/?"
}

The intenion of this change is to increase predictability, as double-clicking PowerShell variables now selects the same portion that the extension highlights (with the exception of scoped variables due to the continued inclusion of : as a word separator).

For the full list of updates please refer to the changelog.

More about the OmniSharp update

The most significant change is the update to OmniSharp v0.19.2, from the previous version v0.18.3, released in November 2020. OmniSharp is the underlying Language Server Protocol (LSP) and Debug Adapter Protocol (DAP) server library, and as such is our biggest dependency. This update brings us to the LSP 3.16 and DAP 1.48.x specifications, enabling us to start incorporating all the latest LSP changes, and it includes numerous bug fixes and enhancements resulting in a faster and more stable server and extension experience.

After our initial upgrade to OmniSharp v0.19.0, as early adopters we encountered two major bugs in the library. Rob and Andy spent a month identifying and solving a serialization bug in the Debug Adapter Protocol which would have broken the extension’s debugger, and a race condition which temporarily impacted startup reliability in the preview extension. As our fixes went upstream, we improved the OmniSharp library not only for the PowerShell extension, but also for several other Visual Studio Code extensions similarily relying on OmniSharp.

What’s next for the extensions

Over the coming months we plan to continue work on the Editor Services pipeline stability (intellisense, formatting, etc.), work to maintain compatibility with changes to Visual Studio Code, and improve testing infrastructure (to allow for more community contribution and more predictability with preview releases). You can track the progress on all of these projects, and others on our roadmap, in our GitHub repository.

Getting support and giving feedback

If you encounter any issues with the PowerShell extension in Visual Studio Code or have feature requests, the best place to get support is through our GitHub repository.

Sydney Smith, Andy Schwartzmeyer, Rob Holt

PowerShell Team

The post PowerShell for Visual Studio Code May 2021 Update appeared first on PowerShell Team.

Wireshark 3.4.6 (and 3.2.14) released, (Wed, Jun 2nd)

This post was originally published on this site

A new version of wireshark is out, a couple of bugfixes including a QUIC TLK decryption issue. Also, the Windows version now comes with npcap 1.31 (updated from 1.10).

Find the source code and installation pkgs at https://www.wireshark.org/download.html

—————
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.

Amazon Location Service Is Now Generally Available with New Routing and Satellite Imagery Capabilities

This post was originally published on this site

In December of 2020, we made Amazon Location Service available in preview form for you to start building web and mobile applications with location-based features. Today I’m pleased to announce that we are making Amazon Location generally available along with two new features: routing and satellite imagery.

I have been a full-stack developer for over 15 years. On multiple occasions, I was tasked with creating location-based applications. The biggest challenges I faced when I worked with location providers were integrating the applications into the existing application backend and frontend and keeping the data shared with the location provider secure. When Amazon Location was made available in preview last year, I was so excited. This service makes it possible to build location-based applications with a native integration with AWS services. It uses trusted location providers like Esri and HERE and customers remain in control of their data.

Amazon Location includes the following features:

  • Maps to visualize location information.
  • Places to enable your application to offer point-of-interest search functionality, convert addresses into geographic coordinates in latitude and longitude (geocoding), and convert a coordinate into a street address (reverse geocoding).
  • Routes to use driving distance, directions, and estimated arrival time in your application.
  • Trackers to allow you to retrieve the current and historical location of the devices running your tracking-enabled application.
  • Geofences to give your application the ability to detect and act when a tracked device enters or exits a geographical boundary you define as a geofence. When a breach of the geofence is detected, Amazon Location will send an event to Amazon EventBridge, which can trigger a downstream set of actions, like invoking an AWS Lambda function or sending a notification using Amazon Simple Notification Service (SNS). This level of integration with AWS services is one of the most powerful features of Amazon Location. It will help shorten your application’s time to production.

In the preview announcement blog post, Jeff introduced the service functionality in a lot of detail. In this blog post, I want to focus on the new two features: satellite imagery and routing.

Satellite Imagery

You can use satellite imagery to pack your maps with information and provide more context to the map users. It helps the map users answer questions like “Is there a swamp in that area?” or “What does that building look like?”

To get started with satellite imagery maps, go to the Amazon Location console. On Create a new map, choose Esri Imagery. 

Creating a new map with satellite imagery

Routing
With Amazon Location Routes, your application can request the travel time, distance, and all directions between two locations. This makes it possible for your application users to obtain accurate travel-time estimates based on live road and traffic information.

If you provide these extra attributes when you use the route feature, you can get very tailored information including:

  • Waypoints: You can provide a list of ordered intermediate positions to be reached on the route. You can have up to 25 stopover points including the departure and destination.
  • Departure time: When you specify the departure time for this route, you will receive a result optimized for the traffic conditions at that time.
  • Travel mode: The mode of travel you specify affects the speed and the road compatibility. Not all vehicles can travel on all roads. The available travel modes are car, truck and walking. Depending on which travel mode you select, there are parameters that you can tune. For example, for car and truck, you can specify if you want a route without ferries or tolls. But the most interesting results are when you choose the truck travel mode. You can define the truck dimensions and weight and then get a route that is optimized for these parameters. No more trucks stuck under bridges!

Amazon Location Service and its features can be used for interesting use cases with low effort. For example, delivery companies using Amazon Location can optimize the order of the deliveries, monitor the position of the delivery vehicles, and inform the customers when the vehicle is arriving. Amazon Location can be also used to route medical vehicles to optimize the routing of patients or medical supplies. Logistic companies can use the service to optimize their supply chain by monitoring all the delivery vehicles.

To use the route feature, start by creating a route calculator. In the Amazon Location console, choose Route calculators. For the provider of the route information, choose Esri or HERE.

Screenshot of create a new routing calculator

You can use the route calculator from the AWS SDKs, AWS Command Line Interface (CLI) or the Amazon Location HTTP API.

For example, to calculate a simple route between departure and destination positions using the CLI, you can write something like this:

aws location 
    calculate-route 
        --calculator-name MyExampleCalculator 
        --departure-position -123.1376951951309 49.234371474778385 
        --destination-position -122.83301379875074 49.235860182576886

The departure-position and destination-positions are defined as longitude, latitude.

This calculation returns a lot of information. Because you didn’t define the travel mode, the service assumes that you are using a car. You can see the total distance of the route (in this case, 29 kilometers). You can change the distance unit when you do the calculation. The service also returns the duration of the trip (in this case, 29 minutes). Because you didn’t define when to depart, Amazon Location will assume that you want to travel when there is the least amount of traffic.

{
    "Legs": [{
        "Distance": 26.549,
        "DurationSeconds": 1711,
        "StartPosition":[-123.1377012, 49.2342994],
        "EndPosition": [-122.833014,49.23592],
        "Steps": [{
            "Distance":0.7,
            "DurationSeconds":52,
            "EndPosition":[-123.1281,49.23395],
            "GeometryOffset":0,
            "StartPosition":[-123.137701,49.234299]},
            ...
        ]
    }],
    "Summary": {
        "DataSource": "Esri",
        "Distance": 29.915115551209176,
        "DistanceUnit": "Kilometers",
        "DurationSeconds": 2275.5813682980006,
        "RouteBBox": [
            -123.13769762299995,
            49.23068000000006,
            -122.83301399999999,
            49.258440000000064
        ]
    }
}

It will return an array of steps, which form the directions to get from departure to destination. The steps are represented by a starting position and end position. In this example, there are 11 steps and the travel mode is a car.

Screenshot of route drawn in map

The result changes depending on the travel mode you selected. For example, if you do the calculation for the same departure and destination positions but choose a travel mode of walking, you will get a series of steps that draw the map as shown below. The travel time and distance are different: 24.1 kilometers and 6 hours and 43 minutes.

Map of route when walking

Available Now
Amazon Location Service is now available in the US East (N. Virginia), US East (Ohio), US West (Oregon), Europe (Frankfurt), Europe (Ireland), Europe (Stockholm), Asia Pacific (Singapore), Asia Pacific (Sydney), and Asia Pacific (Tokyo) Regions.

Learn about the pricing models of Amazon Location Service. For more about the service, see Amazon Location Service

Marcia

Guildma is now using Finger and Signed Binary Proxy Execution to evade defenses, (Mon, May 31st)

This post was originally published on this site

 

We recently identified a new Guildma/Astaroth campaign targeting South America, mainly Brazil, using a new variant of the malware. Guildma is known by its multiple-staged infection chain and evasion techniques to reach victim’s data and exfiltrate them. In a previous diary [1] at Morphus Labs, we analyzed a Guildma variant which employed an innovative strategy to stay active, using Facebook and YouTube to get a new list of its C2 servers.

The innovation this time is the use of Finger, an old service designed to retrieve information about a particular user or host on a network but employed by Guildma to retrieve the command that will download and start the new victim’s computer infection. In addition, Guildma is bringing its own legit binary to the victim’s machine to employ a technique named Signed Binary Proxy Execution, reducing the chances of being detected.

In today’s diary, check the results of the analysis of this new variant along with MITRE ATT&CK TTPs and IOCs. To start, look at Figure 1. This is the traffic generated by the new variant while contacting attackers’ Finger server and receiving back the malicious command to be executed.

Figure 1 – Guilma traffic while contacting attackers’ Finger server

 

Threat Analysis

                

Figure 2 – New Guildma variant analysis

               The ongoing campaign starts with an e-mail phishing with a link to a ZIP file which contains an LNK. If the user executes the LNK file, instead of opening a supposed PDF with a proof of payment (Comprovante.pdf7.lnk), it will execute Windows native binary Finger.exe do retrieve the malicious command from attacker’s server on port TCP/79 and pass it to ‘cmd’ to get it executed.

                The malicious LNK file is prepared to ‘cmd.exe’ with an obfuscated argument, as seen in Figure 3.

Figure 3 – LNK content

               Analyzing the environment variables created by the above argument, it is possible to see the arguments which will be passed to ‘cmd.exe’. Surprisingly, it calls finger.exe, a native Windows binary to an old service, and pipes its results to a new cmd, as seen in Figure 4.

Figure 4 – Deobuscated arguments

               The result of the finger execution is another obfuscated command with a list of environment variables, as seen in Figure 5.

Figure 5 – Result of finger execution

               Once executed, the above command will create a JS file containing a VB Script on “%Public%Videos” and execute it. This execution will result in five more files downloaded and stored into a random path into Videos, as seen in Figure 6. The download is performed using the legitimate binary bitsadmin.exe.

Figure 6 – JS and random directory created by Guildma to store malicious artifacts

               The downloaded files are listed in Figure 7.

Figure 7 – Downloaded artifacts

               The ‘ctfmon.exe’, despite the name, is in fact, a copy of a legitimate binary named ‘coregen.exe’ which is part of Microsoft Silverlight product, as seen in Figure 8.

Figure 8 – ‘coregen.exe’ legitimate binary brought over by the attackers

               The ‘coregen.exe’ binary is used to load ‘helper.dll’ in a technique named Signed Binary Proxy Execution (T1218) [2]. It is like DLL Side Loading attack, but here the DLL name is passed as argument, as seen in Figure 9. In other words, the attacker is bringing the ‘coregen.exe’ legitimate binary to the victim’s machine and using it as a rundll32 to have its malicious DLL loaded into it as a strategy to evade security controls.

Figure 9 – Coregen.exe used to load malicious DLL

               This type of misuse of ‘coregen.exe’ is mapped by Stronic [3], as seen in Figure 10.

Figure 10 – Possible misuse of ‘coregen.exe’ by Stronic

 

Once loaded, the ‘helper.dll’ will decrypt and load the other DLLs ‘log32.dll’ and ‘log33.dll’ previously downloaded. In the Figure 11 I highlight the routing which decrypts the DLL contents.

 

Figure 11 – Log32.dll decrypt routine

And finally, once loaded, Log32.dll will perform multiple anti-debugging, anti-vm and a series of system verification, like keyboard type and system language, the presence of a DLL belonging to Diebold Warsaw (wslbscr32.dll), before unpacking and launching information stealer procedures.

Final Considerations

Reflecting on the use of Finger on this new variant, a possible reason that came to my mind was the attempt to bypass security filters that are usually applied to the HTTP/HTTPS traffic. Even employees in home office, may have some type of web browsing filter applied by the company, like web proxies. However, it may not be so common for home firewalls to make a more restrictive Internet outgoing filter, preventing, for example, the exit to the TCP/79 port. In the end, as much as the content travels in clear text on Finger, the attacker may end up having more luck with this strategy than if he used the most common path.

Finally, it is interesting to highlight the use of Signed Binary Proxy Execution technique by the new Guildma variant. Binaries signed with trusted digital certificates can execute on Windows systems protected by digital signature validation – specially those signed by Microsoft, as ‘coregen.exe’.

There are mitigations and detection strategies for Signed Binary Proxy Execution mapped on MITRE ATT&CK [2] which include restricting the execution of particularly vulnerable binaries to privileged accounts that need to use them and establish a baseline for processes and command line parameters for signed binaries to monitor and spot uncommon usage. There is a great project named LOLBAS [5] (Living Off The Land Binaries and Scripts) which maps ‘coregen.exe’ and other binaries that could be abused in a similar way.

References

[1] https://isc.sans.edu/diary/Guildma+malware+is+now+accessing+Facebook+and%A0YouTube+to+keep+up-to-date/25222

[2] https://attack.mitre.org/techniques/T1218/

[3]https://strontic.github.io/xcyclopedia/library/coregen.exe-3BF709AEDF5042C39515756FB72E9EC0.html

[4]https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/finger

[5] https://github.com/LOLBAS-Project/LOLBAS

 

IOCs

Category

Type

Value

Comment

Artifacts dropped

sha256

412a6b755b2029126d46e7469854add3faa850f5a4700dd1e078fcc536ca418a

ctfmon.exe (coregen.exe) – legitimate file being used to start malicious helper.dll

Artifacts dropped

sha1

5f536e6701d928dd262d475cd6987777b9fa5e33

ctfmon.exe (coregen.exe) – legitimate file being used to start malicious helper.dll

Artifacts dropped

md5

3bf709aedf5042c39515756fb72e9ec0

ctfmon.exe (coregen.exe) – legitimate file being used to start malicious helper.dll

Artifacts dropped

sha256

4fe8e09c61858df60222c5188af91b934d1358ee802d6dc06b4a25e162a71413

helper.dll

Artifacts dropped

sha1

cc19f43dbc98a5f471bb9fc926da6e9b190a925c

helper.dll

Artifacts dropped

md5

1d270124b1e61f21eed666afc4e60d9a

helper.dll

Artifacts dropped

sha256

7889a7cc80dabc034cd02a3667e1f0028332669ca5ccf9a66b4f853064968158

log32.dll

Artifacts dropped

sha1

883bba850a4a6b84bb734841de823c25e09cc4dd

log32.dll

Artifacts dropped

md5

ea6ebcf305585d692fc4d519c94ed215

log32.dll

Artifacts dropped

sha256

5abfff61dcde664006db334859055d22da3b419e2fa2ae734bec48688c564dea

log33.dll

Artifacts dropped

sha1

6aa3cd190f670671c2a93076dc1a77a551dfc3d3

log33.dll

Artifacts dropped

md5

126058c017ca37541da16c5ab6d91257

log33.dll

Payload installation

sha256

9f61fc62aa9734406c164decc00f9c027574c4c5f6865d5fb297fb431f75c3bb

Rt6.js

Payload installation

sha1

77f1cc8b7ce1cbffe91f050cb1e7f790de62e257

Rt6.js

Payload installation

md5

50222aecc6a722564bb5844fa07af4d0

Rt6.js

Network activity

ip-dst

45.79.215.94

 

Network activity

domain

martin21.xyz

 

Network activity

domain

martin23.xyz

 

Network activity

domain

martin24.xyz

 

Network activity

domain

martin05.xyz

 

Network activity

domain

martin17.xyz

 

Network activity

domain

martin27.xyz

 

Network activity

domain

martin06.xyz

 

Network activity

domain

martin03.xyz

 

Network activity

domain

martin04.xyz

 

Network activity

domain

martin02.xyz

 

Network activity

domain

martin01.xyz

 

Network activity

domain

martin08.xyz

 

Network activity

domain

martin07.xyz

 

Network activity

domain

martin10.xyz

 

Network activity

domain

martin11.xyz

 

Network activity

domain

go8357.xyz

 

Network activity

domain

alinester07.xyz

 

Network activity

domain

martin19.xyz

 

Network activity

domain

martin18.xyz

 

Network activity

domain

martin16.xyz

 

Network activity

domain

martin15.xyz

 

Network activity

domain

martin14.xyz

 

Network activity

domain

martin13.xyz

 

Network activity

domain

martin12.xyz

 

Network activity

domain

martin31.xyz

 

Network activity

domain

martin30.xyz

 

Network activity

domain

martin29.xyz

 

Network activity

domain

martin28.xyz

 

Network activity

domain

martin26.xyz

 

Network activity

domain

martin25.xyz

 

Network activity

domain

martin22.xyz

 

Renato Marinho
Morphus Labs| LinkedIn|Twitter

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

Quick and dirty Python: nmap, (Mon, May 31st)

This post was originally published on this site

Continuing on from the "Quick and dirty Python: masscan" diary, which implemented a simple port scanner in Python using masscan to detect web instances on TCP ports 80 or 443.  Masscan is perfectly good as a blunt instrument to quickly find open TCP ports across large address spaces, but for fine details it is better to use a scanner like nmap that, while much slower, is able to probe the port to get a better idea of what is running.

First lets backtrack.  Since the previous diary, I converted the masscan code to a function and created another function to parse the masscan results to return the list of IPs on which masscan detected open ports.  The current script scan_web.py script is:

#!/usr/local/bin/python3
import sys,getopt,argparse
import masscan
import pprint

def scan_masscan(ips):

   try:
      maso = masscan.PortScanner()
      maso.scan(ips, ports='80,443')
   except:
      print("Error:", sys.exc_info()[0])
      sys.exit(1)

   return(maso)

def parse_masscan_host_list(massout):

    #initialize
    host_list = list()

    # Build a list from the massscan output
    for host in massout.all_hosts:
       host_list.append(host)
    return(host_list)

def main():
   # read in the IP parameter 
   parser = argparse.ArgumentParser()
   parser.add_argument('IP', help="IP address or range")
   args=parser.parse_args()
   ip=args.IP

   maso=scan_masscan(ip)

   if int(maso.scanstats['uphosts']) > 0:
      host_list=parse_masscan_host_list(maso)
      pprint.pprint(host_list)

   else:
      print("No Masscan results")
      sys.exit(1)

if __name__ == "__main__":
    main()

Running the script results in a list of IPs where either 80 or 443 were detected open by masscan.

# ./scan_web.py 45.60.103.0,45.60.31.34,1.2.3.4
[2021-05-31 18:28:51,335] [DEBUG] [masscan.py 10 line] Scan parameters: "masscan -oX - 45.60.103.0,45.60.31.34,1.2.3.4 -p 80,443"
['45.60.103.0', '45.60.31.34']

Extending this script to pass the masscan output list to nmap is relatively easy as well.  As somebody pointed out on a comment to the last diary, there are a lot of Python nmap modules and they all provide differing functionality.  After messing with a few of them, as the comment stated, the libnmap module appears to be the most functional and easiest to use.  libnmap does not implement nmap functionality, it needs nmap already installed on the device and interfaces with that version.  I will not be going over nmap functionality in this diary. If you are not clear on the nmap command parameters you can find a quick tutorial in this older diary.

To implement the nmap scan will require two functions.  One to run the scan, and one to parse the results.

The scanning function:

def scan_nmap(ip_list):
    print("Starting nmap for: {0}".format(ip_list))
    nm = NmapProcess(ip_list, options="-Pn -n -A -sT -p80,443 -r --max-retries 2 --host-timeout 2h --open --reason")
    nrc = nm.run()
    if nrc != 0:
        print("nmap scan failed: {0}".format(nm.stderr))
        exit(0)
    try:
        nparse = NmapParser.parse(nm.stdout)
    except NmapParserExcetion as e:
        print("Exception raised while parsing scan: {0}".format(e.msg))

    return(nparse)

and the function to parse and output the scan result.  This example is almost verbatim from the libnmap documentation.

def print_nmap(nmap_report):
    print("Starting Nmap {0} ( http://nmap.org ) at {1}".format(
        nmap_report.version,
        nmap_report.started))

    for host in nmap_report.hosts:
        if len(host.hostnames):
            tmp_host = host.hostnames.pop()
        else:
            tmp_host = host.address

        print("Nmap scan report for {0} ({1})".format(
            tmp_host,
            host.address))
        print("Host is {0}.".format(host.status))
        print("  PORT     STATE         SERVICE")

        for serv in host.services:
            pserv = "{0:>5s}/{1:3s}  {2:12s}  {3}".format(
                    str(serv.port),
                    serv.protocol,
                    serv.state,
                    serv.service)
            if len(serv.banner):
                pserv += " ({0})".format(serv.banner)
            print(pserv)
    print(nmap_report.summary)

The output from the finished script is:

# ./scan_web.py 45.60.103.0,45.60.31.34,1.2.3.4
[2021-05-31 19:00:56,329] [DEBUG] [masscan.py 10 line] Scan parameters: "masscan -oX - 45.60.103.0,45.60.31.34,1.2.3.4 -p 80,443"
Starting nmap for: ['45.60.103.0', '45.60.31.34']
Starting Nmap 7.91 ( http://nmap.org ) at 1622487670
Nmap scan report for 45.60.103.0 (45.60.103.0)
Host is up.
  PORT     STATE         SERVICE
   80/tcp  open          http
  443/tcp  open          https
Nmap scan report for 45.60.31.34 (45.60.31.34)
Host is up.
  PORT     STATE         SERVICE
   80/tcp  open          http
  443/tcp  open          https
Nmap done at Mon May 31 19:01:49 2021; 2 IP addresses (2 hosts up) scanned in 40.03 seconds

In about 80 lines of python code. I have implemented a simple script that can quickly scan a large address space using the very quick masscan and then send the output to nmap to do detailed scanning of a single port. This script is the basic framework I use for dozens of scripts to scan an entire ASN looking for devices that may be at risk for the current vulnerability of the week.

The final version of the scan_web.py script is:

#!/usr/local/bin/python3
import sys,getopt,argparse
import masscan
from libnmap.process import NmapProcess
from libnmap.parser import NmapParser, NmapParserException
import pprint

def scan_masscan(ips):

   try:
      maso = masscan.PortScanner()
      maso.scan(ips, ports='80,443')
   except:
      print("Error:", sys.exc_info()[0])
      sys.exit(1)

   return(maso)

def parse_masscan_host_list(massout):

    #initialize
    host_list = list()

    # Build a list from the massscan output
    for host in massout.all_hosts:
       host_list.append(host)
    return(host_list)

def scan_nmap(ip_list):
    print("Starting nmap for: {0}".format(ip_list))
    nm = NmapProcess(ip_list, options="-Pn -n -A -sT -p80,443 -r --max-retries 2 --host-timeout 2h --open --reason")
    nrc = nm.run()
    if nrc != 0:
        print("nmap scan failed: {0}".format(nm.stderr))
        exit(0)
    try:
        nparse = NmapParser.parse(nm.stdout)
    except NmapParserExcetion as e:
        print("Exception raised while parsing scan: {0}".format(e.msg))
    pprint.pprint(nparse)
    return(nparse)

def print_nmap(nmap_report):
    print("Starting Nmap {0} ( http://nmap.org ) at {1}".format(
        nmap_report.version,
        nmap_report.started))

    for host in nmap_report.hosts:
        if len(host.hostnames):
            tmp_host = host.hostnames.pop()
        else:
            tmp_host = host.address

        print("Nmap scan report for {0} ({1})".format(
            tmp_host,
            host.address))
        print("Host is {0}.".format(host.status))
        print("  PORT     STATE         SERVICE")

        for serv in host.services:
            pserv = "{0:>5s}/{1:3s}  {2:12s}  {3}".format(
                    str(serv.port),
                    serv.protocol,
                    serv.state,
                    serv.service)
            if len(serv.banner):
                pserv += " ({0})".format(serv.banner)
            print(pserv)
    print(nmap_report.summary)

def main():
   # read in the IP parameter 
   parser = argparse.ArgumentParser()
   parser.add_argument('IP', help="IP address or range")
   args=parser.parse_args()
   ip=args.IP

   maso=scan_masscan(ip)

   if int(maso.scanstats['uphosts']) > 0:
      host_list=parse_masscan_host_list(maso)
      nreport = scan_nmap(host_list)
      print_nmap(nreport)
   else:
      print("No Masscan results")
      sys.exit(1)

if __name__ == "__main__":
    main()

 

Caveat1: Never scan an IP range you don't have permission to scan.  While port scanning is not illegal in most jurisdictions it is questionable ethically to scan things you don't own or have permission to scan.

Caveat2: I am not a professional Python programmer.  My scripting gets the job done that I need it to do.  I know there are many smart people out there who can write way better code than I can. 

— Rick Wanner MSISE – rwanner at isc dot sans dot edu – Twitter:namedeplume (Protected)

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

Careers in Cybersecurity

This post was originally published on this site

Have you considered a career in cybersecurity? It is a fast-paced, highly dynamic field with a huge number of specialties to choose from, including forensics, endpoint security, critical infrastructure, incident response, secure coding, and awareness and training. In addition, a career in cybersecurity allows you to work almost anywhere in the world, with amazing benefits and an opportunity to make a real difference. However, the most exciting thing is you do NOT need a technical background, anyone can get started.

Iron Castle Systems