Пример #1
0
 def __str__(self):
     self.parse()
     contents = StringIO()
     for (line_type, components) in self._contents:
         if line_type == 'blank':
             contents.write("%s\n" % (components[0]))
         elif line_type == 'all_comment':
             contents.write("%s\n" % (components[0]))
         elif line_type == 'hostname':
             (hostname, tail) = components
             contents.write("%s%s\n" % (hostname, tail))
     # Ensure trailing newline
     contents = contents.getvalue()
     if not contents.endswith("\n"):
         contents += "\n"
     return contents
Пример #2
0
 def __str__(self):
     self.parse()
     contents = StringIO()
     for (line_type, components) in self._contents:
         if line_type == 'blank':
             contents.write("%s\n" % (components[0]))
         elif line_type == 'all_comment':
             contents.write("%s\n" % (components[0]))
         elif line_type == 'hostname':
             (hostname, tail) = components
             contents.write("%s%s\n" % (hostname, tail))
     # Ensure trailing newline
     contents = contents.getvalue()
     if not contents.endswith("\n"):
         contents += "\n"
     return contents
Пример #3
0
def error_msg(debugger_args):
    """Error has been caught and we were given chance to report it"""

    debug_no, params = parse_args(debugger_args)

    if debug_no == '3':
        exc_info =  sys.exc_info()
        if exc_info[0]:
            exception_data = StringIO()
            traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], None, exception_data)
            exception_data = exception_data.getvalue()
            if exception_data.endswith('\n'):
                    exception_data = exception_data[:-1]
            #pydev is truncating data (no help printing in loop)
            sys.stderr.write('\n\n...')
            sys.stderr.write(exception_data[-600:])
            sys.stderr.write('\n\n')
Пример #4
0
def error_msg(debugger_args):
    """Error has been caught and we were given chance to report it"""

    debug_no, params = parse_args(debugger_args)

    if debug_no == '3':
        exc_info = sys.exc_info()
        if exc_info[0]:
            exception_data = StringIO()
            traceback.print_exception(exc_info[0], exc_info[1], exc_info[2],
                                      None, exception_data)
            exception_data = exception_data.getvalue()
            if exception_data.endswith('\n'):
                exception_data = exception_data[:-1]
            #pydev is truncating data (no help printing in loop)
            sys.stderr.write('\n\n...')
            sys.stderr.write(exception_data[-600:])
            sys.stderr.write('\n\n')
Пример #5
0
def elevate(stix_package):
    global MESSAGES_GENERATED
    MESSAGES_GENERATED = False
    print("Results produced by the stix2-elevator are not for production purposes.")
    clear_globals()
    fn = None

    validator_options = get_validator_options()

    output.set_level(validator_options.verbose)
    output.set_silent(validator_options.silent)

    try:
        if isinstance(stix_package, MarkingContainer):
            # No need to re-parse the MarkingContainer.
            container = stix_package
        elif isinstance(stix_package, STIXPackage):
            io = BytesIO(stix_package.to_xml())
            container = stixmarx.parse(io)
        elif isinstance(stix_package, text_type):
            if stix_package.endswith(".xml") or os.path.isfile(stix_package):
                # a path-like string was passed
                fn = stix_package
                if os.path.exists(fn) is False:
                    raise IOError("The file '{}' was not found.".format(fn))
            else:
                stix_package = StringIO(stix_package)
            container = stixmarx.parse(stix_package)
        elif isinstance(stix_package, binary_type):
            if stix_package.endswith(b".xml") or os.path.isfile(stix_package):
                # a path-like string was passed
                fn = stix_package
                if os.path.exists(fn) is False:
                    raise IOError("The file '{}' was not found.".format(fn))
            else:
                stix_package = BytesIO(stix_package)
            container = stixmarx.parse(stix_package)
        else:
            raise RuntimeError("Unable to resolve object {} of type {}".format(stix_package, type(stix_package)))

        container_package = container.package
        set_option_value("marking_container", container)

        if not isinstance(container_package, STIXPackage):
            raise TypeError("Must be an instance of stix.core.STIXPackage")
    except (OSError, IOError, lxml.etree.Error) as ex:
        log.error("Error occurred: %s", ex)
        # log.exception(ex)
        return None

    try:
        setup_logger(container_package.id_)
        warn("Results produced by the stix2-elevator may generate warning messages which should be investigated.", 201)
        env = Environment(get_option_value("package_created_by_id"))
        json_string = json.dumps(
            convert_package(container_package, env),
            ensure_ascii=False,
            indent=4,
            separators=(',', ': '),
            sort_keys=True
        )

        bundle_id = re.findall(
            r"bundle--[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
            json_string
        )
        validation_results = validate_stix2_string(json_string, validator_options, fn or bundle_id[0])
        output.print_results([validation_results])

        if get_option_value("policy") == "no_policy":
            return json_string
        else:
            if not MESSAGES_GENERATED and validation_results._is_valid:
                return json_string

    except ValidationError as ex:
        output.error("Validation error occurred: '{}'".format(ex))
        output.error("Error Code: {}".format(codes.EXIT_VALIDATION_ERROR))