Exemple #1
0
 def __init__(self, config, filename):
     Thread.__init__(self)
     try:
         import pcapy
         self.pcap = pcapy
     except:
         print_dizzy(
             "No usable pcap library found. Be sure you have pcapy installed!"
         )
         print_dizzy("Pcap recording disabled!")
         self.pcap = None
         return
     self.interface = config.get("interface", "any")
     check_root("use the PCAP feature")
     print_dizzy("pcap/init: listening on interface '%s'." % self.interface,
                 VERBOSE_1)
     if not self.interface is "any":
         if not self.interface in self.pcap.findalldevs():
             print_dizzy(
                 "Device '%s' not found, recording on _all_ interfaces.")
             self.interface = "any"
     self.filter = config.get("filter", "")
     if not self.filter is "":
         print_dizzy("pcap/init: using bpf '%s'." % self.filter, VERBOSE_1)
     self.snaplen = config.getint("snaplen", 8192)
     self.promisc = config.getboolean("promisc", True)
     self.to_ms = config.getint("to_ms", 10)
     self.cooldown = config.getint("cooldown", 0)
     self.filename = filename
     self.is_open = False
Exemple #2
0
def parse_interaction(file,
                      filename,
                      fuzz="std",
                      start_at=0,
                      config_values={}):
    def not_impl(*args, **kwargs):
        raise InteractParseException("Not implemented")

    def load_dizz_conf(*args, **kwargs):
        if not 'config_values' in kwargs:
            kwargs['config_values'] = config_values
        return load_dizz(*args, **kwargs)

    def config_value(name):
        return config_values[name]

    ns = {
        "Dizzy": load_dizz_conf,
        "NullDizzy": null_dizz,
        "copy": not_impl,
        "call": call,
        "f": not_impl,
        "print_dizz": not_impl,
        "print_field": not_impl,
        "global": CONFIG["GLOBALS"]["INTERACTION_GLOBALS"],
        "get_session": lambda: CONFIG["GLOBALS"]["SESSION"],
        "config_value": config_value
    }

    exec(compile(file, filename, 'exec'), ns)
    act = Interaction(ns["name"], ns["objects"], ns["functions"], fuzz,
                      start_at)
    print_dizzy("interaction/%s: '%s'." % (act.name, act.dump()), DEBUG)
    return act
Exemple #3
0
    def probe(self):
        try:
            self.socket = socket(self.af, SOCK_STREAM)
            if self.target_host == "255.255.255.255":
                self.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
            self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
            self.socket.settimeout(self.timeout)
            if not self.source_host is None and not self.source_port is None:
                self.socket.bind((self.source_host, self.source_port))
        except Exception as e:
            if not self.socket is None:
                self.socket.close()
            print_dizzy("probe/tcp: open error: %s" % e)
            print_dizzy(e, DEBUG)

        for attempt in range(1, self.retry + 1):
            print_dizzy("probe/tcp: probe attempt: %d" % attempt, VERBOSE_1)
            try:
                self.socket.connect((self.target_host, self.target_port))
            except (ConnectionAbortedError, ConnectionRefusedError) as e:
                pass
            except Exception as e:
                print_dizzy("probe/tcp: probe error: '%s'" % type(e))
                print_dizzy(e, DEBUG)
            else:
                self.socket.close()
                return True
        return False
Exemple #4
0
def check_root(text):
    if hasattr(os, 'geteuid'):
        if os.geteuid() != 0:
            print_dizzy("You must be root to " + text + ".")
            exit(1)
    else:
        if ctypes.windll.shell32.IsUserAnAdmin() != 1:
            print_dizzy("You must be Admin to " + text + ".")
            exit(1)
Exemple #5
0
 def open(self):
     try:
         self.socket = socket(self.af, SOCK_RAW, self.proto)
     except error as e:
         if not self.socket is None:
             self.socket.close()
         print_dizzy("probe/icmp: open error: '%s'" % e)
         print_dizzy(e, DEBUG)
     self.is_open = True
Exemple #6
0
 def func(dizzy_iterator):
     if target not in dizzy_iterator.current_mutated_objects:
         size = dizzy_iterator[target].size
         value = Value(
             pack_with_length(dizzy_iterator[start:stop].size, size,
                              endian), size)
         print_dizzy("length/%s: seting to %s." % (target, value), DEBUG)
         dizzy_iterator[target] = value
     else:
         print_dizzy("length/%s: is not updated." % (target, ), DEBUG)
Exemple #7
0
 def send(self, data):
     try:
         self.s.sendto(data, (self.dest, self.dport))
     except Exception as e:
         if self.auto_reopen:
             print_dizzy("session/udp: session got closed '%s', autoreopening..." % e, DEBUG)
             self.close()
             self.open()
         else:
             self.close()
             raise SessionException("error on sending '%s', connection closed." % e)
Exemple #8
0
 def func(dizzy_iterator):
     if target not in dizzy_iterator.current_mutated_objects:
         size = str((dizzy_iterator[start:stop].size + 7) // 8)
         value = Value(bytes(size, encoding), len(size) * 8)
         print_dizzy(
             "length_string_bytes/%s: seting to %s." % (target, value),
             DEBUG)
         dizzy_iterator[target] = value
     else:
         print_dizzy("length_string_bytes/%s: is not updated." % (target, ),
                     DEBUG)
Exemple #9
0
 def send(self, data):
     try:
         self.f.write(hexlify(data))
     except Exception as e:
         if self.auto_reopen:
             print_dizzy(
                 "session/stdout-hex: session got closed '%s', autoreopening..."
                 % e, DEBUG)
             self.close()
             self.open()
         else:
             self.close()
             raise SessionException(
                 "error on sending '%s', connection closed." % e)
Exemple #10
0
 def all_methods(self):
     (addr, port) = self.client_address
     if addr == self.dest:
         print_dizzy(
             "http/request_handler: handling request from %s" %
             addr, VERBOSE_2)
         while True and not self.server._BaseServer__shutdown_request:
             with self.recv_lock:
                 if len(self.rlist) == 0:
                     break
             print_dizzy("http/request_handler: rlist not empty",
                         DEBUG)
             sleep(0.1)
         with self.recv_lock:
             length = int(self.headers['content-length'])
             self.rlist.append(self.rfile.read(length))
         while True and not self.server._BaseServer__shutdown_request:
             with self.send_lock:
                 if len(self.slist) == 1:
                     break
             print_dizzy("http/request_handler: slist empty", DEBUG)
             sleep(0.1)
         with self.send_lock:
             data = self.slist.pop()
             self.send_response(200)
             for i in self.set_headers:
                 self.send_header(i, self.set_headers[i])
             self.send_header('Content-Length', len(data))
             self.end_headers()
             self.wfile.write(data)
     else:
         print_dizzy(
             "http/request_handler: denied access for %s" % addr,
             VERBOSE_2)
Exemple #11
0
 def stop(self):
     if self.pcap is None:
         return
     if self.cooldown > 0:
         print_dizzy(
             "pcap/stop: cooling down for %d seconds." % self.cooldown,
             VERBOSE_1)
         sleep(self.cooldown)
     self.run = False
     self.is_open = False
     self.pcap_dumper.close()
     print_dizzy(
         "pcap/stop: pcap dumper closed for file '%s'." % self.filename,
         VERBOSE_2)
Exemple #12
0
    def probe(self):
        if not self.is_open:
            print_dizzy("probe/tcp: not opened.", DEBUG)
            return False
        for attempt in range(1, self.retry + 1):
            print_dizzy("probe/icmp: probe attempt: %d" % attempt, VERBOSE_1)

            try:
                if self.af == AF_INET6:
                    self.socket.sendto(self.header + self.data, (self.target_host, 0, 0, 0))
                else:
                    self.socket.sendto(self.header + self.data, (self.target_host, 0))

                if self.af == AF_INET6:
                    (data, (address, _, _, _)) = self.socket.recvfrom(2048)
                    if address == self.target_host:
                        pid, = unpack("!H", data[4:6])
                        if data[0] == self.ICMP6_ECHO_REPLY and pid == self.pid:
                            return True
                else:
                    (data, (address, _)) = self.socket.recvfrom(2048)
                    if address == self.target_host:
                        hl = (data[0] & 0x0f) * 4
                        pid, = unpack("!H", data[hl + 4:hl + 6])
                        if data[hl] == self.ICMP_ECHO_REPLY and pid == self.pid:
                            return True
            except error as e:
                print_dizzy("probe/icmp: reopening: '%s'" % e)
                print_dizzy(e, DEBUG)
                self.close()
                self.open()

        return False
Exemple #13
0
    def call_functions(self, when=PRE):
        # Call the functions of the objects, if it is a dizz object(nested dizz)
        for a in self.state:
            if a.is_dizz():
                a.call_functions(when)

        # Call the functions
        for (func, call_at) in self.dizz.functions:
            if call_at == when or call_at == BOTH:
                try:
                    func(self)
                except Exception as e:
                    print_dizzy("%s: Exception in function: %s" %
                                (self.dizz, e))
        return self.get_current_state()
Exemple #14
0
 def do_probe(self):
     res = True
     if not self.probe is None:
         if 'pcap' in self.config:
             self.pcap = Pcap(self.config['pcap'], path.join(self.tempdir.name, "trace-%s-probe.pcap" % self.index))
             self.pcap.start()
             while not self.pcap.is_open:
                 sleep(0.1)
         res = self.probe.probe()
         if not self.pcap is None:
             self.pcap.stop()
             self.pcap.join()
         if not res:
             print_dizzy("job/run: probe failed")
     return res
Exemple #15
0
def read_with_length(data, length, endian='!'):
    try:
        out = None
        if length <= 8:
            (out,) = unpack("%sB" % endian, data[0])
        elif length <= 16:
            (out,) = unpack("%sH" % endian, data[0:1])
        elif length <= 32:
            (out,) = unpack("%sI" % endian, data[0:3])
        elif length <= 64:
            (out,) = unpack("%sQ" % endian, data[0:7])
        else:
            raise DizzyRuntimeException("cant read with len >64")
    except Exception as e:
        print_dizzy("Can't unpack %s: %s" % (data, str(e)), DEBUG)
        raise e
Exemple #16
0
    def call_functions(self):
        if self.current_object is None:
            return None

        # Call the act functions
        if self.index in self.interaction.functions:
            # There is a function list to call
            for func in self.interaction.functions[self.index]:
                try:
                    func(self, self.current_object.iter,
                         self.interaction.response)
                except Exception as e:
                    print_dizzy("%s: Exception in function" % self.interaction)
                    print_dizzy(e)

        # Call the dizz functions(for example to correct the length fields) and return the current state
        return self.current_object.call_functions(POST)
Exemple #17
0
 def send(self, data):
     try:
         if not self.server_side:
             headers = self.headers
             cookies = ";".join(
                 ["%s=%s" % (n, v) for (n, v) in self.cookies.items()])
             if len(cookies) > 0:
                 headers.update({"Cookie": cookies})
             self.connection.request(self.method,
                                     self.url,
                                     body=data,
                                     headers=headers)
             self.res = self.connection.getresponse()
             headers = dict(self.res.getheaders())
             for h in headers:
                 if h == "Set-Cookie":
                     try:
                         nv = headers[h].split(";")[0].split("=")
                         self.cookies[nv[0]] = nv[1]
                     except:
                         print_dizzy(
                             "http/send: failed to parse set-cookie: %s" %
                             headers[h], VERBOSE_1)
         else:
             while True:
                 with self.send_lock:
                     if len(self.slist) == 0:
                         break
                 print_dizzy("http/send: slist not empty", DEBUG)
                 sleep(0.1)
             with self.send_lock:
                 self.slist.append(data)
                 print_dizzy("http/send: pushed %s" % data, DEBUG)
     except Exception as e:
         if self.auto_reopen:
             print_dizzy(
                 "http/send: session got closed '%s', auto reopening..." %
                 e, DEBUG)
             print_dizzy(e, DEBUG)
             self.close()
             self.open()
         else:
             self.close()
             raise SessionException(
                 "http/send: error on sending '%s', connection closed." % e)
Exemple #18
0
    def recv(self):
        #from traceback import print_stack
        #print_stack()

        if not self.server_side:
            if not self.res is None:
                return self.res.read()
        else:
            while True:
                with self.recv_lock:
                    if len(self.rlist) == 1:
                        break
                print_dizzy("http/recv: rlist empty", DEBUG)
                sleep(0.1)
            with self.recv_lock:
                data = self.rlist.pop()
                print_dizzy("http/recv: poped %s" % data, DEBUG)
                return data
Exemple #19
0
 def run(self):
     if self.pcap is None:
         return
     self.run = True
     self.pcap_object = self.pcap.open_live(self.interface, self.snaplen,
                                            self.promisc, self.to_ms)
     print_dizzy("pcap/run: pcap object opened.", VERBOSE_2)
     if not self.filter is "":
         self.pcap_object.setfilter(self.filter)
     self.pcap_dumper = self.pcap_object.dump_open(self.filename)
     print_dizzy(
         "pcap/run: pcap dumper opened for file '%s'." % self.filename,
         VERBOSE_2)
     self.is_open = True
     while self.run:
         hdr, data = self.pcap_object.next()
         if not hdr is None:
             if self.is_open:
                 self.pcap_dumper.dump(hdr, data)
Exemple #20
0
 def send(self, data, streamid=None):
     try:
         if not self.maxsize is None and len(data) > self.maxsize:
             data = data[:self.maxsize - 1]
             print_dizzy("session/sctp: Truncated data to %d byte." % self.maxsize, DEBUG)
         if not streamid is None:
             sndrcvinfo = sctp_sndrcvinfo()
             sndrcvinfo.sinfo_stream = streamid
             sndrcvinfo.sinfo_ppid = htonl(self.ppid)
             self.s.sendmsg([data], [(self.IPPROTO_SCTP, self.SCTP_SNDRCV, sndrcvinfo)], 0, (self.dest, self.dport))
         else:
             self.s.sendto(data, (self.dest, self.dport))
     except Exception as e:
         if self.auto_reopen:
             print_dizzy("session/sctp: session got closed '%s', autoreopening..." % e, DEBUG)
             self.close()
             self.open()
         else:
             self.close()
             raise SessionException("error on sending '%s', connection closed." % e)
Exemple #21
0
 def send(self, data):
     try:
         if not self.maxsize is None and len(data) > self.maxsize:
             data = data[:self.maxsize - 1]
             print_dizzy("Truncated data to %d byte." % self.maxsize, DEBUG)
         if self.server_side:
             if not self.cs:
                 raise SessionException("no client connection, cant send")
             self.cs.send(data)
         else:
             self.s.send(data)
     except Exception as e:
         if self.auto_reopen:
             print_dizzy("session got closed '%s', autoreopening..." % e,
                         DEBUG)
             self.close()
             self.open()
         else:
             self.close()
             raise SessionException(
                 "error on sending '%s', connection closed." % e)
Exemple #22
0
 def probe(self):
     if not self.is_open:
         print_dizzy("probe/http: not opened.", DEBUG)
         return False
     for attempt in range(1, self.retry + 1):
         print_dizzy("probe/http: probe attempt: %d" % attempt, VERBOSE_1)
         try:
             self.connection.request(self.method, self.url, body=self.body, headers=self.headers)
             self.res = self.connection.getresponse()
             self.connection.close()
         except Exception as e:
             print_dizzy("probe/http: probe error: '%s'" % type(e))
             print_dizzy(e, DEBUG)
         else:
             return True
     return False
Exemple #23
0
    def print_status(self):
        self.state_lock.acquire()
        self.time_list.append(time() - self.start_time)
        time_mean = mean(self.time_list)
        if len(self.time_list) > self.TIME_LIST_MAX_LEN:
            self.time_list = [time_mean] * 50
        
        secs = (self.mutations - self.index) * time_mean
        m, s = divmod(secs, 60)
        h, m = divmod(m, 60)
        d, h = divmod(h, 24)

        self.start_time = time()

        status = "%05.2f%% %i/%i iterations done.\n" % ((self.index / self.mutations) * 100, self.index, self.mutations)
        if d == 0:
            status += "eta %02d:%02d:%02d" % (h, m, s)
        else:
            status += "eta %d days %02d:%02d:%02d" % (d, h, m, s)

        if self.print_index == self.index or print_level == DEBUG:
            print_dizzy(status)
            self.print_index *= 2
        self.state_lock.release()
Exemple #24
0
    def __init__(self, config_file, start_at=0, options={}, daemon=True):
        Thread.__init__(self, daemon=daemon)
        self.config_file = config_file
        self.config = ConfigParser(allow_no_value=True, interpolation=None)
        if path.exists(config_file):
            self.config.read(config_file)
        elif config_file in CONFIG["JOB"]:
                self.config.read_string(CONFIG["JOB"][config_file])
        else:
            raise JobParseException("Job '%s' not found." % config_file)
        self.config.read_dict(options)
        
        self.outfile = self.config['job'].get('outfile', './outfile_%s.tar.xz' % strftime("%Y-%m-%d_%H-%M-%S"))
        self.tempdir = TemporaryDirectory(prefix="dizzy-")
        atexit.register(create_archive, self.outfile, self.tempdir)
        sys.stdout = Logger(sys.stdout, path.join(self.tempdir.name, "stdout.log"))
        print_dizzy("job/run: cmd was: '%s'." % " ".join(sys.argv))

        if 'job' not in self.config:
            raise JobParseException("No 'job' section found in conf.")
        if 'file' not in self.config['job']:
            raise JobParseException("No 'file' found in conf.")
        if 'mode' not in self.config['job']:
            raise JobParseException("No 'mode' found in conf.")
        self.mode = self.config['job']['mode']
        self.file = self.config['job']['file']

        self.delay = self.config['job'].getfloat('delay', 1)
        self.verbose = self.config['job'].getint('verbose', NORMAL)
        set_print_level(self.verbose)

        if 'output' not in self.config:
            raise JobParseException("No 'output' section found in conf.")
        if 'type' not in self.config['output']:
            raise JobParseException("No 'type' found in conf.")
        self.out_type = self.config['output']['type']
        self.session_reopen = self.config['output'].getboolean('session_reopen', False)
        
        if 'values' in self.config:
            self.config_values = dict(self.config['values'])
        else:
            self.config_values = {}

        self.config_values['_output'] = dict(self.config['output'])

        if self.file.endswith('.act'):
            self.act = load_interaction(self.file, self.mode, start_at, \
                config_values=self.config_values)
            self.dizz = None
            self.mutations = self.act.iterations()
        elif self.file.endswith('.dizz'):
            self.dizz = load_dizz(self.file, self.file, 0, self.mode, start_at, \
                                  config_values=self.config_values)
            self.act = None
            self.mutations = self.dizz.length()
        else:
            raise JobParseException("Wrong input file in conf.")

        self.state_lock = RLock()

        self.probe = None
        self.probe_type = None
        if 'probe' in self.config:
            self.probe_type = self.config['probe'].get('type', None)

        if not self.probe_type is None:
            if self.probe_type in CONFIG["PROBE"]:
                self.probe = CONFIG["PROBE"][self.probe_type].DizzyProbe(self.config["probe"])
            else:
                print_dizzy("job/init: target probe '%s' not found." % self.probe_type)
                exit(1)
        if self.out_type in CONFIG["SESSION"]:
            self.session = CONFIG["SESSION"][self.out_type].DizzySession(self.config['output'])
            CONFIG["GLOBALS"]["SESSION"] = self.session
        else:
            print_dizzy("job/init: session '%s' not found." % self.out_type)
            exit(1)

        self.print_index = start_at + 1
        self.start_time = 0
        self.index = 0
        self.time_list = []
        self.session_reset = False
        self.pcap = None
Exemple #25
0
 def read(self, session, read_back=None):
     d = b""
     reconnect = False
     try:
         reading = True
         while reading:
             r = session.recv()
             if not r:
                 reading = False
                 print_dizzy("job/read: read end on NONE", DEBUG)
             else:
                 d += r
                 #print_dizzy(d, DEBUG)
             if not read_back is None:
                 if len(d) >= read_back:
                     reading = False
     except socket.timeout:
         print_dizzy("job/read: read end on timeout", VERBOSE_2)
     except socket.error as e:
         print_dizzy("job/read: read end on sock error '%s', reopening..." % str(e), VERBOSE_2)
         reconnect = True
     except Exception as e:
         print_dizzy("job/read: cant read input: %s" % str(e), VERBOSE_2)
         return "", True
     if not read_back is None and read_back > 0 and len(d) < read_back:
         print_dizzy("job/read: len(read): %i < rlen: %i, reconnect..." % (len(d), read_back), DEBUG)
         reconnect = True
     print_dizzy("job/read: data: %s reconnect: %s" % (d, reconnect), DEBUG)
     return d, reconnect
Exemple #26
0
    def run(self):
        self.start_time = time()
        self.session.open()

        if self.probe:
            self.probe.open()
            if not self.probe.probe():
                print_dizzy("job/run: initial probe failed")
                return

        if self.act is None:
            for self.index, value in enumerate(self.dizz, self.print_index):
                if 'pcap' in self.config:
                    self.pcap = Pcap(self.config['pcap'], path.join(self.tempdir.name, "trace-%s.pcap" % self.index))
                    self.pcap.start()
                    while not self.pcap.is_open:
                        sleep(0.1)
                try:
                    self.session.send(value.byte)
                except Exception as e:
                    print_dizzy(e)
                    print_exc()
                self.read(self.session, 1)
                if not self.pcap is None:
                    self.pcap.stop()
                    self.pcap.join()
                if not self.do_probe():
                    break
                self.print_status()
        else:
            if 'pcap' in self.config:
                self.pcap = Pcap(self.config['pcap'], path.join(self.tempdir.name, "trace-%s.pcap" % self.index))            
                self.pcap.start()
                while not self.pcap.is_open:
                    sleep(0.1)

            if self.session.read_first:
                self.act.response, session_reset = self.read(self.session, 1)

            for self.index, value in enumerate_interactions(self.act, self.print_index):
                print_dizzy("job/run: index: %d, value: %s" % (self.index, value), DEBUG)
                if self.session_reset:
                    print_dizzy("job/run: Session reset triggered", DEBUG)
                    if not value is None:
                        continue

                if value is None:
                    if self.session_reopen or self.session_reset:
                        print_dizzy("job/run: Reseting session", DEBUG)
                        self.session.close()
                        if not self.pcap is None:
                            self.pcap.stop()
                            self.pcap.join()
                        sleep(self.delay)
                        if 'pcap' in self.config:
                            self.pcap = Pcap(self.config['pcap'], path.join(self.tempdir.name, "trace-%s.pcap" % self.index))            
                            self.pcap.start()
                            while not self.pcap.is_open:
                                sleep(0.1)
                        self.session.open()
                        self.session_reset = False
                    if not self.do_probe():
                        break
                    self.print_status()
                    continue

                try:
                    self.session.send(value.byte)
                except Exception as e:
                    print_dizzy(e)
                    self.session_reset = True
                    continue
                self.act.response, session_reset = self.read(self.session, value.dizz_iterator.dizz.readback)
        
        print_dizzy("job/run: end")

        if not self.pcap is None:
            self.pcap.stop()
            self.pcap.join()

        if self.probe:
            self.probe.close()
Exemple #27
0
    def load(self):
        inventory = self.zipimport.load_module(self.name).__all__

        if "deps" in inventory:
            depspath = self.path + "/" + self.name + "/deps"
            sys.path.insert(0, depspath)
            print_dizzy(
                "mod:%s/load: added dependency path '%s'" %
                (self.name, depspath), VERBOSE_1)

        sys.path.insert(0, self.path)
        if "dizz" in inventory:
            dizz = __import__(self.name + ".dizz").dizz
            self.dizz = []
            for i in dizz.__all__:
                name = self.name + "/dizz/" + i
                obj = dizz.__loader__.get_data(name)
                self.dizz.append(name)
                self.global_config["DIZZ"][name] = obj.decode(
                    self.global_config["GLOBALS"]["CODEC"])

            print_dizzy(
                "mod:%s/load: Loaded %d dizz files." %
                (self.name, len(self.dizz)), VERBOSE_1)
            print_dizzy("mod:%s/load: %s" % (self.name, self.dizz), DEBUG)

        if "act" in inventory:
            act = __import__(self.name + ".act").act
            self.act = []
            for i in act.__all__:
                name = self.name + "/act/" + i
                obj = act.__loader__.get_data(name)
                self.act.append(name)
                self.global_config["ACT"][name] = obj.decode(
                    self.global_config["GLOBALS"]["CODEC"])

            print_dizzy(
                "mod:%s/load: Loaded %d act files." %
                (self.name, len(self.act)), VERBOSE_1)
            print_dizzy("mod:%s/load: %s" % (self.name, self.act), DEBUG)

        if "job" in inventory:
            job = __import__(self.name + ".job").job
            self.job = []
            for i in job.__all__:
                name = self.name + "/job/" + i
                obj = job.__loader__.get_data(name)
                self.job.append(name)
                self.global_config["JOB"][name] = obj.decode(
                    self.global_config["GLOBALS"]["CODEC"])

            print_dizzy(
                "mod:%s/load: Loaded %d job files." %
                (self.name, len(self.job)), VERBOSE_1)
            print_dizzy("mod:%s/load: %s" % (self.name, self.job), DEBUG)

        if "probe" in inventory:
            probe = __import__(self.name + ".probe").probe
            self.probe = []
            for i in probe.__all__:
                name = self.name + ".probe." + i
                obj = getattr(__import__(name).probe, i)
                self.probe.append(name)
                self.global_config["PROBE"][name] = obj

            print_dizzy(
                "mod:%s/load: Loaded %d target probes." %
                (self.name, len(self.probe)), VERBOSE_1)
            print_dizzy("mod:%s/load: %s" % (self.name, self.probe), DEBUG)

        if "session" in inventory:
            session = __import__(self.name + ".session").session
            self.session = []
            for i in session.__all__:
                name = self.name + ".session." + i
                obj = getattr(__import__(name).session, i)
                self.session.append(name)
                self.global_config["SESSION"][name] = obj

            print_dizzy(
                "mod:%s/load: Loaded %d sessions." %
                (self.name, len(self.session)), VERBOSE_1)
            print_dizzy("mod:%s/load: %s" % (self.name, self.session), DEBUG)

        sys.path.remove(self.path)
Exemple #28
0
def print_config():
    print_dizzy("### global sessions ###")
    for i in CONFIG["SESSION"]:
        if i.startswith("session."):
            print_dizzy("  - %s" % i)
    print_dizzy("### global probes ###")
    for i in CONFIG["PROBE"]:
        if i.startswith("probe."):
            print_dizzy("  - %s" % i)
    for i in CONFIG["MODULES"]:
        print_dizzy("### module '%s' loaded from '%s' v%s ###" % (i, CONFIG["MODULES"][i].path, CONFIG["MODULES"][i].version))
        for j in CONFIG["DIZZ"]:
            if j.startswith("%s/" % i):
                print_dizzy("  - %s" % j)
        for j in CONFIG["ACT"]:
            if j.startswith("%s/" % i):
                print_dizzy("  - %s" % j)
        for j in CONFIG["JOB"]:
            if j.startswith("%s/" % i):
                print_dizzy("  - %s" % j)
        for j in CONFIG["SESSION"]:
            if j.startswith("%s." % i):
                print_dizzy("  - %s" % j)
        for j in CONFIG["PROBE"]:
            if j.startswith("%s." % i):
                print_dizzy("  - %s" % j)
Exemple #29
0
def init_config():
    try:
        #read main config
        global CONFIG
        cfg = ConfigParser(allow_no_value=True)
        root = Path(CONFIG["GLOBALS"]["ROOTDIR"]).expanduser()
        str_lib_path = root / CONFIG["GLOBALS"]["DEFAULT_STR_LIB_NAME"]
        CONFIG["GLOBALS"]["DEFAULT_STR_LIB"] = str(str_lib_path)
        if not root.exists():
            Path.mkdir(root)
        if (root / CONFIG["GLOBALS"]["CONFIGFILE"]).exists():
            cfg.read(str(root / CONFIG["GLOBALS"]["CONFIGFILE"]))
        else:
            print_dizzy("config/init: no config file found, creating default config.")
            cfg['dizzy'] = {'module_path' : '%s/modules' % CONFIG["GLOBALS"]["ROOTDIR"],
                            'overwrite_path' : '%s/local' % CONFIG["GLOBALS"]["ROOTDIR"]}
            with (root / CONFIG["GLOBALS"]["CONFIGFILE"]).open('x') as cfile:
                cfg.write(cfile)
            Path.mkdir(root / "modules", exist_ok=True)
            Path.mkdir(root / "local", exist_ok=True)

        if not str_lib_path.exists():
            if str_lib_path.is_symlink():
                str_lib_path.unlink()
            dflt_str_lib_path = Path(prefix + CONFIG["GLOBALS"]["DEFAULT_STR_LIB_NAME"])
            if dflt_str_lib_path.exists():
                print_dizzy("config/init: creating symlink to std_lib.")
                str_lib_path.symlink_to(dflt_str_lib_path.resolve())
            dflt_str_lib_path = Path("./lib/" + CONFIG["GLOBALS"]["DEFAULT_STR_LIB_NAME"])
            if dflt_str_lib_path.exists():
                print_dizzy("config/init: creating symlink to std_lib.")
                str_lib_path.symlink_to(dflt_str_lib_path.resolve())

        CONFIG.update(dict(cfg))
        modp = CONFIG['dizzy'].get("module_path")
        if modp is None:
            print_dizzy("config/init: no module_path in config file.")
            exit(1)
        print_dizzy("config/init: using module path '%s'." % modp, VERBOSE_1)
        
        #check dependencies
        CONFIG["DEPS"] = {}
        try:
            import exrex
        except:
            CONFIG["DEPS"]["exrex"] = False
        else:
            CONFIG["DEPS"]["exrex"] = True

        try:
            import Crypto
        except:
            CONFIG["DEPS"]["Crypto"] = False
        else:
            CONFIG["DEPS"]["Crypto"] = True
        
        #load modules
        CONFIG["DIZZ"] = {}
        CONFIG["ACT"] = {}
        CONFIG["JOB"] = {}
        CONFIG["MODULES"] = {}
        CONFIG["PROBE"] = {}
        CONFIG["SESSION"] = {}
        module_path = Path(modp).expanduser()
        for f in module_path.glob("*.zip"):
            if f.is_dir():
                continue
            print_dizzy("config/init: trying to load module '%s'." % f, VERBOSE_2)
            try:
                mod = DizzyModule(str(f), CONFIG)
            except Exception as e:
                print_dizzy("config/init: can't init module '%s'." % f)
                print_dizzy(e, DEBUG)

            load = True
            #check module dependencies
            for d in mod.dependencies:
                if d in CONFIG["DEPS"]:
                    if not CONFIG["DEPS"][d]:
                        print_dizzy("config/init: can't load module '%s', dependency '%s' not found." % (mod.name, d), VERBOSE_1)
                        load = False
                        continue
                else:
                    try:
                        __import__(d)
                    except:
                        CONFIG["DEPS"][d] = False
                        print_dizzy("config/init: can't load module '%s', dependency '%s' not found." % (mod.name, d), VERBOSE_1)
                        load = False
                        continue
                CONFIG["DEPS"][d] = True
            if load:
                try:
                    mod.load()
                except Exception as e:
                    print_dizzy("config/init: can't load module '%s'." % f)
                    print_dizzy(e, DEBUG)
                    continue

                CONFIG["MODULES"][mod.name] = mod
                if mod.name in CONFIG["MODULES"]:
                    print_dizzy("config/init: module %s loaded successfully." % mod.name, VERBOSE_1)

        #load default sessions
        sessions = __import__("dizzy.session").session.__all__
        for i in sessions:
            CONFIG["SESSION"]["session." + i] = getattr(__import__('dizzy.session.' + i).session, i)

        #load default probes
        probes = __import__("dizzy.probe").probe.__all__
        for i in probes:
            CONFIG["PROBE"]["probe." + i] = getattr(__import__('dizzy.probe.' + i).probe, i)

        #look for overwrite folder
        overwritep = CONFIG["dizzy"].get("overwrite_path")
        if not overwritep is None:
            overwrite_path = Path(overwritep).expanduser()
            if not overwrite_path.is_dir():
                print_dizzy("config/init: overwrite_path is not a directory.", VERBOSE_1)
            else:
                for module in overwrite_path.iterdir():
                    if not module.is_dir():
                        print_dizzy("config/init: %s is not a directory, skipping." % module, VERBOSE_2)
                        continue
                    for component in module.iterdir():
                        if not component.is_dir():
                            print_dizzy("config/init: %s is not a directory, skipping." % component, VERBOSE_2)
                            continue
                        if component.stem == "act":
                            for act in component.iterdir():
                                if not act.is_file():
                                    print_dizzy("config/init: %s is not a file, skipping." % act, VERBOSE_2)
                                    continue
                                with act.open() as input:
                                    name = "%s/%s/%s" % (module.stem, component.stem, act.name)
                                    CONFIG["ACT"][name] = input.read()
                                    print_dizzy("Overwriting %s from %s" % (name, act))
                        elif component.stem == "dizz":
                            for dizz in component.iterdir():
                                if not dizz.is_file():
                                    print_dizzy("config/init: %s is not a file, skipping." % dizz, VERBOSE_2)
                                    continue
                                with dizz.open() as input:
                                    name = "%s/%s/%s" % (module.stem, component.stem, dizz.name)
                                    CONFIG["DIZZ"][name] = input.read()
                                    print_dizzy("Overwriting %s from %s" % (name, dizz))
                        elif component.stem == "job":
                            for job in component.iterdir():
                                if not job.is_file():
                                    print_dizzy("config/init: %s is not a file, skipping." % job, VERBOSE_2)
                                    continue
                                with job.open() as input:
                                    name = "%s/%s/%s" % (module.stem, component.stem, job.name)
                                    CONFIG["JOB"][name] = input.read()
                                    print_dizzy("Overwriting %s from %s" % (name, job))
                        elif component.stem == "probe":
                            for probe in component.iterdir():
                                if not probe.is_file():
                                    print_dizzy("config/init: %s is not a file, skipping." % probe, VERBOSE_2)
                                    continue
                            name = "%s.%s.probe.%s" % (overwrite_path.stem, module.stem, probe.stem)
                            obj = getattr(getattr(__import__(name), module.stem).probe, probe.stem)
                            name = "%s.probe.%s" % (module.stem, probe.stem)
                            CONFIG["PROBE"][name] = obj
                            print_dizzy("Overwriting %s from %s" % (name, probe))
                        elif component.stem == "session":
                            for session in component.iterdir():
                                if not session.is_file():
                                    print_dizzy("config/init: %s is not a file, skipping." % session, VERBOSE_2)
                                    continue
                                name = "%s.%s.session.%s" % (overwrite_path.stem, module.stem, session.stem)
                                obj = getattr(getattr(__import__(name), module.stem).session, session.stem)
                                name = "%s.session.%s" % (module.stem, session.stem)
                                CONFIG["SESSION"][name] = obj
                                print_dizzy("Overwriting %s from %s" % (name, session))
                    if not module.stem in CONFIG["MODULES"]:
                        class Object(object):
                            pass
                        obj = Object()
                        obj.path = "%s" % module
                        obj.version = 0
                        name = "%s" % module.stem
                        CONFIG["MODULES"][name] = obj

        print_dizzy("config/init: init finished, config:", DEBUG)
        #pprint_dizzy(CONFIG, DEBUG)
    except Exception as e:
        raise DizzyParseException("Can't read config file %s: %s" % (CONFIG["GLOBALS"]["CONFIGFILE"], e))
Exemple #30
0
 def open(self):
     try:
         self.socket = socket(self.af, SOCK_STREAM)
         if self.dest == "255.255.255.255":
             self.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
         self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
         self.socket.settimeout(self.timeout)
         sendbuf = self.socket.getsockopt(SOL_SOCKET, SO_SNDBUF)
         if sendbuf < self.maxsize:
             self.maxsize = sendbuf
         if not self.sport is None and not self.src is None:
             if self.af == AF_INET:
                 self.socket.bind((self.src, self.sport))
             elif self.af == AF_INET6:
                 try:
                     #this should be the way for v6 addr, for some reason failed on me ):
                     #self.socket.bind((self.src, self.sport, 0, 0))
                     self.socket.bind((self.src, self.sport))
                 except:
                     if not self.interface is '':
                         (_, _, _, _, addri) = getaddrinfo(
                             "%s%%%s" % (self.src, self.interface),
                             self.sport,
                             family=AF_INET6,
                             proto=IPPROTO_TCP)[0]
                         self.socket.bind(addri)
                     else:
                         raise SessionException(
                             "cant bind to ipv6 LL without interface!")
         if self.server_side:
             self.socket.listen(1)
             (self.client_socket, (rip, rport)) = self.socket.accept()
             if self.dport:
                 while self.dport != rport or self.src != rip:
                     if self.dport != rport:
                         print_dizzy(
                             "session/tcp: remote port %i not destination port %i"
                             % (rport, self.dport), DEBUG)
                     if self.src != rip:
                         print_dizzy(
                             "session/tcp: remote ip %s not destination ip %i"
                             % (rip, self.dst))
                     (self.client_socket, (sip,
                                           rport)) = self.socket.accept()
             self.client_socket.settimeout(self.timeout)
         else:
             connected = False
             attempt = 1
             try:
                 self.socket.connect((self.dest, self.dport))
                 connected = True
             except timeout:
                 print_dizzy(
                     "session/tcp: Connection attempt %d timed out." %
                     (attempt))
                 while not connected and attempt <= self.connect_retry:
                     try:
                         (r, w, x) = select([], [self.socket], [],
                                            self.timeout)
                         if self.socket in w:
                             connected = True
                     except:
                         pass
                     attempt += 1
                 if not connected:
                     raise SessionException("too much connection attempts")
     except Exception as e:
         raise SessionException("cant open session: %s" % e)
     else:
         self.is_open = True