Sharing a little programming know-how…

Latest

Living to work? Or working to live?

“I don’t live to work, I work to live.”

A good friend of mine used to say this when we were in our 20’s. Now that I’m older and wiser, I have to admit that it was pretty wise of him to understand this when so young and full of beans. As a long time practitioner in cyber security incident response, I’ve worked my fair share of all-nighters and long running incident response cycles. These scenarios are never pleasant and often disrupt our lives significantly. If you’ve ever had to respond to a network outage or widespread compromise, you know what I’m talking about. I’ve got some very memorable moments around MS014-68 and WannaCry (and it’s little cousin NotPetya). Unfortunately, these are not happy moments. Although the thrill of investigating something new does make life exciting, generally speaking, that thrill is only temporary and then the fatigue and days and nights eating at your desk start to take their toll.

What’s funny is that the way you deal with uncertainty is to plan for it. As intelligent beings, we have the ability of foresight and planning that can help prevent major disruptions to our lives. The problem we run into is the drive for efficiency and cost reduction. As we improve reliability and security controls, our true “the world is on fire” incidents become fewer and far between. This makes it more difficult to justify a fully redundant IT security team that can surge to meet the demand of 24/7 operations required by a security incident.

Enter the MSSP, which can spread the cost of redundant staff across multiple clients. This is where economies of scale can have a major impact to the bottom line IF you are poised to take advantage of them. Critical to the use of an MSSP is the ability to integrate the security function into your operations just as if they were your own team. Response time, programmatic integrations for automation, and ITSM best practices are all critical to this relationship. Without direct control of the security response function, you need transparent understanding that all is working as expected. This isn’t a nice to have. It’s an absolute must.

Brute-force Encrypted Archive

Given a list of potential passwords it is entirely possible to brute-force an encrypted archive.  A recent challenge I encountered involved an encrypted archive with a password that was likely derived from a list of popular restaurant’s in PDF form.  The PDF was a listing you might find on a tourist information website, so it included addresses, ratings, descriptions, etc.  So not just a simple text list.  The names were also properly capitalized and included punctuation (hyphens, apostrophes, etc.) in addition to grammatical articles (the, a/an).

A simple approach would be to simply try these names using your favorite archive program (e.g. 7-Zip).  That get’s boring pretty quick, so let’s script it!


import subprocess
import re
passlist = ["A Place", "The Fine Diner", "Moe's Eatery"] # You get the idea, this could also be put in a text file and read in

passset = set()
for x in passlist:
    passset.add(x)
    passset.add(x.lower())
    passset.add(x.upper())
    passset.add(re.sub('[^a-zA-Z0-9]','',x))

passlist = passset
success = False
for attempt in passlist:
    try:
        print "Trying " + attempt
        subprocess.check_output(r'"C:\Program Files\7-Zip\7z.exe" e -y -p"'+attempt+ r'" -oC:\tmp "C:\tmp\encrypted-archive.zip"')
        success = True
        break
    except subprocess.CalledProcessError as e:
        print "Try again!"

if success:
    print "Success!"
else:
    print "All permutations attempted! Exiting program..."

Nothing groundbreaking here. The first for takes the original list and adds permutations (lower case, upper case, no punctuation or spaces). Then the second for simply invokes the 7z.exe executable with command-line arguments. 7-Zip is well-written and returns an exit code/number that indicates an error. Python handles this by throwing a subprocess.CalledProcessError, which nicely allows my script to test for success.

Automating Time Card Entry in Outlook

I’ve got a weekly recurring task to enter my time card information into a intranet web site.  This is pretty mundane stuff and I would often forget to do this when I first started my job.  Thankfully there was a grace period for noobs and I didn’t miss any paychecks.

Eventually the grace period did run out so I set up a recurring task in Outlook to help me remember.  I put the hyperlink to the site in the notes of the task so that I could just click the link to open up the website.  This worked great the first week, but the following week I got no reminder!  What happened?  Well, it turns out when I clicked the link the browser opened and took focus away from the task and I never “circled back” to complete the task.  After the task is marked complete, Outlook generates a new task for the next recurrence.  If it’s not marked complete, it is simply marked as incomplete.  Rather than get a reminder every time I open Outlook for incomplete tasks, which would just get lost in the noise (I have a lot of tabled and pending projects that are “overdue”), I figured I could fix this “quirk” with a little Visual Basic for Applications.

Here’s the code:

Sub TimeCard()
Dim olkTask As Outlook.TaskItem

On Error GoTo ErrHandler:

Set olkTask = ActiveInspector.CurrentItem
'If you name your tasks appropriately, you can filter on the name
'to prevent taking this action on another task
If InStr(olkTask.Subject, "TimeCard")  1 Then
  MsgBox "This is not a 'TimeCard' task!"
  Exit Sub
End If

'Mark it complete so Outlook will generate the next recurrence
olkTask.MarkComplete

'Now go to your website
Set browser = CreateObject("InternetExplorer.Application")
browser.navigate ("http://yourwebsite.net")

ActiveInspector.Close olSave

ErrHandler:
  'Don't care
End Sub

If you have a better way to accomplish this, I’d love to hear about it.  Right now, I just have this macro mapped to a custom toolbar that appears on every task Inspector I open. 😦  I’d like it to just be on the time card tasks, but I did not take the time to figure that out.

Starting and Stopping Tomcat on Windows

Using schedule tasks and group policy editor, you can start and stop a Tomcat server on Windows startup and shutdown. I had to search for this a couple of times. First when I discovered it and then again when I needed to reproduce the rules on another machine. I’m not crazy about running tomcat as a service under Windows, particularly because I was running into permission problems with my particular web application. Depending on what you are trying to do, this may not be an issue. I was interacting with the filesystem and executing Python scripts from within my servlet. There’s probably a proper way to run as a service and provide all the security credentials required for what I was doing, but I found the method I came up with much more simple.

So, the method is pretty simple. Using the provided startup.bat and shutdown.bat batch scripts provided with the tomcat distribution, you’ll execute these scripts upon system startup and shutdown within Windows. The methods for doing each differ, but they achieve the same effect.

Okay, so on system startup, you’ll be creating a scheduled task. Here are the steps…

  1. Navigate to Start -> Control Panel -> System and Security. Under Administrative Tools, click the “Schedule Tasks” link. This opens the Task Scheduler dialog.
  2. We’ll be creating a task to run the startup.bat script foud in the bin folder of the Tomcat distribution. If you need help on how to create a task, use the Help menu in Windows. It will provide a much more thorough explanation than I’m willing to spend time writing. I’ll briefly hit on any settings I changed from the defaults.
  3. Under the first tab “General”, you’ll need to name your task and select the account you’ll use to run the task. I selected an account belonging to the Administrators group and selected the option to have the task run whether the user is logged on or not. I also selected the option to “Run with highest privileges”. I DID NOT select the “do not store password”.
  4. Under triggers, click New and then select “At startup” for when to begin the task. That’s it.
  5. Under actions, click New and the Browse. Navigate to your Tomcat install directory and select the startup.bat script under bin. I chose to set the “Start in (optional):” value to the same directory as the startup script.
  6. I did not change any options under the Conditions tab.
  7. Finally, under settings you’ll want to unselect “Stop the task if it runs longer than:” and “If the running task does not end when requested, force it to stop”. You’ll soon see that this task just starts up another process and exits

That’s it for starting up Tomcat. You could stop here, but when Windows is shutdown, Tomcat will be forcefully stopped and if you have any code designed to do cleanup on server shutdown, it won’t be executed. This part is not as obvious.

  1. Using the Group Policy editor (Run -> gpedit.msc), you’ll simply add the Tomcat shutdown.bat script to the list of scripts that run on shutdown.
  2. On the left hand hierarchy view, select “Local Computer Policy” -> “Computer Configuration” -> “Windows Settings” -> “Scripts (Startup/Shutdown)”
  3. From here, open the Shutdown properties and then add the shutdown.bat script to the list (if any other scripts are present).

You might be thinking, “Why not add the startup.bat script to the startup properties?” For one thing, you won’t have any say as to which account runs the startup script. It runs as System and that’s it. Secondly, if you need to shutdown Tomcat and perform maintenance, you’ll either have to manually startup Tomcat, which will leave you with a command shell for the running process you’ll have to be very careful about not closing, or reboot the system. With the Task Scheduler, you can rerun the task “On Demand”, which will start the Tomcat server under the Task Engine service and you will not see it while logged on to the system.

Version Control Everywhere

Version control seems to be everywhere I look these days. The number and variety of version control systems prompted me to write this article. Of course, you can always consult Wikipedia’s article on Version Control for more up-to-date information.

I code a lot in Java, which is a fairly open language although since Oracle’s acquisition of Sun Microsystems and subsequently the intellectual property of the Java language it is becoming less so. I mean one of their first actions after the acquisition was to sue Google over the use of Java in the Android operating system. I digress. That’s a whole other topic. My point is that Java is used in lots of open source projects and by consequence these are typically managed by some type of version control.

How many have I come across in just the past few months you ask? Let me count the ways:

  • There’s SVN, which has gained considerable popularity as the defacto version control system for Google Code
  • There’s Mercurial, which I’m not familiar with but is used by a few open source projects I’ve checked
  • There’s Maven, which is project management framework with version control built-in
  • There’s Git, which again, I’m not really familiar with but it’s used in some projects I’ve come across
  • Lest I forget the granddaddy of them all, you’ve got CVS as well if you are feeling nostalgic

Of these, Maven is probably not a true version control system. But when discussing projects managed with Maven, you’ll hear “repository” used a lot, but “checkout” not so much. I’m also not saying these two words alone describe a version control system. Geesh, lighten up! This article’s being written for fun.

Okay, so all these version control systems are out there including many more proprietary systems… check the Wikipedia article for a full list. So what? My real gripe is having to learn all these systems to work with the various open source projects. And then, learning is not even so bad. It’s having to download and install the clients for each one of these systems. It would be nice if someone developed a universal version control client that could interface with all the different systems out there… Oh wait, someone’s doing that too! Check out Amp, a fledgling universal version control system.

McAfee ePO Logs

The McAfee ePO logs made available by the McAfee ePolicy Orchestrator agent can be easily queried and parsed to obtain the version number. The code below is a simple script for obtaining the current version of McAfee running on the target machine. I built the tool as a way to obtain information on infected hosts identified by network sensors. I was not using the ePO server and had absolutely no interest in manually opening the server UI to obtain this information.

Of course, this would be useful if you are doing penetration tests. You get the bonus of identifying online hosts AND vulnerable hosts with outdated virus definitions. The script as is will take an IP address, NetBios name or a fully-qualified domain name.

I’ve not tested this beyond the environment I wrote it for, so depending on the enterprise environment this tool may fail. It assumes the agent is configured with the default listening port of 8081 and also expects no authentication or challenge to the query. I believe the agent can be configured to only respond to the ePO server, which would provide your enterprise with an added layer of defense against network mapping tools.


import socket
import argparse
import httplib
import xml.dom.minidom

def initArgParser():
	description = 'Automated script to capture ePO version from network host.'
	parser = argparse.ArgumentParser(description=description)
	parser.add_argument('address',help='The address or name of the host to analyze.')
	return parser

def get_element(node,tag):
	try:
		root,tail = tag.split('.',1)
		nl = node.getElementsByTagName(root)
		if len(nl) > 0:
			return get_element(nl[0],tail)
	except ValueError:
		nl = node.getElementsByTagName(tag)
		if len(nl) > 0:
			return nl[0]
	return None
	
def get_version(fqdn):
	version = ''
	try:
		conn = httplib.HTTPConnection(fqdn,8081)
		name = fqdn.split(".")[0]
		get_request = "/Agent_{0}.xml".format(name)
		conn.request("GET",get_request)
		r = conn.getresponse()
		conn.close()
		data = r.read()
	
		dom = xml.dom.minidom.parseString(data)
		e = get_element(dom,'naLog.version')
		version = str(e.childNodes[0].data)
	except:
		pass
	return version
	
	
if __name__ == "__main__":
	parser = initArgParser()
	args = parser.parse_args()
	print get_version(socket.getfqdn(args.address))

Name That Theorem

I exercised this theorem recently for a conditional statement in python. I wanted the opposite of:
if A and B:
so I came up with:
if not (A and B):
That worked fine, but I thought it would be easier to read as:
if not A or not B:

Can you name the theorem that allowed me to distribute the “not”?

Fun with XML-RPC and Introspection

You can use introspection to write a generic XML-RPC client. Introspection is not part of the “core” XML-RPC specification, but is a popular feature supported by most implementations of XML-RPC. I developed this code to interact with the Apache XML-RPC implementation specified here.

My ultimate goal in creating this client was to provide for rapid prototyping and limit the amount of client coding (I was already spending enough time implementing the server component). The concept is fairly simple. I wanted a client that I could run again-and-again and handle changes to the server’s available methods “on-the-fly”. I chose Python to write the client because Python is a dynamically typed language and great for fast-prototyping. It also helped that it has support for XML-RPC “baked in”.

I used the “listMethods” call to validate the input and use the “methodSignature” call to handle the output. My first instinct was to use the built-in getattr function in Python to obtain the appropriate method from the ServerProxy object. This worked great for methods with zero-length arguments. But what if I need to provide one or more parameters? I fumbled around a bit trying to pass the arguments as an array, then a tuple. No go in either instance. I finally decided to forgo getattr all together in favor of eval. This allowed me to dynamically build the method call to the XML-RPC server on the fly. Check out the code!


import xmlrpclib
import os, sys
import subprocess
import argparse
import logging

def initArgParser():
	description = 'XML-RPC client for MTA Server.'
	parser = argparse.ArgumentParser(description=description)
	parser.add_argument('method',help='The method you wish to invoke.')
	parser.add_argument('parameters',nargs='*',help='The parameters for the method.')
	return parser

def handleResponse(response,signature):
	if signature[0][0] == 'array':
		for item in response:
			print item
	else:
		print response

def callMethod(methodname,parameters):
	serverproxy = xmlrpclib.ServerProxy('YOUR SERVER URL HERE')
	methods = serverproxy.system.listMethods()
	if methodname not in methods:
		for method in methods:
			fqcn = method.__str__()
			if fqcn[len(fqcn) - len(methodname):] == methodname:
				methodname = fqcn
				break
	try:
		signature = serverproxy.system.methodSignature(methodname)
		if len(parameters) == len(signature[0])-1:
			if len(parameters) == 0:
				method = getattr(serverproxy,methodname)
				response = method()
			else:
				statement = 'serverproxy.' + methodname + '('
				index = 1
				for param in parameters:
					if signature[0][index] == 'string':
						statement+= '"' + param + '",'
					else:
						statement+= param + ','
					index+=1
				statement = statement[:len(statement)-1] + ')'
				response = eval(statement)
			return (response,signature)
		else:
			response = []
			response.add("Invalid number of arguments for" + methodname)
			response.add("Requires" + signature[0])
			signature[0][0] = 'array'
			return (response,signature)
	except AttributeError:
		print "Invalid method name."
		sys.exit(1)
		
if __name__ == "__main__":
	parser = initArgParser()
	args = parser.parse_args()
	response,signature = callMethod(args.method,args.parameters)
	handleResponse(response,signature)

Renewing My GIAC Certified Forensic Analyst (GCFA) Certification

I recently began the quest to renew my GCFA certification. GIAC recently changed the way it handles renewals. The association now allows for maintaining credentials through certification maintenance units (CMUs). This follows closely ISC2‘s technique for maintenance of it’s certification programs such as the CISSP. Unlike ISC2 however the options for obtaining CMUs are a bit more challenging under the GIAC program. Those options are:

  1. Retaking the standard certification exam
  2. Attend or teach ISO 17024 related information assurance training courses, such as SANS training courses or post graduate level information assurance courses.
  3. Submit a published technical research paper, such as a GIAC Gold Paper

I won’t go into ISC2‘s program here, but suffice it to say that there are a lot more options to earn continuing professional education (CPE) credits. Since my time is limited, I chose option one above as my avenue for renewal. I received my study materials just last week and I’ll admit it will be a major effort to study for this test. I’m pretty excited though as I’ve been away from the forensics world for a few years and this is just what I need to brush up my skills.

New RAO Blog

Well, after 4.5 days of concerted effort the new look of the RAO blog is finally complete. Check it out. The theme is a child theme of the WordPress 3.0 default theme, Twenty Ten (as in 2010, the year it was released… those cheeky wordpress developers… pfft!). Anyways, it took a bit of researching on theme development before I was able to actually understand what I needed to do. The WordPress Codex is not as intuitive as one might think. I found the most frustrating thing to be the lack of date stamps or version numbers on the articles. I was never quite sure the information I was reading actually applied to WordPress 3.0. I muddled through it and was able to minimally change Twenty Ten to meet my goal of getting the same look and feel as RAO’s main site.

The RAO theme uses a custom header.php and footer.php and functions.php, which overrides the twentyten_setup() function of the parent theme. It also borrows from Themeshaper’s Thematic theme library of style sheets. We decided to go with a two column approach as opposed to the old three column style, but thanks to Thematic’s 2c-r-fixed.css and 3c-fixed.css templates, I can make the switch between the two with the deletion of a few comments in the child theme stylesheet. I also dabbled in widgets and created a custom RSS subscription widget. There are tons of these plugins available for download, but they didn’t have quite the desired formatting (or maybe I just wanted to make life difficult for myself). I learned a lot in the process and plan to make some improvements in the near future.

For now, I’m going to learn as I blog. I figure that will be the best way to become a true WordPress guru and hopefully learn how to make some dough off this whole blogging thing.