CompTIA PenTest+ Chapter 3 : Attacks and Exploits

Table of contents

3.1 Compare and contrast social engineering attacks.
3.2 Given a scenario, exploit network-based vulnerabilities.
3.3 Given a scenario, exploit wireless and RF-based vulnerabilities.
3.4 Given a scenario, exploit application-based vulnerabilities.
3.5 Given a scenario, exploit local host vulnerabilities.
3.6 Summarise physical security attacks related to facilities.
3.7 Given a scenario, perform post-exploitation techniques.

3.1 Compare and contrast social engineering attacks.

Social engineering attacks comprises of a set of techniques ambivalent to whether they’re physical or network-based tests and they encompass a few dynamics that aim to trick an untrained person , in a position of power, to give us some kind of business information like employee details or to perform actions that would probably violate their security policy if could figure out that we weren’t who we said we were. It ultimately stems from the human need to be helpful and this psychological weakness can be exploited if we’re sufficiently convincing.

Phishing

This is where people are contacted, typically through email , by a seemingly legitimate and trustworthy source in an attempt to extract sensitive information. Phishing in its most common form is just spam mail, sent to thousands of harvested emails, hoping to catch the stupid percentile to the scam and fingers crossed they disclose their bank details etc. What we may use it for is to target employees, and for them to hand over their employee ID and or password to a “technician”. In its most sophisticated form it can be a cybercrime organisation that constructs an incredibly detailed , well-informed email pertinent to an employee or manager, with a link that includes the malware itself - or a hyperlink to a website that installs malware. So from just one successful click it may put us in the position to pivot to other systems. Pro tip, for bigger organisations, their mail servers will run diagnostics , sort of like an email firewall and scan them for any malicious links that contain code etc. It’s best to drag them out of their nest of security and into the deep dark forest.

Types of Phishing attacks (aside from the standard spam) include:

  • Spear phishing is where we use our knowledge of a target to craft an email that looks like it came from one of their close contacts, and hence the success rate goes up as it seems more believable.
  • SMS Phishing is where we employ the same spam-type message , or more targeted text message , over SMS messaging.
  • Vishing is where we employ social engineering techniques over the phone, we might spoof someone’s voice, pretend to a friend or family member of the person… whatever it takes!
  • Whales in the phishing world are high-profile, rich and/or important members of an organisation, like the CEO or senior vice presidents.

Social Engineering

Social engineering requires a good understanding of human behaviour and human weaknesses. The goal of social engineering is to persuade your target to provide information or access that will allow you succeed in performing your penetration test. To do so, you will often appeal to one or more of these common social engineering targets:

  • Trust is the foundation of many social engineering attacks. Creating a perception of trust can be done in many ways. Most individuals unconsciously want to trust others, providing a useful target for social engineers!
  • Reciprocation relies on the target feeling indebted, or that they need to return a favour.
  • Authority focuses on making the target believe that you have the power or right to ask them to perform actions or provide information.
  • Urgency is the sense that the action needs to be performed, often because of one of the other reasons listed here.
  • Fear that something will go wrong or that they will be punished if they do not respond or help is a common target.
  • Likeness or similarity between the social engineer and the target is a means of building trust, as the target is set up to sympathise with the pen-tester due to their similarity.
  • Social proof relies on persuading the target that other people have behaved similarly and, thus, that they should or could as well.
  • Scarcity is related to fear-based approaches but focuses on there being fewer rewards or opportunities, requiring faster action and thus creating a sense of urgency.
  • Helpful nature is the straightforward truth about most decent people. When given an innocent opportunity to be appreciated, a target will be helpful to the pen-tester.

In-person social engineering requires a strong understanding of individuals and how they respond, and it leverages the social engineer’s skills to elicit desired responses. There are many in-person social engineering techniques, including those documented in the [Social Engineering Framework]( https://www.social-engineer.org/framework/ general-discussion/).

Elicitation

Gathering information is a core element of any social engineering exercise, and elicitation is the process of gathering information (the word literally means to draw forth) and we can be extract with varying degrees of forcefulness or subtlety. Sometimes we may try to gather data without directly asking for it, as asking an individual for information directly can often make them suspicious, but asking other questions or talking about unrelated areas that may lead them to reveal the information you need can be very effective. A lot of the times these “meta-conversations” , talking around a subject will make someone chime in with a relation to that subject, and hence the ice is broken and you can start lapping up content. Common techniques include using open-ended or leading questions and then narrowing them down as topics become closer to the desired information. Elicitation will escalate in the amount of relevant data exposed depending obviously on how quickly the person is to share, so try not to seem in a hurry - just ask the right questions.

The PenTest+ exam objectives specifically link business email compromise to elicitation. A compromised business email account can be used for elicitation exercises because it provides an automatic level of trust for many targets, so additional information can be gathered by asking questions via business email, but really we can use any of the media that we would use for Phishing , as well as in-person.

Interrogation and Interviews

Interrogation and interview tactics can be used as part of a social engineering process. Interrogation techniques focus on the social engineer directing the conversation and asking most, if not all, of the questions. This is less subtle and less comfortable for the target, and it means that interrogation is less frequently used unless the target has a reason to allow being interrogated, this may be because we spoofed into a position of power, or that the employee has responsibilities of which they need to answer for, it depends on the angle that you come in. Interview tactics are similar but place the subject more at ease. In both cases, body language is an important clue to the target’s feelings and responses. Doing this in-person gives the target a lot less time to think, as you’re pretty much relying on their composure and logic in the heat of the moment.

Impersonation

Many social engineering techniques involve some form of impersonation. Impersonation involves disguising yourself as another person to gain access to facilities or resources. This may be as simple as claiming to be a staff member or as complex as wearing a uniform and presenting a false or cloned company ID. Impersonating a technical support worker, maintenance employee, delivery person, or administrative assistant is also common. Impersonation frequently involves pretexting, a technique where the social engineer claims to need information about the person they are talking to, thus gathering information about the individual so that they can better impersonate them.

Quid Pro Quo

Quid pro quo attacks rely on the social engineer offering something of value to the target in order for the target to feel safe and indebted to them. This builds perceived trust, luring the target into feeling safe in returning the favour.

Shoulder Surfing

Simply watching over a target’s shoulder can provide valuable information like passwords or access codes. This is known as shoulder surfing, and high-resolution cameras with zoom lenses can make it possible from long distances.

USB Key Drops

Physical honeypots like USB keys or other media can be used when other means of accessing an organisation aren’t possible. To perform this type of attack, the penetration tester preloads a thumb drive with attack tools aimed at common operating systems or software found in the target company. They then drop one or more of these drives in locations where they are likely to be found, sometimes with a label that indicates that the drive has interesting or important data on it. The goal of attacks like these is to have the drives or media found, then accessed on target computers. If the attack tools are successful, they phone home to a system set up by the penetration tester, allowing remote access through firewalls and other security barriers.

Bribery

Bribing employees at the target organisation to allow you to access systems or facilities will not be in scope for many penetration tests, but penetration testers should be aware that it may be a valid technique under some circumstances. Bribery is a sensitive topic and should be carefully addressed via scoping agreements and the rules of engagement for a penetration test.

Use of Social Engineering Tools

Aside from the standard message -> message format of Phishing and other social engineering methods there is a strong argument to also use web-based tools and techniques. The two most commonly used web-based attacks are the watering hole attack and the use of cloned websites for phishing. The watering hole is where , through information gathering , we have identified a site where employees frequent , and if we can focus on hitting that website and modifying its code - usually in the form of ad code or plug-ins , then we can infect malware into all visitors. Obviously the compromise of the site will have to be within scope, and this limits it to employee websites and anything owned by the company that was implicitly specified. The cloned website has many more options, but it does presuppose an insecure web infrastructure, as their browser should tell them it’s not secure , or the public keys should be checked… Either way they may just click the link as it looks familiar, and it may be from someone they think they know.

Now onto the actual tools. Social engineering attacks as they stand already with minimal technology use is immensely powerful, but leveraging the pre-built attack vectors and automation can give a penetration tester a major advantage. The Social Engineering Toolkit, or SET, is a menu-driven social engineering attack system. Metasploit users will already be familiar with this type of menu-driven attack system. It provides spear phishing, website, infectious media, and other attack vectors, all built into Kali Linux, allowing penetration testers to easily integrate it into testing activities. It integrates with Metasploit to generate payloads and you can interact with the victim from the same shell.

The Browser Exploitation Framework (BeEF) is a penetration testing tool designed to allow exploitation of web browsers. Like Metasploit and SET, BeEF is built into Kali Linux. Once you have persuaded a user to visit a BeEF-enabled site, the tool takes over, providing “hooks” into a large number of browser features and capabilities. Once you have a browser hooked, BeEF provides a large set of tools that you can use to take action inside the browser. These include detection capabilities for settings and programs, as well as direct actions like playing sounds or asking the remote page for permission to turn on the webcam or getting lists of visited sites and domains. If the browser allows it, BeEF can also detect locally installed plug-ins and software, use specific exploits against the browser, perform DoS attacks, or even attempt to install persistence tools. The power of this XSS framework would depend on the degree to which you compromised the watering hole site, or the extent to which employees who visited your cloned website were insecurely connecting , and ultimately their common sense and lack of training would be the biggest factor in them clicking random links.

3.2 Given a scenario, exploit network-based vulnerabilities.

When we say network-based vulnerabilities what we mean is that some exploits will focus on specific protocol or configuration weaknesses, whereas others want to establish themselves as legitimate servers or to squeeze in between two clients (MITM).

  • Man-In-The-Middle Attack. Family of attacks that aim to intercept messages, either promiscuously in monitor mode for wireless networks, which is a lot harder to trace back to us , or whether we have to insert ourselves as a malicious proxy of sorts into the session between client and server, hence making our IP visible. Attack may modify , regenerate or forward intercepted messages. Pass-the-hash attacks are based on the intercepting function and we intercept a packet containing a hash and we reuse it when making a request to the service later as the user - just change the IP address and we’re good. SSL stripping is where we have “take away” , or strip, the benefits of TLS from the client be interjecting ourselves and setting an HTTPS connection with the server, but then using our own certificate we talk to the client, which they may catch onto if their browser is any good. SSL downgrading is also deadly, and if we can say to the server we can only communicate in HTTP 1.0/1.1 then they may comply and we can have an unencrypted (or weakly encrypted - null cipher) session and extract the data from them. We can do a DOS attack where the proxy generates traffic and takes down a small server. NAC Bypass is where we hope a NAC (who watches DHCP servers , SNMP traps etc) that their database of MAC addresses is complete, but their authentication is sparse, hopefully all we have to do is change the MAC to one that is whitelisted and we’re in. See here for details.
  • VLAN Hopping is where we try and get away with double tagging, which is where the first packet is directed for the native VLAN , but inside that is another set of headers to try and get around in the target VLAN, and it may be accepted , as it shows us to be from the internal network thanks to the parent wrapper. Double tagging does have a couple of critical flaws that limit its use for penetration testers. First, since the VLAN tags won’t be replicated on responses, no responses will be received by the originating system. Second, double tagging can only be used when switches are configured to allow native VLANs, and many organisations use mitigation techniques to prevent this type of abuse. double-tagging
  • DNS Cache poisoning, which is where the hacker would watch the traffic of a particular client, and if their traffic is slow enough we could send them our own DNS response for that domain and update their cache for our IP for that site…
  • ARP spoofing, which is where we spoof local MAC addresses.
  • Name resolution exploits
    • NETBIOS name service (NBT-NS). Part of NetBIOS-over-TCP. Similar functionality to DNS.
    • LLMNR (Link-Local Multicast Name Resolution). Protocol based on DNS packet format, allows IPv4 and IPv6 name resolution on the same local link.
    • DNS and ARP Poisoning
  • SMB exploits. Server Message Block protocol was originally made on top of NetBIOS and was primarily used in Windows networks to provide file and printer access, but the standard was improved and the translations were extended to Linux systems as well , to access any file and printer services and remote service access too. There are gaps in the translation though and many vulnerabilities have been found in SMB like Eternal Blue, WannaCry used SMB to propagate. Samba is the Linux implementation of the SMB protocol. Speaking of MITM earlier, there is also the SMB relay attack, which sits in the middle and relays all the conversation between it and the server to the client…
  • Simple Network Management Protocol (SNMP). Queries devices and manages IP address, make sure to use version four otherwise communications aren’t encrypted!
  • Simple Mail Transfer Protocol (SMTP) is used for transmitting email over port 25, and is sadly susceptible to open relay, local relay, phishing , spam etc.
  • FTP is another insecure protocol made in the dark ages , but still used for transferring files , but without wrapping it in a TLS layer it can easily be exfiltrated - not to mention the problems with anonymous accounts, hacks with SSH etc.

3.3 Given a scenario, exploit wireless and RF-based vulnerabilities.

Now that wireless networks have become mainstream , they have completely reinvented every aspect of the penetration testing process, as now we have the ability to compromise corporate networks through more effective active reconnaissance, we are able to peruse and sniff traffic without being caught as hubs broadcast their traffic , and tools like aircrack-ng and Wireshark to capture packets and to break their encryption.

  • An evil twin attack is where we setup a rogue WAP used to eavesdrop on people who have their devices set to auto-reconnect each time they see a network with a particular SSID - good for mesh networks. Evil twins can attempt to reconnect to that client using a more insecure protocol , and the downgrade may give us an easier time of cracking packets. There is also the Karma attack (KARMA Attacks Radio Machines Automatically), which is where an attacker’s device(s) listen for probe requests, they pretend to be the access point to which the connecting system tried to connect- and hence we become a MITM.
  • Deauthentication attacks. This is where an attacker sends a cancel packet to the AP that stops communications with the client, and tries to reconnect, as that procedure is happening the tester can capture the packets used to find their agreement , and hopefully a key in there somewhere we can offline crack!
  • Next up are fragmentation attacks. They were only popular really on WEP networks , where we wanted to generate as much traffic as possible (and so fragment one packet into many pieces and repeat for each packet…). With all this ciphertext we could work on extracting the key , but with modern networks fragmented is really just used to bypass firewalls and other blacklists where possible. You can configure nmap to fragment packets by using -f but nowadays you want to set your offset size with --mtu as firewalls watch for specific sizes.
  • Credential harvesting. Process of capturing or discovering valid login processes. Social engineering etc.
  • WPS implementation weaknesses. If they leave the 8-bit pin feature on, then we don’t need the password, we just brute-force for the PIN.

Aside from the 802.11 standard of Wi-Fi there is Bluetooth for wireless communication.

  • Bluejacking. Send unsolicited messages to open Bluetooth devices.
  • Bluesnarfing. Stealing information from the device.
  • RFID cloning. Unauthorised copy of the device’s RF signal - which is used for access cards , ID badges/cards and other tokens to grant access to facilities.
  • Jamming. DoS attack where we litter the network with packets to disable communication among devices. Whilst it is certainly a very loud attack, if the company is spread out over many regions, if the company has outsourced some of their functionality to other parties, then jamming them may not spark instant recognition in the technicians, as they don’t know whether they’re being hacked or whether the third-party is just having an issue. Once it has been resolved though , I pray we got what we came for!
  • Repeating. This is where we receive and re-transmit a signal to increase range. If we need the packets to be accessible to us from , say , back home , then we need to plant an antenna somewhere, or a subtle repeater in their network can allows us to relay traffic to local networks, or within the public reception bay of a company.

3.4 Given a scenario, exploit application-based vulnerabilities.

Applications, be it web , desktop etc are great ways to exfiltrate data and are subject to a huge variety of vulnerabilities - one of the most potent and quick to exploit being the injection attack. They are one of the primary weapons in our wheelhouse because if an application is vulnerable it will take us minutes before we can either grab a ton of data (via SQL injection), or we can inject content , with HTML injection and get people to use our malicious code - as is possible with the comment sections on websites.

SQL injection attacks are a specific example of code injection attacks. This is where we may use JavaScript, maybe the website has a python interactive module who knows. Some JS injection attacks are called XSS attacks as we make use of the inability of the website to handle edge cases of its API or content.

Sometimes I dream of this case but so rarely does it spring into view, and that is the command injection. Like, Linux command injection. So we could type in python -e "..." and insert the standard bash session script in the input field - provided that it does reach down to a Linux OS…

Authentication Exploits

Credential brute forcing. Offline cracking with John the Ripper or Hydra , for SSH or any type of service…

Session hijacking. Intercepting and grabbing another user’s token, which we can do in combination with XSS, as the script may be persistent on the server and load for each client, we could then do var cookie = document.cookie; send(cookie); or something like that we have successfully stolen their credentials.

A redirect attack can happen at any level of the organisation’s infrastructure, but essentially what we want to do is either send the user to a different site from what they expected either by typosquatting , poisoning a cache on their laptop, phone , having them click a bogus link etc.

Onto the actual credentials now. A lot of manufacturers for new devices will leave a very simple default username and password, so remember to update these. Weak credentials aren’t much better , as we presume they are search-able by large databases of popular passwords, or they follow a very predictable password scheme of including names and then numbers at the end.

Some organisations will use an authentication and authorisation server layer between the server and the client which checks to see if the client is right for that requested resource. One of the most popular ways to implement this is using Kerberos - which uses a ticket system where each client has to request a new ticket for each resource they wish to access. If a user is able to forge a ticket by using a different set of credentials, then they get all the access privileges of that user, so make sure to encrypt the Kerberos channels.

Authorisation Exploits

Insecure Direct Object References In some cases, web developers design an application to directly retrieve information from a database based upon an argument provided by the user in either a query string or a POST request. For example, this query string might be used to retrieve a document from a document management system:

https://www.mycompany.com/getDocument.php?documentID=1842 

There is nothing wrong with this approach, as long as the application also implements other authorisation mechanisms. The application is still responsible for ensuring that the user is properly authenticated and is authorised to access the requested document. The reason for this is that an attacker can easily view this URL and then modify it to attempt to retrieve other documents, such as in these examples:

https://www.mycompany.com/getDocument.php?documentID=1841 

https://www.mycompany.com/getDocument.php?documentID=1843

https://www.mycompany.com/getDocument.php?documentID=1844 

If the application does not perform authorisation checks, the user may be permitted to view information that exceeds their authority. This situation is known as an insecure direct object reference.

Parameter Pollution.

Parameter pollution works by sending a web application more than one value for the same input variable, or by adding custom variables to a map, which the developers may have thought only certain groups would run, but we can provide tricky edge cases for developers. For example, a web application might have a variable named account that is specified in a URL like this:

http://www.mycompany.com/status.php?account=12345

An attacker might try to exploit this application by injecting SQL code into the application:

http://www.mycompany.com/status.php?account=12345' OR 1=1;--

However, this string looks quite suspicious to a web application firewall and would likely be blocked. An attacker seeking to obscure the attack and bypass content filtering mechanisms might instead send a command with two different values for account :

http://www.mycompany.com/status.php?account=12345&account=12345' OR 1=1;--

This approach relies on the premise that the web platform won’t handle this URL properly. It might perform input validation on only the first argument but then execute the second argument, allowing the injection attack to slip through the filtering technology. Parameter pollution attacks depend upon defects in web platforms that don’t handle multiple copies of the same parameter properly.

These vulnerabilities have been around for a while and most modern platforms are defended against them, but successful parameter pollution attacks still occur today due to unpatched systems or insecure custom code.

Cross-Site Scripting (XSS) and Cross-Site Request Forgery (XSRF)

The former is where the tester uses JavaScript to invoke some kind of function, either locally within the tester’s browser (which is called a DOM-based XSS attack) - this kind being very hard for the developers to know about, as it leverages intrinsic faults with the content that has been loaded on site, and doesn’t always have to make requests (and those made seem innocuous) it can just be fiddling with some of the functions to show more content then users should be seeing. Another type is called the Persistent/Stored XSS attack, which is where the website presumably keeps content about the user, but if they don’t sanitise our input then we could store a script, and if my account was publicly viewable, then it would mean that stored script would run whenever someone requested for my account page… Lastly there is the reflected XSS which is using JavaScript to concoct a request and the server gives us back some information, the script itself not being stored. This can be done by just putting a <script>alert("does this work")</script> in the input box to see if this vulnerability exists, but you can also do <p onload="alert('does this work')"></p>.

So, XSS is focused primarily on exploiting the server , XSRF is focused on exploiting the user due to a weak API. We can send a user a link for example which is a script which calls a particular site, with the action in the URL string, they may have their cookie cached in the browser or still be within an authenticated session in which case they are automatically authenticated and the action runs as a privileged user…

Clickjacking

This is where we make use of overlays , that have an attacker click on a different link than was intended - whether we use transparent or opaque layers doesn’t matter, and it might be wrapping some seemingly innocent like an image, button etc.

Security Misconfiguration

It may be that the application itself has been structurally compromised by design decisions, certain configuration options etc. It may be that some applications will allow certain requests beyond their set of routes, and so we could run GET requests for:

https://insecure-website.com/loadImage?filename=../../../etc/passwd

This would pull us out of the webserver directory and into the /etc/password directory. Remember the app itself is served from /var/www/html but if we strip back three layers we’re back at / so then we just include the last bit to grab the credential file - and we assume the server is running at a privilege where it has the permissions to do so. The following is a directory traversal attack.

Cookie manipulation. Access to cookies can allow an attacker to change their permission level, by changing fields like admin : False to true instead, or we can get the session ID of someone of the same privilege level - and then encrypting it back up with their schema. This would mean we are authenticated to view the admin page, though we would probably need some credentials in most cases…

File Inclusion

This is related to directory traversal , but it’s where we want to upload or execute files on the server. The latter is called a Local File Inclusion (LFI) attack , as it resides on the webserver itself - and this is akin to a directory traversal attack, though more to do with loading resources, being able to execute programs and not so much just reading the output on the page.

The other type is remote file inclusion (RFI) which is to do with an attacker uploading their file(s) onto a webserver, so it could be a shell script which you later call by exploiting the LFI weaknesses.

Resources:

Insecure Coding Practices

The first thing which you may not see very often in web applications, but certainly in other programs , are loads and loads of comments. Developers find them useful to explain to themselves what the functionality of a particular function is, maybe it shows an test input and the expected output. Remember that HTML is interpreted in the browser, so we see the actual source code and moreover can divulge any comments. Compiled programs optimise comments out of the executable so not so much a worry here.

Lack of error handling is another one, and many functions may only expect a few types of input and outside of that they will simply break, like inputting unreadable characters into the username field for example. Proper sanitisation would format the input appropriately into a given type to work and then can see the content , some languages will even force you to articulate all the edge cases (Haskell and Elm for example). Documenting the error handling and customising error messages may give an attacker too much , some websites may let you know if the username is invalid, or if the password is invalid and messages may tell you whether you got the username right but not the password… Output messages for functions can be very rich, as they list all the functions which were involved in that call stack, and hence you can divulge where you need to start looking next.

Hard-coded credentials is where the program has variables which hold the credentials for a given service, database etc within the code itself, which is a massive problem! Also , some open-source projects will begin by using default credentials when testing, but in later commits replace the code for a proper solution, but the version control still archives those credentials in that snapshot! For compiled programs you can try using strings in Linux with any executable to see what pops out.

Now onto race conditions, which is where many threads within an asynchronous program will use the same resource, be it a variable, file, database etc , and if the ordering of the threads isn’t what matches the logic , it could cause a breakdown in the successive threads that want to use that resource. An analogy for this would be a squirrel trying to sink its teeth into a cashew nut, but then another squirrel jumps in and takes it! And the squirrel ends up biting its own hand : and in computer terms this would probably be enough to crash the program :/ The most common causes are with things like airline tickets , concert tickets etc where people click on them at the same time…It may be that the entire output of a program is dependent on a specific sequence of events, and so threads that maybe are scheduled differently by the scheduling algorithm could cause a breakdown or crash. If the attacker wants to create a DOS , or manipulate the file to use the attacker’s data to execute some script is up to him/her.

The first thing we can do to defend this is set up reference counters. These are structures in the kernel that flag when a resource is in use, so the first thread that makes a request will set this counter, and other threads that want to contact the resource may increment the flag , some reference counter modes come with memory barriers that specify space for each thread, but some might be just as simple (in the case of a variable) as a flag. See this to get the full low-down on reference counters. Another thing we can do to stop race conditions is to simply lock the kernel down and have the resource become inaccessible whilst a thread is operating on it. The simplest type of lock is called a spinlock, which will keep trying to lock down a resource, and if it doesn’t manage it the first try, it will continue to do so, hence the spinning. Read and write locks use the spinlock functionality when trying to access a resource. Instead of shutting a resource down to a single thread, lots of threads can have a read lock, but if a thread wants to write to the resource, then no other process can have any lock, as they would be seeing the updated data structure.

APIs can sometimes be quite light, quite liberal and the same sorts of error handling may occur, parameter pollution is an example of an unauthorised use of certain functions, but again , we need to know the fields, the parameters, their values before we know how best to crack it - starting capturing as much traffic as possible !

Hidden elements are also a thing used in websites, and they store cookies and other program data which the user doesn’t need to see as its completely separate to the content. The attacker will no doubt come snooping though, and it shouldn’t mean the developers get lazy here! Explore this HTML/XML structure to find out how the website represents you as data.

Last up is code signing. Which is where developers sign their code with a private key, and the user of the program will have a public key on their side to authenticate the author’s identity to ensure integrity and that the developers were all employed by the company etc - the owners of the public key certificate. You can then check that every chunk of the code is written and endorsed by the company themselves. However, a lack of code signing would mean attackers could insert their own code between deployment and execution. Worse would be an attacker grabbing a developer’s private key!

Resources:

  • How code signing works.
  • Gist on code signing.
  • In-depth paper detailing the threats of private key loss for code signing vulnerabilities.

3.5 Given a scenario, exploit local host vulnerabilities.

Host computers, clients or servers, have to maintain their security at a multitude of levels, from the wireless networking layer, to the configurations of services and any default settings, privilege escalation attack vectors from user accounts, applications and kernel exploits which meddle with the core of the OS itself… This will be a heavy chapter.

We tend to need a foothold in the network before we can start targeting clients, but you may get lucky. We’ll be looking at how we can exploit all the most common Operating Systems (assuming the patching is poor) and how we could attack them given physical access. We’ll cover mobile devices and the basics of hacking containers and virtual machines to exploit the underlying system.

First and foremost , the easiest local vulnerability by far is where there remains default account settings. Whether this be for a new application, a new device that connects to the network, service accounts with default passwords but more often than this is that the configurations for these accounts are usually left on their defaults: sure the password has been changed, but there may be some permissions which are a bit too liberal and will allow you to escalate the privileges of a user to root - which is more innocuous than compromising the admin account on the system, device or service.

Operating System Vulnerabilities

Linux

The state of security of the Linux kernel is probably the highest among the major three, however it’s not just the transparency , the thought and care that went into development but also the benefit of being obscure and not widely adopted, meaning hackers don’t spend a lot of time trying to hack the system as much as a product like Windows. Saying this though, there are now many different flavours of Linux like AWS Linux, Red Hat, Ubuntu, SE Linux etc and they all seem to be holding up. Having such complexity is a double-edged sword though, as the diverse environment makes it difficult for defenders to keep up and secure those systems. You will have to be aware of the differences, and the principles in one may not transfer to the other.

Fortunately, for the purposes of the PenTest+ exam, you can largely focus on common vulnerabilities, exploits, and attack methods that are shared by most modern Linux systems. As you read through the following pages, bear in mind the differences that you may find between distributions, and remember that your intelligence gathering may need to include version-specific vulnerability and attack research in addition to more typical information-gathering activities.

Since the Linux philosophy is - “Everything is a file”, we shall start with some of the nuances of filesystems and file management we should look for when conducting reconnaissance. Files allow users any of the three functions: read , write , execute. The owner of the file can specify which entities (root , groups, anyone) have which of these permissions. There are also flags that we can specify outside of just these, and it is called the set user ID (SETUID or SUID) flag , and what this does is that it will execute the file and run it as if it were the owner , hence the owner’s user ID is set. What would be great for us to find is if the SUID were set by root, and then any script executed would be ran as root. You will often see this trick in beginner level boxes. Another thing is the Group ID (GUID) which is the same principle, just running the file as if the group were executing it.

;; if we wanted to find all the SUID files, then we can use find 
 
find / -perm -4000

;; but if we aren't sudo then it will spit back permission denined if we check any 
;; directories the user isn't allowed to view (as we didn't execute find with SUID!)
;; we can use sudo to get around this though.

In reality, most kernels are configured to prevent scripts from having an SUID bit set, which is depressing…Executables aren’t exempt though so there is hope! Things like wget for example can have their SUID bit set, and this was a challenge in a given CTF, where we used the program to pull a botched passwords file that I had made and then pushing it into the folder where the original was, hence overwriting it. This then allowed me to log into root and from there the system was compromised.

;; Running sudo -l is the same as the above command, and it lists all the commands 
;; you can run without sudo as sudo.

sudo-l

This enumeration script I ran to narrow down targets on the linux box checked sudo -l and showed the commands I was able to access.

So far we’ve checked out the SUID and GUID flags , the restricted execution flags, but there are also the restricted deletion flags (sticky bits) which when set stop unprivileged users from deleting or renaming a file or directory unless they own it. This would mean that the admin of a system is more comfortable handing this file out to multiple users, but it may mean that the file is editable. Assuming sufficient permissions for the tester, we can embed a keylogger script or something within the file for further information gathering.

Insecure sudo

The Linux command “Superuser Do” or sudo is where we allow any user to escalate their privileges, based on the settings configured in the /etc/sudoers file to allow them to run certain programs as root, are they blacklisted from any programs etc. For own main account on most linux boxes we are quite liberal with permissions and usually set it to *your-username* ALL = (ALL: ALL)ALL which means that for all hosts on the machine this user can run commands on and manipulate any host’s files and folders. The brackets defines all the usernames and groups for which we can execute sudo within and this would be all of them, and the last one states all the applications that can be ran with sudo , again that would be all of them.

If we can see the /etc/sudoers file then we can see all the accounts which are worth compromising as their sudo settings may be more powerful. Access to run Python or Perl as root is sometimes required for scripts on a system, and an otherwise low-privileged account may have this capability.

Shell Upgrade Attacks

In bigger organisations, low level users will be put into “jails” or restricted shells which heavily restrict the ability to change directories, to set PATH or SHELL variables, to specify absolute path names and even stops redirecting output. Fortunately, breaking out may be as simple as starting a separate shell , or using a utility that has a built-in shell function like vi hence creating a new shell space. All of our abilities to do this and other things ultimately depends on:

  • The commands we can run, as specified by sudo (if any) .
  • Check for SUID bits.
  • Check to see if we can run any languages like Perl, Python, Ruby etc.
  • Check to see if you can use redirect operators like | , > and escape characters.

Buffer overflow attacks using the ret2libc library:

The ret2libc library is a core Linux utility holding many useful functions with simplify many system processes, in particular one function allows you to specify the return address of a subroutine after a given job has finished executing. Obviously an attacker could use this for malicious purposes in that he/she could specify the return address as the start of a script or process … It’s technically a buffer overflow in that the program was within a given buffer and its now spilled out into the larger heap. However , this presupposes that the attacker knows the address of their script - which is pretty much impossible if the host is running Address Space Layout Randomisation (ASLR) as it constantly scrambles where fragments of the script are held… Even more difficult on a 64-bit machine. Here is a guide that covers the basics of buffer overflow exploitation.

Linux Kernel Exploits

The Linux kernel is the core of the Linux operating system, and it handles everything from input and output, memory management, and interfacing with the processor to interfacing with peripherals like keyboards and mice. Exploiting the kernel can allow us to manipulate any one of its functions. The difficulty of executing kernel exploits and the fact that most kernel patches will require a system reboot also mean that many administrators will delay kernel patches. This provides an opportunity for penetration testers who can gain access to a system, as kernel exploits may not be patched due to a lower perceived risk! For a massive repository of links, guides, tutorials and exploits go to this repo.

Windows

The Windows world has quite a few differing conventions to Linux, in terms of how security, file and password management is done, comparing the /etc/shadow file for where passwords are kept on Linux, in Windows they’re stored with the SYSVOL folder (of the domain controller) , the admin computer which stores the encrypted passwords of client computers. Whilst this is all in encrypted XML, for years passwords could be stored as an attribute called cPassword in Windows Group Policy items, making it easier to use those passwords for a preference item. The cPassword is just a sliver of XML detailing a particular password, but due to the weak encryption and relative ease of access it compromises domain controllers. Administrators tend to use this capability to easily create local administrator accounts using Group Policy, and if so Microsoft recommends that you keep a script that will scan the SYSVOL folder for any anomalous behaviour, or you could just use something different. See this post for recommendations.

Passwords stored in the cPassword are accessible to any authenticated user in the domain, where they are stored in a shared directory on the domain controller and they are easily decrypted using a static public key published by Microsoft. For the penetration tester, cracking cPassword credentials is made even easier by the Group Policy Preferences module in Metasploit (post/windows/gather/credentials/gpp) or via PowerSploit modules like Get-CachedGPPPassword and Get-GPPPassword, which can be used on the cPassword values found in $SYSVOL in a file named Groups.xml.

Clear-text credentials in LDAP…

LDAP , the Lightweight Directory Access Protocol is the layer below Active Directory (which is the Windows Implementation of the standard) and is used for authentication for many services within the AD domain. Good news for testers is that it’s also a commonly misconfigured service. In fact AD doesn’t force SSL/TLS by default because of compatibility errors and developers who use LDAP commonly don’t use the proper security practices for their authentication… If Group Policy is not configured to prevent it, LDAP Simple Binds will expose credentials by sending them in plain text. This means that passwords can be recovered easily if you can capture LDAP network traffic headed to the AD server using something like Wireshark.

You can easily check to see if LDAP signing is not being enforced on a Windows domain controller by checking the Directory Service log for event IDs 2886 and 2887. Event 2886 indicates that LDAP signing is not enforced and that cleartext LDAP binds are possible. Event 2887 occurs once every 24 hours and reports how many unsigned and cleartext binds have been handled by the domain controller! As a penetration tester, you may not have access to these logs early in a test, but if you do, simply checking for these two event IDs will let you know if you have found an easy target!

Kerberoasting. This is where domain users can query the Kerberos TGS for tickets for other users, if we have sufficient identification material about them. Service accounts are accounts that exist to run services rather than to allow users to log in. They can be a powerful tool for penetration testers. Because service account passwords often don’t expire, compromising a service account can provide long-term access to a system. Kerberoasting is a technique that relies on requesting service tickets for service account service principal names (SPNs) - which are the identifiers that Kerberos uses to associate a service logon account with a service instance, hence we could request to authenticate the account even if we didn’t know the account name. The tickets are encrypted with the password of the service account associated with the SPN, meaning that once you have extracted the service tickets using a tool like Mimikatz, you can crack the tickets to obtain the service account password using offline cracking tools. The Kerberoasting toolkit is found here . Kerberoasting is most effective against shorter, less complex passwords, as it relies on offline cracking, which can be slow when service accounts use long passwords. Kerberoasting is a four-step process: 1. Scan Active Directory for user accounts with service principal names (SPNs) set. 2. Request service tickets using the SPNs. 3. Extract the service tickets from memory and save to a file. 4. Conduct an offline brute-force attack against the passwords in the service tickets.

Acquiring and using hashes. Windows frequently relies on NT LAN Manager (NTLM) password hashes for authentication purposes, and tools like Mimikatz can make retrieving hashes relatively trivial. NTLM hashes are unsalted, meaning that you can frequently crack NTLM hashes to retrieve user passwords—but why bother if you don’t actually need the password and can simply use the hash itself by presenting it to a service? Pass-the-hash attacks rely on injecting hashes into LSASS, or presenting NTLM hashes to services like SMB. This is made easier by the fact that the Sysinternals psexec tool can directly accept an NTLM hash as an argument instead of a password. LSASS is a program that is used to enforce security policy and is used as a point of reference in Windows OSs for things like login verification, and records policies for permissions towards groups and users. Obviously if we can login to LSASS , just providing the hash

Unattended installations. PXE (Preboot Execution Environment) credentials. PXE is where there is a server which can send over images , configured by the security team , and most of the installation itself is automated, meaning the PXE server holds the credentials which would be inserted - moreover if an attacker can grab this configuration files, then they will be able to install an image onto one of their computers, and log into other accounts!

A SAM database (Security Account Manager). The Windows Security Accounts Manager (SAM) database is one of the first places that you are likely to target when you gain access to a Windows system. The SAM contains password hashes that can be easily dumped using Mimikatz or the Mimikatz functionality built into Metasploit. Note that first debugging has to be set, then privileges escalated to NT Authority/System, and finally the SAM gets dumped. Without appropriate privileges, this process will not work!

Dynamic Link Library (DLL) Hijacking. Many Windows applications rely on Dynamic Link Libraries (DLLs) to function. DLLs are modular program elements that can be loaded as they are needed. DLLs are often found with the .dll , .ocx , .cpl , or .drv filename extension, so if you’re looking for DLLs to attack, you’ll find a lot to work with! DLL hijacking replaces the original DLL that would be loaded by an application with a malicious DLL. DLL injection is different from DLL hijacking. DLL injection causes a running process to load a library of your choice.

Exploitable Services

  • Unquoted service paths. This is pretty much the same sort of vulnerability which allows SQL injection to exist due to the fact we don’t escape the characters , whatever data a program allows as input, we can just put the service path of a program in there, or the code which would call our DLL etc…
  • Writable services. Allows an attacker to replace services with malicious programs. We were talking about permissions earlier and if we see that a service is a bit too liberal, then we may have higher than appropriate privilege , and hence we could inject a malicious program.

Insecure file/folder permissions

Things like root files having user level read/write permissions on them…

Keylogger

Records every keystroke

Scheduled tasks

Attacker may add new tasks to run persistently with elevated privileges

Kernel exploits

Unpatched systems are vulnerable…

Attacking virtual machines

Virtual machines (VMs) and containers are both potential targets for penetration testers, but compromising the underlying hypervisor or container host is an even more desirable goal. After all, if you can take over the underlying system, you can then seize control of many virtual machines or containers! The concept of sandbox escape is key to this, as compromising the underlying system requires either access to that system or the ability to escape from the virtual machine or container to attack the system they are running on— thus, escaping the sandbox. Both virtual machines and containers are a type of sandbox, a form of isolation either for a particular OS or for an application, but sandboxes extend past this notion as we see that we can sandbox users in a given OS for when they need to install updates, as seen by NAC , we can create “jails”, or restricted sections of memory with things like chroot which “change root” for a user to a directory of your choosing, and that user cannot access any other directory of file outside of that designation, meaning then you would have to copy all of your necessary programs for them to work in that directory. When setting up things like bash to work in the jail , you can run ldd /bin/bash which shows all the files bash depends on , with their corresponding location, then we can cp all those files in and we’re good to go. A guide on this sort of sandboxing can be found here.

What’s the difference between a virtual machine and a container? A virtual machine is a complete system running in a virtual environment, including emulated hardware that makes the operating system and applications believe they are running on an actual system. Containers run on a physical server and operating system, and they share the host operating system’s kernel (and typically binaries and libraries) in a read-only mode. Containers allow you to isolate applications or services while being lighter weight than a full virtual machine. Containers are often managed as a swarm, making it easier to manage them as a single virtual system.

Attacking individual virtual machines normally follows the same process that attacks against a physical system would. In fact, in many cases you won’t know if you’re attacking a virtual machine, a container, or a physical machine until you have compromised it (and perhaps not even then!). If you suspect that you have compromised a virtual machine, you can look for common signs that the system is virtual, including the hardware that is presented to the operating system. In many cases, checking for the network interface card, or for virtualisation plug-ins like VMware tools or VirtualBox extensions, can tell you if you have compromised a VM. On a Windows system, you can do this quite easily by using wmic:

wmic baseboard get manufacturer,product

The Linux system-detect-virt command is an easy way to determine what virtualisation package is running if the system is running system-d. Other options include using the demidecode command, which can provide similar information, and checking the disk IDs to see if the system is being virtualised by using the ls -l /dev/disk/by-id listing command. Virtualisation is rarely obfuscated in real-world production system environments, so detecting virtualisation should be possible on most systems you encounter. Once you know which hypervisor you are dealing with, you can conduct research on the attack methods that may be available for that specific environment. Exploit tools that allow attackers to escape a virtual machine to directly attack the hypervisor have been sought after for years, with high prices paid for working exploits on the open market. Exploits have been found for VMware, Xen Project, Hyper-V, and VirtualBox, but each has been patched shortly after it was found. In most virtualisation environments, VM escape isn’t likely to work unless a new exploit is introduced and you are able to use it to exploit a compromised host before it is patched by your target organisation. That means that most penetration testers will be far more successful attacking the underlying administrative infrastructure so that they can access the virtualisation management tools and systems than they will be if they rely on VM escape exploits.

Attacking containers

Attacks against OS-level virtualisation tools like Docker often start by compromising the application that is running in the container. Typical penetration testing processes can be used, including port and vulnerability scanning and service exploitation. Once you have compromised a container, you can then attempt to access the container’s host—in fact, in some cases, you can simply run the Docker client from one of the vulnerable Docker containers and connect to the Docker daemon running on the virtual machine! As with most penetration testing efforts, you should carefully document the environment, check for misconfigurations and exposed or vulnerable services, and then pivot as you gain further access.

Now onto the physical world. Physical device security

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 . 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:

3.6 Summarise physical security attacks related to facilities.

Physical access to systems , networks and facilities can provide opportunities that remote network attacks can’t. In most cases, direct physical access is one of the best ways to gain higher-level access, as we could plant Raspberry Pi’s everywhere, we could steal backup media, we could lock-pick (remember pre-engagements here). Here we want to test the physical security controls like the entry access systems of the reception, to get to offices, to even get on site. We shall see the coordination between security guards, sensors , cameras and the security training of staff and the procedures they follow. Essentially we need to draw out our own Zenmap topography, listing where each control is, how they’re linked to each other, how it works etc.

Much like any network-based test, it is important that we first do some passive and active reconnaissance , analysis and enumeration - using any of the knowledge gained from network-based assessments too if possible. Part of our reconnaissance phase will be the on-site observation phase in which you document the facility , its environment and visible controls. With a networked test you can send active probes to network devices that mostly do the work (you don’t have to physically go and check the device each time!) . I mean, we could use a drone for this and still claim to have a degree of “remoteness” , but this drone would be easy to spot, trigger a security alarm and they can be noisy. What would be better is pretending to be a surveyor or something and having some context as to your acquaintance (hence making it believable). This pretext is the fictional situation you need to concoct in order to seem believable, and this is part of your social engineering toolkit. Relying on our active reconnaissance work here to make an airtight alibi , what would be good is to dress in the uniform of their local electrician , or to get a temporary job at the place where the employees go for lunch etc. Hopefully our pretexting is sufficient to eventually get us through the door! Once we’re in though we need to stay sharp, how will we deal with unexpected encounters with security and facility staff? If we run into someone who asks who we are , how we do identify ourselves and what stories do we use? Do we have any form of identification to get us out of this?

As we really don’t have a good idea of the facility yet , there is a probability that we set off an alarm, we get caught or worst case scenario is we spook someone enough for he/she to call the police… I remember reading somewhere that a pen tester wasn’t aware onetime that the police were called, and they arrested him and detained him overnight , eventually it got resolved , but again you need to remember the people that are in power need to be aware of your work.

All of these possible outcomes need to be outlined in the SOW for the onsite test.

Entering Facilities

Gaining access to a facility is one of the first steps we shall do when conducting our on-site (physical) assessment. One of the easiest ways into a facility is to accompany a legitimate employee. If you look like you belong in the facility, and the organisation is one in which not all employees know each other, piggybacking is a good option. Piggybacking attacks rely on following employees in through secured doors or other entrances. Higher-security organisation may use mantraps to prevent piggybacking and tailgating. A properly implemented mantrap will allow only one person through at a time, and that person will have to unlock two doors, only one of which can be unlocked and opened at a time. While piggybacking can be a useful solution, other related techniques include dressing as a delivery driver and bringing a box or other delivery in or finding another likely reason to be admitted by employees. Even if they won’t let you follow them in because of security concerns, there is almost always a reason that will persuade them to open the door for you!

mantrap

Many entry control systems still use basic locks to guard at particular points and so it makes it possible for us to lockpick doors, desks, filing cabinets and other types of secure storage. There are several ways to duplicate keys, including copying them from photos of keys, creating an impression of a key (impressions also work for biometric fingerprints - see Mr.Robot). There will be many individual keys which map to a single layer, and they are given to low-level security staff, but there is also the manager’s master key - which is compatible with any given lock. It may be possible to reverse-engineer the design of the master key given sufficient numbers of lower-level keys. The basic premise though is that you use any number of metal rods, called picks, and they aim to jiggle the key pins so that the shear line is the same for all of them. Here is a good guide to lockpicking.

Bypassing locks without using keys is also possible depending on the door - so you also need to pay attention to RFID systems (so we can clone the badge) and magnetic stripe access card systems and cloning tools, as well as any other entry access mechanisms in use in the organisation. Push-button locks, electronic keypads, and other mechanisms may be used, and gaining access can be as simple as watching for a legitimate user to punch in their code in plain sight! Aside from having to use lockpicking tools we can also do some lock bypass techniques like using what’s called a shove key, which is a thin metal shim that can be hooked over latches and locks to allow a pen tester to disengage the locks by shoving it into the main shaft, behind the keypad and using these can pop the lock and grant access. Using an old-school bolt-cutter that removes hinges or snaps the lock is also an option, but one strong enough is usually a pain to carry around and it doesn’t help with a convincing alibi if we’re caught…

Egress sensors are a type of door which automatically opens in one direction, they are often used in heavy traffic areas to automatically unlock or open doors so that staff can exit easily, but this means that some especially agile penetration testers can use them as an access method. This vulnerability has prompted some organisations to remove or disable egress sensor systems in areas like data centres - but they do remain in many locations. Once an organisation had placed egress sensors on a heavily used door to allow it to open easily for valuable but heavy portable equipment that moved frequently between facilities to be transferred more easily. Thieves with knowledge of the organisation used a crack between the access doors to slide a thin probe with a flag on it through and wave it in front of the egress sensor. This activated the external doors, allowing the thieves into the building. From there, they proceeded to steal highly valuable equipment from a locked secure storage room. The egress doors happily opened themselves again to allow the thieves out, too!

Dumpster diving is a good way of looking through useful information, though some companies will lock their bins first which may be an obstacle it would be of incredibly high value and often times with these documents we care more about the metadata than the data - the sender and recipient emails, their phone numbers etc. This will make social engineering and phishing attacks exponentially more successful, as they now have the ability to morph into spear phishing, if the pretext is sufficiently relevant and up to date.

Bypassing the perimeter defences and barriers

Physically bypassing a control by simply jumping over a fence or gate is pretty old school and if there aren’t any spiked tips or barbed wire then go for it! Fences can be quite low down to deter vehicles, they may be reinforced with aircraft cable , which is a twisted metal wire capable of withstanding impact and for this sort of threat a proportion of the fences may also be dug underground to increase sturdiness and to deter people digging under them. High security locations such as this may have guard posts, including gate guards (possibly on a routine patrol). Our reconnaissance for this sort of entry would need to include:

  • Which groups of people, or individuals are allowed through.
  • What kinds of identification do they need.
  • What their entry schedules and habits are.

As a penetration tester, you should fully document fences, their layout and weaknesses, and where and how access is provided through them. In many cases, your focus will be on how to use existing gates and entrances rather than breaching the fence, but a complete penetration test should also document existing breaches and weaknesses.

Other physical defences to watch out for

Whilst not directly quoted on the PenTest+ exam, no doubt you will have to face these physical controls:

  • Alarms, which may need to be bypassed or disabled.
  • Lighting, including motion-activated lighting.
  • Motion sensors that may active alarm systems.
  • Video surveillance and camera systems that may record your activities.

3.7 Given a scenario, perform post-exploitation techniques.

Right ! We’ve made it a long way, exploit after exploit has worked its magic and the system is ours. Before we write our report we need to persist ourselves on the system , we need to add a backdoor onto the system that will make compromising it much easier next time, if our exploit is patched and there was only one way in, it would silly not to instantiate ourselves into the registry or have some other daemon setup which does the work of connecting for us.

Lateral Movement

Now we’re in , we need to move along the machine itself, looking for any gaps that we can squeeze code into:

RPC/DCOM. Historically, RPC/DCOM (Remote Procedure Call/Distributed Component Object Model) exploits were a common way to attack Windows NT, 2000, XP, and 2003 Server systems, and even modern attack tools often have RPC/DCOM exploits available. DCOM is a Microsoft software component and it essentially means two Component Objects are trying to establish a connection each other over the network so they can pass messages two and fro. We would want to use this to connect to the victim’s machine and to start calling procedures using the application’s privilege space. More modern exploits tend to focus on other elements, such as the .NET interoperability layers for DCOM. While occasionally RPC/DCOM vulnerabilities continue to appear, and exploits are often written for them, RPC/DCOM exploits are far less common today. Classifies as remote execution within an application.

PsExec The Sysinternals Windows toolkit includes PsExec, a tool designed to allow administrators to run programs on remote systems via SMB on port 445. That makes it an incredibly useful tool if it is available to you during a penetration test, as you can execute arbitrary commands, up to and including running an interactive shell. Unfortunately for modern attackers, this has been abused so much over time that most anti-malware tools will flag PsExec the moment it lands on a system. A number of Metasploit exploit modules also reference PsExec, which isn’t actually the Microsoft Sysinternals tool. Instead, the Metasploit PsExec exploit embeds a payload into a service executable, connects to the ADMIN$ share, uses the Service Control Manager to start the service, loads the code into memory and runs it, and then connects back to the Metasploit machine and cleans up after itself! For an in-depth look at this and related techniques, visit https://toshellandback.com/2017/02/11/psexec/. This classifies as remote execution for installed programs. More power !

More resources on PsExec:

PS Remoting/WinRM Modern Windows systems running Windows 7 or later use Windows Remote Management (WinRM) to support remote PowerShell command execution. For a penetration tester, being able to run PowerShell commands on remote systems is very handy, but this feature has to be turned on first. Fortunately, it is simple. Remote PowerShell command execution can be turned on using the enable-PSRemoting -force command while running PowerShell as an administrator. If the systems aren’t part of the same domain, you will still have to set up trust between them using the TrustedHosts setting: Set-Item wsman:\localhost\client\trustedhosts [ipaddress or hostname]. Once you have done this, you have to restart WinRM, and then you can run remote PowerShell commands at will. For a penetration tester, this can make further exploits and retaining access even easier, as long as it remains undetected. This is to execute any command remotely within the terminal, just as powerful !

WMI Windows Management Instrumentation (WMI) allows for remote management and data gathering installed on all Windows systems, making it an attractive target for penetration testers and attackers. WMI provides access to a huge variety of information, ranging from Windows Defender information to SNMP to Application Inventory listings. WMI can allow remote execution of commands, file transfers, and data gathering from files and the Registry, among many other capabilities. Multiple PowerShell tools have been written to exploit WMI, including WMImplant and WmiSploit . WMImplant has a number of useful functions for lateral movement, including information gathering using basic_info and checks to see if there is a logged-in user via vacant_ system . This would be remotely executing data analytics, registry information etc which is a very valuable data source.

SMB is a protocol which allows you to access services and if we can compromise the server which hosts the services we will gain a much larger topology map, we can remotely execute commands and services if we wish etc. To compromise the server it is important to know what the underlying architecture is, as the implementation of SMB will differ between Windows - which keeps the original name , current version being 3 , and Linux which has the Samba implementation of the protocol. For Kali tools like smbmap and other NSE scripts will do the scanning, enumeration phases for us.

RDP is the Remote Desktop Protocol for Windows and whilst exploits are rare they’re certainly powerful. Apple Remote Desktop , ARD , shares the same sorts functionality and there was a vulnerability present in Mac OS 10 High Sierra which included a remote root exploit via Screen Sharing or remote management, but these not only get patched quickly they are also complicated to execute.

VNC. Virtual Network Computing (VNC) is another common remote desktop tool. There are quite a few variants of VNC, including versions for Windows, Mac OS, and Linux. Like RDP and ARD, VNC provides a handy graphical remote access capability, but it may also have vulnerabilities that can be exploited, and it offers a way for an attacker to use captured credentials or to attempt to brute-force a remote system. Metasploit also includes VNC payloads, making VNC one of the easier means of gaining a remote GUI when delivering a Metasploit payload.

X-Server Forwarding X11, or X-Windows, often simply called X, is the graphical windowing system used for many Linux and Unix systems. X sessions can be forwarded over a network connection, passing along an entire desktop or a single application. In most modern use, this is done via an SSH tunnel, but X sessions that are not secure can be captured and exploited through session hijacking or capture.

Telnet is an unencrypted service that provides remote shell access. Because the service is unencrypted, Telnet connections can be sniffed to capture credentials if they are in use. Simply finding Telnet accessible on a remote system does not mean that there is a vulnerability, but it does mean that you can target any logins if you can find an intermediate host that can capture network traffic bound for the Telnet server.

SSH (Secure Shell) provides remote shell access via an encrypted connection. Exploiting it normally relies on one of two methods. The first looks for a vulnerable version of the SSH server. If the SSH server service is vulnerable, various issues can occur, including credential exposure or even remote access. Replacing the SSH server service with a Trojan included or modified version to capture credentials or provide silent access is also possible if you are able to gain sufficient access to a system. Another common SSH attack method is through the acquisition of SSH keys and their associated passphrases from compromised hosts or other exposures. SSH keys are often shared inside organisations, and once they are shared they often remain static without a regular change process. This means that capturing an SSH key, particularly one that is embedded into scripts or otherwise part of an organisation’s infrastructure, can result in long-term access to the system or systems using that key. Since SSH keys that are shared sometimes have blank passphrases, or the passphrases are distributed with the shared key, even that layer of security is often compromised.

Scheduled Tasks and cron jobs

Using scheduled tasks to perform actions on a compromised Windows host is a tried-and true method of retaining access. The same is true of cron jobs on Linux and Unix hosts, and this means that defenders will often monitor these locations for changes or check them early in an incident response process. That doesn’t mean that the technique isn’t useful—it merely means that it may be detected more easily than a more subtle method; but unlike memory resident exploits, both scheduled tasks and cron jobs can survive reboots.

To schedule a task via the command line for Windows, you can use a command like this, which starts the calculator once a day at 8:00 am:

SchTasks /create /SC Daily /TN "Calculator" /TR "C:\Windows\System32\calc.exe" / ST 08:00 

The same technique works with Linux or Unix systems using cron, although cron keeps multiple directories in /etc/ on most systems, including /etc/cron.hourly , /etc/cron .daily , /etc/cron.weekly , and /etc/cron.monthly . Scripts placed into these directories will be executed as you would expect based on the name of the directory, and the scripts can include a specific number of minutes after the hour, the 24-hour military time, the day of the month, the month, the day of the week, and the command to run. Thus 0 30 1 * * /home/hackeduser/hackscript.sh would run the first day of every month at 12:30 am. and would execute hackscript.sh in the /home/hackeduser directory. Of course, if you’re trying to retain access to a system, you’ll want to be a lot more subtle with filenames and locations! One of the most common uses of this type of scheduled task is to retain access to systems via a remotely initiated “call home” script. This prevents defenders from seeing a constant inbound or outbound connection and can be used to simply pick up files or commands from a system that you control on a regular basis.

Daemons are processes that run autonomously and in the background, we can specify our daemons using cron or SchTasks manager.

Back doors are those which aim to bypass standard security control by sitting at a level below checks, or being outside of the domain of properties which the system would check for. We can install a backdoor with the assistance of a rootkit , which are a set of “surgeon tools” which effectively perform keyhole surgery, aiming to place a virus where things like the kernel may not see, the Antivirus may not see it etc. All our information gathering , reconnaissance and vulnerability scanning will determine the most effective spot , and the most effective rootkit tool to place our persistence scripts.

Trojans may help us to get the rootkit onto the system, by disguising itself as useful software.

New user creation may be very suspicious … but nonetheless its a user space for an attacker. Make sure to try and fuddle the creation date of the new user to coincide with on-boarding with other staff.

Stealth

Clean up all unnecessary files you used (like bash_history), all directories and tools that we installed - including any new dependencies ! This is why many exploits are compiled products, which are pre-packaged self-contained units.

Hiding files we need to leave by encrypting them, changing their name or permissions , changing the code to become more obfuscated etc. Sanitise log files , remove certain entries or entire service files all together if possible.

Remove any traces of activity while accessing the environment.