#!/usr/bin/env python
"""
Takes a TACACS+ file (tac_plus.cfg) and outputs a passwd file for doing
password audits with john the ripper.  Tested against v4.0.3.

Aaron Peterson -- aaron@midnightresearch.com
"""

import os, sys, re

def usage():
	print " usage: %s <input tacacs file> <output passwd file>" % sys.argv[0]
	sys.exit(1)

###########################################################
### Start Main
###########################################################
def main():
	if len(sys.argv) < 3:
		usage()

	inputFile = sys.argv[1]
	outputFile = sys.argv[2]

	if not os.path.exists(inputFile):
		print " [!] Input file [%s] does not exist" % inputFile
		sys.exit(1)
	if os.path.exists(outputFile):
		print " [!] Output file [%s] exists, will not overwrite" % outputFile
		sys.exit(1)

	try:
		input = open(inputFile, "r")
		output = open(outputFile, "w")
	except IOError:
		print " [!] Problems opening file [%s] or [%s] " % (inputFile, outputFile)
		sys.exit(1)

	user=None
	name="na"
	hash=None
	inStanza=0
	count=0
	for line in input:
		# Starts the user section
		match = re.search(r"user = ([^\s]*) \{", line)	
		if match: 
			inStanza=1
			user = match.group(1)

		# Parameters in the stanza
		if inStanza:
			match = re.search(r"login = ([^\s]*) ([^\s]*)", line)
			if match:
				hash = match.group(2)
				hashType = match.group(1)
			match = re.search(r"name = \"([^\"]*)\"", line)	
			if match: 
				inStanza=1
				name = match.group(1)

		# Ends the stanza, and writes line if it has the data
		if line.startswith("}"):
			if user and name and hash:
				print " [*] Got user [%s] [%s]" % (user, name)
				output.write("%s:%s:::%s::\n" % (user, hash, name))
				count += 1
			user=None
			name="na"
			hash=None
			inStanza=0

	print " [*] Imported [%s] accounts" % count
	print " [*] Done."

if __name__=="__main__":
	main()
