Posts

Showing posts from 2013

Searching Log Files for a List of IP Addresses

Tried to create a script that would be a little more efficient than greping one IP Address at a time from a long list provided:

#!/bin/bash

# Tried to make searching through logs more efficient with this script by batching the grep statements
arrayIPAddr=()
while read line
do
        arrayIPAddr+=("$line")
        arrayIPSize=${#arrayIPAddr[@]}
        # Only issue is the last 1 to 14 records will not be looked at due to the hard cutoff at 15
        if [ $arrayIPSize == 15 ]; then

                cat logfile.txt | grep -e ${arrayIPAddr[0]} -e ${arrayIPAddr[1]} -e ${arrayIPAddr[2]} -e ${arrayIPAddr[3]} -e ${arrayIPAddr[4]}  -e ${arrayIPAddr[5]} -e ${arrayIPAddr[6]} -e ${arrayIPAddr[7]} -e ${arrayIPAddr[8]} -e ${arrayIPAddr[9]}  -e ${arrayIPAddr[10]} -e ${arrayIPAddr[11]} -e ${arrayIPAddr[12]} -e ${arrayIPAddr[13]} -e ${arrayIPAddr[14]}
                arrayIPAddr=()

        fi

done < "ipList.txt"

As far as results, with this I was able to cut the amount of time it took down…

Cisco Password 7 Decrypter

#!/usr/bin/perl
use File::Copy;

############################################################################
# Vigenere translation table
############################################################################
@V=(0x64, 0x73, 0x66, 0x64, 0x3b, 0x6b, 0x66, 0x6f, 0x41, 0x2c, 0x2e,
    0x69, 0x79, 0x65, 0x77, 0x72, 0x6b, 0x6c, 0x64, 0x4a, 0x4b, 0x44,
    0x48, 0x53, 0x55, 0x42, 0x73, 0x67, 0x76, 0x63, 0x61, 0x36, 0x39,
    0x38, 0x33, 0x34, 0x6e, 0x63, 0x78, 0x76, 0x39, 0x38, 0x37, 0x33,
    0x32, 0x35, 0x34, 0x6b, 0x3b, 0x66, 0x67, 0x38, 0x37);
############################################################################

############################################################################
# Usage guidelines
############################################################################
if ($ARGV[0] eq ""){
   print "This script reveals the IOS passwords obfuscated using the Vigenere algorithm.n";
   print "n";
   print "Usage guidelines:n";
   print "…

Using aircrack-ng, airdecap-ng, tshark, and grep regex

Recently in a capture the flag event I had to utilize aircrack-ng to break the WEP key on a packet capture, then airdecap-ng to decrypt the contents of the WEP packets and export them to another packet capture, use tshark to output to text and then use a grep regular expression to extract base64 Authentication Basic username and passwords.

Below are the commands that I ran to accomplish this:

# aircrack-ng WIRELESS-C2.cap 
Opening WIRELESS-C2.cap
Read 73650 packets.

   #  BSSID              ESSID                     Encryption

   1  00:40:10:20:00:03  Wireless Challenge Two    WEP (25704 IVs)

Choosing first network as target.

Opening WIRELESS-C2.cap
Attack will be restarted every 5000 captured ivs.
Starting PTW attack with 25704 ivs.


                                            Aircrack-ng 1.2 beta1


                            [00:00:00] Tested 397 keys (got 25082 IVs)

   KB    depth   byte(vote)
    0    2/  4   DA(31232) C0(30976) 22(30720) E8(30720) 16(30208) 25(30208) D0(30208) 
    1    0/  1  …

Using python inside of gdb

To use python inside of gdb:

(gdb) run < <(python -c 'print "A"*345')

Man-in-the-middle Testing of a Mobile Application

On initial tests of a mobile application that I was utilizing it sent the username and password in plain-text to a server for authentication.  Upon working with the company they fixed the issue and asked me to test again.

I was very impressed with them fixing the mobile application so quickly.  Here are my chicken scratches of how I tested the mobile application the second time.

Using my laptop I have a wireless interface (wlan0) and then a LAN connection (eth0).  I connected a wireless access points internet side of the connection to eth0.  The wireless access points IP is 192.168.3.5 and my eth0 is 192.168.3.1.  Then the access points internal addressing was 192.168.5.1 with DHCP range of 192.168.5.100~.  I then connected my mobile device to the DHCP range of that access point.

My wlan0 card was connected to 192.168.1.100~ with a router IP of 192.168.1.1.

So in essence the flow of outbound traffic would be:
192.168.5.100
to
192.168.5.1
to
192.168.3.5
to
192.168.3.1 (eth0)
to
192.168…

Create Windows User from the Command Prompt

To create a windows user from the command prompt:

net user /add <username> <password> To add the user to the local administrators group:

net localgroup administrators <username> /add

SL4A Python Script - Built Simple Python Listener to Allow Remote Execution on Droid

I built this python script to take remote commands and execute them locally on the droid as if I had terminal access.  It establishes a connection on port 21000 on the droid.  Then you can connect using netcat or other clients.  Then I added the functionality (since the 1st terminal emulator would not allow cat of files) to view the contents of files.  With this I discovered the insecure storage of files on the sdcard that other researchers have also recognized.

import android
import os

from socket import *

droid = android.Android()

HOST=''
PORT=21000
BUFSIZE=1024
ADDR = (HOST, PORT)

tcpSrvSocket = socket(AF_INET, SOCK_STREAM)
tcpSrvSocket.bind(ADDR)
tcpSrvSocket.listen(5)

while True:
    tcpClientSocket, addr = tcpSrvSocket.accept()
    print 'Connected from:', addr

    while True:
        data = tcpClientSocket.recv(BUFSIZE)
        if not data:
            break
        if "cat" in data:
            # Remove the 'cat ' in the data
            fileName = data[4:]
      …

SL4A Python Script - Delete SMS Messages from Phone based on Keyword

I developed this script to run on my droid to remove the SMS messages that are sent to me from the python script that logs into Twitter using OAUTH and sends me a text through an email account.

This was to assist in keeping my text messages cleaned out.

import android

droid = android.Android()

msgids = droid.smsGetMessages(False).result
for message in msgids:
    if "14100" in message['address']:
        #print message['_id']
        #droid.ttsSpeak(message['body'])
        droid.smsDeleteMessage(message['_id'])

The script also has the capability to speak the messages prior to deleting them.

Great Book: Violent Python by TJ O'Conner - Geo Location Script Adapted

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Script was adapted from Violent Python by TJ O'Conner

import dpkt
import socket
import pygeoip
import optparse
# Geodatabase from Maxmind
gi = pygeoip.GeoIP('geo.dat')


def retKML(description, ip):
    rec = gi.record_by_name(ip)
    try:
        longitude = rec['longitude']
        latitude = rec['latitude']
        kml = (
               '<Placemark>\n'
               '<name>%s</name>\n'
               '<Point>\n'
               '<coordinates>%6f,%6f</coordinates>\n'
               '</Point>\n'
               '</Placemark>\n'
               ) %(description, longitude, latitude)
        return kml
    except:
        return ''



def main():
        # logfile.log contains 2 columns consisting of the label and the IP Address
        f = open('logfile.log', 'r')
        kmlPoints = ''
        count = 1
        for line in …

Powershell Script to Fix Unquoted Path Vulnerability

# This script is designed to fix an unquoted path vulnerability that could be detected as a vulnerability
# Designed for Powershell

$Username = 'username'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass

# Resolve the IP Address to a Hostname
$hostName = [System.Net.DNS]::GetHostbyAddress("IP Address").HostName

# Created to change the unquoted path for "A Service"
$info = Invoke-Command -ComputerName $hostName -ScriptBlock {
    (Get-ItemProperty "hklm:\SYSTEM\CurrentControlSet\Services\Service Name" -Name ImagePath).ImagePath
} -credential $Cred

if ($info -eq 'Z:\Path Name')
{
    Write-Host "Service does not contain quotes adding them for Service"
    Invoke-Command -ComputerName $hostName -ScriptBlock {
        Set-ItemProperty "hklm:\SYSTEM\CurrentControlSet\Services\Service Name" -Name ImagePath -…

Java IDX Notes from BSidesSLC

To find the files that are left behind by Java go to \\comp\c$\Users\*\AppData\LocalLow\Sun\Java\Deployment\cache\6.0  The path may vary.

In each numbered folder it will contain an IDX file and the actual file.

By utilizing https://github.com/Rurik/Java_IDX_Parser/blob/master/idx_parser.py you can evaluate the IDX file to see if the information contained could be malicious.

Lifehacker - Supercharge your Command Line

To be able to search forward and backward based on keyword create a .inputrc file with the following contents:

"\e[A": history-search-backward
"\e[B": history-search-forward
set show-all-if-ambiguous on
set completion-ignore-case on

Then from the command line $ (keyword or letters) up or down to navigate!

Sweet!

Twitter with OAuth - Download Tweets and Email

I have found that I can receive alerts of security advisories on Twitter quicker than going to news sites.  So I started looking into building a python app to authenticate, download the last 20 tweets, and then send through an email the tweet based on the keyword identified.

To setup python for this:
apt-get install python-pip
pip install tweepy
pip install oauth
pip install oauth-python-twitter

I also had to log into the development side of Twitter and create an application and approve it for authentication to get the keys and secrets.  Then the following python script came about:

#!/usr/bin/env python

import sys
import string
import tweepy
import smtplib

# Twitter account information
CONSUMER_KEY = 'xxxxx'
CONSUMER_SECRET = 'xxxxx'
ACCESS_KEY = 'xxxxx'
ACCESS_SECRET = 'xxxxx'

# Gmail Access for the sending of an email
server = smtplib.SMTP("smtp.gmail.com", 587)
server.starttls()
server.login('email@address.com', 'password')

auth = tweepy.OAut…

De-obfuscating Malware (Subtracting Hex)

Recently I came across some webpages that were referring to the Redkit malware.  The page that I was directed to contained some javascript like the following:

!40!12!f!25!25!25!25!25!25!25!25!69!74!68!7a!72
!6a!73!79!33!6c!6a!79!4a!71!6a!72!6a!73!79!47!7e
!4e!69!2d!2c!76

Then I noticed in the javascript that it was subtracting 5 from the hex values after the !40 was converted to a hex value.

So I built this quick python script to convert the hex to decimal subtract 5 and then back to hex. (I also noticed another webpage variation that would subtract 7)

#!/usr/bin/env python

ins = open("temp", "r")
array = []
for line in ins:
    print hex(int(line, 16) - 5)

Then I used the hex to ASCII converter to pull the websites out that I was interested in seeing that were being obfuscated.


Scapy is Awesome

Created 2 scripts using scapy to analyze some packet captures.  Just wanted to preserve what took some time to design.

This first capture takes a packet capture and displays the Destination, Source, data in the packet, and the time.  A challenge was to identify a way to display the time in a readable format.

#!/usr/bin/env python


from scapy.all import *
import time

packets = rdpcap("file.pcap")
totalPackets = 0
totalDataSize = 0

for pkt in packets:
        pktSrc = pkt.sprintf("%IP.src%")
        pktDst = pkt.sprintf("%IP.dst%")
        # Remember that the time is in UTC format
        pktTime = time.strftime("%d %b %Y %H:%M:%S", time.gmtime(pkt.time))
        pktHour = time.strftime("%H", time.gmtime(pkt.time))
        pktMinute = time.strftime("%M", time.gmtime(pkt.time))
        pktData = pkt.sprintf("%Raw.load%")
        pktDataLength = len(pkt.sprintf("%Raw.load%"))
        if pktHour == "7" and int(pktMin…

Decode ASCII CharCode to ASCII

Needed to create an ASCII decoder thought I would set it aside for later use:

#!/bin/bash

cat $1 | sed 's/48,/0/g' | sed 's/49,/1/g' | sed 's/50,/2/g' | sed 's/51,/3/g' | sed 's/52,/4/g' | sed 's/53,/5/g' | \
         sed 's/54,/6/g' | sed 's/55,/7/g' | sed 's/56,/8/g' | sed 's/57,/9/g' | sed 's/65,/A/g' | sed 's/66,/B/g' | \
         sed 's/67,/C/g' | sed 's/68,/D/g' | sed 's/69,/E/g' | sed 's/70,/F/g' | sed 's/71,/G/g' | sed 's/72,/H/g' | \
         sed 's/73,/I/g' | sed 's/74,/J/g' | sed 's/75,/K/g' | sed 's/76,/L/g' | sed 's/77,/M/g' | sed 's/78,/N/g' | \
         sed 's/79,/O/g' | sed 's/80,/P/g' | sed 's/81,/Q/g' | sed 's/82,/R/g' | sed 's/83,/S/g' | sed 's/84,/T/g' | \
         sed 's/85,/U/g' | sed 's/86,/V/g' | sed 's/87,/W/g&#…

Creation of a Simple CTF Scoreboard and DB

I created a simple PHP/MySQL Capture the Flag Scoreboard / Flag Submission web app.  It is simple and vulnerable to web exploits.  I designed this for a CS4740 class that I am teaching as we are learning Metasploitable.

Create MySQL Database and Tables for the CTF
create database ctf;




create table flagsFound(flagID VARCHAR(8) NOT NULL PRIMARY KEY, finderID INT);




create table students (studentID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(40));




create table flagsDB(flagID INT NOT NULL AUTO_INCREMENT PRIMARY KEY, studentID INT, flagChecksum VARCHAR(50));
Populate Table with Participants insert into students VALUES (1,"Ann");

insert into students VALUES (2,"Bob");

insert into students VALUES (3,"Curt");

insert into students VALUES (4,"Dan");


Create Text File with Flags and Call it flags.txt Make it with 2 columns of data the owner of the flag and the keyword 1 Asteroid 2 You 3 Red 4 Blue …
Create and Run Simple Bash Script to Populate SQL File for f…

Python or Perl Quick Notes on Creating a String

To use python from the command line to create a string of characters:

python -c 'print "A"*5' - This will print a string of 5 A's

To use perl from the command line to create a string of characters:

perl -e 'print "A"x5 - This will print a string of 5 A's


Comparing 2 Nessus Scans

I had to face a challenge today of comparing 2 nessus reports and identifying the progress made towards fixing the vulnerabilities.

First, I used nessus to export each report respectively to a csv file.

Second, I removed the first line of the csv file.

Third, I built 2 tables to accept the input with the following sql respectively:

create table nessusScan1(pluginID INT, CVE VARCHAR(40), CVSS VARCHAR(40), risk VARCHAR(40), ip VARCHAR(40), protocol VARCHAR(40), port INT, name mediumblob, synopsis mediumblob, description mediumblob, solution mediumblob, pluginoutput mediumblob);

create table nessusScan2(pluginID INT, CVE VARCHAR(40), CVSS VARCHAR(40), risk VARCHAR(40), ip VARCHAR(40), protocol VARCHAR(40), port INT, name mediumblob, synopsis mediumblob, description mediumblob, solution mediumblob, pluginoutput mediumblob);

Forth, I inserted the data from the csv file into the respective table:

load data local infile 'Nessus1.csv' into table nessusScan1 fields terminated by ',…