петък, юли 15, 2022

Check remote computers for open UDP ports with PowerShell (ext. script) 2

Minimalistic-offensive-security-tools/port-scan-udp.ps1 at master · InfosecMatter/Minimalistic-offensive-security-tools · GitHub 

Function port-scan-udp {

  param($hosts,$ports)

  if (!$ports) {

    Write-Host "usage: port-scan-udp <host|hosts> <port|ports>"

    Write-Host " e.g.: port-scan-udp 192.168.1.2 445`n"

    return

  }

  $out = ".\scanresults.txt"

  foreach($p in [array]$ports) {

   foreach($h in [array]$hosts) {

    $x = (gc $out -EA SilentlyContinue | select-string "^$h,udp,$p,")

    if ($x) {

      gc $out | select-string "^$h,udp,$p,"

      continue

    }

    $msg = "$h,udp,$p,"

    $u = new-object system.net.sockets.udpclient

    $u.Client.ReceiveTimeout = 500

    $u.Connect($h,$p)

    # Send a single byte 0x01

    [void]$u.Send(1,1)

    $l = new-object system.net.ipendpoint([system.net.ipaddress]::Any,0)

    $r = "Filtered"

    try {

      if ($u.Receive([ref]$l)) {

        # We have received some UDP data from the remote host in return

        $r = "Open"

      }

    } catch {

      if ($Error[0].ToString() -match "failed to respond") {

        # We haven't received any UDP data from the remote host in return

        # Let's see if we can ICMP ping the remote host

        if ((Get-wmiobject win32_pingstatus -Filter "address = '$h' and Timeout=1000 and ResolveAddressNames=false").StatusCode -eq 0) {

          # We can ping the remote host, so we can assume that ICMP is not

          # filtered. And because we didn't receive ICMP port-unreachable before,

          # we can assume that the remote UDP port is open

          $r = "Open"

        }

      } elseif ($Error[0].ToString() -match "forcibly closed") {

        # We have received ICMP port-unreachable, the UDP port is closed

        $r = "Closed"

      }

    }

    $u.Close()

    $msg += $r

    Write-Host "$msg"

    echo $msg >>$out

   }

  }

}


# Examples:

#

# port-scan-udp 10.10.0.1 137

# port-scan-udp 10.10.0.1 (135,137,445)

# port-scan-udp (gc .\ips.txt) 137

# port-scan-udp (gc .\ips.txt) (135,137,445)

# 0..255 | foreach { port-scan-udp 10.10.0.$_ 137 }

# 0..255 | foreach { port-scan-udp 10.10.0.$_ (135,137,445) }

Check remote computers for open TCP ports with PowerShell (ext. script) 1

Minimalistic-offensive-security-tools/port-scan-tcp.ps1 at master · InfosecMatter/Minimalistic-offensive-security-tools · GitHub 

Function port-scan-tcp {

  param($hosts,$ports)

  if (!$ports) {

    Write-Host "usage: port-scan-tcp <host|hosts> <port|ports>"

    Write-Host " e.g.: port-scan-tcp 192.168.1.2 445`n"

    return

  }

  $out = ".\scanresults.txt"

  foreach($p in [array]$ports) {

   foreach($h in [array]$hosts) {

    $x = (gc $out -EA SilentlyContinue | select-string "^$h,tcp,$p,")

    if ($x) {

      gc $out | select-string "^$h,tcp,$p,"

      continue

    }

    $msg = "$h,tcp,$p,"

    $t = new-Object system.Net.Sockets.TcpClient

    $c = $t.ConnectAsync($h,$p)

    for($i=0; $i -lt 10; $i++) {

      if ($c.isCompleted) { break; }

      sleep -milliseconds 100

    }

    $t.Close();

    $r = "Filtered"

    if ($c.isFaulted -and $c.Exception -match "actively refused") {

      $r = "Closed"

    } elseif ($c.Status -eq "RanToCompletion") {

      $r = "Open"

    }

    $msg += $r

    Write-Host "$msg"

    echo $msg >>$out

   }

  }

}


# Examples:

#

# port-scan-tcp 10.10.0.1 137

# port-scan-tcp 10.10.0.1 (135,137,445)

# port-scan-tcp (gc .\ips.txt) 137

# port-scan-tcp (gc .\ips.txt) (135,137,445)

# 0..255 | foreach { port-scan-tcp 10.10.0.$_ 137 }

# 0..255 | foreach { port-scan-tcp 10.10.0.$_ (135,137,445) }

Check remote computers for open TCP ports with PowerShell

Fast and simple: 


Test-NetConnection -ComputerName 172.30.33.11 -Port 22

Script:

Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force -Scope Currentuser

cd $env:temp

Start-Transcript -LiteralPath .\Test_results.txt

$ip = Read-Host -Prompt 'Enter server IP'

$p1 = Read-Host -Prompt 'Enter 1st port to test (ENTER or 0 to skip): '

$p2 = Read-Host -Prompt 'Enter 2nd port to test (ENTER or 0 to skip): '

$p3 = Read-Host -Prompt 'Enter 3rd port to test (ENTER or 0 to skip): '

Write-Host ""

Write-Host "Open ports test results:"

if ($p1 -gt 0)

{

if (Test-NetConnection -ComputerName $ip -Port $p1 -InformationLevel Quiet -WarningAction SilentlyContinue) {"Port $p1 is open" } else {"Port $p1 is closed"}

}

else {"No port - no test"}

if ($p2 -gt 0)

{

if (Test-NetConnection -ComputerName $ip -Port $p2 -InformationLevel Quiet -WarningAction SilentlyContinue) {"Port $p2 is open" } else {"Port $p2 is closed"}

}

else {"No port - no test"}


if ($p3 -gt 0)

{

if (Test-NetConnection -ComputerName $ip -Port $p3 -InformationLevel Quiet -WarningAction SilentlyContinue) {"Port $p3 is open" } else {"Port $p3 is closed"}

}

else {"No port - no test"}

Test-NetConnection -ComputerName $ip -TraceRoute -InformationLevel Detailed

Stop-Transcript

Set-ExecutionPolicy -ExecutionPolicy Undefined -Force -Scope CurrentUser


Start-Process notepad .\Test_results.txt



Retrieving IPsec VPN PSK key from Fortigate

The API entry point is ;

"https://x.x.x.x/api/v2/cmdb/vpn.ipsec/phase1-interface?plain-text-password=1?

The full http get would look like the following ;

curl -k -H "Authorization: rest_api_admin_user zw7q8QyGrHwtfrn8tkGyfNbnGGN7js" "https://192.168.1.99/api/v2/cmdb/vpn.ipsec/phase1-interface?plain-text-password=1?access_token=zw7q8QyGrHwtfrn8tkGyfNbnGGN7js"

The output and field for "psksecret": will show the text value. 

Account with API permissions is must

Ken Felix Security Blog: fortios how to recover ipsec-vpn PSK string in text format (socpuppet.blogspot.com)

вторник, април 05, 2022

Linux, allow SFTP only users (with shared and chroot-ed env)

Users must upload/download files only via sftp/scp (no ssh, local login) to a pre-defined directory.

Users must not browse other directories or list directory tree.

Multiply users may share single directory (e.g. list of users assotiated with particular organization)

1. Creating of local users and home/upload dir structure

adduser --no-create-home --home /opt/sftp/chroot/org1 --shell /bin/nosuch u1

adduser --no-create-home --home /opt/sftp/chroot/org1 --shell /bin/nosuch u2

addgroup sftp

adduser u1 sftp

adduser u2 sftp

mkdir -p /opt/sftp/chroot/org1/upload

chmod -R 0755 /opt/sftp/chroot/org1  # 755 is must

chown -R root:root /opt/sftp/chroot/org1 # owner=root is must

chgrp sftp /opt/sftp/chroot/org1/upload

chmod 0764 /opt/sftp/chroot/org1/upload


2. Edit sshd_config (after UsePAM yes)


Subsystem sftp internal-sftp -l VERBOSE -f LOCAL3 # VERBOSE and LOCAL3 are used for logging via rsyslog.d/sftp.log

Match Group sftp # only users members of sftp group are allowed

ChrootDirectory %h # chrooted to $HOME_DIR e.g. /opt/sftp/chroot/org1

 AllowTcpForwarding no

 X11Forwarding no

 ForceCommand internal-sftp  -l VERBOSE -f AUTHPRIV # force to use only sftp/scp but not ssh -> shell=/bin/such helps too


service sshd restart


3. Update rsyslog configuration by editing /etc/rsyslog.d/sftp_log.conf

input(type="imuxsock" Socket="/opt/sftp/chroot/org1/dev/log" CreatePath="on")

local3.*                                                /var/log/sftp_org1.log

AUTHPRIV.*                                                /var/log/sftp_org1.log


4. Test 

tail -n 20 /var/log/sftp_org1.log

Apr  5 17:42:53 vs sshd[32700]: pam_unix(sshd:session): session opened for user u1 by (uid=0)

Apr  5 17:42:54 vs internal-sftp[32723]: session opened for local user u1 from [1.2.3.4]

Apr  5 17:42:54 vs internal-sftp[32723]: received client version 3

Apr  5 17:42:54 vs internal-sftp[32723]: realpath "."

Apr  5 17:43:04 vs internal-sftp[32723]: realpath "/up"

Apr  5 17:43:05 vs internal-sftp[32723]: stat name "/up"

Apr  5 17:43:06 vs internal-sftp[32723]: opendir "/up"

Apr  5 17:43:06 vs internal-sftp[32723]: closedir "/up"

Apr  5 17:43:19 vs internal-sftp[32723]: opendir "/up/"

Apr  5 17:43:19 vs internal-sftp[32723]: closedir "/up/"

Apr  5 17:43:19 vs internal-sftp[32723]: lstat name "/up/file1.txt"

Apr  5 17:43:20 vs internal-sftp[32723]: remove name "/up/file1.txt"

Apr  5 17:43:23 vs internal-sftp[32723]: open "/up/file2.sftp" flags WRITE,CREATE,TRUNCATE mode 0644

Apr  5 17:43:23 vs internal-sftp[32723]: close "/up/file2.sftp" bytes read 0 written 854

Apr  5 17:43:27 vs internal-sftp[32723]: lstat name "/up/file2.sftp"

Apr  5 17:43:27 vs internal-sftp[32723]: stat name "/up/file2.sftp"

Apr  5 17:43:27 vs internal-sftp[32723]: open "/up/file2.sftp" flags READ mode 0666

Apr  5 17:43:27 vs internal-sftp[32723]: close "/up/file2.sftp" bytes read 854 written 0

Apr  5 17:43:36 vs internal-sftp[32723]: session closed for local user u1 from [1.2.3.4]

Apr  5 17:43:36 vs sshd[32700]: pam_unix(sshd:session): session closed for user u1



вторник, март 29, 2022

Generate test syslog message on Junos

 
The logger utility is a shell command, and so the user must first start a system shell by invoking the start shell command:

    user@Junos> start shell %

The logger utility has the following command syntax: logger -e EVENT_ID -p SYSLOG_PRIORITY -d DAEMON -a ATTRIBUTE=VALUE MESSAGE. Only the EVENT_ID is required, and it must be entered entirely in uppercase:

    % logger -e UI_COMMIT
    % logger -e UI_COMMIT -d mgd "This is a fake commit."

 Some syslog tips

I’m ONLY sending messages to external host 192.168.56.11 if the facility is ‘external’ AND the severity is ‘info’ or greater (ie. not debug) AND the regex of the message matches LICENSE. Otherwise, we’ll likely have a local catch-all configured with any-any to locally log messages we may not be explicitly interested in looking at on the remote server.

root@vSRX-NAT-GW> show configuration
system {
  syslog {
    host 192.168.56.11 {
      external info;
      match LICENSE;
    }
   file messages {
     any any;
     authorization info;
   }
   file interactive-commands {
     interactive-commands any;
   }
}


The following configuration command will transfer output from all activated traces to your syslog server: 

set system tracing destination-override syslog host 10.0.0.13 

To exclude some of traces to be send to remote syslog (for example dhcp): 

 set forwarding-options dhcp traceoptions no-remote-trace


To send information from syslog to every (currently) logged in user console:  (except matching regex "Login attempt")

set system syslog user * any critical
set system syslog user * authorization info
set system syslog user * interactive-commands notice
set system syslog user * match "!(.*Login attempt.*)"

сряда, януари 05, 2022

Hyper-V trunk port to VM

Passing through VLAN ID/tags to Hyper-V virtual machine NIC

This functionality is not exposed via the UI but here's an example of how to configure it via PowerShell.

Add-VMNetworkAdapter -SwitchName Switch -VMName "VmName" -Name "TrunkNic"
Set-VMNetworkAdapterVlan -Trunk -AllowedVlanIdList "100,101" -VMName "VmName" -VMNetworkAdapterName "TrunkNic" -NativeVlanId 1

 

https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc816585(v=ws.10)?redirectedfrom=MSDN#Anchor_2

https://docs.microsoft.com/en-us/archive/blogs/adamfazio/understanding-hyper-v-vlans

https://docs.microsoft.com/en-us/powershell/module/hyper-v/set-vmnetworkadaptervlan?view=winserver2012-ps&redirectedfrom=MSDN