Skip to content

Commit

Permalink
Code polishing
Browse files Browse the repository at this point in the history
  • Loading branch information
Nex committed Mar 4, 2012
1 parent 735c713 commit c97a893
Show file tree
Hide file tree
Showing 23 changed files with 377 additions and 581 deletions.
6 changes: 3 additions & 3 deletions conf/cuckoo.conf
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,13 @@ watchdog_timeout = 600
results_path = analysis/
# Enable or disable this option to instruct Cuckoo to delete the original file
# submitted for the analysis. [on/off]
delete_original = on
delete_file = off

[Processing]
# Specify here the interpreter path to be used to launch the script.
interpreter = /usr/bin/python
# Specify here the path to the analysis results processing script.
processor = processor.py
script = processor.py

[Sniffer]
# Enable or disable the following option by assigning a True or False value.
Expand Down Expand Up @@ -68,7 +68,7 @@ mode = gui
python = C:\Python27\python.exe

[cuckoo1]
name = Cuckoo1
name = Cuckoo_1
username = Me
password = cuckoo
# Please notice that the shared folder name must coincide with the current
Expand Down
102 changes: 44 additions & 58 deletions cuckoo.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,36 +28,37 @@
from time import time, sleep
from threading import Thread

from cuckoo.config.config import CuckooConfig
from cuckoo.config.constants import *
from cuckoo.logging.logo import logo
from cuckoo.config.cuckooconfig import CuckooConfig
from cuckoo.config.constants import *
from cuckoo.core.db import CuckooDatabase
from cuckoo.core.getfiletype import get_filetype
from cuckoo.core.getpackage import get_package
from cuckoo.common.getfiletype import get_file_type
from cuckoo.logging.crash import crash

# Check the virtualization engine from the config fle and tries to retrieve
# and import the corresponding Cuckoo's module.
if CuckooConfig().get_vm_engine().lower() == "virtualbox":
if CuckooConfig().virt_engine().lower() == "virtualbox":
try:
from cuckoo.core.virtualbox import VirtualMachine
except ImportError, why:
sys.stderr.write("ERROR: Unable to load Cuckoo's VirtualBox module. " \
"Please verify your installation.\n")
sys.exit(-1)
sys.stderr.write("Unable to load Cuckoo's VirtualBox module, " \
"please verify your installation. Abort.\n")
raise SystemExit
# If no valid option has been specified, aborts the execution.
else:
sys.stderr.write("ERROR: No valid virtualization option identified. " \
"Please check your configuration file.\n")
sys.exit(-1)
sys.stderr.write("No valid virtualization option identified, " \
"please check your configuration file. Abort.\n")
raise SystemExit

# Import the external sniffer module only if required.
if CuckooConfig().use_external_sniffer():
if CuckooConfig().sniffer_use():
try:
from cuckoo.core.sniffer import Sniffer
except ImportError, why:
sys.stderr.write("ERROR: Unable to import sniffer module. " \
"Please verify your installation.\n")
sys.exit(-1)
sys.stderr.write("Unable to import sniffer module, " \
"please verify your installation. Abort.\n")
raise SystemExit

#------------------------------ Global Variables ------------------------------#
# Initialize complete list of virtual machines.
Expand Down Expand Up @@ -249,7 +250,7 @@ def _processing(self, save_path, message = None):
"""
log = logging.getLogger("Core.Analysis.Processing")

interpreter = CuckooConfig().get_processing_interpreter()
interpreter = CuckooConfig().processing_interpreter()

if not interpreter:
return False
Expand All @@ -258,7 +259,7 @@ def _processing(self, save_path, message = None):
log.error("Cannot find interpreter at path \"%s\"." % interpreter)
return False

processor = CuckooConfig().get_processing_processor()
processor = CuckooConfig().processing_script()

if not processor:
return False
Expand Down Expand Up @@ -304,7 +305,7 @@ def run(self):
self.db = CuckooDatabase()

# Generate analysis results storage folder path with current task id.
results_path = CuckooConfig().get_analysis_results_path()
results_path = CuckooConfig().analysis_results_path()
save_path = os.path.join(results_path, str(self.task["id"]))

# Additional check to verify that the are not saved results with the
Expand Down Expand Up @@ -339,54 +340,40 @@ def run(self):
# 4. If analysis package has not been specified, I'll try to identify
# the correct one depending on the file type of the target.
if self.task["package"] is None:
file_type = get_filetype(self.task["target"]).lower()
file_extension = os.path.splitext(self.dst_filename)[1].lower()

if file_type:
# Check the file format and see if the file name has the
# appropriate extension, otherwise fix it. Assign proper
# default analysis package.
if file_type == "exe":
if file_extension != ".exe":
self.dst_filename += ".exe"

self.task["package"] = "exe"
elif file_type == "dll":
if file_extension != ".dll":
self.dst_filename += ".dll"

self.task["package"] = "dll"
elif file_type == "pdf":
if file_extension != ".pdf":
self.dst_filename += ".pdf"

self.task["package"] = "pdf"
else:
log.error("Unsupported file format (%s) for target \"%s\"."\
" Abort." % (file_type, self.task["target"]))
self.db.complete(self.task["id"], False)
self._processing(None,
CUCKOO_ERROR_INVALID_TARGET_FILE_TYPE)
return False
file_type = get_file_type(self.task["target"])
package = get_package(file_type)
current_extension = os.path.splitext(self.dst_filename)[1].lower()

if package:
correct_extension = ".%s" % package

if current_extension != correct_extension:
self.dst_filename += correct_extension

self.task["package"] = package
else:
log.error("Unsupported file format (%s) for target \"%s\"."\
" Abort." % (file_type, self.task["target"]))
self.db.complete(self.task["id"], False)
self._processing(None,
CUCKOO_ERROR_INVALID_TARGET_FILE_TYPE)
return False

# 5. If no analysis timeout is set, get the default from the config
# file.
if self.task["timeout"] is None:
timeout = int(CuckooConfig().get_analysis_analysis_timeout())
timeout = int(CuckooConfig().analysis_timeout())
self.task["timeout"] = timeout
# If the specified timeout is bigger than the watchdog timeout set in
# the configuration file, I redefine it to the maximum - 30 seconds.
elif int(self.task["timeout"]) > CuckooConfig().get_analysis_watchdog_timeout():
self.task["timeout"] = CuckooConfig().get_analysis_watchdog_timeout() - 30
elif int(self.task["timeout"]) > CuckooConfig().analysis_watchdog():
self.task["timeout"] = CuckooConfig().analysis_watchdog() - 30
log.info("Specified analysis timeout is bigger than the watchdog " \
"timeout (see cuckoo.conf). Redefined to %s seconds."
% self.task["timeout"])

# 6. Acquire a virtual machine from pool.
vm_pop_timeout = CuckooConfig().get_analysis_watchdog_timeout() * 3
vm_pop_timeout = CuckooConfig().analysis_watchdog() * 3
for i in xrange(0, vm_pop_timeout):
if self.task["vm_id"]:
if not VM_LIST.has_key(self.task["vm_id"]):
Expand Down Expand Up @@ -423,7 +410,7 @@ def run(self):
return False

# Get path to current virtual machine's shared folder.
self.vm_share = CuckooConfig().get_vm_share(self.vm_id)
self.vm_share = CuckooConfig().vm_share(self.vm_id)

if not os.path.exists(self.vm_share):
log.error("Shared folder \"%s\" for virtual machine \"%s\" " \
Expand Down Expand Up @@ -459,7 +446,7 @@ def run(self):
return False

# If necessary, delete the original file.
if CuckooConfig().get_analysis_delete_original():
if CuckooConfig().analysis_delete_file():
try:
os.remove(self.task["target"])
log.debug("Successfuly deleted original file at path \"%s\"."
Expand All @@ -471,11 +458,11 @@ def run(self):
# 9. Start sniffer.
# Check if the user has decided to adopt the external sniffer or not.
# In first case, initialize the sniffer and start it.
if CuckooConfig().use_external_sniffer():
if CuckooConfig().sniffer_use():
pcap_file = os.path.join(self.vm_share, "dump.pcap")
self.sniffer = Sniffer(pcap_file)

interface = CuckooConfig().get_sniffer_interface().lower()
interface = CuckooConfig().sniffer_interface().lower()
guest_mac = VM_LIST[self.vm_id]

if not self.sniffer.start(interface, guest_mac):
Expand Down Expand Up @@ -513,7 +500,7 @@ def run(self):

# Get virtual machines' local Python installation path from config
# file.
python_path = CuckooConfig().get_vm_python()
python_path = CuckooConfig().virt_python()
python_path = python_path.replace("\\", "\\\\")

args = []
Expand Down Expand Up @@ -645,7 +632,7 @@ def init_logging():

# If user enabled debug logging in the configuration file, I modify the
# root logger level accordingly.
if CuckooConfig().get_logging_debug():
if CuckooConfig().logging_debug():
root = logging.getLogger()
root.setLevel(logging.DEBUG)

Expand All @@ -668,7 +655,7 @@ def init_logging():
log.info("Populating virtual machines pool...")

# Acquire Virtual Machines IDs list from the config file.
virtual_machines = CuckooConfig().get_vms()
virtual_machines = CuckooConfig().virt_machines()

# Start checking informations regarding each enabled virtual machine
# specified in the config file. Detailed errors and informations are
Expand Down Expand Up @@ -733,4 +720,3 @@ def init_logging():
pass
except:
crash()

19 changes: 19 additions & 0 deletions cuckoo/common/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Cuckoo Sandbox - Automated Malware Analysis
# Copyright (C) 2010-2012 Claudio "nex" Guarnieri ([email protected])
# http://www.cuckoobox.org
#
# This file is part of Cuckoo.
#
# Cuckoo 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.
#
# Cuckoo 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/.

18 changes: 4 additions & 14 deletions cuckoo/core/getfiletype.py → cuckoo/common/getfiletype.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
# along with this program. If not, see http://www.gnu.org/licenses/.

import os
import re
import sys
import logging

Expand All @@ -27,9 +26,9 @@
except ImportError, why:
sys.stderr.write("ERROR: Unable to locate Python libmagic bindings. " \
"Please verify your installation. Exiting...\n")
sys.exit(-1)
raise SystemExit

def get_filetype(file_path):
def get_file_type(file_path):
"""
Get file format identifier based on the type of the given file.
@param file_path: file path
Expand All @@ -55,14 +54,5 @@ def get_filetype(file_path):
except Exception, why:
log.error("Something went wrong while retrieving magic: %s" % why)
return None

if re.search("DLL", file_type):
return "dll"
elif re.search("PE32", file_type) or re.search("MS-DOS", file_type):
return "exe"
elif re.match("PDF", file_type):
return "pdf"
elif re.search("HTML", file_type):
return "html"
else:
return file_type

return file_type
Loading

0 comments on commit c97a893

Please sign in to comment.