binwalk 17.1 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/env python

import sys
import os.path
import binwalk
from threading import Thread
from getopt import GetoptError, getopt as GetOpt

9 10 11
def display_status():
	global bwalk

12 13
	while True:
		# Display the current scan progress when the enter key is pressed.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
		try:
			raw_input()
			print "Progress: %.2f%% (%d / %d)\n" % (((float(bwalk.total_scanned) / float(bwalk.scan_length)) * 100), bwalk.total_scanned, bwalk.scan_length)
		except Exception, e:
			pass

def examples():
	name = os.path.basename(sys.argv[0])

	print """
Scanning firmware for file signatures:

\t$ %s firmware.bin

Extracting files from firmware:

\t$ %s -Me firmware.bin

Scanning firmware for executable code:

\t$ %s -A firmware.bin

Performing a firmware strings analysis:

\t$ %s -S firmware.bin

Performing a firmware entropy analysis:

\t$ %s -E firmware.bin

Display identified file signatures on entropy graph:

\t$ %s -EB firmware.bin

See http://code.google.com/p/binwalk/wiki/TableOfContents for more.
""" % (name, name, name, name, name, name)
	sys.exit(0)
51 52 53

def usage(fd):
	fd.write("\n")
54
	
55 56 57
	fd.write("Binwalk v%s\n" % binwalk.Config.VERSION)
	fd.write("Craig Heffner, http://www.devttys0.com\n")
	fd.write("\n")
58
	
59 60
	fd.write("Usage: %s [OPTIONS] [FILE1] [FILE2] [FILE3] ...\n" % os.path.basename(sys.argv[0]))
	fd.write("\n")
61 62 63 64 65 66
	
	fd.write("Signature Analysis:\n")
	fd.write("\t-B, --binwalk                 Perform a file signature scan (default)\n")
	fd.write("\t-R, --raw-bytes=<string>      Search for a custom signature\n")
	fd.write("\t-A, --opcodes                 Scan for executable code signatures\n")
	fd.write("\t-C, --cast                    Cast file contents as various data types\n")
67 68
	fd.write("\t-m, --magic=<file>            Specify an alternate magic file to use\n")
	fd.write("\t-x, --exclude=<filter>        Exclude matches that have <filter> in their description\n")
69
	fd.write("\t-y, --include=<filter>        Only search for matches that have <filter> in their description\n")
70 71
	fd.write("\t-I, --show-invalid            Show results marked as invalid\n")
	fd.write("\t-k, --keep-going              Show all matching results at a given offset, not just the first one\n")
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
	fd.write("\t-b, --dumb                    Disable smart signature keywords\n")
	fd.write("\n")

	fd.write("Strings Analysis:\n")
	fd.write("\t-S, --strings                 Scan for ASCII strings (may be combined with -B, -R, -A, or -E)\n")
	fd.write("\t-s, --strlen=<n>              Set the minimum string length to search for (default: 3)\n")
	fd.write("\n")
	
	fd.write("Entropy Analysis:\n")
	fd.write("\t-E, --entropy                 Plot file entropy (may be combined with -B, -R, -A, or -S)\n")
	fd.write("\t-K, --block=<int>             Set the block size for entropy analysis\n")
	fd.write("\t-a, --shannon                 Use the Shannon entropy algorithm\n")
	fd.write("\t-N, --no-plot                 Do not generate an entropy plot graph\n")
	fd.write("\t-F, --marker=<offset:name>    Add a marker to the entropy plot graph\n")
	fd.write("\t-Q, --no-legend               Omit the legend from the entropy plot graph\n")
	fd.write("\t-J, --save-plot               Save plot as an SVG (implied if multiple files are specified)\n")
	fd.write("\n")

	fd.write("Extraction Options:\n")
	fd.write("\t-D, --dd=<type:ext[:cmd]>     Extract <type> signatures, give the files an extension of <ext>, and execute <cmd>\n")
	fd.write("\t-e, --extract=[file]          Automatically extract known file types; load rules from file, if specified\n")
	fd.write("\t-M, --matryoshka              Recursively scan extracted files, up to 8 levels deep\n")
	fd.write("\t-r, --rm                      Cleanup extracted files and zero-size files\n")
	fd.write("\t-d, --delay                   Delay file extraction for files with known footers\n")
	fd.write("\n")

	fd.write("Plugin Options:\n")
	fd.write("\t-X, --disable-plugin=<name>   Disable a plugin by name\n")
	fd.write("\t-Y, --enable-plugin=<name>    Enable a plugin by name\n")
	fd.write("\t-p, --disable-plugins         Do not load any binwalk plugins\n")
	fd.write("\t-L, --list-plugins            List all user and system plugins by name\n")
	fd.write("\n")

	fd.write("General Options:\n")	
	fd.write("\t-o, --offset=<int>            Start scan at this file offset\n")
	fd.write("\t-l, --length=<int>            Number of bytes to scan\n")
	fd.write("\t-g, --grep=<text>             Grep results for the specified text\n")
	fd.write("\t-f, --file=<file>             Log results to file\n")
	fd.write("\t-c, --csv                     Log results to file in csv format\n")
	fd.write("\t-O, --skip-unopened           Ignore file open errors and process only the files that can be opened\n")
	fd.write("\t-t, --term                    Format output to fit the terminal window\n")
113 114 115
	fd.write("\t-q, --quiet                   Supress output to stdout\n")
	fd.write("\t-v, --verbose                 Be verbose (specify twice for very verbose)\n")
	fd.write("\t-u, --update                  Update magic signature files\n")
116
	fd.write("\t-?, --examples                Show example usage\n")
117 118 119 120 121 122 123 124 125
	fd.write("\t-h, --help                    Show help output\n")
	fd.write("\n")

	if fd == sys.stderr:
		sys.exit(1)
	else:
		sys.exit(0)

def main():
126 127 128
	# The Binwalk class instance must be global so that the display_status thread can access it.
	global bwalk

129
	MIN_ARGC = 2
130 131

	requested_scans = []	
132 133
	offset = 0
	length = 0
134
	strlen = 0
135
	verbose = 0
136 137 138 139 140
	matryoshka = 1
	entropy_block = 0
	failed_open_count = 0
	quiet = False
	do_files = False
141
	log_file = None
142 143 144 145 146 147
	do_csv = False
	save_plot = False
	show_plot = True
	show_legend = True
	entropy_scan = False
	enable_plugins = True
148
	show_invalid = False
149 150
	entropy_algorithm = None
	format_to_terminal = False
151 152 153
	custom_signature = None
	delay_extraction = False
	extract_rules_file = None
154
	ignore_failed_open = False
155 156
	extract_from_config = False
	cleanup_after_extract = False
157 158
	explicit_signature_scan = False
	ignore_signature_keywords = False
159
	magic_flags = binwalk.magic.MAGIC_NONE
160
	markers = []
161
	magic_files = []
162
	file_opt_list = []
163 164 165 166 167
	target_files = []
	greps = []
	excludes = []
	searches = []
	extracts = []
168 169 170 171
	options = []
	arguments = []
	plugin_whitelist = []
	plugin_blacklist = []
172 173 174

	config = binwalk.Config()

175
	short_options = "AaBbCcdEehIJkLMNnOPpQqrStuv?D:F:f:g:K:o:l:m:R:s:X:x:Y:y:"
176 177
	long_options = [
			"rm",
178 179
			"help",
			"examples",
180
			"quiet", 
181
			"csv",
182 183 184 185
			"verbose",
			"opcodes",
			"cast",
			"update",
186
			"binwalk", 
187 188 189 190
			"keep-going",
			"show-invalid",
			"profile",
			"delay",
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
			"skip-unopened",
			"term",
			"tim",
			"dumb",
			"entropy",
			"shannon",
			"save-plot",
			"no-plot",
			"no-legend", 
			"matryoshka",
			"strings",
			"list-plugins",
			"disable-plugins",
			"disable-plugin=",
			"enable-plugin=",
			"marker=",
			"strlen=",
208
			"file=", 
209
			"block=",
210 211 212
			"offset=", 
			"length=", 
			"exclude=",
213
			"include=",
214
			"search=",
215
			"extract=",
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
			"dd=",
			"grep=",
			"magic=",
			"raw-bytes=",
	]

	# Require at least one argument (the target file)
	if len(sys.argv) < MIN_ARGC:
		usage(sys.stderr)

	try:
		opts, args = GetOpt(sys.argv[1:], short_options, long_options)
	except GetoptError, e:
		sys.stderr.write("%s\n" % str(e))
		usage(sys.stderr)

	for opt, arg in opts:
		if opt in ("-h", "--help"):
			usage(sys.stdout)
235 236
		elif opt in ("-?", "--examples"):
			examples()
237 238 239 240
		elif opt in ("-d", "--delay"):
			delay_extraction = True
		elif opt in ("-f", "--file"):
			log_file = arg
241 242
		elif opt in ("-c", "--csv"):
			do_csv = True
243 244
		elif opt in ("-q", "--quiet"):
			quiet = True
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
		elif opt in ("-s", "--strlen"):
			strlen = binwalk.common.str2int(arg)
		elif opt in ("-Q", "--no-legend"):
			show_legend = False
		elif opt in ("-J", "--save-plot"):
			save_plot = True
		elif opt in ("-E", "--entropy"):
			requested_scans.append(binwalk.Binwalk.ENTROPY)
		elif opt in ("-a", "--shannon"):
			entropy_algorithm = 'shannon'
		elif opt in("-t", "--term", "--tim"):
			format_to_terminal = True
		elif opt in("-p", "--disable-plugins"):
			enable_plugins = False
		elif opt in ("-b", "--dumb"):
			ignore_signature_keywords = True
261 262
		elif opt in ("-v", "--verbose"):
			verbose += 1
263 264 265 266 267 268
		elif opt in ("-N", "--no-plot"):
			show_plot = False
		elif opt in ("-S", "--strings"):
			requested_scans.append(binwalk.Binwalk.STRINGS)
		elif opt in ("-O", "--skip-unopened"):
			ignore_failed_open = True
269
		elif opt in ("-o", "--offset"):
270
			offset = binwalk.common.str2int(arg)
271
		elif opt in ("-l", "--length"):
272 273
			length = binwalk.common.str2int(arg)
		elif opt in ("-y", "--search", "--include"):
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
			searches.append(arg)
		elif opt in ("-x", "--exclude"):
			excludes.append(arg)
		elif opt in ("-D", "--dd"):
			extracts.append(arg)
		elif opt in ("-g", "--grep"):
			greps.append(arg)
		elif opt in ("-r", "--rm"):
			cleanup_after_extract = True
		elif opt in ("-m", "--magic"):
			magic_files.append(arg)
		elif opt in ("-k", "--keep-going"):
			magic_flags |= binwalk.magic.MAGIC_CONTINUE
		elif opt in ("-I", "--show-invalid"):
			show_invalid = True
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
		elif opt in ("-B", "--binwalk"):
			requested_scans.append(binwalk.Binwalk.BINWALK)
		elif opt in ("-M", "--matryoshka"):
			# Original Zvyozdochkin matrhoska set had 8 dolls. This is a good number.
			matryoshka = 8
		elif opt in ("-K", "--block"):
			entropy_block = binwalk.common.str2int(arg)
		elif opt in ("-X", "--disable-plugin"):
			plugin_blacklist.append(arg)
		elif opt in ("-Y", "--enable-plugin"):
			plugin_whitelist.append(arg)

		elif opt in ("-F", "--marker"):
			if ':' in arg:
				(location, description) = arg.split(':', 1)
				location = int(location)
				markers.append((location, [{'description' : description, 'offset' : location}]))
		elif opt in("-L", "--list-plugins"):
			# List all user and system plugins, then exit
			print ''
			print 'NAME             TYPE       ENABLED    DESCRIPTION'
			print '-' * 115
			with binwalk.Binwalk() as bw:
				for (key, info) in binwalk.plugins.Plugins(bw).list_plugins().iteritems():
					for module_name in info['modules']:
						print '%-16s %-10s %-10s %s' % (module_name, key, info['enabled'][module_name], info['descriptions'][module_name])
			print ''
                	sys.exit(1)
		elif opt in ("-e", "--extract"):
			# If a file path was specified, use that as the extraction rules file
			if arg:
				extract_from_config = False
				extract_rules_file = arg
			# Else, use the default rules file
			else:
				extract_from_config = True
325
		elif opt in ("-A", "--opcodes"):
326
			requested_scans.append(binwalk.Binwalk.BINARCH)
327 328 329 330
			# Load user file first so its signatures take precedence
			magic_files.append(config.paths['user'][config.BINARCH_MAGIC_FILE])
			magic_files.append(config.paths['system'][config.BINARCH_MAGIC_FILE])
		elif opt in ("-C", "--cast"):
331
			requested_scans.append(binwalk.Binwalk.BINCAST)
332 333 334 335 336 337 338
			# Don't stop at the first match (everything matches everything in this scan)
			magic_flags |= binwalk.magic.MAGIC_CONTINUE
			# Load user file first so its signatures take precedence
			magic_files.append(config.paths['user'][config.BINCAST_MAGIC_FILE])
			magic_files.append(config.paths['system'][config.BINCAST_MAGIC_FILE])
		elif opt in ("-R", "--raw-bytes"):
			custom_signature = arg
339 340
			requested_scans.append(binwalk.Binwalk.BINWALK)
			explicit_signature_scan = True
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
		elif opt in ("-u", "--update"):
			try:
				sys.stdout.write("Updating signatures...")
				sys.stdout.flush()

				binwalk.Update().update()

				sys.stdout.write("done.\n")
				sys.exit(0)
			except Exception, e:
				if 'Permission denied' in str(e):
					sys.stderr.write("failed (permission denied). Check your user permissions, or run the update as root.\n")
				else:
					sys.stderr.write('\n' + str(e) + '\n')
				sys.exit(1)
356
		
357 358 359 360
		# The --profile option is handled prior to calling main()
		elif opt not in ('-P', '--profile'):
			usage(sys.stderr)

361 362
		# Keep track of the options and arguments.
		# This is used later to determine which argv entries are file names.
363 364 365
		options.append(opt)
		options.append("%s%s" % (opt, arg))
		options.append("%s=%s" % (opt, arg))
366 367 368
		arguments.append(arg)
		
	# Treat any command line options not processed by getopt as target file paths.
369
	for opt in sys.argv[1:]:
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
		if opt not in arguments and opt not in options and not opt.startswith('-'):
			file_opt_list.append(opt)

	# Validate the target files listed in target_files
	for tfile in file_opt_list:
		# Ignore directories.
		if not os.path.isdir(tfile):
			# Make sure we can open the target files
			try:
				fd = open(tfile, "rb")
				fd.close()
				target_files.append(tfile)
			except Exception, e:
				sys.stdout.write("Cannot open file : %s\n" % str(e))
				failed_open_count += 1

	# Unless -O was specified, don't run the scan unless we are able to scan all specified files
	if failed_open_count > 0 and not ignore_failed_open:
		if failed_open_count > 1:
			plural = 's'
		else:
			plural = ''
		sys.stdout.write("Failed to open %d file%s for scanning, quitting...\n" % (failed_open_count, plural))
		sys.exit(1)
394 395 396

	# If more than one target file was specified, enable verbose mode; else, there is
	# nothing in the output to indicate which scan corresponds to which file.
397 398 399 400 401 402
	if (matryoshka > 1 or len(target_files) > 1):
		save_plot = True
		if not verbose:
			verbose = 1
	elif len(target_files) == 0:
		usage(sys.stderr)
403 404

	# Instantiate the Binwalk class
405
	bwalk = binwalk.Binwalk(flags=magic_flags, verbose=verbose, log=log_file, quiet=quiet, ignore_smart_keywords=ignore_signature_keywords, load_plugins=enable_plugins)
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434

	# If a custom signature was specified, create a temporary magic file containing the custom signature
	# and ensure that it is the only magic file that will be loaded when Binwalk.scan() is called.
	if custom_signature is not None:
		magic_files = bwalk.parser.file_from_string(custom_signature)

	# Set any specified filters
	bwalk.filter.exclude(excludes)
	bwalk.filter.include(searches)
	bwalk.filter.grep(filters=greps)

	# Add any specified extract rules
	bwalk.extractor.add_rule(extracts)

	# If -e was specified, load the default extract rules
	if extract_from_config:
		bwalk.extractor.load_defaults()

	# If --extract was specified, load the specified extraction rules file
	if extract_rules_file is not None:
		bwalk.extractor.load_from_file(extract_rules_file)

	# Set the extractor cleanup value (True to clean up files, False to leave them on disk)
	bwalk.extractor.cleanup_extracted_files(cleanup_after_extract)

	# Enable delayed extraction, which will prevent supported file types from having trailing data when extracted
	bwalk.extractor.enable_delayed_extract(delay_extraction)

	# Load the magic file(s)
435
	bwalk.load_signatures(magic_files=magic_files)
436

437 438 439
	# If --term was specified, enable output formatting to terminal
	if format_to_terminal:
		bwalk.display.enable_formatting(True)
440

441 442 443 444 445 446 447
	# Enable log file CSV formatting, if specified
	if do_csv:
		bwalk.display.enable_csv()

	# If no scan was explicitly rquested, do a binwalk scan
	if not requested_scans:
		requested_scans.append(binwalk.Binwalk.BINWALK)
448

449 450
	# Sort the scan types to ensure the entropy scan is performed last
	requested_scans.sort()
451

452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
	# Everything is set up, let's do a scan
	try:
		results = {}

		# Start the display_status function as a daemon thread.
		t = Thread(target=display_status)
		t.setDaemon(True)
		t.start()
		
		for scan_type in requested_scans:

			if scan_type in [binwalk.Binwalk.BINWALK, binwalk.Binwalk.BINARCH, binwalk.Binwalk.BINCAST]:

				# There's no generic way for the binwalk class to know what
				# scan type is being run, since these are all signature scans,
				# just with different magic files. Manually set the scan sub-type
				# here to ensure that plugins can differentiate between the
				# scans being performed.
				bwalk.scan_type = scan_type

				r = bwalk.scan(target_files,
						offset=offset, 
						length=length, 
						show_invalid_results=show_invalid, 
						callback=bwalk.display.results, 
						start_callback=bwalk.display.header,
						end_callback=bwalk.display.footer,
						matryoshka=matryoshka,
						plugins_whitelist=plugin_whitelist,
						plugins_blacklist=plugin_blacklist)

				bwalk.concatenate_results(results, r)

			elif scan_type == binwalk.Binwalk.STRINGS:

				r = bwalk.analyze_strings(target_files, 
							length=length, 
							offset=offset, 
							n=strlen, 
							block=entropy_block, 
							algorithm=entropy_algorithm,
							load_plugins=enable_plugins, 
							whitelist=plugin_whitelist, 
							blacklist=plugin_blacklist)
					
				bwalk.concatenate_results(results, r)

			elif scan_type == binwalk.Binwalk.ENTROPY:

				if not results:
					for target_file in target_files:
						results[target_file] = []
				else:
					bwalk.display.quiet = True
					bwalk.display.cleanup()

				for target_file in results.keys():
					bwalk.concatenate_results(results, {target_file : markers})

				bwalk.analyze_entropy(results,
							offset, 
							length, 
							entropy_block, 
							show_plot, 
							show_legend, 
							save_plot,
							algorithm=entropy_algorithm,
							load_plugins=enable_plugins,
							whitelist=plugin_whitelist,
							blacklist=plugin_blacklist)

	except KeyboardInterrupt:
		pass
#	except Exception, e:
#		print "Unexpected error:", str(e)
		
528 529 530 531 532 533 534 535 536 537 538 539 540
	bwalk.cleanup()

try:
	# Special options for profiling the code. For debug use only.
	if '--profile' in sys.argv or '-P' in sys.argv:
		import cProfile
		cProfile.run('main()')
	else:
		main()
except KeyboardInterrupt:
	pass