Using SMB sniffing to determine target’s host name, domain, OS version, system time and time zone

Once again needed an alternative method to “verify” a massive list of computers :

1) The machines existed on the network

2) that DNS was resolving to the actual machine on the list. i.e. when verifying machine name “PC-1234” I had to verify it actually was “PC-1234” not just a old DNS entry pointing to some other machine

Simple enough eh? But a few challenges were added:

1) Firewall is enabled on machines, blocking ICMP traffic. This cannot be changed. Effectively ping is out.

2) NetBios has been disabled on these machines, so nbtstat is out

3) DNS aging/scavenging cannot be enabled for the time being

4) There may not be a consistent method to delivery packages/logons scripts to these machines

5) The local administrator password on these machines may not be consistent (There is no Active Directory domain membership of these computers)

6) Approval for any policy changes on these machines anytime soon is unlikely

7) Physical audit will be difficult, multiple sites spread across the world

OK so first tool that came into my mind in this type of situation is NMap which along with Ping, TracerT, Ipconfig, WireShark, Microsoft Network Monitor, Fiddler, ProcMon, ProcExp, netsh (Windows 7/2008R2 version!), telnet, and netstat make up my network diagnostic essentials toolkit. Please don’t leave home without these tools, I  don’t.

A preliminary scan of a single host using Nmap identified despite firewall being enabled there was some stuff allowed through – file sharing.

This gives me an option…

But first just a reminder – don’t go scanning stuff on corporate networks (or even ISPs) like crazy without appropriate approvals

First step is to get nmap, which you can download from here http://nmap.org/download.html

If using on Windows get the Windows setup package which will be named something like nmap-5.51-setup.exe and which includes the following:

Product Description
Nmap Network Mapper, discovers hosts and services on a network with ability to create a “map” of the network. Nmap sends specially crafted packets to the target host and then analyzes the responses. Unlike many simple port scanners that just send packets at some predefined constant rate, nmap accounts for the network conditions (latency fluctuations, network congestion, the target interference with the scan) during the run.
Nmap discovery goes beyond basic host being up/down or port being open/closed to being able to determine operating system of the target, names and versions of the listening services, estimate uptime, the type of device, presence of the firewall.

As of version 5.5 Nmap includes 177 NSE scripts, 2,982 OS fingerprints, and 7,319 version detection signatures.

It’s so good it picks up my Cisco IP phone down to the exact model.

Nmap runs on Linux, Windows, Solaris, HP-UX, BSD Variants (including MacOS), AmigaOS and SGI IRIX.[

WinPcap

WinPcap is required for almost all Nmap operations. WinPcap includes:

  • x86 and x64 drivers for the Windows NT family (Windows NT 4.0, Windows 2000, Windows XP, Windows Server 2003, Windows Vista, Windows 7, etc.), which use NDIS to read packets directly from a network adapter;
  • implementations of a lower-level library for the listed operating systems, to communicate with those drivers;
  • a port of libpcap that uses the API offered by the low-level library implementations.

Although the Windows setup package for nmap already includes WinPcap you can find the latest versions here http://www.winpcap.org/

Network Performance Improvements Modifies registry values to improve TCP Connect scan performance

It sets the following registry values:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
“MaxUserPort”=dword:0000fffe
“TcpTimedWaitDelay”=dword:0000001e
“StrictTimeWaitSeqCheck”=dword:00000001

By default none of these values are set.

For MaxUserPort (when not set default is 0×1388 or 5,000 decimal) refer to http://support.microsoft.com/kb/196271 (note: fffe is hex for 65,536)

For TcpTimedWaitDelay and StrictTimeWaitSeqCheck refer to:

http://support.microsoft.com/kb/840618

http://support.microsoft.com/kb/314053

(there are other KB articles that mention these values as well, search http://support.microsoft.com )

Zenmap GUI Frontend for NMap
Ncat Modern netcat reincarnation. Often referred to as a “swiss army knife” for TCP/IP, can be used for port scanning, transferring files, port listening, and as a backdoor.  NCat can chain ncats together, redirect both TCP & UDP ports to other sites, support SSL, proxy connections & proxy authentication. More importantly it has a beautiful ASCII art logo:

  .       .      
  \`-”‘”-’/      
   } 6 6 {       
  ==. Y ,==      
    /^^^\  .     
   /     \  )    
  (  )-(  )/     _
  -””—””—   /
/   Ncat    \_/ 
(     ____       
\_.=|____E

Ndiff A tool for comparing NMap scans. Can output report in human readable text (or hacker readable more specifically) or machine readable XML (also readable by those who live 90% of their waking life in a debugger of some sorts) The typical use of ndiff is when running nmap as a scheduled task, to then highlight any changes occurred to the network between scans. It also integrated into the ZenMap GUI.
Nping

Nping is an open source tool for network packet generation, response analysis and response time measurement. Nping allows to generate network packets of a wide range of protocols, letting users to tune virtually any field of the protocol headers. While Nping can be used as a simple ping utility to detect active hosts, it can also be used as a raw packet generator for network stack stress tests, ARP poisoning, Denial of Service attacks, route tracing, etc.

Nping has a very flexible and powerful command-line interface that grants the user full control of the generated packets. These are some of Nping’s features:

  • Custom TCP, UDP, ICMP and ARP packet generation.
  • Support for multiple target host specification.
  • Support for multiple target port specification.
  • Unprivileged modes for non-root users.
  • Support for Ethernet frame generation.
  • Support for IPv6 (currently experimental).
  • Runs on Linux, Mac OS and MS Windows.
  • Route tracing capabilities.
  • Highly customizable.
  • Free and open-source.

Nping was started as a “Google Summer of Code” Project in 2009. While it is already useful for many purposes, it is still in an early stage of development so it may contain bugs and some functionality may have not been implemented yet.

Hopefully by the time you’ve finished downloading Nmap your network security administrator hasn’t blocked your machine from network access. (The power of NMap is great for legitimate uses, but of course also great for bad guys to assist in identification of potential vulnerabilities that could be exploited to break into a target system)

On Windows after Nmap is installed you might want to start out with the GUI version before going hardcore into pure command line bliss. If you used the setup package for Windows you will find it at Start > All Programs > Nmap > Nmap – Zenmap GUI

On Windows Vista/7 though I would just type Zenmap [enter] into the Start Menu search bar.

Once ZenMap GUI is loaded we can specify a target machine in the Target section. We can then select from a list of built in profiles on the right:

  • Intense scan
  • Intense scan plus UDP
  • Intense scan, all TCP ports
  • Intense scan, no ping
  • Ping scan
  • Quick scan
  • Quick scan plus
  • Quick traceroute
  • Regular scan
  • Slow comprehensive scan

In this case as we know Ping is blocked I’m selecting Intense scan, no ping. In this scenario I’m just pointing it at a single test machine:

image

When I scroll down the results I find the section Host script results: The part that interests me is the smb-os-discovery script:

image

We can see here from the discovery script three pieces of information we can retrieve when SMB is enabled on a machine, without requiring any authentication:

  • The OS Version
  • The computer workgroup/domain and computer name
  • The system time

Now we’ll go to the command line and put this into a script we can use in an automated fashion. To run specific scripts against a target we use the –script= option followed by the script(s) we want to run separated by semicolons. Because we want this to work even if ping doesn’t work we’ll add –pN option, although as a consequence it will take longer to fail on non-existent targets. I also want to limit port scanning to only those ports necessary for SMB, so I’m setting it to only scan port 445. In this case my host is DELL-007

So the command I use is:

nmap -p 445 -Pn –script=smb-os-discovery dell-007

image

And important note about the system time:

  • The System Time is displayed in your local time
  • The Time Zone (i.e. UTC+11) is the time zone of the target machine
  • However where daylight savings can be enabled this UTC value will increment when daylight savings is in effect. i.e. a machine in UTC+10 time zone will show UTC+11 during daylight savings, if the machine is configured to automatically change time for daylight savings. (and it has the correct time zone info! I’ll try to forgive Australian state governments for all the times they changed daylight savings in the past few years)

Also if you are wondering YOU CANNOT SCAN THE MACHINE YOU ARE USING, it will FAIL.

For those who want to know how the SMB OS scan detection works you can open the script from %ProgramFiles%\Nmap\scripts\smb-os-discovery.nse in a text editor that supports *nix text file format (not Notepad, but editors like PSPad will be OK)

Many other SMB scripts are included with Nmap which you can experiment with, although if you value your job you may want to skip some such as smb-flood:

  • smb-brute
  • smb-check-vulns
  • smb-enum-domains
  • smb-enum-groups
  • smb-enum-processes
  • smb-enum-sessions
  • smb-enum-shares
  • smb-enum-users
  • smb-flood
  • smb-os-discovery
  • smb-psexec
  • smb-security-mode
  • smb-server-stats
  • smb-system-info
  • smbv2-enabled

In any case back onto the topic at hand…

I want to rip out some of these values into variables for my automated script. So I started with a test script to use against single machines:

@echo off
cls
REM we need this so we change variables during batch execution
SETLOCAL ENABLEDELAYEDEXPANSION
set /p RemotePC=Please enter remote PC name:

echo Scanning !RemotePC! using NMap…
nmap -p 445 -Pn –script=smb-os-discovery !RemotePC! > “%temp%\nmap.txt”
echo Scan complete.

REM Assume any data not returned will be “Not Detected”
SET NMAP_OS=Not Detected
SET NMAP_NAME=Not Detected
SET NMAP_DATETIME=Not Detected
SET NMAP_DOMAIN=Not Detected
SET NMAP_HOSTNAME=Not Detected

FOR /F “tokens=1,2* delims=:” %%i IN (%temp%\nmap.txt) DO (

REM We use !VALUE:~1! to get rid of leading space
SET VALUE=%%j
IF “%%i” EQU “|   OS” SET NMAP_OS=!VALUE:~1!
IF “%%i” EQU “|   Name” SET NMAP_NAME=!VALUE:~1!
IF “%%i” EQU “|_  System time” SET NMAP_DATETIME=!VALUE:~1!:%%k

)

FOR /F “tokens=1,2 delims=\” %%i IN (‘echo !NMAP_NAME!’) DO (
  IF “%%i” NEQ “” (
    SET NMAP_DOMAIN=%%i
    SET NMAP_HOSTNAME=%%j
  )
)

echo Results for !RemotePC!
echo.
echo OS    : !NMAP_OS!
echo Name  : !NMAP_NAME!
echo Domain: !NMAP_DOMAIN!
echo Host  : !NMAP_HOSTNAME!
echo Time  : !NMAP_DATETIME!

Here is an example of running the script. Note: It doesn’t matter where in path you run it from as NMAP adds itself to path environment variable:

image

Now my final step is to build this into my automated scanning script as mentioned in previous post :

This script produces output like below:

image

If the Computer in column A matches name in column D then SMB Host Match will be set to “TRUE”

To use the script

  • Install NMap
  • Populate list of computers in filename Computers.txt with each computer on a separate line
  • Place computers.txt in same folder as the script
  • Optionally change the number of runs you want it to go for by changing MAXRUNS variable. Currently set to 5 loops. What that means is that each time it will re-check all failed machines

image

The script can be downloaded here: http://www.tiange.com.au/pingpcs.zip and is the file called pingPCs_withSMBscan.cmd

The code is (straight copy and paste might not work, as quotes have been messed up thanks to WordPress auto-correctio smarts, haven’t been able to disable those smarts yet)

@echo off
Rem pingPCs by malcolm mccaffery – pings all PCs in a text file and logs results to CSV
REM enabled delayed expansion so we can change variables during batch file execution
SETLOCAL ENABLEDELAYEDEXPANSION

Rem set the maximum number of runs…
SET MAXRUNS=5

REM the output CSV file
SET OUTPUTFILE=PC_LOG.csv

REM set input file, which is a list of computer names in an ASCII text file, each computer name on a new line
SET INPUTFILE=computers.txt

REM create the header row for the CSV file
echo Computer Name,IP Address,Ping Status,SMB Hostname,SMB Domain,SMB Name,SMB OS,SMB DateTime,SMB Host Match,Date Time > “%OUTPUTFILE%”

echo Reading computer list from %INPUTFILE%
echo Saving log to %OUTPUTFILE%
FOR /F %%i IN (%INPUTFILE%) DO (    
  echo Pinging %%i…
  ping %%i > “%temp%\ping.txt”
 
  IF !ERRORLEVEL! EQU 0 (
    REM machine is pingable!
    SET result=SUCCESS
 
    REM we filter by ‘ping statistics’ to get IP because it’s easy to process,
    REM whether IPv6 or IPv4 it’s consistent across legacy and lates MS OSes
    REM dummy delims \ as we don’t want it separating any of the output
    FOR /F “delims=\” %%j IN (‘type ^”%temp%\ping.txt^” ^| find ^”Ping statistics^”‘) DO (
      SET IPAddress=%%j
      SET IPAddress=!IPAddress:~20,-1!
      echo SUCCESS … !IPAddress!
    )
  ) ELSE (
    REM machine is not pingable!
    SET RESULT=FAILED
   
    REM Assume guilty until proven innocent
    SET IPAddress=NOT FOUND
    REM did we get IP, but machine not online?
    type “%temp%\ping.txt” | find “Request timed out.”
    IF !ERRORLEVEL! EQU 0 (
      FOR /F “delims=\” %%j IN (‘type ^”%temp%\ping.txt^” ^| find ^”Ping statistics^”‘) DO (
        SET IPAddress=%%j
        SET IPAddress=!IPAddress:~20,-1!
        echo FAILED … !IPAddress!
      )
    ) ELSE (
      echo FAILED … NOT FOUND
    )
  )

echo Scanning %%i using NMap…
REM nmap -p 445 -Pn –script=smb-os-discovery %%i > “%temp%\nmap.txt”
echo Scan complete.
SET NMAP_OS=Not Detected
SET NMAP_NAME=Not Detected
SET NMAP_DATETIME=Not Detected
SET NMAP_DOMAIN=Not Detected
SET NMAP_HOSTNAME=Not Detected

FOR /F “tokens=1,2* delims=:” %%j IN (‘type ^”%temp%\nmap.txt^”‘) DO (

REM We use !VALUE:~1! to get rid of leading space
SET VALUE=%%k
IF “%%j” EQU “|   OS” SET NMAP_OS=!VALUE:~1!
IF “%%j” EQU “|   Name” SET NMAP_NAME=!VALUE:~1!
IF “%%j” EQU “|_  System time” SET NMAP_DATETIME=!VALUE:~1!:%%l

)

FOR /F “tokens=1,2 delims=\” %%j IN (‘echo !NMAP_NAME!’) DO (
  IF “%%j” NEQ “” (
    SET NMAP_DOMAIN=%%j
    SET NMAP_HOSTNAME=%%k
  )
)

IF /I !NMAP_HOSTNAME! EQU %%i (
   SET NMAP_MATCH=TRUE
) ELSE (
   SET NMAP_MATCH=FALSE
)

  echo %%i,!IPAddress!,!result!,!NMAP_HOSTNAME!,!NMAP_DOMAIN!,!NMAP_NAME!,!NMAP_OS!,!NMAP_DATETIME,!NMAP_MATCH!,%DATE%%TIME% >> “%OUTPUTFILE%”
)
 
SET COUNTER=0

:REPEAT

SET /A COUNTER=!COUNTER!+1

echo Completed Cycle #!COUNTER!. Output in “%OUTPUTFILE%”
IF !COUNTER! GEQ !MAXRUNS! GOTO :EOF

Rem Allows for conditional operations in batch processing.
IF EXIST “%INPUTFILE%.csv” DEL “%INPUTFILE%.csv”
copy “%OUTPUTFILE%” “%INPUTFILE%.csv” /y
IF EXIST “%OUTPUTFILE%.tmp” DEL “%OUTPUTFILE%.tmp”
Rem Allows for conditional operations in batch processing.
FOR /F “delims=, TOKENS=1,2,3,4,5,6,7,8,9,10″ %%i IN (%INPUTFILE%.csv) DO (    
  Rem only retry failed machines…
  SET RETRY=FALSE
 
  Rem if ping failed last time, retry
  IF “%%k” EQU “FAILED” SET RETRY=TRUE
 
  Rem if nmap match successed last time, then don’t retry
  IF “%%q” EQU “TRUE” SET RETRY=FALSE
 
  Rem if nmap match failed last time, retry
  IF “%%q” EQU “FALSE” SET RETRY=TRUE
 
  IF “!RETRY!” EQU “TRUE” (
    Rem Allows for conditional operations in batch processing.
    echo Pinging %%i…
    ping %%i > “%temp%\ping.txt”
   
    IF !ERRORLEVEL! EQU 0 (
      REM machine is pingable!
      SET result=SUCCESS
   
      REM we filter by ‘ping statistics’ to get IP because it’s easy to process,
      REM whether IPv6 or IPv4 it’s consistent across legacy and lates MS OSes
      REM dummy delims \ as we don’t want it separating any of the output
      REM May need to change ,-1 to ,-2 on XP pinging IPv4 machines to remove trailing :
      FOR /F “delims=\” %%x IN (‘type ^”%temp%\ping.txt^” ^| find ^”Ping statistics^”‘) DO (
        SET IPAddress=%%x
        SET IPAddress=!IPAddress:~20,-1!
        echo SUCCESS … !IPAddress!
      )
    ) ELSE (
      REM machine is not pingable!
      SET RESULT=FAILED
     
      REM Assume guilty until proven innocent
      SET IPAddress=NOT FOUND
 
      REM did we get IP, but machine not online?
      type “%temp%\ping.txt” | find “Request timed out.”
      IF !ERRORLEVEL! EQU 0 (
        FOR /F “delims=\” %%x IN (‘type ^”%temp%\ping.txt^” ^| find ^”Ping statistics^”‘) DO (
          SET IPAddress=%%x
          SET IPAddress=!IPAddress:~20,-1!
          echo FAILED … !IPAddress!
        )
      ) ELSE (
        echo FAILED … NOT FOUND
      )
    )
 

echo Scanning %%i using NMap…
REM nmap -p 445 -Pn –script=smb-os-discovery %%i > “%temp%\nmap.txt”
echo Scan complete.
SET NMAP_OS=Not Detected
SET NMAP_NAME=Not Detected
SET NMAP_DATETIME=Not Detected
SET NMAP_DOMAIN=Not Detected
SET NMAP_HOSTNAME=Not Detected

FOR /F “tokens=1,2* delims=:” %%x IN (‘type ^”%temp%\nmap.txt^”‘) DO (

REM We use !VALUE:~1! to get rid of leading space
SET VALUE=%%y
IF “%%x” EQU “|   OS” SET NMAP_OS=!VALUE:~1!
IF “%%x” EQU “|   Name” SET NMAP_NAME=!VALUE:~1!
IF “%%x” EQU “|_  System time” SET NMAP_DATETIME=!VALUE:~1!:%%z

)

FOR /F “tokens=1,2 delims=\” %%x IN (‘echo !NMAP_NAME!’) DO (
  IF “%%x” NEQ “” (
    SET NMAP_DOMAIN=%%x
    SET NMAP_HOSTNAME=%%y
  )
)

IF /I !NMAP_HOSTNAME! EQU %%i (
   SET NMAP_MATCH=TRUE
) ELSE (
   SET NMAP_MATCH=FALSE
)

  echo %%i,!IPAddress!,!result!,!NMAP_HOSTNAME!,!NMAP_DOMAIN!,!NMAP_NAME!,!NMAP_OS!,!NMAP_DATETIME,!NMAP_MATCH!,%DATE%%TIME% >> “%OUTPUTFILE%.tmp”
  ) ELSE (
    echo %%i was SUCCESSFUL in previous test
    echo %%i,%%j,%%k,%%l,%%m,%%n,%%o,%%p,%%q,%%r >> “%OUTPUTFILE%.tmp”
  )
)

IF EXIST %OUTPUTFILE% del %OUTPUTFILE%
rename %OUTPUTFILE%.tmp %OUTPUTFILE%

GOTO :REPEAT

About Malcolm McCaffery

specializes in end-user computing technologies. disclaimer 1) use at your own risk. test any solution in your environment. if you do not understand the impact/consequences of what you're doing please stop, and ask advice from somebody who does. 2) views are my own at the time of posting and do not necessarily represent my current view or the view of my employer and family members/relatives. 3) over the years Microsoft/Citrix/VMWare have given me a few free shirts, pens, paper notebooks/etc. despite these gifts i will try to remain unbiased.
This entry was posted in Batch Files, Network, NMap, Scripting and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s