Package lib :: Package cuckoo :: Package core :: Module startup
[hide private]
[frames] | no frames]

Source Code for Module lib.cuckoo.core.startup

  1  # Copyright (C) 2010-2014 Cuckoo Foundation. 
  2  # This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org 
  3  # See the file 'docs/LICENSE' for copying permission. 
  4   
  5  import os 
  6  import sys 
  7  import copy 
  8  import json 
  9  import urllib 
 10  import urllib2 
 11  import logging 
 12  import logging.handlers 
 13   
 14  import modules.auxiliary 
 15  import modules.processing 
 16  import modules.signatures 
 17  import modules.reporting 
 18   
 19  from lib.cuckoo.common.colors import red, green, yellow, cyan 
 20  from lib.cuckoo.common.config import Config 
 21  from lib.cuckoo.common.constants import CUCKOO_ROOT, CUCKOO_VERSION 
 22  from lib.cuckoo.common.exceptions import CuckooStartupError 
 23  from lib.cuckoo.common.exceptions import CuckooOperationalError 
 24  from lib.cuckoo.common.utils import create_folders 
 25  from lib.cuckoo.core.database import Database, TASK_RUNNING 
 26  from lib.cuckoo.core.plugins import import_plugin, import_package, list_plugins 
 27   
 28  log = logging.getLogger() 
 29   
30 -def check_python_version():
31 """Checks if Python version is supported by Cuckoo. 32 @raise CuckooStartupError: if version is not supported. 33 """ 34 if sys.version_info[:2] != (2, 7): 35 raise CuckooStartupError("You are running an incompatible version " 36 "of Python, please use 2.7")
37 38
39 -def check_working_directory():
40 """Checks if working directories are ready. 41 @raise CuckooStartupError: if directories are not properly configured. 42 """ 43 if not os.path.exists(CUCKOO_ROOT): 44 raise CuckooStartupError("You specified a non-existing root " 45 "directory: {0}".format(CUCKOO_ROOT)) 46 47 cwd = os.path.join(os.getcwd(), "cuckoo.py") 48 if not os.path.exists(cwd): 49 raise CuckooStartupError("You are not running Cuckoo from it's " 50 "root directory")
51 52
53 -def check_configs():
54 """Checks if config files exist. 55 @raise CuckooStartupError: if config files do not exist. 56 """ 57 configs = [os.path.join(CUCKOO_ROOT, "conf", "cuckoo.conf"), 58 os.path.join(CUCKOO_ROOT, "conf", "reporting.conf"), 59 os.path.join(CUCKOO_ROOT, "conf", "auxiliary.conf")] 60 61 for config in configs: 62 if not os.path.exists(config): 63 raise CuckooStartupError("Config file does not exist at " 64 "path: {0}".format(config)) 65 66 return True
67
68 -def create_structure():
69 """Creates Cuckoo directories.""" 70 folders = [ 71 "log", 72 "storage", 73 os.path.join("storage", "analyses"), 74 os.path.join("storage", "binaries") 75 ] 76 77 try: 78 create_folders(root=CUCKOO_ROOT, folders=folders) 79 except CuckooOperationalError as e: 80 raise CuckooStartupError(e)
81
82 -def check_version():
83 """Checks version of Cuckoo.""" 84 cfg = Config() 85 86 if not cfg.cuckoo.version_check: 87 return 88 89 print(" Checking for updates...") 90 91 url = "http://api.cuckoosandbox.org/checkversion.php" 92 data = urllib.urlencode({"version": CUCKOO_VERSION}) 93 94 try: 95 request = urllib2.Request(url, data) 96 response = urllib2.urlopen(request) 97 except (urllib2.URLError, urllib2.HTTPError): 98 print(red(" Failed! ") + "Unable to establish connection.\n") 99 return 100 101 try: 102 response_data = json.loads(response.read()) 103 except ValueError: 104 print(red(" Failed! ") + "Invalid response.\n") 105 return 106 107 if not response_data["error"]: 108 if response_data["response"] == "NEW_VERSION": 109 msg = "Cuckoo Sandbox version {0} is available " \ 110 "now.\n".format(response_data["current"]) 111 print(red(" Outdated! ") + msg) 112 else: 113 print(green(" Good! ") + "You have the latest version " 114 "available.\n")
115 116
117 -class DatabaseHandler(logging.Handler):
118 """Logging to database handler.""" 119
120 - def emit(self, record):
121 if hasattr(record, "task_id"): 122 db = Database() 123 db.add_error(record.msg, int(record.task_id))
124
125 -class ConsoleHandler(logging.StreamHandler):
126 """Logging to console handler.""" 127
128 - def emit(self, record):
129 colored = copy.copy(record) 130 131 if record.levelname == "WARNING": 132 colored.msg = yellow(record.msg) 133 elif record.levelname == "ERROR" or record.levelname == "CRITICAL": 134 colored.msg = red(record.msg) 135 else: 136 if "analysis procedure completed" in record.msg: 137 colored.msg = cyan(record.msg) 138 else: 139 colored.msg = record.msg 140 141 logging.StreamHandler.emit(self, colored)
142
143 -def init_logging():
144 """Initializes logging.""" 145 formatter = logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s") 146 147 fh = logging.handlers.WatchedFileHandler(os.path.join(CUCKOO_ROOT, "log", "cuckoo.log")) 148 fh.setFormatter(formatter) 149 log.addHandler(fh) 150 151 ch = ConsoleHandler() 152 ch.setFormatter(formatter) 153 log.addHandler(ch) 154 155 dh = DatabaseHandler() 156 dh.setLevel(logging.ERROR) 157 log.addHandler(dh) 158 159 log.setLevel(logging.INFO)
160
161 -def init_tasks():
162 """Check tasks and reschedule uncompleted ones.""" 163 db = Database() 164 cfg = Config() 165 166 if cfg.cuckoo.reschedule: 167 log.debug("Checking for locked tasks...") 168 169 tasks = db.list_tasks(status=TASK_RUNNING) 170 171 for task in tasks: 172 db.reschedule(task.id) 173 log.info("Rescheduled task with ID {0} and " 174 "target {1}".format(task.id, task.target))
175 176
177 -def init_modules():
178 """Initializes plugins.""" 179 log.debug("Importing modules...") 180 181 # Import all auxiliary modules. 182 import_package(modules.auxiliary) 183 # Import all processing modules. 184 import_package(modules.processing) 185 # Import all signatures. 186 import_package(modules.signatures) 187 # Import all reporting modules. 188 import_package(modules.reporting) 189 190 # Import machine manager. 191 import_plugin("modules.machinery." + Config().cuckoo.machinery) 192 193 for category, entries in list_plugins().items(): 194 log.debug("Imported \"%s\" modules:", category) 195 196 for entry in entries: 197 if entry == entries[-1]: 198 log.debug("\t `-- %s", entry.__name__) 199 else: 200 log.debug("\t |-- %s", entry.__name__)
201