Commit 851618cf by yinqidi

Emulation

parent e25f0abc
[DEFAULT]
sudo_password=yinqidi
firmadyne_path=/home/yinqidi/Desktop/EmuFuzz/Emulation
#! /usr/bin/python
import os
import os.path
import pexpect
import sys
import argparse
from configparser import ConfigParser
config = ConfigParser()
config.read("emu.config")
firmadyne_path = config["DEFAULT"].get("firmadyne_path", "")
sudo_pass = config["DEFAULT"].get("sudo_password", "")
def get_next_unused_iid():
for i in range(1, 1000):
if not os.path.isdir(os.path.join(firmadyne_path, "scratch", str(i))):
return str(i)
return ""
def run_extractor(firm_name):
print ("[+] Firmware:", os.path.basename(firm_name))
print ("[+] Extracting the firmware...")
extractor_cmd = os.path.join(firmadyne_path, "extractor/extractor.py")
extractor_args = [
"-np",
"-nk",
firm_name,
os.path.join(firmadyne_path, "images")
]
child = pexpect.spawn(extractor_cmd, extractor_args, timeout=None)
child.expect_exact("Tag: ")
tag = child.readline().strip().decode("utf8")
child.expect_exact(pexpect.EOF)
image_tgz = os.path.join(firmadyne_path, "images", tag + ".tar.gz")
if os.path.isfile(image_tgz):
iid = get_next_unused_iid()
if iid == "" or os.path.isfile(os.path.join(os.path.dirname(image_tgz), iid + ".tar.gz")):
print ("[!] Too many stale images")
print ("[!] Please run reset.py or manually delete the contents of the scratch/ and images/ directory")
return ""
os.rename(image_tgz, os.path.join(os.path.dirname(image_tgz), iid + ".tar.gz"))
print ("[+] Image ID:", iid)
return iid
return ""
def identify_arch(image_id):
print ("[+] Identifying architecture...")
identfy_arch_cmd = os.path.join(firmadyne_path, "scripts/getArch.sh")
identfy_arch_args = [
os.path.join(firmadyne_path, "images", image_id + ".tar.gz")
]
child = pexpect.spawn(identfy_arch_cmd, identfy_arch_args, cwd=firmadyne_path)
child.expect_exact(":")
arch = child.readline().strip().decode("utf8")
print ("[+] Architecture: " + arch)
try:
child.expect_exact(pexpect.EOF)
except Exception as e:
child.close(force=True)
return arch
def make_image(image_id, arch):
print ("[+] Building QEMU disk image...")
makeimage_cmd = os.path.join(firmadyne_path, "scripts/makeImage.sh")
makeimage_args = ["--", makeimage_cmd, image_id, arch]
child = pexpect.spawn("sudo", makeimage_args, cwd=firmadyne_path)
child.sendline(sudo_pass)
child.expect_exact(pexpect.EOF)
def infer_network(image_id, arch):
print ("[+] Setting up the network connection, please standby...")
network_cmd = os.path.join(firmadyne_path, "scripts/inferNetwork.sh")
network_args = [image_id, arch]
child = pexpect.spawn(network_cmd, network_args, cwd=firmadyne_path)
child.expect_exact("Interfaces:", timeout=None)
interfaces = child.readline().strip().decode("utf8")
print ("[+] Network interfaces:", interfaces)
child.expect_exact(pexpect.EOF)
def final_run(image_id, arch, qemu_dir):
runsh_path = os.path.join(firmadyne_path, "scratch", image_id, "run.sh")
if not os.path.isfile(runsh_path):
print ("[!] Cannot emulate firmware, run.sh not generated")
return
print ("[+] All set! Press ENTER to run the firmware...")
input ("[+] When running, press Ctrl + A X to terminate qemu")
print ("[+] Command line:", runsh_path)
run_cmd = ["--", runsh_path]
child = pexpect.spawn("sudo", run_cmd, cwd=firmadyne_path)
child.sendline(sudo_pass)
child.interact()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("firm_path", help="The path to the firmware image", type=str)
args = parser.parse_args()
image_id = run_extractor(args.firm_path)
if image_id == "":
print ("[!] Image extraction failed")
else:
arch = identify_arch(image_id)
make_image(image_id, arch)
infer_network(image_id, arch)
# final_run(image_id, arch)
# final_run("1", "mipseb")
if __name__ == "__main__":
main()
FROM python:2-wheezy
WORKDIR /root
RUN apt-get update && \
apt-get upgrade -y && \
apt-get install -y git-core wget build-essential liblzma-dev liblzo2-dev zlib1g-dev unrar-free && \
pip install -U pip
RUN git clone https://github.com/firmadyne/sasquatch && \
cd sasquatch && \
make && \
make install && \
cd .. && \
rm -rf sasquatch
RUN git clone https://github.com/devttys0/binwalk.git && \
cd binwalk && \
./deps.sh --yes && \
python setup.py install && \
pip install 'git+https://github.com/ahupp/python-magic' && \
pip install 'git+https://github.com/sviehb/jefferson' && \
cd .. && \
rm -rf binwalk
RUN \
adduser --disabled-password \
--gecos '' \
--home /home/extractor \
extractor
USER extractor
WORKDIR /home/extractor
RUN git clone https://github.com/firmadyne/extractor.git
The MIT License (MIT)
Copyright (c) 2015 - 2016, Daming Dominic Chen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Introduction
============
This is a recursive firmware extractor that aims to extract a kernel image
and/or compressed filesystem from a Linux-based firmware image. A number of
heuristics are included to avoid extraction of certain blacklisted file types,
and to avoid unproductive extraction beyond certain breadth and depth
limitations.
Firmware images with multiple filesystems are not fully supported; this tool
cannot reassemble them and will instead extract the first filesystem that has
sufficient UNIX-like root directories (e.g. `/bin`, `/etc/`, etc.)
For the impatients: Dockerize all the things!
=============================================
1. Install [Docker](https://docs.docker.com/engine/getstarted/)
2. Run the dockerized extractor
```
git clone https://github.com/firmadyne/extractor.git
cd extractor
./extract.sh path/to/firmware.img path/to/output/directory
```
Dependencies
============
* [fakeroot](https://fakeroot.alioth.debian.org)
* [psycopg2](http://initd.org/psycopg/)
* [binwalk](https://github.com/devttys0/binwalk)
* [python-magic](https://github.com/ahupp/python-magic)
Please use the latest version of `binwalk`. Note that there are two
Python modules that both share the name `python-magic`; both should be usable,
but only the one linked above has been tested extensively.
Binwalk
-------
* [jefferson](https://github.com/sviehb/jefferson)
* [sasquatch](https://github.com/firmadyne/sasquatch) (optional)
When installing `binwalk`, it is optional to use the forked version of the
`sasquatch` tool, which has been modified to make SquashFS file extraction
errors fatal to prevent false positives.
Usage
=====
During execution, the extractor will temporarily extract files into `/tmp`
while recursing. Since firmware images can be large, preferably mount this
mount point as `tmpfs` backed by a large amount of memory, to optimize
performance.
To preserve filesystem permissions during extraction, while avoiding execution
with root privileges, wrap execution of this extractor within `fakeroot`. This
will emulate privileged operations.
`fakeroot python3 ./extractor.py -np <infile> <outdir>`
Notes
=====
This tool is beta quality. In particular, it was written before the
`binwalk` API was updated to provide an interface for accessing information
about the extraction of each signature match. As a result, it walks the
filesystem to identify the extracted files that correspond to a given
signature match. Additionally, parallel operation has not been thoroughly
tested.
Pull requests are greatly appreciated!
#! /bin/bash
infile=$1
outdir=$2
# override 65535k docker default size with tmpfs default
mem=$(($(free | awk '/^Mem:/{print $2}') / 2))k
indir=$(realpath $(dirname "${infile}"))
outdir=$(realpath "${outdir}")
infilebn=$(basename "${infile}")
docker run --rm -t -i --tmpfs /tmp:rw,size=${mem} \
-v "${indir}":/firmware-in:ro \
-v "${outdir}":/firmware-out \
"ddcc/firmadyne-extractor:latest" \
fakeroot /home/extractor/extractor/extractor.py \
-np \
/firmware-in/"${infilebn}" \
/firmware-out
#!/usr/bin/env python3
"""
Module that performs extraction. For usage, refer to documentation for the class
'Extractor'. This module can also be executed directly,
e.g. 'extractor.py <input> <output>'.
"""
import argparse
import hashlib
import multiprocessing
import os
import shutil
import tempfile
import traceback
import magic
import binwalk
class Extractor(object):
"""
Class that extracts kernels and filesystems from firmware images, given an
input file or directory and output directory.
"""
# Directories that define the root of a UNIX filesystem, and the
# appropriate threshold condition
UNIX_DIRS = ["bin", "etc", "dev", "home", "lib", "mnt", "opt", "root",
"run", "sbin", "tmp", "usr", "var"]
UNIX_THRESHOLD = 4
# Lock to prevent concurrent access to visited set. Unfortunately, must be
# static because it cannot be pickled or passed as instance attribute.
visited_lock = multiprocessing.Lock()
def __init__(self, indir, outdir=None, rootfs=True, kernel=True,
numproc=True, server=None, brand=None):
# Input firmware update file or directory
self._input = os.path.abspath(indir)
# Output firmware directory
self.output_dir = os.path.abspath(outdir) if outdir else None
# Whether to attempt to extract kernel
self.do_kernel = kernel
# Whether to attempt to extract root filesystem
self.do_rootfs = rootfs
# Brand of the firmware
self.brand = brand
# Hostname of SQL server
self.database = server
# Worker pool.
self._pool = multiprocessing.Pool() if numproc else None
# Set containing MD5 checksums of visited items
self.visited = set()
# List containing tagged items to extract as 2-tuple: (tag [e.g. MD5],
# path)
self._list = list()
def __getstate__(self):
"""
Eliminate attributes that should not be pickled.
"""
self_dict = self.__dict__.copy()
del self_dict["_pool"]
del self_dict["_list"]
return self_dict
@staticmethod
def io_dd(indir, offset, size, outdir):
"""
Given a path to a target file, extract size bytes from specified offset
to given output file.
"""
if not size:
return
with open(indir, "rb") as ifp:
with open(outdir, "wb") as ofp:
ifp.seek(offset, 0)
ofp.write(ifp.read(size))
@staticmethod
def magic(indata, mime=False):
"""
Performs file magic while maintaining compatibility with different
libraries.
"""
try:
if mime:
mymagic = magic.open(magic.MAGIC_MIME_TYPE)
else:
mymagic = magic.open(magic.MAGIC_NONE)
mymagic.load()
except AttributeError:
mymagic = magic.Magic(mime)
mymagic.file = mymagic.from_file
return mymagic.file(indata)
@staticmethod
def io_md5(target):
"""
Performs MD5 with a block size of 64kb.
"""
blocksize = 65536
hasher = hashlib.md5()
with open(target, 'rb') as ifp:
buf = ifp.read(blocksize)
while buf:
hasher.update(buf)
buf = ifp.read(blocksize)
return hasher.hexdigest()
@staticmethod
def io_rm(target):
"""
Attempts to recursively delete a directory.
"""
shutil.rmtree(target, ignore_errors=False, onerror=Extractor._io_err)
@staticmethod
def _io_err(function, path, excinfo):
"""
Internal function used by '_rm' to print out errors.
"""
print(("!! %s: Cannot delete %s!\n%s" % (function, path, excinfo)))
@staticmethod
def io_find_rootfs(start, recurse=True):
"""
Attempts to find a Linux root directory.
"""
# Recurse into single directory chains, e.g. jffs2-root/fs_1/.../
path = start
while (len(os.listdir(path)) == 1 and
os.path.isdir(os.path.join(path, os.listdir(path)[0]))):
path = os.path.join(path, os.listdir(path)[0])
# count number of unix-like directories
count = 0
for subdir in os.listdir(path):
if subdir in Extractor.UNIX_DIRS and \
os.path.isdir(os.path.join(path, subdir)):
count += 1
# check for extracted filesystem, otherwise update queue
if count >= Extractor.UNIX_THRESHOLD:
return (True, path)
# in some cases, multiple filesystems may be extracted, so recurse to
# find best one
if recurse:
for subdir in os.listdir(path):
if os.path.isdir(os.path.join(path, subdir)):
res = Extractor.io_find_rootfs(os.path.join(path, subdir),
False)
if res[0]:
return res
return (False, start)
def extract(self):
"""
Perform extraction of firmware updates from input to tarballs in output
directory using a thread pool.
"""
if os.path.isdir(self._input):
for path, _, files in os.walk(self._input):
for item in files:
self._list.append(os.path.join(path, item))
elif os.path.isfile(self._input):
self._list.append(self._input)
else:
print("!! Cannot read file: %s" % (self._input,))
if self.output_dir and not os.path.isdir(self.output_dir):
os.makedirs(self.output_dir)
if self._pool:
self._pool.map(self._extract_item, self._list)
else:
for item in self._list:
self._extract_item(item)
def _extract_item(self, path):
"""
Wrapper function that creates an ExtractionItem and calls the extract()
method.
"""
ExtractionItem(self, path, 0).extract()
class ExtractionItem(object):
"""
Class that encapsulates the state of a single item that is being extracted.
"""
# Maximum recursion breadth and depth
RECURSION_BREADTH = 5
RECURSION_DEPTH = 3
def __init__(self, extractor, path, depth, tag=None):
# Temporary directory
self.temp = None
# Recursion depth counter
self.depth = depth
# Reference to parent extractor object
self.extractor = extractor
# File path
self.item = path
# Database connection
if self.extractor.database:
import psycopg2
self.database = psycopg2.connect(database="firmware",
user="firmadyne",
password="firmadyne",
host=self.extractor.database)
else:
self.database = None
# Checksum
self.checksum = Extractor.io_md5(path)
# Tag
self.tag = tag if tag else self.generate_tag()
# Output file path and filename prefix
self.output = os.path.join(self.extractor.output_dir, self.tag) if \
self.extractor.output_dir else None
# Status, with terminate indicating early termination for this item
self.terminate = False
self.status = None
self.update_status()
def __del__(self):
if self.database:
self.database.close()
if self.temp:
self.printf(">> Cleaning up %s..." % self.temp)
Extractor.io_rm(self.temp)
def printf(self, fmt):
"""
Prints output string with appropriate depth indentation.
"""
print(("\t" * self.depth + fmt))
def generate_tag(self):
"""
Generate the filename tag.
"""
if not self.database:
return os.path.basename(self.item) + "_" + self.checksum
try:
image_id = None
cur = self.database.cursor()
if self.extractor.brand:
brand = self.extractor.brand
else:
brand = os.path.relpath(self.item).split(os.path.sep)[0]
cur.execute("SELECT id FROM brand WHERE name=%s", (brand, ))
brand_id = cur.fetchone()
if not brand_id:
cur.execute("INSERT INTO brand (name) VALUES (%s) RETURNING id",
(brand, ))
brand_id = cur.fetchone()
if brand_id:
cur.execute("SELECT id FROM image WHERE hash=%s",
(self.checksum, ))
image_id = cur.fetchone()
if not image_id:
cur.execute("INSERT INTO image (filename, brand_id, hash) \
VALUES (%s, %s, %s) RETURNING id",
(os.path.basename(self.item), brand_id[0],
self.checksum))
image_id = cur.fetchone()
self.database.commit()
except BaseException:
traceback.print_exc()
self.database.rollback()
finally:
if cur:
cur.close()
if image_id:
self.printf(">> Database Image ID: %s" % image_id[0])
return str(image_id[0]) if \
image_id else os.path.basename(self.item) + "_" + self.checksum
def get_kernel_status(self):
"""
Get the flag corresponding to the kernel status.
"""
return self.status[0]
def get_rootfs_status(self):
"""
Get the flag corresponding to the root filesystem status.
"""
return self.status[1]
def update_status(self):
"""
Updates the status flags using the tag to determine completion status.
"""
kernel_done = os.path.isfile(self.get_kernel_path()) if \
self.extractor.do_kernel and self.output else \
not self.extractor.do_kernel
rootfs_done = os.path.isfile(self.get_rootfs_path()) if \
self.extractor.do_rootfs and self.output else \
not self.extractor.do_rootfs
self.status = (kernel_done, rootfs_done)
if self.database and kernel_done and self.extractor.do_kernel:
self.update_database("kernel_extracted", "True")
if self.database and rootfs_done and self.extractor.do_rootfs:
self.update_database("rootfs_extracted", "True")
return self.get_status()
def update_database(self, field, value):
"""
Update a given field in the database.
"""
ret = True
if self.database:
try:
cur = self.database.cursor()
cur.execute("UPDATE image SET " + field + "='" + value +
"' WHERE id=%s", (self.tag, ))
self.database.commit()
except BaseException:
ret = False
traceback.print_exc()
self.database.rollback()
finally:
if cur:
cur.close()
return ret
def get_status(self):
"""
Returns True if early terminate signaled, extraction is complete,
otherwise False.
"""
return True if self.terminate or all(i for i in self.status) else False
def get_kernel_path(self):
"""
Return the full path (including filename) to the output kernel file.
"""
return self.output + ".kernel" if self.output else None
def get_rootfs_path(self):
"""
Return the full path (including filename) to the output root filesystem
file.
"""
return self.output + ".tar.gz" if self.output else None
def extract(self):
"""
Perform the actual extraction of firmware updates, recursively. Returns
True if extraction complete, otherwise False.
"""
self.printf("\n" + self.item.encode("utf-8", "replace").decode("utf-8"))
# check if item is complete
if self.get_status():
self.printf(">> Skipping: completed!")
return True
# check if exceeding recursion depth
if self.depth > ExtractionItem.RECURSION_DEPTH:
self.printf(">> Skipping: recursion depth %d" % self.depth)
return self.get_status()
# check if checksum is in visited set
self.printf(">> MD5: %s" % self.checksum)
with Extractor.visited_lock:
if self.checksum in self.extractor.visited:
self.printf(">> Skipping: %s..." % self.checksum)
return self.get_status()
else:
self.extractor.visited.add(self.checksum)
# check if filetype is blacklisted
if self._check_blacklist():
return self.get_status()
# create working directory
self.temp = tempfile.mkdtemp()
try:
self.printf(">> Tag: %s" % self.tag)
self.printf(">> Temp: %s" % self.temp)
self.printf(">> Status: Kernel: %s, Rootfs: %s, Do_Kernel: %s, \
Do_Rootfs: %s" % (self.get_kernel_status(),
self.get_rootfs_status(),
self.extractor.do_kernel,
self.extractor.do_rootfs))
for analysis in [self._check_archive, self._check_firmware,
self._check_kernel, self._check_rootfs,
self._check_compressed]:
# Move to temporary directory so binwalk does not write to input
os.chdir(self.temp)
# Update status only if analysis changed state
if analysis():
if self.update_status():
self.printf(">> Skipping: completed!")
return True
except Exception:
traceback.print_exc()
return False
def _check_blacklist(self):
"""
Check if this file is blacklisted for analysis based on file type.
"""
# First, use MIME-type to exclude large categories of files
filetype = Extractor.magic(self.item.encode("utf-8", "surrogateescape"),
mime=True)
if any(s in filetype for s in ["application/x-executable",
"application/x-dosexec",
"application/x-object",
"application/pdf",
"application/msword",
"image/", "text/", "video/"]):
self.printf(">> Skipping: %s..." % filetype)
return True
# Next, check for specific file types that have MIME-type
# 'application/octet-stream'
filetype = Extractor.magic(self.item.encode("utf-8", "surrogateescape"))
if any(s in filetype for s in ["executable", "universal binary",
"relocatable", "bytecode", "applet"]):
self.printf(">> Skipping: %s..." % filetype)
return True
# Finally, check for specific file extensions that would be incorrectly
# identified
if self.item.endswith(".dmg"):
self.printf(">> Skipping: %s..." % (self.item))
return True
return False
def _check_archive(self):
"""
If this file is an archive, recurse over its contents, unless it matches
an extracted root filesystem.
"""
return self._check_recursive("archive")
def _check_firmware(self):
"""
If this file is of a known firmware type, directly attempt to extract
the kernel and root filesystem.
"""
for module in binwalk.scan(self.item, "-y", "header", signature=True,
quiet=True):
for entry in module.results:
# uImage
if "uImage header" in entry.description:
if not self.get_kernel_status() and \
"OS Kernel Image" in entry.description:
kernel_offset = entry.offset + 64
kernel_size = 0
for stmt in entry.description.split(','):
if "image size:" in stmt:
kernel_size = int(''.join(
i for i in stmt if i.isdigit()), 10)
if kernel_size != 0 and kernel_offset + kernel_size \
<= os.path.getsize(self.item):
self.printf(">>>> %s" % entry.description)
tmp_fd, tmp_path = tempfile.mkstemp(dir=self.temp)
os.close(tmp_fd)
Extractor.io_dd(self.item, kernel_offset,
kernel_size, tmp_path)
kernel = ExtractionItem(self.extractor, tmp_path,
self.depth, self.tag)
return kernel.extract()
# elif "RAMDisk Image" in entry.description:
# self.printf(">>>> %s" % entry.description)
# self.printf(">>>> Skipping: RAMDisk / initrd")
# self.terminate = True
# return True
# TP-Link or TRX
elif not self.get_kernel_status() and \
not self.get_rootfs_status() and \
"rootfs offset: " in entry.description and \
"kernel offset: " in entry.description:
kernel_offset = 0
kernel_size = 0
rootfs_offset = 0
rootfs_size = 0
for stmt in entry.description.split(','):
if "kernel offset:" in stmt:
kernel_offset = int(stmt.split(':')[1], 16)
elif "kernel length:" in stmt:
kernel_size = int(stmt.split(':')[1], 16)
elif "rootfs offset:" in stmt:
rootfs_offset = int(stmt.split(':')[1], 16)
elif "rootfs length:" in stmt:
rootfs_size = int(stmt.split(':')[1], 16)
# compute sizes if only offsets provided
if kernel_offset != rootfs_size and kernel_size == 0 and \
rootfs_size == 0:
kernel_size = rootfs_offset - kernel_offset
rootfs_size = os.path.getsize(self.item) - rootfs_offset
# ensure that computed values are sensible
if (kernel_size > 0 and kernel_offset + kernel_size \
<= os.path.getsize(self.item)) and \
(rootfs_size != 0 and rootfs_offset + rootfs_size \
<= os.path.getsize(self.item)):
self.printf(">>>> %s" % entry.description)
tmp_fd, tmp_path = tempfile.mkstemp(dir=self.temp)
os.close(tmp_fd)
Extractor.io_dd(self.item, kernel_offset, kernel_size,
tmp_path)
kernel = ExtractionItem(self.extractor, tmp_path,
self.depth, self.tag)
kernel.extract()
tmp_fd, tmp_path = tempfile.mkstemp(dir=self.temp)
os.close(tmp_fd)
Extractor.io_dd(self.item, rootfs_offset, rootfs_size,
tmp_path)
rootfs = ExtractionItem(self.extractor, tmp_path,
self.depth, self.tag)
rootfs.extract()
return self.update_status()
return False
def _check_kernel(self):
"""
If this file contains a kernel version string, assume it is a kernel.
Only Linux kernels are currently extracted.
"""
if not self.get_kernel_status():
for module in binwalk.scan(self.item, "-y", "kernel",
signature=True, quiet=True):
for entry in module.results:
if "kernel version" in entry.description:
self.update_database("kernel_version",
entry.description)
if "Linux" in entry.description:
if self.get_kernel_path():
shutil.copy(self.item, self.get_kernel_path())
else:
self.extractor.do_kernel = False
self.printf(">>>> %s" % entry.description)
return True
# VxWorks, etc
else:
self.printf(">>>> Ignoring: %s" % entry.description)
return False
return False
return False
def _check_rootfs(self):
"""
If this file contains a known filesystem type, extract it.
"""
if not self.get_rootfs_status():
for module in binwalk.scan(self.item, "-e", "-r", "-y",
"filesystem", signature=True,
quiet=True):
for entry in module.results:
self.printf(">>>> %s" % entry.description)
break
if module.extractor.directory:
unix = Extractor.io_find_rootfs(module.extractor.directory)
if not unix[0]:
self.printf(">>>> Extraction failed!")
return False
self.printf(">>>> Found Linux filesystem in %s!" % unix[1])
if self.output:
shutil.make_archive(self.output, "gztar",
root_dir=unix[1])
else:
self.extractor.do_rootfs = False
return True
return False
def _check_compressed(self):
"""
If this file appears to be compressed, decompress it and recurse over
its contents.
"""
return self._check_recursive("compressed")
# treat both archived and compressed files using the same pathway. this is
# because certain files may appear as e.g. "xz compressed data" but still
# extract into a root filesystem.
def _check_recursive(self, fmt):
"""
Unified implementation for checking both "archive" and "compressed"
items.
"""
desc = None
# perform extraction
for module in binwalk.scan(self.item, "-e", "-r", "-y", fmt,
signature=True, quiet=True):
for entry in module.results:
# skip cpio/initrd files since they should be included with
# kernel
# if "cpio archive" in entry.description:
# self.printf(">> Skipping: cpio: %s" % entry.description)
# self.terminate = True
# return True
desc = entry.description
self.printf(">>>> %s" % entry.description)
break
if module.extractor.directory:
unix = Extractor.io_find_rootfs(module.extractor.directory)
# check for extracted filesystem, otherwise update queue
if unix[0]:
self.printf(">>>> Found Linux filesystem in %s!" % unix[1])
if self.output:
shutil.make_archive(self.output, "gztar",
root_dir=unix[1])
else:
self.extractor.do_rootfs = False
return True
else:
count = 0
self.printf(">> Recursing into %s ..." % fmt)
for root, _, files in os.walk(module.extractor.directory):
# sort both descending alphabetical and increasing
# length
files.sort()
files.sort(key=len)
# handle case where original file name is restored; put
# it to front of queue
if desc and "original file name:" in desc:
orig = None
for stmt in desc.split(","):
if "original file name:" in stmt:
orig = stmt.split("\"")[1]
if orig and orig in files:
files.remove(orig)
files.insert(0, orig)
for filename in files:
if count > ExtractionItem.RECURSION_BREADTH:
self.printf(">> Skipping: recursion breadth %d"\
% ExtractionItem.RECURSION_BREADTH)
self.terminate = True
return True
else:
new_item = ExtractionItem(self.extractor,
os.path.join(root,
filename),
self.depth + 1,
self.tag)
if new_item.extract():
# check that we are actually done before
# performing early termination. for example,
# we might decide to skip on one subitem,
# but we still haven't finished
if self.update_status():
return True
count += 1
return False
def main():
parser = argparse.ArgumentParser(description="Extracts filesystem and \
kernel from Linux-based firmware images")
parser.add_argument("input", action="store", help="Input file or directory")
parser.add_argument("output", action="store", nargs="?", default="images",
help="Output directory for extracted firmware")
parser.add_argument("-sql ", dest="sql", action="store", default=None,
help="Hostname of SQL server")
parser.add_argument("-nf", dest="rootfs", action="store_false",
default=True, help="Disable extraction of root \
filesystem (may decrease extraction time)")
parser.add_argument("-nk", dest="kernel", action="store_false",
default=True, help="Disable extraction of kernel \
(may decrease extraction time)")
parser.add_argument("-np", dest="parallel", action="store_false",
default=True, help="Disable parallel operation \
(may increase extraction time)")
parser.add_argument("-b", dest="brand", action="store", default=None,
help="Brand of the firmware image")
result = parser.parse_args()
extract = Extractor(result.input, result.output, result.rootfs,
result.kernel, result.parallel, result.sql,
result.brand)
extract.extract()
if __name__ == "__main__":
main()
![logo](https://github.com/craigz28/firmwalker/blob/master/firmwalker-logo.jpg)
# firmwalker
A simple bash script for searching the extracted or mounted firmware file system.
It will search through the extracted or mounted firmware file system for things of interest such as:
* etc/shadow and etc/passwd
* list out the etc/ssl directory
* search for SSL related files such as .pem, .crt, etc.
* search for configuration files
* look for script files
* search for other .bin files
* look for keywords such as admin, password, remote, etc.
* search for common web servers used on IoT devices
* search for common binaries such as ssh, tftp, dropbear, etc.
* search for URLs, email addresses and IP addresses
* Experimental support for making calls to the Shodan API using the Shodan CLI
## Usage
* If you wish to use the static code analysis portion of the script, please install eslint: `npm i -g eslint`
* `./firmwalker {path to root file system} {path for firmwalker.txt}`
* Example: `./firmwalker linksys/fmk/rootfs ../firmwalker.txt`
* A file `firmwalker.txt` will be created in the same directory as the script file unless you specify a different filename as the second argument
* Do not put the firmwalker.sh file inside the directory to be searched, this will cause the script to search itself and the file it is creating
* `chmod 0700 firmwalker.sh`
## How to extend
* Have a look under 'data' where the checks live or add eslint rules - http://eslint.org/docs/rules/ to eslintrc.json
## Example Files - https://1drv.ms/f/s!AucQMYXJNefdvGZyeYt16H72VCLv
* squashfs-root.zip - contains files from random extracted router firmware. Firmwalker can be run against this file system.
* rt-ac66u.txt - firmwalker output file
* xc.txt - firmwalker output file from Ubiquiti device
### Script created by Craig Smith and expanded by:
* Athanasios Kostopoulos
* misterch0c
### Links
* https://craigsmith.net
* https://woktime.wordpress.com
* https://www.owasp.org/index.php/OWASP_Internet_of_Things_Project#tab=Firmware_Analysis
ssh
sshd
scp
sftp
tftp
dropbear
busybox
telnet
telnetd
openssl
upgrade
admin
root
password
passwd
pwd
dropbear
ssl
private key
telnet
secret
pgp
gpg
token
api key
oauth
authorized_keys
*authorized_keys*
host_key
*host_key*
id_rsa
*id_rsa*
id_dsa
*id_dsa*
*.pub
*.crt
*.pem
*.cer
*.p7b
*.p12
*.key
apache
lighttpd
alphapd
httpd
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
"no-eval": 2,
"no-alert": 2,
"no-console": 2
}
}
#!/usr/bin/env bash
set -e
set -u
function usage {
echo "Usage:"
echo "$0 {path to extracted file system of firmware}\
{optional: name of the file to store results - defaults to firmwalker.txt}"
echo "Example: ./$0 linksys/fmk/rootfs/"
exit 1
}
function msg {
echo "$1" | tee -a $FILE
}
function getArray {
array=() # Create array
while IFS= read -r line
do
array+=("$line")
done < "$1"
}
# Check for arguments
if [[ $# -gt 2 || $# -lt 1 ]]; then
usage
fi
# Set variables
FIRMDIR=$1
if [[ $# -eq 2 ]]; then
FILE=$2
else
FILE="firmwalker.txt"
fi
# Remove previous file if it exists, is a file and doesn't point somewhere
if [[ -e "$FILE" && ! -h "$FILE" && -f "$FILE" ]]; then
rm -f $FILE
fi
# Perform searches
msg "***Firmware Directory***"
msg $FIRMDIR
msg "***Search for password files***"
getArray "data/passfiles"
passfiles=("${array[@]}")
for passfile in "${passfiles[@]}"
do
msg "##################################### $passfile"
find $FIRMDIR -name $passfile | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg "***Search for Unix-MD5 hashes***"
egrep -sro '\$1\$\w{8}\S{23}' $FIRMDIR | tee -a $FILE
msg ""
if [[ -d "$FIRMDIR/etc/ssl" ]]; then
msg "***List etc/ssl directory***"
ls -l $FIRMDIR/etc/ssl | tee -a $FILE
fi
msg ""
msg "***Search for SSL related files***"
getArray "data/sslfiles"
sslfiles=("${array[@]}")
for sslfile in ${sslfiles[@]}
do
msg "##################################### $sslfile"
find $FIRMDIR -name $sslfile | cut -c${#FIRMDIR}- | tee -a $FILE
certfiles=( $(find ${FIRMDIR} -name ${sslfile}) )
: "${certfiles:=empty}"
# Perform Shodan search. This assumes Shodan CLI installed with an API key.
if [ "${certfiles##*.}" = "pem" ] || [ "${certfiles##*.}" = "crt" ]; then
for certfile in "${certfiles[@]}"
do
serialno=$(openssl x509 -in $certfile -serial -noout) || echo "Incorrect File Content:Continuing"
serialnoformat=(ssl.cert.serial:${serialno##*=})
if type "shodan" &> /dev/null ; then
shocount=$(shodan count $serialnoformat)
if (( $shocount > 0 )); then
msg "################# Certificate serial # found in Shodan ####################"
echo $certfile | cut -c${#FIRMDIR}- | tee -a $FILE
echo $serialno | tee -a $FILE
echo "Number of devices found in Shodan =" $shocount | tee -a $FILE
cat $certfile | tee -a $FILE
msg "###########################################################################"
fi
else
echo "Shodan cli not found."
fi
done
fi
msg ""
done
msg ""
msg "***Search for SSH related files***"
getArray "data/sshfiles"
sshfiles=("${array[@]}")
for sshfile in ${sshfiles[@]}
do
msg "##################################### $sshfile"
find $FIRMDIR -name $sshfile | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg ""
msg "***Search for files***"
getArray "data/files"
files=("${array[@]}")
for file in ${files[@]}
do
msg "##################################### $file"
find $FIRMDIR -name $file | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg ""
msg "***Search for database related files***"
getArray "data/dbfiles"
dbfiles=("${array[@]}")
for dbfile in ${dbfiles[@]}
do
msg "##################################### $dbfile"
find $FIRMDIR -name $dbfile | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg ""
msg "***Search for shell scripts***"
msg "##################################### shell scripts"
find $FIRMDIR -name "*.sh" | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
msg "***Search for other .bin files***"
msg "##################################### bin files"
find $FIRMDIR -name "*.bin" | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
msg "***Search for patterns in files***"
getArray "data/patterns"
patterns=("${array[@]}")
for pattern in "${patterns[@]}"
do
msg "-------------------- $pattern --------------------"
grep -lsirnw $FIRMDIR -e "$pattern" | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg ""
msg "***Search for web servers***"
msg "##################################### search for web servers"
getArray "data/webservers"
webservers=("${array[@]}")
for webserver in ${webservers[@]}
do
msg "##################################### $webserver"
find $FIRMDIR -name "$webserver" | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg ""
msg "***Search for important binaries***"
msg "##################################### important binaries"
getArray "data/binaries"
binaries=("${array[@]}")
for binary in "${binaries[@]}"
do
msg "##################################### $binary"
find $FIRMDIR -name "$binary" | cut -c${#FIRMDIR}- | tee -a $FILE
msg ""
done
msg ""
msg "***Search for ip addresses***"
msg "##################################### ip addresses"
grep -sRIEho '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b' --exclude-dir='dev' $FIRMDIR | sort | uniq | tee -a $FILE
msg ""
msg "***Search for urls***"
msg "##################################### urls"
grep -sRIEoh '(http|https)://[^/"]+' --exclude-dir='dev' $FIRMDIR | sort | uniq | tee -a $FILE
msg ""
msg "***Search for emails***"
msg "##################################### emails"
grep -sRIEoh '([[:alnum:]_.-]+@[[:alnum:]_.-]+?\.[[:alpha:].]{2,6})' "$@" --exclude-dir='dev' $FIRMDIR | sort | uniq | tee -a $FILE
#Perform static code analysis
#eslint -c eslintrc.json $FIRMDIR | tee -a $FILE
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
***Firmware Directory***
../scratch/1/image
***Search for password files***
##################################### passwd
e/usr/bin/passwd
e/usr/etc/passwd
e/tmp/etc/passwd
##################################### shadow
##################################### *.psk
***Search for Unix-MD5 hashes***
***Search for SSL related files***
##################################### *.crt
e/usr/etc/802_1X/Certificates/client.crt
##################################### *.pem
e/usr/etc/cert.pem
e/usr/etc/key.pem
e/usr/etc/802_1X/CA/cacert.pem
e/userfs/default_ssl_ca.pem
##################################### *.cer
##################################### *.p7b
##################################### *.p12
##################################### *.key
e/usr/etc/802_1X/PKEY/client.key
***Search for SSH related files***
##################################### authorized_keys
##################################### *authorized_keys*
##################################### host_key
##################################### *host_key*
e/usr/etc/dropbear/dropbear_dss_host_key
e/usr/etc/dropbear/dropbear_rsa_host_key
##################################### id_rsa
##################################### *id_rsa*
##################################### id_dsa
##################################### *id_dsa*
##################################### *.pub
***Search for files***
##################################### *.conf
e/usr/etc/radvd.conf
e/usr/etc/usb_modeswitch.conf
e/usr/etc/bftpd.conf
e/usr/etc/hwver.conf
e/usr/etc/resolv_ipv6.conf
e/usr/etc/dhcp6c.conf
e/usr/etc/inetd.conf
e/usr/etc/defaultWan.conf
e/usr/etc/fwver.conf
e/usr/etc/minidlna.conf
e/usr/etc/dhcp6s.conf
e/usr/etc/igd/portmap.conf
e/usr/etc/dproxy.conf
e/usr/etc/fwTCver.conf
e/usr/etc/resolv.conf
e/usr/etc/lld2d.conf
e/usr/etc/devInf.conf
e/usr/etc/resolv_ipv4.conf
e/usr/etc/snmp/snmpd.conf
e/userfs/led.conf
e/userfs/string2.conf
e/userfs/string1.conf
e/boaroot/boa.conf
##################################### *.cfg
e/userfs/romfile.cfg
e/userfs/profile.cfg
e/boaroot/html/romfile.cfg
##################################### *.ini
***Search for database related files***
##################################### *.db
##################################### *.sqlite
##################################### *.sqlite3
***Search for shell scripts***
##################################### shell scripts
e/usr/script/fw_start.sh
e/usr/script/alpha_wifi_schedule_5g.sh
e/usr/script/ipv6_filter_forward_stop.sh
e/usr/script/alpha_wireless_eapinfo_5G.sh
e/usr/script/ipv6_filter_forward_start.sh
e/usr/script/nat_start.sh
e/usr/script/restart_boa.sh
e/usr/script/AppFilterStop.sh
e/usr/script/urlfilter_start.sh
e/usr/script/alpha_wireless_stainfo_5G_for_statistics.sh
e/usr/script/ppp_start.sh
e/usr/script/wan_start_ipv4.sh
e/usr/script/spi_fw_stop.sh
e/usr/script/vserver.sh
e/usr/script/udhcpc.sh
e/usr/script/wan_start_ipv6.sh
e/usr/script/dslite_start.sh
e/usr/script/alpha_wireless_stainfo_5G.sh
e/usr/script/ipv6rd_start.sh
e/usr/script/udhcpc_nodef.sh
e/usr/script/alpha_usb_umount.sh
e/usr/script/usb_insmod.sh
e/usr/script/alpha_firewall.sh
e/usr/script/spi_fw_start.sh
e/usr/script/wan_start.sh
e/usr/script/dmz.sh
e/usr/script/ipv6_acl_stop.sh
e/usr/script/alpha_usbinfo.sh
e/usr/script/alpha_urlfilter.sh
e/usr/script/before_web_download_remove_wifi.sh
e/usr/script/br_conf.sh
e/usr/script/alpha_wireless_5G_bin_to_flash.sh
e/usr/script/alpha_wireless_channelscan_5G.sh
e/usr/script/before_web_download.sh
e/usr/script/dongle_dial_off.sh
e/usr/script/alpha_lanhost.sh
e/usr/script/ipmacfilter_stop.sh
e/usr/script/samba.sh
e/usr/script/UrlFilterStop.sh
e/usr/script/samba_add_dir.sh
e/usr/script/ipfilter_stop.sh
e/usr/script/filter_forward_stop.sh
e/usr/script/alpha_dsl_support.sh
e/usr/script/dlnaOff.sh
e/usr/script/filter_forward_start.sh
e/usr/script/channel_period.sh
e/usr/script/lanAlias_stop.sh
e/usr/script/alpha_cfm.sh
e/usr/script/alpha_klogd.sh
e/usr/script/ipaddr_mapping.sh
e/usr/script/ddns_run.sh
e/usr/script/alpha_upnp_scan.sh
e/usr/script/ntpclient.sh
e/usr/script/alpha_dlna_start.sh
e/usr/script/dlnaOn.sh
e/usr/script/settime.sh
e/usr/script/alpha_macfilter.sh
e/usr/script/lanAlias_start.sh
e/usr/script/alpha_wireless_stainfo.sh
e/usr/script/ipfilter_start.sh
e/usr/script/acl_stop.sh
e/usr/script/fw_stop.sh
e/usr/script/alpha_diag.sh
e/usr/script/ipfilter.sh
e/usr/script/alpha_wireless_stainfo_to_LanHost.sh
e/usr/script/before_web_upgrade.sh
e/usr/script/alpha_wifi_schedule.sh
e/usr/script/alpha_wireless_channelscan.sh
e/usr/script/alpha_wireless_eapinfo.sh
e/usr/script/ddns.sh
e/usr/script/5g_channel_period.sh
e/usr/script/nat_stop.sh
e/usr/script/upgrade_firmware.sh
e/usr/script/before_tr069_download.sh
e/usr/script/alpha_ipfilter.sh
e/usr/script/alpha_fun_lib.sh
e/usr/script/dongle_dial_on.sh
e/usr/script/ether_mac.sh
e/usr/script/alpha_usbcheck.sh
e/usr/script/wan_stop.sh
e/usr/script/alpha_syslogd.sh
e/usr/script/urlfilter_stop.sh
e/usr/script/getnow.sh
e/usr/etc/8021xaction.sh
e/usr/etc/igd/igd.sh
e/usr/etc/ppp/peers/ppp_on_dialer.sh
e/firmadyne/preInit.sh
***Search for other .bin files***
##################################### bin files
e/usr/etc/RT30xxEEPROM.bin
e/usr/etc/Wireless/RT2860AP_AC/RT30xxEEPROM.bin
***Search for patterns in files***
-------------------- upgrade --------------------
e/usr/bin/utelnetd
e/userfs/string2.conf
e/userfs/bin/cfg_manager
e/userfs/bin/ecmh
e/userfs/bin/boa
e/userfs/bin/tr69
e/userfs/bin/tftpd
e/userfs/bin/bftpd
e/userfs/bin/smbd
e/userfs/bin/ntfs-3g
e/userfs/string1.conf
e/boaroot/html/js/New_GUI/localization/en-us.js
e/boaroot/html/LanguageFamily/en/MAINTENANCE/mt_firmware.js
e/boaroot/html/LanguageFamily/en/msg_multipe.js
e/boaroot/html/LanguageFamily/de/msg_multipe.js
-------------------- admin --------------------
e/usr/bin/syslogd
e/usr/bin/iptables
e/usr/script/samba.sh
e/usr/script/samba_add_dir.sh
e/usr/etc/usertty
e/usr/etc/passwd
e/lib/libbigballofmud.so
e/userfs/romfile.cfg
e/userfs/string2.conf
e/userfs/bin/cfg_manager
e/userfs/bin/diap
e/userfs/bin/tr69
e/userfs/bin/ez-ipupdate
e/userfs/bin/smbpasswd
e/userfs/bin/smbd
e/userfs/string1.conf
e/boaroot/html/js/New_GUI/localization/en-us.js
e/boaroot/html/js/New_GUI/menu.js
e/boaroot/html/mobile/LanguageFamily/en/mobile_msg_multipe.js
e/boaroot/html/mobile/LanguageFamily/de/mobile_msg_multipe.js
e/boaroot/html/mobile/LanguageFamily/fr/mobile_msg_multipe.js
e/boaroot/html/LanguageFamily/it/msg_multipe.js
e/boaroot/html/LanguageFamily/es/msg_multipe.js
e/boaroot/html/LanguageFamily/en/MAINTENANCE/mt_admin.js
e/boaroot/html/LanguageFamily/en/msg_multipe.js
e/boaroot/html/LanguageFamily/de/msg_multipe.js
e/boaroot/html/LanguageFamily/fr/msg_multipe.js
e/boaroot/cgi-bin/Login.asp
e/boaroot/cgi-bin/mobile/login.asp
e/boaroot/cgi-bin/New_GUI/System.asp
e/boaroot/cgi-bin/New_GUI/Admin.asp
-------------------- root --------------------
e/usr/bin/ip
e/usr/bin/minidlna
e/usr/bin/wscd
e/usr/bin/pppd
e/usr/bin/tc
e/usr/bin/iptables
e/usr/bin/qoscmd
e/usr/bin/wscd_ac
e/usr/bin/ip6tables
e/usr/bin/brctl
e/usr/etc/bftpd.conf
e/usr/etc/xml/WFADeviceDesc_ac.xml
e/usr/etc/usertty
e/usr/etc/inetd.conf
e/usr/etc/group
e/usr/etc/minidlna.conf
e/usr/etc/passwd
e/firmadyne/preInit.sh
e/lib/libebt_stp.so
e/lib/modules/usbhost/usbcore.ko
e/lib/libpppoe.so
e/lib/libsqlite3.so.0.8.6
e/lib/libavformat.so.53
e/lib/libbigballofmud.so
e/bin/busybox
e/userfs/bin/dnsmasq
e/userfs/bin/cfg_manager
e/userfs/bin/snmpd
e/userfs/bin/boa
e/userfs/bin/radvd
e/userfs/bin/dropbear
e/userfs/bin/tr69
e/userfs/bin/cfm
e/userfs/bin/dhcrelay
e/userfs/bin/smbpasswd
e/userfs/bin/wpa_supplicant
e/userfs/bin/pppoe-relay
e/userfs/bin/bftpd
e/userfs/bin/smbd
e/userfs/bin/ntfs-3g
e/tmp/etc/passwd
e/boaroot/boa.conf
e/boaroot/html/js/New_GUI/localization/en-us.js
e/boaroot/html/js/New_GUI/excanvas.js
e/boaroot/html/scss/_bootstrap/_normalize.scss
e/boaroot/html/layout/screen.css
e/boaroot/html/mobile/jquery.min.js
-------------------- password --------------------
e/usr/sbin/cli
e/usr/sbin/mfc
e/usr/bin/pppd
e/usr/script/ppp_start.sh
e/usr/script/wan_start_ipv4.sh
e/usr/script/wan_start_ipv6.sh
e/usr/script/wan_start.sh
e/usr/script/ddns.sh
e/usr/script/dongle_dial_on.sh
e/usr/etc/bftpd.conf
e/usr/etc/l7-protocols/aim.pat
e/usr/etc/ppp/peers/ppp_on_dialer.sh
e/lib/libmatrixssl.so
e/lib/libc.so.0
e/lib/modules/mt7662e_ap.ko
e/lib/modules/mt7603eap.ko
e/lib/libbigballofmud.so
e/bin/busybox
e/userfs/romfile.cfg
e/userfs/string2.conf
e/userfs/bin/snmpd
e/userfs/bin/wpa_cli
e/userfs/bin/dropbear
e/userfs/bin/tr69
e/userfs/bin/ez-ipupdate
e/userfs/bin/smbpasswd
e/userfs/bin/wpa_supplicant
e/userfs/bin/bftpd
e/userfs/bin/smbd
e/userfs/string1.conf
e/boaroot/boa.conf
e/boaroot/html/js/New_GUI/localization/en-us.js
e/boaroot/html/js/New_GUI/comm.js
e/boaroot/html/js/New_GUI/libajax.js
e/boaroot/html/js/New_GUI/Settings/Internet_auto.js
e/boaroot/html/js/New_GUI/Settings/Internet_setup_hidden.js
e/boaroot/html/js/New_GUI/Settings/Internet_setup.js
e/boaroot/html/js/New_GUI/Settings/Internet_3g.js
e/boaroot/html/js/New_GUI/Advanced/Tr069.js
e/boaroot/html/js/New_GUI/jquery.validate.js
e/boaroot/html/js/New_GUI/jquery-1.8.2.min.js
e/boaroot/html/scss/_bootstrap/_forms.scss
e/boaroot/html/mobile/jquery.mobile-1.4.5.min.js
e/boaroot/html/mobile/LanguageFamily/it/mobile_msg_multipe.js
e/boaroot/html/mobile/LanguageFamily/en/mobile_msg_multipe.js
e/boaroot/html/mobile/LanguageFamily/fr/mobile_msg_multipe.js
e/boaroot/html/mobile/jquery.min.js
e/boaroot/html/LanguageFamily/it/msg_multipe.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_wireless.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_dynamic_dns.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_wireless_wizard.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_tr069.js
e/boaroot/html/LanguageFamily/en/MAINTENANCE/mt_admin.js
e/boaroot/html/LanguageFamily/en/msg_comm.js
e/boaroot/html/LanguageFamily/en/SETUP/l_wan_wizard.js
e/boaroot/html/LanguageFamily/en/SETUP/sp_wan.js
e/boaroot/html/LanguageFamily/en/New_GUI/Settings/Internet_auto.js
e/boaroot/html/LanguageFamily/en/New_GUI/Settings/WiFi.js
e/boaroot/html/LanguageFamily/en/New_GUI/Settings/Internet_setup.js
e/boaroot/html/LanguageFamily/en/msg_multipe.js
e/boaroot/html/public/__wan_adv.js
e/boaroot/cgi-bin/get/New_GUI/Internet_setup.asp
e/boaroot/cgi-bin/get/New_GUI/Internet_auto.asp
e/boaroot/cgi-bin/get/New_GUI/Internet_3g.asp
e/boaroot/cgi-bin/get/New_GUI/wizard_pppoa.asp
e/boaroot/cgi-bin/get/New_GUI/wizard_ppp.asp
e/boaroot/cgi-bin/Login.asp
e/boaroot/cgi-bin/mobile/login.asp
e/boaroot/cgi-bin/New_GUI/Internet_setup.asp
e/boaroot/cgi-bin/New_GUI/Tr069.asp
e/boaroot/cgi-bin/New_GUI/Set/wizard_ppp_setting.asp
e/boaroot/cgi-bin/New_GUI/Set/DynamicDNS.asp
e/boaroot/cgi-bin/New_GUI/Set/wizard_pppoa_setting.asp
e/boaroot/cgi-bin/New_GUI/Set/Admin.asp
e/boaroot/cgi-bin/New_GUI/Set/wizard_wan_setting.asp
e/boaroot/cgi-bin/New_GUI/Internet_auto_loading.asp
e/boaroot/cgi-bin/New_GUI/Internet_auto.asp
e/boaroot/cgi-bin/New_GUI/WiFi.asp
e/boaroot/cgi-bin/New_GUI/Internet_auto_hidden.asp
e/boaroot/cgi-bin/New_GUI/Internet_setup_hidden.asp
e/boaroot/cgi-bin/New_GUI/Wizard_Manual.asp
e/boaroot/cgi-bin/New_GUI/Internet_3g_loading.asp
e/boaroot/cgi-bin/New_GUI/Internet_adsl_loading.asp
e/boaroot/cgi-bin/New_GUI/DynamicDNS.asp
e/boaroot/cgi-bin/New_GUI/Internet_3g.asp
e/boaroot/cgi-bin/New_GUI/Admin.asp
-------------------- passwd --------------------
e/usr/bin/pppd
e/usr/script/samba.sh
e/usr/etc/bftpd.conf
e/usr/etc/services
e/lib/libc.so.0
e/lib/libbigballofmud.so
e/bin/busybox
e/userfs/romfile.cfg
e/userfs/string2.conf
e/userfs/bin/cfg_manager
e/userfs/bin/snmpd
e/userfs/bin/tr69
e/userfs/bin/ez-ipupdate
e/userfs/bin/bftpd
e/userfs/bin/smbd
e/userfs/string1.conf
e/boaroot/boa.conf
-------------------- pwd --------------------
e/usr/etc/ppp/peers/ppp_on_dialer.sh
e/lib/libc.so.0
e/lib/libbigballofmud.so
e/bin/busybox
e/userfs/bin/boa
e/userfs/bin/tr69
e/userfs/bin/pppoe-relay
e/boaroot/cgi-bin/Login.asp
e/boaroot/cgi-bin/mobile/login.asp
-------------------- dropbear --------------------
e/usr/script/before_web_download_remove_wifi.sh
e/usr/script/before_web_download.sh
e/usr/script/before_tr069_download.sh
e/userfs/bin/cfg_manager
e/userfs/bin/dropbear
-------------------- ssl --------------------
e/usr/etc/services
e/lib/libmatrixssl.so
e/lib/libbigballofmud.so
e/userfs/bin/snmpd
e/userfs/bin/boa
e/userfs/bin/tr69
e/userfs/bin/wpa_supplicant
e/boaroot/html/graphic/New_GUI/router-setup-prefiltered.jpg
-------------------- private key --------------------
e/usr/etc/key.pem
e/usr/etc/802_1X/PKEY/client.key
e/lib/libmatrixssl.so
e/lib/modules/mt7662e_ap.ko
e/userfs/bin/snmpd
e/userfs/bin/wpa_cli
e/userfs/bin/wpa_supplicant
-------------------- telnet --------------------
e/usr/bin/tcci
e/usr/script/ipv6_acl_stop.sh
e/usr/script/acl_stop.sh
e/usr/etc/inetd.conf
e/usr/etc/services
e/usr/etc/igd/portmap.conf
e/usr/etc/init.d/rcS
e/userfs/romfile.cfg
e/userfs/string2.conf
e/userfs/bin/cfg_manager
e/userfs/bin/tr69
e/userfs/string1.conf
e/boaroot/html/js/New_GUI/MacList.js
e/boaroot/html/LanguageFamily/it/msg_multipe.js
e/boaroot/html/LanguageFamily/es/msg_multipe.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_virtual_server.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_dmz.js
e/boaroot/html/LanguageFamily/en/msg_multipe.js
e/boaroot/html/LanguageFamily/de/msg_multipe.js
e/boaroot/html/LanguageFamily/fr/msg_multipe.js
e/boaroot/cgi-bin/New_GUI/Acl.asp
-------------------- secret --------------------
e/usr/bin/pppd
e/lib/modules/mt7662e_ap.ko
e/lib/libavformat.so.53
e/lib/libbigballofmud.so
e/userfs/string2.conf
e/userfs/bin/rtacdot1xd
e/userfs/bin/wpa_supplicant
e/userfs/bin/dhcp6s
e/userfs/bin/rtdot1xd
e/userfs/bin/dhcp6c
e/userfs/string1.conf
e/boaroot/boa.conf
e/boaroot/html/js/New_GUI/Settings/WiFi_multiple_settings.js
e/boaroot/html/js/New_GUI/Settings/WiFi_multiple_settings_ac.js
e/boaroot/html/js/New_GUI/Settings/WiFi.js
e/boaroot/html/js/New_GUI/Settings/WiFi_ac.js
e/boaroot/html/LanguageFamily/en/ADVANCED/ad_wireless.js
e/boaroot/html/LanguageFamily/en/New_GUI/Settings/WiFi.js
e/boaroot/html/LanguageFamily/en/msg_multipe.js
e/boaroot/html/LanguageFamily/fr/msg_multipe.js
-------------------- pgp --------------------
e/usr/etc/services
e/lib/libiconv.so.2.2.0
e/lib/modules/tc3162_dmt.ko
-------------------- gpg --------------------
e/usr/etc/services
e/lib/libiconv.so.2.2.0
-------------------- token --------------------
e/usr/bin/pppd
e/usr/bin/tc
e/lib/modules/mt7662e_ap.ko
e/lib/libsqlite3.so.0.8.6
e/lib/libbigballofmud.so
e/bin/busybox
e/userfs/bin/snmpd
e/userfs/bin/radvd
e/userfs/bin/dhcrelay
e/userfs/bin/wpa_supplicant
e/userfs/bin/smbd
e/userfs/bin/iwlist
e/userfs/bin/nmbd
-------------------- api key --------------------
-------------------- oauth --------------------
***Search for web servers***
##################################### search for web servers
##################################### apache
##################################### lighttpd
##################################### alphapd
##################################### httpd
***Search for important binaries***
##################################### important binaries
##################################### ssh
##################################### sshd
##################################### scp
##################################### sftp
##################################### tftp
e/usr/bin/tftp
##################################### dropbear
e/usr/etc/dropbear
e/userfs/bin/dropbear
##################################### busybox
e/bin/busybox
##################################### telnet
##################################### telnetd
##################################### openssl
***Search for ip addresses***
##################################### ip addresses
0.0.0.0
0.93.17.2
1.0.0.0
10.0.0.1
10.128.32.112
10.128.32.12
10.38.0.5
10.64.64.64
11.0.0.0
1.1.1.1
1.1.1.2
11.127.255.255
11.255.255.255
122.193.99.166
127.0.0.0
127.0.0.1
128.0.0.1
128.255.255.254
129.1.0.0
129.1.255.255
1.3.6.1
136.16.0.1
136.32.255.254
142.64.0.1
142.64.255.255
168.95.1.1
168.95.1.2
192.0.0.1
192.168.0.1
192.168.1.1
192.168.1.2
192.168.1.200
192.168.168.100
192.168.2.1
192.168.2.3
192.168.5.234
192.168.7.203
192.255.255.254
192.68.0.5
193.1.1.0
193.1.1.255
200.16.32.1
224.0.0.0
224.0.0.1
239.0.0.1
240.0.0.1
254.0.0.1
254.0.0.10
255.255.0.0
255.255.255.0
255.255.255.253
255.255.255.255
2.6.22.15
3.10.0.24
5.44.82.100
5.44.82.200
58.211.230.102
69.252.80.66
7.0.1.0
7.3.94.4
***Search for urls***
##################################### urls
http://192.168.0.1
http://192.168.1.1
http://a11yproject.com
http://api.jqueryui.com
http://bassistance.de
http://dcms.dlink.com.tw
http://developer.mozilla.org
http://dev.rgraph.net
http://docs.jquery.com
http://elsewhere
http://ethereal.com
http://getbootstrap.com
http://gridley.res.carleton.edu
http://jquery.org
http://jqueryui.com
http://localhost
http://msnpiki.msnfanatic.com
http://nicolasgallagher.com
https://github.com
https://' : 'http:
https://oiwifi.register.fon.com
http://stubbornella.org
https://www.mydlink.com
http://<%TCWebApi_get(
http://timkadlec.com
http://true
http://webfx.eae.net
http://www.apache.org
http://www.bulgaria-web-developers.com
http://www.dlink.com
http://www.dyndns.org) or no-ip.com (http:
http://www.gnu.org
http://www.hypothetic.org
http://www.iana.org
http://www.macromedia.com
http://www.madiatek.com
http://www.mediatek.com
http://www.mediatek.com<
http://www.opensource.org
http://www.protocolinfo.org
http://www.rgraph.net
http://www.rgraph.net |
http://www.rtsp.org - RFC 2326
http://www.venkydude.com
http://www.w3c.org
http://www.w3.org
http://www.whatwg.org
http://yahoo.com
***Search for emails***
##################################### emails
ca@email.com
client@email.com
didier@raboud.com
ppp@A1plus.at
quadong@hotmail.com
someone@somewhere.org
Tim@Rikers.org
webppp@a1plus.at
web@telering.at
william.gregory@talktalkplc.com
/usr/script/fw_start.sh/usr/script/alpha_wifi_schedule_5g.sh/usr/script/ipv6_filter_forward_stop.sh/usr/script/alpha_wireless_eapinfo_5G.sh/usr/script/ipv6_filter_forward_start.sh/usr/script/nat_start.sh/usr/script/restart_boa.sh/usr/script/AppFilterStop.sh/usr/script/urlfilter_start.sh/usr/script/alpha_wireless_stainfo_5G_for_statistics.sh/usr/script/ppp_start.sh/usr/script/wan_start_ipv4.sh/usr/script/spi_fw_stop.sh/usr/script/vserver.sh/usr/script/udhcpc.sh/usr/script/wan_start_ipv6.sh/usr/script/dslite_start.sh/usr/script/alpha_wireless_stainfo_5G.sh/usr/script/ipv6rd_start.sh/usr/script/udhcpc_nodef.sh/usr/script/alpha_usb_umount.sh/usr/script/usb_insmod.sh/usr/script/alpha_firewall.sh/usr/script/spi_fw_start.sh/usr/script/wan_start.sh/usr/script/dmz.sh/usr/script/ipv6_acl_stop.sh/usr/script/alpha_usbinfo.sh/usr/script/alpha_urlfilter.sh/usr/script/before_web_download_remove_wifi.sh/usr/script/br_conf.sh/usr/script/alpha_wireless_5G_bin_to_flash.sh/usr/script/alpha_wireless_channelscan_5G.sh/usr/script/before_web_download.sh/usr/script/dongle_dial_off.sh/usr/script/alpha_lanhost.sh/usr/script/ipmacfilter_stop.sh/usr/script/samba.sh/usr/script/UrlFilterStop.sh/usr/script/samba_add_dir.sh/usr/script/ipfilter_stop.sh/usr/script/filter_forward_stop.sh/usr/script/alpha_dsl_support.sh/usr/script/dlnaOff.sh/usr/script/filter_forward_start.sh/usr/script/channel_period.sh/usr/script/lanAlias_stop.sh/usr/script/alpha_cfm.sh/usr/script/alpha_klogd.sh/usr/script/ipaddr_mapping.sh/usr/script/ddns_run.sh/usr/script/alpha_upnp_scan.sh/usr/script/ntpclient.sh/usr/script/alpha_dlna_start.sh/usr/script/dlnaOn.sh/usr/script/settime.sh/usr/script/alpha_macfilter.sh/usr/script/lanAlias_start.sh/usr/script/alpha_wireless_stainfo.sh/usr/script/ipfilter_start.sh/usr/script/acl_stop.sh/usr/script/fw_stop.sh/usr/script/alpha_diag.sh/usr/script/ipfilter.sh/usr/script/alpha_wireless_stainfo_to_LanHost.sh/usr/script/before_web_upgrade.sh/usr/script/alpha_wifi_schedule.sh/usr/script/alpha_wireless_channelscan.sh/usr/script/alpha_wireless_eapinfo.sh/usr/script/ddns.sh/usr/script/5g_channel_period.sh/usr/script/nat_stop.sh/usr/script/upgrade_firmware.sh/usr/script/before_tr069_download.sh/usr/script/alpha_ipfilter.sh/usr/script/alpha_fun_lib.sh/usr/script/dongle_dial_on.sh/usr/script/ether_mac.sh/usr/script/alpha_usbcheck.sh/usr/script/wan_stop.sh/usr/script/alpha_syslogd.sh/usr/script/urlfilter_stop.sh/usr/script/getnow.sh/usr/etc/8021xaction.sh/usr/etc/igd/igd.sh/usr/etc/ppp/peers/ppp_on_dialer.sh/firmadyne/preInit.sh
\ No newline at end of file
text='''
e/usr/script/fw_start.sh
e/usr/script/alpha_wifi_schedule_5g.sh
e/usr/script/ipv6_filter_forward_stop.sh
e/usr/script/alpha_wireless_eapinfo_5G.sh
e/usr/script/ipv6_filter_forward_start.sh
e/usr/script/nat_start.sh
e/usr/script/restart_boa.sh
e/usr/script/AppFilterStop.sh
e/usr/script/urlfilter_start.sh
e/usr/script/alpha_wireless_stainfo_5G_for_statistics.sh
e/usr/script/ppp_start.sh
e/usr/script/wan_start_ipv4.sh
e/usr/script/spi_fw_stop.sh
e/usr/script/vserver.sh
e/usr/script/udhcpc.sh
e/usr/script/wan_start_ipv6.sh
e/usr/script/dslite_start.sh
e/usr/script/alpha_wireless_stainfo_5G.sh
e/usr/script/ipv6rd_start.sh
e/usr/script/udhcpc_nodef.sh
e/usr/script/alpha_usb_umount.sh
e/usr/script/usb_insmod.sh
e/usr/script/alpha_firewall.sh
e/usr/script/spi_fw_start.sh
e/usr/script/wan_start.sh
e/usr/script/dmz.sh
e/usr/script/ipv6_acl_stop.sh
e/usr/script/alpha_usbinfo.sh
e/usr/script/alpha_urlfilter.sh
e/usr/script/before_web_download_remove_wifi.sh
e/usr/script/br_conf.sh
e/usr/script/alpha_wireless_5G_bin_to_flash.sh
e/usr/script/alpha_wireless_channelscan_5G.sh
e/usr/script/before_web_download.sh
e/usr/script/dongle_dial_off.sh
e/usr/script/alpha_lanhost.sh
e/usr/script/ipmacfilter_stop.sh
e/usr/script/samba.sh
e/usr/script/UrlFilterStop.sh
e/usr/script/samba_add_dir.sh
e/usr/script/ipfilter_stop.sh
e/usr/script/filter_forward_stop.sh
e/usr/script/alpha_dsl_support.sh
e/usr/script/dlnaOff.sh
e/usr/script/filter_forward_start.sh
e/usr/script/channel_period.sh
e/usr/script/lanAlias_stop.sh
e/usr/script/alpha_cfm.sh
e/usr/script/alpha_klogd.sh
e/usr/script/ipaddr_mapping.sh
e/usr/script/ddns_run.sh
e/usr/script/alpha_upnp_scan.sh
e/usr/script/ntpclient.sh
e/usr/script/alpha_dlna_start.sh
e/usr/script/dlnaOn.sh
e/usr/script/settime.sh
e/usr/script/alpha_macfilter.sh
e/usr/script/lanAlias_start.sh
e/usr/script/alpha_wireless_stainfo.sh
e/usr/script/ipfilter_start.sh
e/usr/script/acl_stop.sh
e/usr/script/fw_stop.sh
e/usr/script/alpha_diag.sh
e/usr/script/ipfilter.sh
e/usr/script/alpha_wireless_stainfo_to_LanHost.sh
e/usr/script/before_web_upgrade.sh
e/usr/script/alpha_wifi_schedule.sh
e/usr/script/alpha_wireless_channelscan.sh
e/usr/script/alpha_wireless_eapinfo.sh
e/usr/script/ddns.sh
e/usr/script/5g_channel_period.sh
e/usr/script/nat_stop.sh
e/usr/script/upgrade_firmware.sh
e/usr/script/before_tr069_download.sh
e/usr/script/alpha_ipfilter.sh
e/usr/script/alpha_fun_lib.sh
e/usr/script/dongle_dial_on.sh
e/usr/script/ether_mac.sh
e/usr/script/alpha_usbcheck.sh
e/usr/script/wan_stop.sh
e/usr/script/alpha_syslogd.sh
e/usr/script/urlfilter_stop.sh
e/usr/script/getnow.sh
e/usr/etc/8021xaction.sh
e/usr/etc/igd/igd.sh
e/usr/etc/ppp/peers/ppp_on_dialer.sh
e/firmadyne/preInit.sh
'''
if __name__ =='__main__':
with open("result.txt", "w")as file:
for line in text.split():
file.write(line[1:])
#!/usr/bin/env python3
import pexpect
import os.path
from configparser import ConfigParser
config = ConfigParser()
config.read("emu.config")
firmadyne_path = config["DEFAULT"].get("path", "")
sudo_pass = config["DEFAULT"].get("sudo_password", "")
print ("[+] Cleaning previous images and created files by firmadyne")
child = pexpect.spawn("/bin/sh" , ["-c", "sudo rm -rf " + os.path.join(firmadyne_path, "images/*.tar.gz")])
child.sendline(sudo_pass)
child.expect_exact(pexpect.EOF)
child = pexpect.spawn("/bin/sh", ["-c", "sudo rm -rf " + os.path.join(firmadyne_path, "scratch/*")])
child.sendline(sudo_pass)
child.expect_exact(pexpect.EOF)
print ("[+] All done. Go ahead and run emu.py to continue firmware analysis")
#!/bin/bash
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: $0 <image ID>"
echo "This script deletes a whole project"
exit 1
fi
IID=${1}
#Check that no qemu is running:
echo "checking the process table for a running qemu instance ..."
PID=`ps -ef | grep qemu | grep "${IID}" | grep -v grep | awk '{print $2}'`
if ! [ -z $PID ]; then
echo "killing process ${PID}"
sudo kill -9 ${PID}
fi
PID1=`ps -ef | grep "${IID}\/run.sh" | grep -v grep | awk '{print $2}'`
if ! [ -z $PID1 ]; then
echo "killing process ${PID1}"
sudo kill ${PID1}
fi
#Check that nothing is mounted:
echo "In case the filesystem is mounted, umount it now ..."
sudo ./scripts/umount.sh ${IID}
#Check network config
echo "In case the network is configured, reconfigure it now ..."
for i in 0 .. 4; do
sudo ifconfig tap${IID}_${i} down
sudo tunctl -d tap${IID}_${i}
done
#Cleanup database:
echo "Remove the database entries ..."
psql -d firmware -U firmadyne -h 127.0.0.1 -t -q -c "DELETE from image WHERE id=${IID};"
#Cleanup filesystem:
echo "Clean up the file system ..."
if [ -f "/tmp/qemu.${IID}*" ]; then
sudo rm /tmp/qemu.${IID}*
fi
if [ -f ./images/${IID}.tar.gz ]; then
sudo rm ./images/${IID}.tar.gz
fi
if [ -f ./images/${IID}.kernel ]; then
sudo rm ./images/${IID}.kernel
fi
if [ -d ./scratch/${IID}/ ]; then
sudo rm -r ./scratch/${IID}/
fi
echo "Done. Removed project ID ${IID}."
#!/bin/bash
#The paths of the directories are specified here
ROOT_DIR="$HOME"
HOME_DIR="$ROOT_DIR/Desktop/EmuFuzz/Emulation"
export EMU_DIR=$HOME_DIR
export WORK_DIR="$HOME_DIR/scratch"
export KERNEL_DIR="$HOME_DIR/source/Kernel-mips/build"
export KERNEL_DIR_ARMEL="$HOME_DIR/source/Kernel-armel/build"
export LIB_DIR="$HOME_DIR/source/LIB"
export SCRIPT_DIR="$HOME_DIR/scripts"
export TARBALL_DIR="$HOME_DIR/images"
#!/bin/sh
# use busybox statically-compiled version of all binaries
BUSYBOX="/busybox"
# print input if not symlink, otherwise attempt to resolve symlink
resolve_link() {
TARGET=$($BUSYBOX readlink $1)
if [ -z "$TARGET" ]; then
echo "$1"
fi
echo "$TARGET"
}
# make /etc and add some essential files
mkdir -p "$(resolve_link /etc)"
if [ ! -s /etc/TZ ]; then
echo "Creating /etc/TZ!"
mkdir -p "$(dirname $(resolve_link /etc/TZ))"
echo "EST5EDT" > "$(resolve_link /etc/TZ)"
fi
if [ ! -s /etc/hosts ]; then
echo "Creating /etc/hosts!"
mkdir -p "$(dirname $(resolve_link /etc/hosts))"
echo "127.0.0.1 localhost" > "$(resolve_link /etc/hosts)"
fi
if [ ! -s /etc/passwd ]; then
echo "Creating /etc/passwd!"
mkdir -p "$(dirname $(resolve_link /etc/passwd))"
echo "root::0:0:root:/root:/bin/sh" > "$(resolve_link /etc/passwd)"
fi
# make /dev and add default device nodes if current /dev does not have greater
# than 5 device nodes
mkdir -p "$(resolve_link /dev)"
FILECOUNT="$($BUSYBOX find ${WORKDIR}/dev -maxdepth 1 -type b -o -type c -print | $BUSYBOX wc -l)"
if [ $FILECOUNT -lt "5" ]; then
echo "Warning: Recreating device nodes!"
mknod -m 660 /dev/mem c 1 1
mknod -m 640 /dev/kmem c 1 2
mknod -m 666 /dev/null c 1 3
mknod -m 666 /dev/zero c 1 5
mknod -m 444 /dev/random c 1 8
mknod -m 444 /dev/urandom c 1 9
mknod -m 666 /dev/armem c 1 13
mknod -m 666 /dev/tty c 5 0
mknod -m 622 /dev/console c 5 1
mknod -m 666 /dev/ptmx c 5 2
mknod -m 622 /dev/tty0 c 4 0
mknod -m 660 /dev/ttyS0 c 4 64
mknod -m 660 /dev/ttyS1 c 4 65
mknod -m 660 /dev/ttyS2 c 4 66
mknod -m 660 /dev/ttyS3 c 4 67
mknod -m 644 /dev/adsl0 c 100 0
mknod -m 644 /dev/ppp c 108 0
mknod -m 666 /dev/hidraw0 c 251 0
mkdir -p /dev/mtd
mknod -m 644 /dev/mtd/0 c 90 0
mknod -m 644 /dev/mtd/1 c 90 2
mknod -m 644 /dev/mtd/2 c 90 4
mknod -m 644 /dev/mtd/3 c 90 6
mknod -m 644 /dev/mtd/4 c 90 8
mknod -m 644 /dev/mtd/5 c 90 10
mknod -m 644 /dev/mtd/6 c 90 12
mknod -m 644 /dev/mtd/7 c 90 14
mknod -m 644 /dev/mtd/8 c 90 16
mknod -m 644 /dev/mtd/9 c 90 18
mknod -m 644 /dev/mtd/10 c 90 20
mknod -m 644 /dev/mtd0 c 90 0
mknod -m 644 /dev/mtdr0 c 90 1
mknod -m 644 /dev/mtd1 c 90 2
mknod -m 644 /dev/mtdr1 c 90 3
mknod -m 644 /dev/mtd2 c 90 4
mknod -m 644 /dev/mtdr2 c 90 5
mknod -m 644 /dev/mtd3 c 90 6
mknod -m 644 /dev/mtdr3 c 90 7
mknod -m 644 /dev/mtd4 c 90 8
mknod -m 644 /dev/mtdr4 c 90 9
mknod -m 644 /dev/mtd5 c 90 10
mknod -m 644 /dev/mtdr5 c 90 11
mknod -m 644 /dev/mtd6 c 90 12
mknod -m 644 /dev/mtdr6 c 90 13
mknod -m 644 /dev/mtd7 c 90 14
mknod -m 644 /dev/mtdr7 c 90 15
mknod -m 644 /dev/mtd8 c 90 16
mknod -m 644 /dev/mtdr8 c 90 17
mknod -m 644 /dev/mtd9 c 90 18
mknod -m 644 /dev/mtdr9 c 90 19
mknod -m 644 /dev/mtd10 c 90 20
mknod -m 644 /dev/mtdr10 c 90 21
mkdir -p /dev/mtdblock
mknod -m 644 /dev/mtdblock/0 b 31 0
mknod -m 644 /dev/mtdblock/1 b 31 1
mknod -m 644 /dev/mtdblock/2 b 31 2
mknod -m 644 /dev/mtdblock/3 b 31 3
mknod -m 644 /dev/mtdblock/4 b 31 4
mknod -m 644 /dev/mtdblock/5 b 31 5
mknod -m 644 /dev/mtdblock/6 b 31 6
mknod -m 644 /dev/mtdblock/7 b 31 7
mknod -m 644 /dev/mtdblock/8 b 31 8
mknod -m 644 /dev/mtdblock/9 b 31 9
mknod -m 644 /dev/mtdblock/10 b 31 10
mknod -m 644 /dev/mtdblock0 b 31 0
mknod -m 644 /dev/mtdblock1 b 31 1
mknod -m 644 /dev/mtdblock2 b 31 2
mknod -m 644 /dev/mtdblock3 b 31 3
mknod -m 644 /dev/mtdblock4 b 31 4
mknod -m 644 /dev/mtdblock5 b 31 5
mknod -m 644 /dev/mtdblock6 b 31 6
mknod -m 644 /dev/mtdblock7 b 31 7
mknod -m 644 /dev/mtdblock8 b 31 8
mknod -m 644 /dev/mtdblock9 b 31 9
mknod -m 644 /dev/mtdblock10 b 31 10
mkdir -p /dev/tts
mknod -m 660 /dev/tts/0 c 4 64
mknod -m 660 /dev/tts/1 c 4 65
mknod -m 660 /dev/tts/2 c 4 66
mknod -m 660 /dev/tts/3 c 4 67
fi
# create a gpio file required for linksys to make the watchdog happy
if ($BUSYBOX grep -sq "/dev/gpio/in" /bin/gpio) ||
($BUSYBOX grep -sq "/dev/gpio/in" /usr/lib/libcm.so) ||
($BUSYBOX grep -sq "/dev/gpio/in" /usr/lib/libshared.so); then
echo "Creating /dev/gpio/in!"
mkdir -p /dev/gpio
echo -ne "\xff\xff\xff\xff" > /dev/gpio/in
fi
# prevent system from rebooting
#echo "Removing /sbin/reboot!"
#rm -f /sbin/reboot
echo "Removing /etc/scripts/sys_resetbutton!"
rm -f /etc/scripts/sys_resetbutton
# add some default nvram entries
if $BUSYBOX grep -sq "ipv6_6to4_lan_ip" /sbin/rc; then
echo "Creating default ipv6_6to4_lan_ip!"
echo -n "2002:7f00:0001::" > /firmadyne/libnvram.override/ipv6_6to4_lan_ip
fi
if $BUSYBOX grep -sq "time_zone_x" /lib/libacos_shared.so; then
echo "Creating default time_zone_x!"
echo -n "0" > /firmadyne/libnvram.override/time_zone_x
fi
if $BUSYBOX grep -sq "rip_multicast" /usr/sbin/httpd; then
echo "Creating default rip_multicast!"
echo -n "0" > /firmadyne/libnvram.override/rip_multicast
fi
if $BUSYBOX grep -sq "bs_trustedip_enable" /usr/sbin/httpd; then
echo "Creating default bs_trustedip_enable!"
echo -n "0" > /firmadyne/libnvram.override/bs_trustedip_enable
fi
if $BUSYBOX grep -sq "filter_rule_tbl" /usr/sbin/httpd; then
echo "Creating default filter_rule_tbl!"
echo -n "" > /firmadyne/libnvram.override/filter_rule_tbl
fi
if $BUSYBOX grep -sq "rip_enable" /sbin/acos_service; then
echo "Creating default rip_enable!"
echo -n "0" > /firmadyne/libnvram.override/rip_enable
fi
#!/bin/bash
set -e
set -u
function getArch() {
if (echo ${FILETYPE} | grep -q "MIPS64")
then
ARCH="mips64"
elif (echo ${FILETYPE} | grep -q "MIPS")
then
ARCH="mips"
elif (echo ${FILETYPE} | grep -q "ARM64")
then
ARCH="arm64"
elif (echo ${FILETYPE} | grep -q "ARM")
then
ARCH="arm"
elif (echo ${FILETYPE} | grep -q "Intel 80386")
then
ARCH="intel"
elif (echo ${FILETYPE} | grep -q "x86-64")
then
ARCH="intel64"
elif (echo ${FILETYPE} | grep -q "PowerPC")
then
ARCH="ppc"
else
ARCH=""
fi
}
function getEndian() {
if (echo ${FILETYPE} | grep -q "LSB")
then
END="el"
elif (echo ${FILETYPE} | grep -q "MSB")
then
END="eb"
else
END=""
fi
}
INFILE=${1}
BASE=$(basename "$1")
IID=${BASE%.tar.gz}
mkdir -p "/tmp/${IID}"
set +e
FILES="$(tar -tf $INFILE | grep -e "/busybox\$") "
FILES+="$(tar -tf $INFILE | grep -E "/sbin/[[:alpha:]]+")"
FILES+="$(tar -tf $INFILE | grep -E "/bin/[[:alpha:]]+")"
set -e
for TARGET in ${FILES}
do
SKIP=$(echo "${TARGET}" | fgrep -o / | wc -l)
tar -xf "${INFILE}" -C "/tmp/${IID}/" --strip-components=${SKIP} ${TARGET}
TARGETLOC="/tmp/$IID/${TARGET##*/}"
if [ -h ${TARGETLOC} ] || [ ! -f ${TARGETLOC} ]
then
continue
fi
FILETYPE=$(file ${TARGETLOC})
echo -n "${TARGET}: "
getArch
getEndian
if [ -n "${ARCH}" ] && [ -n "${END}" ]
then
# ARCHEND=${ARCH}${END}
# echo ${ARCHEND}
# #psql -d firmware -U firmadyne -h 127.0.0.1 -q -c "UPDATE image SET arch = '$ARCHEND' WHERE id = $IID;"
# rm -fr "/tmp/${IID}"
# exit 0
# else
echo -n ${ARCH}
echo ${END}
fi
done
rm -fr "/tmp/${IID}"
exit 1
#!/bin/bash
set -e
set -u
source scripts/env.config
IID=${1}
ARCH=${2}
WORK_DIR="${WORK_DIR}/${IID}"
if [ "$ARCH" == "mipseb" ]; then
cp "${KERNEL_DIR}/${ARCH}/vmlinux" "${WORK_DIR}/vmlinux"
chmod a+x "${WORK_DIR}/vmlinux"
elif [ "$ARCH" == "mipsel" ]; then
cp "${KERNEL_DIR}/${ARCH}/vmlinux" "${WORK_DIR}/vmlinux"
chmod a+x "${WORK_DIR}/vmlinux"
elif [ "$ARCH" == "armel" ]; then
cp "${KERNEL_DIR_ARMEL}/${ARCH}/arch/arm/boot/zImage" "${WORK_DIR}/zImage"
chmod a+x "${WORK_DIR}/zImage"
else
echo "Unsupported architecture"
fi
echo "Running firmware ${IID}: terminating after 60 secs..."
timeout --preserve-status --signal SIGINT 60 "${SCRIPT_DIR}/run.${ARCH}.sh" "${IID}" "${ARCH}"
sleep 1
echo "Inferring network..."
"${SCRIPT_DIR}/makeNetwork.py" -i "${IID}" -q -o -a "${ARCH}" -S "${WORK_DIR}"
echo "Done!"
# Kernel Information Module via gdb
First. Go read the normal kernelinfo [readme](https://github.com/panda-re/panda/blob/master/panda/plugins/osi_linux/utils/kernelinfo/README.md).
## Requirements
- GDB 8 or above. This is needed for the GDB API to support `gdb.execute(to_string=True)`.
- Python 3.6 or above. This is to support fstrings.
- A kernel vmlinux file for linux 3.0.0 or later that is *not stripped and has debug symbols*.
## Where does this apply?
Kernels with debug symbols. Likely one that you built. If it's stripped go back to the other method.
Example: `vmlinux: ELF 32-bit MSB executable, MIPS, MIPS32 rel2 version 1 (SYSV), statically linked, BuildID[sha1]=181ca40a44bef701cf0559b185180053a152029d, with debug_info, not stripped`
## How does this work?
This crux of this is python script run inside of gdb to gather DWARF symbols.
That script creates a command `kernel_info` which runs a bunch of GDB commands to gather information from the DWARF symbols and output it.
## How do I use it?
Run `run.sh` with a vmlinux and an output file.
`./run.sh vmlinux file.out`
Alternatively,
- start up gdb on the `vmlinux` file: `gdb ./vmlinux`
- load our python script: `source extract_kernelinfo.py`
- run our python script: `kernel_info output.file`
- quit: `q`
import gdb
import sys
import re
file_out = sys.stdout
def print_size(structv, cfgmemb, cfgname):
size = gdb.execute(f'printf "%u",(size_t) sizeof({structv})',to_string=True)
print(f"{cfgname}.{cfgmemb} = {size}",file=file_out)
def print_offset(structp, memb, cfgname):
offset = gdb.execute(f'printf "%d",(int)&(({structp}*)0)->{memb}',to_string=True)
print(f"{cfgname}.{memb}_offset = {offset}",file=file_out)
def print_offset_from_member(structp, memb_base, memb_dest, cfgname):
offset = gdb.execute(f'printf "%lld", (int64_t)&(({structp})*0)->{memb_dest} - (int64_t)&(({structp})*0)->{memb_base}',to_string=True)
print(f"{cfgname}.{memb_dest}_offset = {offset}",file=file_out)
def get_symbol_as_string(name):
return gdb.execute(f'printf "%s",{name}',to_string=True)
class KernelInfo(gdb.Command):
def __init__(self):
super(KernelInfo, self).__init__("kernel_info", gdb.COMMAND_DATA)
def invoke(self, arg, from_tty):
global file_out
if arg:
file_out = open(arg, "w+")
print(f"Printing output to {arg}")
print(f"[kernelinfo]",file=file_out)
uts_release = get_symbol_as_string("init_uts_ns->name->release")
uts_version = get_symbol_as_string("init_uts_ns->name->version")
uts_machine = get_symbol_as_string("init_uts_ns->name->machine")
print(f"name = {uts_release}|{uts_version}|{uts_machine}",file=file_out)
release = get_symbol_as_string("init_uts_ns->name->release")
versions = release.split(".")
# version.c can have a bunch of junk - just extract a number
versions[2] = re.search("\d+",versions[2]).group(0)
print(f"version.a = {versions[0]}",file=file_out)
print(f"version.b = {versions[1]}",file=file_out)
print(f"version.c = {versions[2]}",file=file_out)
# TODO: we should use this to generate the file. See issue 651
print(f"#arch = {uts_machine}", file=file_out)
try:
per_cpu_offset_addr = gdb.execute('printf "%llu", &__per_cpu_offset',to_string=True)
per_cpu_offset_0_addr = gdb.execute('printf "%llu", __per_cpu_offset[0]',to_string=True)
except:
# This should be an arch-specific requirement, arm/mips don't have it (#651)
assert("x86" not in uts_machine), "Failed to find __per_cpu_offset_data"
per_cpu_offset_addr = 0
per_cpu_offset_0_addr = 0
print(f"task.per_cpu_offsets_addr = {per_cpu_offset_addr}",file=file_out)
print(f"task.per_cpu_offset_0_addr = {per_cpu_offset_0_addr}",file=file_out)
init_task_addr = gdb.execute('printf "%llu", &init_task',to_string=True)
# current_task is only an x86 thing
# It's defined in /arch/x86/kernel/cpu/common.c
if "x86" in uts_machine:
current_task_addr = gdb.execute('printf "%llu", &current_task',to_string=True)
else:
current_task_addr = init_task_addr
print(f"task.current_task_addr = {current_task_addr}",file=file_out)
print(f"task.init_addr = {init_task_addr}",file=file_out)
print(f"#task.per_cpu_offsets_addr = {hex(int(per_cpu_offset_addr))[2:]}",file=file_out)
print(f"#task.per_cpu_offset_0_addr = {hex(int(per_cpu_offset_0_addr))}",file=file_out)
print(f"#task.current_task_addr = {hex(int(current_task_addr))}",file=file_out)
print(f"#task.init_addr = {hex(int(init_task_addr))}",file=file_out)
print_size("struct task_struct", "size", "task");
print_offset("struct task_struct", "tasks", "task");
print_offset("struct task_struct", "pid", "task");
print_offset("struct task_struct", "tgid", "task");
print_offset("struct task_struct", "group_leader", "task");
print_offset("struct task_struct", "thread_group", "task");
print_offset("struct task_struct", "real_parent", "task");
print_offset("struct task_struct", "parent", "task");
print_offset("struct task_struct", "mm", "task");
print_offset("struct task_struct", "stack", "task");
print_offset("struct task_struct", "real_cred", "task");
print_offset("struct task_struct", "cred", "task");
print_offset("struct task_struct", "comm", "task");
print_size("((struct task_struct*)0)->comm", "comm_size", "task");
print_offset("struct task_struct", "files", "task");
print_offset("struct task_struct", "start_time", "task");
print_offset("struct cred", "uid", "cred");
print_offset("struct cred", "gid", "cred");
print_offset("struct cred", "euid", "cred");
print_offset("struct cred", "egid", "cred");
print_size("struct mm_struct", "size", "mm");
print_offset("struct mm_struct", "mmap", "mm");
print_offset("struct mm_struct", "pgd", "mm");
print_offset("struct mm_struct", "arg_start", "mm");
print_offset("struct mm_struct", "start_brk", "mm");
print_offset("struct mm_struct", "brk", "mm");
print_offset("struct mm_struct", "start_stack", "mm");
print_size("struct vm_area_struct", "size", "vma");
print_offset("struct vm_area_struct", "vm_mm", "vma");
print_offset("struct vm_area_struct", "vm_start", "vma");
print_offset("struct vm_area_struct", "vm_end", "vma");
print_offset("struct vm_area_struct", "vm_next", "vma");
print_offset("struct vm_area_struct", "vm_flags", "vma");
print_offset("struct vm_area_struct", "vm_file", "vma");
# used in reading file information
# This is gross because the name doesn't match the symbol identifier.
fstruct = "struct file"
f_path_offset = gdb.execute(f'printf "%d",(int)&(({fstruct}*)0)->f_path.dentry',to_string=True)
print(f"fs.f_path_dentry_offset = {f_path_offset}",file=file_out)
offset = gdb.execute(f'printf "%d",(int)&(({fstruct}*)0)->f_path.mnt',to_string=True)
print(f"fs.f_path_mnt_offset = {offset}",file=file_out)
print_offset("struct file", "f_pos", "fs");
print_offset("struct files_struct", "fdt", "fs");
print_offset("struct files_struct", "fdtab", "fs");
print_offset("struct fdtable", "fd", "fs");
# used for resolving path names */
print_size("struct qstr", "size", "qstr");
print_offset("struct qstr", "name", "qstr");
print_offset("struct dentry", "d_name", "path");
print_offset("struct dentry", "d_iname", "path");
print_offset("struct dentry", "d_parent", "path");
print_offset("struct dentry", "d_op", "path");
print_offset("struct dentry_operations", "d_dname", "path");
print_offset("struct vfsmount", "mnt_root", "path");
if int(versions[0]) >= 3:
# fields in struct mount
print_offset_from_member("struct mount", "mnt", "mnt_parent", "path");
print_offset_from_member("struct mount", "mnt", "mnt_mountpoint", "path");
else:
# fields in struct vfsmount
print_offset("struct vfsmount", "mnt_parent", "path");
print_offset("struct vfsmount", "mnt_mountpoint", "path");
if file_out != sys.stdout:
file_out.close()
# This registers our class to the gdb runtime at "source" time.
KernelInfo()
#!/bin/bash
if [ "$#" -lt 1 ]; then
echo "run.sh [debuggable vmlinux file] [output file]"
exit
fi
VMLINUX=$1
OUTPUT_FILE=$2
SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
gdb $VMLINUX -ex "source ${SCRIPTDIR}/extract_kernelinfo.py" -ex "kernel_info $OUTPUT_FILE" -ex "q"
#!/bin/bash
set -e
set -u
source scripts/env.config
IID=${1}
ARCH=${2}
echo "----Running----"
WORK_DIR="${WORK_DIR}/${IID}"
IMAGE="${WORK_DIR}/image.raw"
IMAGE_DIR="${WORK_DIR}/image"
LIBNVRAM="${LIB_DIR}/libnvram.so.${ARCH}"
CONSOLE="${LIB_DIR}/console.${ARCH}"
echo "----Copying Filesystem Tarball----"
mkdir -p "${WORK_DIR}"
chmod a+rwx "${WORK_DIR}"
chown -R "${USER}" "${WORK_DIR}"
chgrp -R "${USER}" "${WORK_DIR}"
if [ ! -e "${WORK_DIR}/${IID}.tar.gz" ]; then
if [ ! -e "${TARBALL_DIR}/${IID}.tar.gz" ]; then
echo "Error: Cannot find tarball of root filesystem for ${IID}!"
exit 1
else
cp "${TARBALL_DIR}/${IID}.tar.gz" "${WORK_DIR}/${IID}.tar.gz"
fi
fi
echo "----Creating QEMU Image----"
qemu-img create -f raw "${IMAGE}" 1G
chmod a+rw "${IMAGE}"
echo "----Creating Partition Table----"
echo -e "o\nn\np\n1\n\n\nw" | /sbin/fdisk "${IMAGE}"
echo "----Mounting QEMU Image----"
kpartx_out="$(kpartx -a -s -v "${IMAGE}")"
DEVICE="$(echo $kpartx_out | cut -d ' ' -f 3)"
DEVICE="/dev/mapper/$DEVICE"
echo $DEVICE
sleep 1
echo "----Creating Filesystem----"
mkfs.ext2 "${DEVICE}"
sync
echo "----Making QEMU Image Mountpoint----"
if [ ! -e "${IMAGE_DIR}" ]; then
mkdir "${IMAGE_DIR}"
chown "${USER}" "${IMAGE_DIR}"
fi
echo "----Mounting QEMU Image Partition 1----"
mount "${DEVICE}" "${IMAGE_DIR}"
echo "----Extracting Filesystem Tarball----"
tar -xf "${WORK_DIR}/$IID.tar.gz" -C "${IMAGE_DIR}"
rm "${WORK_DIR}/${IID}.tar.gz"
echo "----Creating FIRMADYNE Directories----"
mkdir "${IMAGE_DIR}/firmadyne/"
mkdir "${IMAGE_DIR}/firmadyne/libnvram/"
mkdir "${IMAGE_DIR}/firmadyne/libnvram.override/"
echo "----Patching Filesystem (chroot)----"
cp $(which busybox) "${IMAGE_DIR}"
cp "${SCRIPT_DIR}/fixImage.sh" "${IMAGE_DIR}"
chroot "${IMAGE_DIR}" /busybox ash /fixImage.sh
rm "${IMAGE_DIR}/fixImage.sh"
rm "${IMAGE_DIR}/busybox"
echo "----Setting up FIRMADYNE----"
cp "${CONSOLE}" "${IMAGE_DIR}/firmadyne/console"
chmod a+x "${IMAGE_DIR}/firmadyne/console"
mknod -m 666 "${IMAGE_DIR}/firmadyne/ttyS1" c 4 65
cp "${LIBNVRAM}" "${IMAGE_DIR}/firmadyne/libnvram.so"
chmod a+x "${IMAGE_DIR}/firmadyne/libnvram.so"
cp "${SCRIPT_DIR}/preInit.sh" "${IMAGE_DIR}/firmadyne/preInit.sh"
chmod a+x "${IMAGE_DIR}/firmadyne/preInit.sh"
# cp -r "${IMAGE_DIR}" "${EMU_DIR}/image_${IID}"
echo "----Unmounting QEMU Image----"
sync
umount "${DEVICE}"
kpartx -d "${IMAGE}"
cd ${WORK_DIR}
qemu-img convert -f raw -O qcow2 image.raw image.qcow2
\ No newline at end of file
#!/usr/bin/env python
import sys
import getopt
import re
import struct
import socket
import stat
import os
debug = 0
QEMUCMDTEMPLATE = """#!/bin/bash
set -u
ARCH="%(ARCHEND)s"
set -u
IID=%(IID)i
%(START_NET)s
function cleanup {
pkill -P $$
%(STOP_NET)s
}
trap cleanup EXIT
echo "Starting firmware emulation... use Ctrl-a + x to exit"
sleep 1s
%(QEMU_ENV_VARS)s %(QEMU)s -m 256 -M %(MACHINE)s -kernel ./vmlinux \\
%(QEMU_DISK)s -append "root=%(QEMU_ROOTFS)s console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1 user_debug=31 firmadyne.syscall=0" \\
-nographic \\
%(QEMU_NETWORK)s | tee qemu.final.serial.log
"""
def stripTimestamps(data):
lines = data.split("\n")
#throw out the timestamps
lines = [re.sub(r"^\[[^\]]*\] firmadyne: ", "", l) for l in lines]
return lines
def findMacChanges(data, endianness):
lines = stripTimestamps(data)
candidates = filter(lambda l: l.startswith("ioctl_SIOCSIFHWADDR"), lines)
if debug:
print("Mac Changes %r" % candidates)
result = []
if endianness == "eb":
fmt = ">I"
elif endianness == "el":
fmt = "<I"
for c in candidates:
g = re.match(r"^ioctl_SIOCSIFHWADDR\[[^\]]+\]: dev:([^ ]+) mac:0x([0-9a-f]+) 0x([0-9a-f]+)", c)
if g:
(iface, mac0, mac1) = g.groups()
m0 = struct.pack(fmt, int(mac0, 16))[2:]
m1 = struct.pack(fmt, int(mac1, 16))
mac = "%02x:%02x:%02x:%02x:%02x:%02x" % struct.unpack("BBBBBB", m0+m1)
result.append((iface, mac))
return result
# Get the netwokr interfaces in the router, except 127.0.0.1
def findNonLoInterfaces(data, endianness):
#lines = data.split("\r\n")
lines = stripTimestamps(data)
candidates = filter(lambda l: l.startswith("__inet_insert_ifa"), lines) # logs for the inconfig process
if debug:
print("Candidate ifaces: %r" % candidates)
result = []
if endianness == "eb":
fmt = ">I"
elif endianness == "el":
fmt = "<I"
for c in candidates:
g = re.match(r"^__inet_insert_ifa\[[^\]]+\]: device:([^ ]+) ifa:0x([0-9a-f]+)", c)
if g:
(iface, addr) = g.groups()
addr = socket.inet_ntoa(struct.pack(fmt, int(addr, 16)))
if addr != "127.0.0.1" and addr != "0.0.0.0":
result.append((iface, addr))
return result
def findIfacesForBridge(data, brif):
#lines = data.split("\r\n")
lines = stripTimestamps(data)
result = []
candidates = filter(lambda l: l.startswith("br_dev_ioctl") or l.startswith("br_add_if"), lines)
for c in candidates:
for p in [r"^br_dev_ioctl\[[^\]]+\]: br:%s dev:(.*)", r"^br_add_if\[[^\]]+\]: br:%s dev:(.*)"]:
pat = p % brif
g = re.match(pat, c)
if g:
iface = g.group(1)
#we only add it if the interface is not the bridge itself
#there are images that call brctl addif br0 br0 (e.g., 5152)
if iface != brif:
result.append(iface.strip())
return result
def findVlanInfoForDev(data, dev):
#lines = data.split("\r\n")
lines = stripTimestamps(data)
results = []
candidates = filter(lambda l: l.startswith("register_vlan_dev"), lines)
for c in candidates:
g = re.match(r"register_vlan_dev\[[^\]]+\]: dev:%s vlan_id:([0-9]+)" % dev, c)
if g:
results.append(int(g.group(1)))
return results
def ifaceNo(dev):
g = re.match(r"[^0-9]+([0-9]+)", dev)
return int(g.group(1)) if g else -1
def qemuArchNetworkConfig(i, arch, n):
if not n:
if arch == "arm":
return "-device virtio-net-device,netdev=net%(I)i -netdev socket,id=net%(I)i,listen=:200%(I)i" % {'I': i}
else:
return "-netdev socket,id=net%(I)i,listen=:200%(I)i -device e1000,netdev=net%(I)i" % {'I': i}
else:
(ip, dev, vlan, mac) = n
# newer kernels use virtio only
if arch == "arm":
return "-device virtio-net-device,netdev=net%(I)i -netdev tap,id=net%(I)i,ifname=${TAPDEV_%(I)i},script=no" % {'I': i}
else:
vlan_id = vlan if vlan else i
mac_str = "" if not mac else ",mac=%s" % mac
return "-netdev tap,id=net%(I)i,ifname=${TAPDEV_%(I)i},script=no -device e1000,netdev=net%(I)i%(MAC)s" % { 'I' : i, 'MAC' : mac_str}
def qemuNetworkConfig(arch, network):
output = []
assigned = []
# Fix Id conflict bug
flag = 0
for k in range(0, 4):
for j, n in enumerate(network):
# need to connect the jth emulated network interface to the corresponding host interface
if k == ifaceNo(n[1]):
output.append(qemuArchNetworkConfig(j, arch, n))
assigned.append(n)
flag = j
break
for i in range(0, 4):
if i != flag:
# otherwise, put placeholder socket connection
if len(output) <= i:
output.append(qemuArchNetworkConfig(i, arch, None))
# find unassigned interfaces
for j, n in enumerate(network):
if n not in assigned:
# guess assignment
print("Warning: Unmatched interface: %s" % (n,))
output[j] = qemuArchNetworkConfig(j, arch, n)
assigned.append(n)
return ' '.join(output)
def buildConfig(brif, iface, vlans, macs):
#there should be only one ip
ip = brif[1]
br = brif[0]
#strip vlanid from interface name (e.g., eth2.2 -> eth2)
dev = iface.split(".")[0]
#check whether there is a different mac set
mac = None
d = dict(macs)
if br in d:
mac = d[br]
elif dev in d:
mac = d[dev]
vlan_id = None
if len(vlans):
vlan_id = vlans[0]
return (ip, dev, vlan_id, mac)
def getIP(ip):
tups = [int(x) for x in ip.split(".")]
if tups[3] != 1:
tups[3] -= 1
else:
tups[3] = 2
return ".".join([str(x) for x in tups])
def startNetwork(network):
template_1 = """
TAPDEV_%(I)i=tap${IID}_%(I)i
HOSTNETDEV_%(I)i=${TAPDEV_%(I)i}
echo "Creating TAP device ${TAPDEV_%(I)i}..."
sudo tunctl -t ${TAPDEV_%(I)i} -u ${USER}
"""
template_vlan = """
echo "Initializing VLAN..."
HOSTNETDEV_%(I)i=${TAPDEV_%(I)i}.%(VLANID)i
sudo ip link add link ${TAPDEV_%(I)i} name ${HOSTNETDEV_%(I)i} type vlan id %(VLANID)i
sudo ip link set ${TAPDEV_%(I)i} up
"""
template_2 = """
echo "Bringing up TAP device..."
sudo ip link set ${HOSTNETDEV_%(I)i} up
sudo ip addr add %(HOSTIP)s/24 dev ${HOSTNETDEV_%(I)i}
echo "Adding route to %(GUESTIP)s..."
sudo ip route add %(GUESTIP)s via %(GUESTIP)s dev ${HOSTNETDEV_%(I)i}
"""
output = []
for i, (ip, dev, vlan, mac) in enumerate(network):
output.append(template_1 % {'I' : i})
if vlan:
output.append(template_vlan % {'I' : i, 'VLANID' : vlan})
output.append(template_2 % {'I' : i, 'HOSTIP' : getIP(ip), 'GUESTIP': ip})
return '\n'.join(output)
def stopNetwork(network):
template_1 = """
echo "Deleting route..."
sudo ip route flush dev ${HOSTNETDEV_%(I)i}
echo "Bringing down TAP device..."
sudo ip link set ${TAPDEV_%(I)i} down
"""
template_vlan = """
echo "Removing VLAN..."
sudo ip link delete ${HOSTNETDEV_%(I)i}
"""
template_2 = """
echo "Deleting TAP device ${TAPDEV_%(I)i}..."
sudo tunctl -d ${TAPDEV_%(I)i}
"""
output = []
for i, (ip, dev, vlan, mac) in enumerate(network):
output.append(template_1 % {'I' : i})
if vlan:
output.append(template_vlan % {'I' : i})
output.append(template_2 % {'I' : i})
return '\n'.join(output)
def qemuCmd(iid, network, arch, endianness):
if arch == "mips":
qemuEnvVars = ""
machine = "malta"
if endianness == 'el':
qemu = "qemu-system-mipsel"
elif endianness == 'eb':
qemu = "qemu-system-mips"
qemu_rootfs = "/dev/sda1"
qemuKernel = "./vmlinux"
qemuDisk = "-drive if=ide,format=qcow2,file=image.qcow2"
if endianness != "eb" and endianness != "el":
raise Exception("You didn't specify a valid endianness")
elif arch == "arm":
qemuDisk = "-drive if=none,file=image.raw,format=raw,id=rootfs -device virtio-blk-device,drive=rootfs"
qemuKernel = "./zImage"
qemu_rootfs = "/dev/vda1"
if endianness == "el":
qemu = "qemu-system-arm"
qemuEnvVars = "QEMU_AUDIO_DRV=none"
elif endianness == "eb":
raise Exception("armeb currently not supported")
else:
raise Exception("You didn't specify a valid endianness")
else:
raise Exception("Unsupported architecture")
return QEMUCMDTEMPLATE % {'IID': iid,
'QEMU': qemu,
'MACHINE': machine,
'ARCHEND' : arch + endianness,
'START_NET' : startNetwork(network),
'STOP_NET' : stopNetwork(network),
'QEMU_DISK' : qemuDisk,
'KERNEL' : qemuKernel,
'QEMU_ROOTFS' : qemu_rootfs,
'QEMU_NETWORK' : qemuNetworkConfig(arch, network),
'QEMU_ENV_VARS' : qemuEnvVars}
def process(infile, iid, arch, endianness=None, makeQemuCmd=False, outfile=None):
brifs = []
vlans = []
data = open(infile).read()
network = set()
success = False
#find interfaces with non loopback ip addresses
ifacesWithIps = findNonLoInterfaces(data, endianness)
#find changes of mac addresses for devices
macChanges = findMacChanges(data, endianness)
print("Interfaces: %r" % ifacesWithIps)
deviceHasBridge = False
for iwi in ifacesWithIps:
#find all interfaces that are bridged with that interface
brifs = findIfacesForBridge(data, iwi[0])
if debug:
print("brifs for %s %r" % (iwi[0], brifs))
for dev in brifs:
#find vlan_ids for all interfaces in the bridge
vlans = findVlanInfoForDev(data, dev)
#create a config for each tuple
network.add((buildConfig(iwi, dev, vlans, macChanges)))
deviceHasBridge = True
#if there is no bridge just add the interface
if not brifs and not deviceHasBridge:
vlans = findVlanInfoForDev(data, iwi[0])
network.add((buildConfig(iwi, iwi[0], vlans, macChanges)))
ips = set()
pruned_network = []
for n in network:
if n[0] not in ips:
ips.add(n[0])
pruned_network.append(n)
else:
if debug:
print("duplicate ip address for interface: ", n)
if makeQemuCmd:
qemuCommandLine = qemuCmd(iid, pruned_network, arch, endianness)
if qemuCommandLine:
success = True
if outfile:
with open(outfile, "w") as out:
out.write(qemuCommandLine)
os.chmod(outfile, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH)
else:
print(qemuCommandLine)
return success
def archEnd(value):
arch = None
end = None
tmp = value.lower()
if tmp.startswith("mips"):
arch = "mips"
elif tmp.startswith("arm"):
arch = "arm"
if tmp.endswith("el"):
end = "el"
elif tmp.endswith("eb"):
end = "eb"
return (arch, end)
def main():
infile = None
makeQemuCmd = False
iid = None
outfile = None
arch = None
endianness = None
(opts, argv) = getopt.getopt(sys.argv[1:], 'f:i:S:a:oqd')
for (k, v) in opts:
if k == '-f':
infile = v
if k == '-d':
global debug
debug += 1
if k == '-q':
makeQemuCmd = True
if k == '-i':
iid = int(v)
if k == '-S':
SCRATCHDIR = v
if k == '-o':
outfile = True
if k == '-a':
(arch, endianness) = archEnd(v)
if not arch or not endianness:
raise Exception("Either arch or endianness not found try mipsel/mipseb/armel/armeb")
if not infile and iid:
infile = "%s/qemu.initial.serial.log" % (SCRATCHDIR)
if outfile and iid:
outfile = """%s/run.sh""" % (SCRATCHDIR)
if debug:
print("processing %i" % iid)
if infile:
process(infile, iid, arch, endianness, makeQemuCmd, outfile)
if __name__ == "__main__":
main()
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: mount.sh <image ID>"
exit 1
fi
IID=${1}
if check_root; then
echo "Error: This script requires root privileges!"
exit 1
fi
echo "----Running----"
WORK_DIR=`get_scratch ${IID}`
IMAGE=`get_fs ${IID}`
IMAGE_DIR=`get_fs_mount ${IID}`
echo "----Adding Device File----"
DEVICE=$(get_device "$(kpartx -a -s -v "${IMAGE}")")
sleep 1
echo "----Making image directory----"
if [ ! -e "${IMAGE_DIR}" ]
then
mkdir "${IMAGE_DIR}"
fi
echo "----Mounting----"
#sudo /bin/mount /dev/nbd0p1 "${IMAGE_DIR}"
mount "${DEVICE}" "${IMAGE_DIR}"
#!/bin/sh
[ -d /dev ] || mkdir -p /dev
[ -d /root ] || mkdir -p /root
[ -d /sys ] || mkdir -p /sys
[ -d /proc ] || mkdir -p /proc
[ -d /tmp ] || mkdir -p /tmp
mkdir -p /var/lock
mount -t sysfs sysfs /sys
mount -t proc proc /proc
ln -sf /proc/mounts /etc/mtab
mkdir -p /dev/pts
mount -t devpts devpts /dev/pts
mount -t tmpfs tmpfs /run
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: run-debug.sh <image ID> [<architecture>]"
exit 1
fi
IID=${1}
if [ $# -gt 1 ]; then
if check_arch "${2}"; then
echo "Error: Invalid architecture!"
exit 1
fi
ARCH=${2}
else
echo -n "Querying database for architecture... "
ARCH=$(psql -d firmware -U firmadyne -h 127.0.0.1 -t -q -c "SELECT arch from image WHERE id=${1};")
ARCH="${ARCH#"${ARCH%%[![:space:]]*}"}"
echo "${ARCH}"
if [ -z "${ARCH}" ]; then
echo "Error: Unable to lookup architecture. Please specify {armel,mipseb,mipsel} as the second argument!"
exit 1
fi
fi
${SCRIPT_DIR}/run.${ARCH}-debug.sh ${IID}
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: run.armel-debug.sh <image ID>"
exit 1
fi
IID=${1}
WORK_DIR=`get_scratch ${IID}`
IMAGE=`get_fs ${IID}`
KERNEL=`get_kernel "armel"`
QEMU_AUDIO_DRV=none qemu-system-arm -m 256 -M virt -kernel ${KERNEL} -drive if=none,file=${IMAGE},format=raw,id=rootfs -device virtio-blk-device,drive=rootfs -append "firmadyne.syscall=0 root=/dev/vda1 console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1 user_debug=31" -nographic -device virtio-net-device,netdev=net1 -netdev socket,listen=:2000,id=net1 -device virtio-net-device,netdev=net2 -netdev socket,listen=:2001,id=net2 -device virtio-net-device,netdev=net3 -netdev socket,listen=:2002,id=net3 -device virtio-net-device,netdev=net4 -netdev socket,listen=:2003,id=net4
#!/bin/bash
set -e
set -u
source scripts/env.config
IID=${1}
ARCH=${2}
WORK_DIR="${WORK_DIR}/${IID}"
IMAGE="${WORK_DIR}/image.raw"
KERNEL="${WORK_DIR}/zImage"
QEMU_AUDIO_DRV=none qemu-system-arm -m 256 -M virt -kernel ${KERNEL} -drive if=none,file=${IMAGE},format=raw,id=rootfs -device virtio-blk-device,drive=rootfs -append "firmadyne.syscall=1 root=/dev/vda1 console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1 user_debug=31" -serial file:${WORK_DIR}/qemu.initial.serial.log -serial unix:/tmp/qemu.${IID}.S1,server,nowait -monitor unix:/tmp/qemu.${IID},server,nowait -display none -device virtio-net-device,netdev=net1 -netdev socket,listen=:2000,id=net1 -device virtio-net-device,netdev=net2 -netdev socket,listen=:2001,id=net2 -device virtio-net-device,netdev=net3 -netdev socket,listen=:2002,id=net3 -device virtio-net-device,netdev=net4 -netdev socket,listen=:2003,id=net4
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: run.mipseb-debug.sh <image ID>"
exit 1
fi
IID=${1}
WORK_DIR=`get_scratch ${IID}`
IMAGE=`get_fs ${IID}`
KERNEL=`get_kernel "mipseb"`
qemu-system-mips -m 256 -M malta -kernel ${KERNEL} -drive if=ide,format=raw,file=${IMAGE} -append "firmadyne.syscall=0 root=/dev/sda1 console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1" -nographic -net nic,vlan=0 -net socket,vlan=0,listen=:2000 -net nic,vlan=1 -net socket,vlan=1,listen=:2001 -net nic,vlan=2 -net socket,vlan=2,listen=:2002 -net nic,vlan=3 -net socket,vlan=3,listen=:2003
#!/bin/bash
set -e
set -u
source scripts/env.config
IID=${1}
ARCH=${2}
WORK_DIR="${WORK_DIR}/${IID}"
IMAGE="${WORK_DIR}/image.raw"
KERNEL="${WORK_DIR}/vmlinux"
qemu-system-mips -m 256 -M malta -kernel ${KERNEL} -drive if=ide,format=raw,file=${IMAGE} -append "firmadyne.syscall=1 root=/dev/sda1 console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1" -serial file:${WORK_DIR}/qemu.initial.serial.log -serial unix:/tmp/qemu.${IID}.S1,server,nowait -monitor unix:/tmp/qemu.${IID},server,nowait -display none -netdev socket,id=s0,listen=:2000 -device e1000,netdev=s0 -netdev socket,id=s1,listen=:2001 -device e1000,netdev=s1 -netdev socket,id=s2,listen=:2002 -device e1000,netdev=s2 -netdev socket,id=s3,listen=:2003 -device e1000,netdev=s3
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: run.mipsel-debug.sh <image ID>"
exit 1
fi
IID=${1}
WORK_DIR=`get_scratch ${IID}`
IMAGE=`get_fs ${IID}`
KERNEL=`get_kernel "mipsel"`
qemu-system-mipsel -m 256 -M malta -kernel ${KERNEL} -drive if=ide,format=raw,file=${IMAGE} -append "firmadyne.syscall=0 root=/dev/sda1 console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1" -nographic -net nic,vlan=0 -net socket,vlan=0,listen=:2000 -net nic,vlan=1 -net socket,vlan=1,listen=:2001 -net nic,vlan=2 -net socket,vlan=2,listen=:2002 -net nic,vlan=3 -net socket,vlan=3,listen=:2003
#!/bin/bash
set -e
set -u
source scripts/env.config
IID=${1}
ARCH=${2}
WORK_DIR="${WORK_DIR}/${IID}"
IMAGE="${WORK_DIR}/image.raw"
KERNEL="${WORK_DIR}/vmlinux"
qemu-system-mipsel -m 256 -M malta -kernel ${KERNEL} -drive if=ide,format=raw,file=${IMAGE} -append "firmadyne.syscall=1 root=/dev/sda1 console=ttyS0 nandsim.parts=64,64,64,64,64,64,64,64,64,64 rdinit=/firmadyne/preInit.sh rw debug ignore_loglevel print-fatal-signals=1" -serial file:${WORK_DIR}/qemu.initial.serial.log -serial unix:/tmp/qemu.${IID}.S1,server,nowait -monitor unix:/tmp/qemu.${IID},server,nowait -display none -netdev socket,id=s0,listen=:2000 -device e1000,netdev=s0 -netdev socket,id=s1,listen=:2001 -device e1000,netdev=s1 -netdev socket,id=s2,listen=:2002 -device e1000,netdev=s2 -netdev socket,id=s3,listen=:2003 -device e1000,netdev=s3
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: run.sh <image ID> [<architecture>]"
exit 1
fi
IID=${1}
if [ $# -gt 1 ]; then
if check_arch "${2}"; then
echo "Error: Invalid architecture!"
exit 1
fi
ARCH=${2}
else
echo -n "Querying database for architecture... "
ARCH=$(psql -d firmware -U firmadyne -h 127.0.0.1 -t -q -c "SELECT arch from image WHERE id=${1};")
ARCH="${ARCH#"${ARCH%%[![:space:]]*}"}"
echo "${ARCH}"
if [ -z "${ARCH}" ]; then
echo "Error: Unable to lookup architecture. Please specify {armel,mipseb,mipsel} as the second argument!"
exit 1
fi
fi
${SCRIPT_DIR}/run.${ARCH}.sh ${IID}
#!/usr/bin/env python
import tarfile
import getopt
import sys
import re
import hashlib
import psycopg2
import six
def getFileHashes(infile):
t = tarfile.open(infile)
files = list()
links = list()
for f in t.getmembers():
if f.isfile():
# we use f.name[1:] to get rid of the . at the beginning of the path
files.append((f.name[1:], hashlib.md5(t.extractfile(f).read()).hexdigest(),
f.uid, f.gid, f.mode))
elif f.issym():
links.append((f.name[1:], f.linkpath))
return (files, links)
def getOids(objs, cur):
# hashes ... all the hashes in the tar file
hashes = [x[1] for x in objs]
hashes_str = ",".join(["""'%s'""" % x for x in hashes])
query = """SELECT id,hash FROM object WHERE hash IN (%s)"""
cur.execute(query % hashes_str)
res = [(int(x), y) for (x, y) in cur.fetchall()]
existingHashes = [x[1] for x in res]
missingHashes = set(hashes).difference(set(existingHashes))
newObjs = createObjects(missingHashes, cur)
res += newObjs
result = dict([(y, x) for (x, y) in res])
return result
def createObjects(hashes, cur):
query = """INSERT INTO object (hash) VALUES (%(hash)s) RETURNING id"""
res = list()
for h in set(hashes):
cur.execute(query, {'hash':h})
oid = int(cur.fetchone()[0])
res.append((oid, h))
return res
def insertObjectToImage(iid, files2oids, links, cur):
query = """INSERT INTO object_to_image (iid, oid, filename, regular_file, uid, gid, permissions) VALUES (%(iid)s, %(oid)s, %(filename)s, %(regular_file)s, %(uid)s, %(gid)s, %(mode)s)"""
cur.executemany(query, [{'iid': iid, 'oid' : x[1], 'filename' : x[0][0],
'regular_file' : True, 'uid' : x[0][1],
'gid' : x[0][2], 'mode' : x[0][3]} \
for x in files2oids])
cur.executemany(query, [{'iid': iid, 'oid' : 1, 'filename' : x[0],
'regular_file' : False, 'uid' : None,
'gid' : None, 'mode' : None} \
for x in links])
def process(iid, infile):
dbh = psycopg2.connect(database="firmware", user="firmadyne",
password="firmadyne", host="127.0.0.1")
cur = dbh.cursor()
(files, links) = getFileHashes(infile)
oids = getOids(files, cur)
fdict = dict([(h, (filename, uid, gid, mode)) \
for (filename, h, uid, gid, mode) in files])
file2oid = [(fdict[h], oid) for (h, oid) in six.iteritems(oids)]
insertObjectToImage(iid, file2oid, links, cur)
dbh.commit()
dbh.close()
def main():
infile = iid = None
opts, argv = getopt.getopt(sys.argv[1:], "f:i:")
for k, v in opts:
if k == '-i':
iid = int(v)
if k == '-f':
infile = v
if infile and not iid:
m = re.search(r"(\d+)\.tar\.gz", infile)
if m:
iid = int(m.group(1))
process(iid, infile)
if __name__ == "__main__":
main()
#!/bin/bash
set -e
set -u
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyne.config
else
echo "Error: Could not find 'firmadyne.config'!"
exit 1
fi
if check_number $1; then
echo "Usage: umount.sh <image ID>"
exit 1
fi
IID=${1}
if check_root; then
echo "Error: This script requires root privileges!"
exit 1
fi
echo "----Running----"
WORK_DIR=`get_scratch ${IID}`
IMAGE=`get_fs ${IID}`
IMAGE_DIR=`get_fs_mount ${IID}`
DEVICE=$(get_device "$(kpartx -u -s -v "${IMAGE}")")
echo "----Unmounting----"
umount "${DEVICE}"
echo "----Disconnecting Device File----"
kpartx -d "${IMAGE}"
losetup -d "${DEVICE}" &>/dev/null
dmsetup remove $(basename "${DEVICE}") &>/dev/null
#!/bin/sh
set -e
sudo apt update
sudo apt install -y python-pip python3-pip python3-pexpect unzip busybox-static fakeroot kpartx snmp uml-utilities util-linux vlan qemu-system-arm qemu-system-mips qemu-system-x86 qemu-utils
echo "Installing binwalk"
git clone --depth=1 https://github.com/devttys0/binwalk.git
cd binwalk
sudo ./deps.sh
sudo python3 ./setup.py install
sudo -H pip3 install git+https://github.com/ahupp/python-magic
sudo -H pip install git+https://github.com/sviehb/jefferson
cd ..
echo "Setting up firmware analysis toolkit"
chmod +x emu.py
chmod +x reset.py
#Set firmadyne_path in fat.config
sed -i "/firmadyne_path=/c\firmadyne_path=$firmadyne_dir" fat.config
# Comment out psql -d firmware ... in getArch.sh
sed -i 's/psql/#psql/' ./scripts/getArch.sh
#Setting up the toolchains
sudo mkdir -p /opt/cross
sudo cp toolchains/* /opt/cross
cd /opt/cross
sudo tar -xf arm-linux-musleabi.tar.xz
sudo tar -xf mipseb-linux-musl.tar.xz
sudo tar -xf mipsel-linux-musl.tar.xz
cd -
mkdir -p ./source/Kernel-mips/build/mipseb
mkdir -p ./source/Kernel-mips/build/mipsel
mkdir -p ./source/Kernel-armel/build/armel
cp ./source/Kernel-mips/config.mipseb ./source/Kernel-mips/build/mipseb/.config
cp ./source/Kernel-mips/config.mipsel ./source/Kernel-mips//build/mipsel/.config
cp ./source/Kernel-armel/config.armel ./source/Kernel-armel/build/armel/.config
# Adding toolchains to PATH
echo "PATH=$PATH:/opt/cross/mipsel-linux-musl/bin:/opt/cross/mipseb-linux-musl/bin:/opt/cross/arm-linux-musleabi/bin" >> ~/.profile
source ~/.profile
# Make the kernels
cd ./source/Kernel-mips/
make ARCH=mips CROSS_COMPILE=mipseb-linux-musl- O=./build/mipseb -j8
make ARCH=mips CROSS_COMPILE=mipsel-linux-musl- O=./build/mipsel -j8
cd - && cd ./source/Kernel-armel/
make ARCH=arm CROSS_COMPILE=arm-linux-musleabi- O=./build/armel zImage -j8
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment