Пример #1
0
def get_message_from_urllib_addinfourl(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    taxii_content_type = http_response.info().getheader('X-TAXII-Content-Type')
    response_message = http_response.read()

    if taxii_content_type is None:  # Treat it as a Failure Status Message, per the spec

        message = []
        header_dict = http_response.info().dict.iteritems()
        for k, v in header_dict:
            message.append(k + ': ' + v + '\r\n')
        message.append('\r\n')
        message.append(response_message)

        m = ''.join(message)

        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=ST_FAILURE, message=m)

    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)

    return None
Пример #2
0
def get_message_from_urllib2_httperror(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    info = http_response.info()

    if hasattr(info, 'getheader'):
        taxii_content_type = info.getheader('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.getheader('Content-Type'))
    else:
        taxii_content_type = info.get('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.get('Content-Type'))

    encoding = params.get('charset', 'utf-8')
    response_message = http_response.read()

    if taxii_content_type is None:
        m = str(http_response) + '\r\n' + str(http_response.info()) + '\r\n' + response_message
        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=ST_FAILURE, message=m)
    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message, encoding)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)
Пример #3
0
def inbox_service(request, inbox_name):
    """Handles TAXII Inbox Service requests."""
    logger = logging.getLogger('yeti.taxii_services.views.inbox_service')
    logger.debug('Entering Inbox service')
    
    resp = handlers.validate_taxii_request(request)
    if resp: return resp # if validation failed, return the response
    
    try:
        taxii_message = tm11.get_message_from_xml(request.body)
    except Exception as ex:
        logger.debug('Unable to parse inbound message: %s', ex.message)
        m = tm11.StatusMessage(tm11.generate_message_id(), '0', status_type=tm11.ST_BAD_MESSAGE, message='Message received could not be parsed')
        return handlers.create_taxii_response(m, use_https=request.is_secure())
    
    logger.debug('Inbox [%s] received TAXII message with id [%s] and type [%s]', 
                 make_safe(inbox_name), make_safe(taxii_message.message_id), make_safe(taxii_message.message_type))
    
    if taxii_message.message_type != tm11.MSG_INBOX_MESSAGE:
        logger.info('TAXII message with id [%s] was not Inbox type [%s]', make_safe(taxii_message.message_id), make_safe(taxii_message.message_type))
        m = tm11.StatusMessage(tm11.generate_message_id(), taxii_message.message_id, status_type=tm11.ST_FAILURE, message='Message sent to Inbox service did not have an inbox Message type')
        return handlers.create_taxii_response(m, use_https=request.is_secure())
    
    resp = handlers.inbox_add_content(request, inbox_name, taxii_message)
    return resp
Пример #4
0
def get_message_from_urllib2_httperror(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    info = http_response.info()

    if hasattr(info, 'getheader'):
        taxii_content_type = info.getheader('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.getheader('Content-Type'))
    else:
        taxii_content_type = info.get('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.get('Content-Type'))

    encoding = params.get('charset', 'utf-8')
    response_message = http_response.read()

    if taxii_content_type is None:
        m = str(http_response) + '\r\n' + str(
            http_response.info()) + '\r\n' + response_message
        return tm11.StatusMessage(message_id='0',
                                  in_response_to=in_response_to,
                                  status_type=ST_FAILURE,
                                  message=m)
    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message, encoding)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' %
                         taxii_content_type)
Пример #5
0
def get_message_from_urllib_addinfourl(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    info = http_response.info()

    if hasattr(info, 'getheader'):
        taxii_content_type = info.getheader('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.getheader('Content-Type'))
    else:
        taxii_content_type = info.get('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.get('Content-Type'))

    encoding = params.get('charset', 'utf-8')
    response_message = http_response.read()

    if taxii_content_type is None:  # Treat it as a Failure Status Message, per the spec

        message = []
        header_dict = six.iteritems(http_response.info().dict)
        for k, v in header_dict:
            message.append(k + ': ' + v + '\r\n')
        message.append('\r\n')
        message.append(response_message)

        m = ''.join(message)

        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=ST_FAILURE, message=m)

    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message, encoding)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)
Пример #6
0
def get_message_from_httplib_http_response(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    if hasattr(http_response, 'getheader'):
        taxii_content_type = http_response.getheader('X-TAXII-Content-Type')
        _, params = cgi.parse_header(http_response.getheader('Content-Type'))
    else:
        taxii_content_type = http_response.get('X-TAXII-Content-Type')
        _, params = cgi.parse_header(http_response.get('Content-Type'))

    encoding = params.get('charset', 'utf-8')
    response_message = http_response.read()

    if taxii_content_type is None:  # Treat it as a Failure Status Message, per the spec

        message = []
        header_tuples = http_response.getheaders()
        for k, v in header_tuples:
            message.append(k + ': ' + v + '\r\n')
        message.append('\r\n')
        message.append(response_message)

        m = ''.join(message)

        return tm11.StatusMessage(message_id='0',
                                  in_response_to=in_response_to,
                                  status_type=ST_FAILURE,
                                  message=m)

    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message, encoding)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' %
                         taxii_content_type)
Пример #7
0
def poll_service(request):
    """Handles TAXII Poll Service requests."""
    logger = logging.getLogger("yeti.taxii_services.views.poll_service")
    logger.debug('Entering poll service')
    
    resp = handlers.validate_taxii_request(request)
    if resp: return resp # if validation failed, return the response
    
    try:
        taxii_message = tm11.get_message_from_xml(request.body)
    except tm11.UnsupportedQueryException as e:
        logger.debug('Unsupported query found in TAXII Message')
        m = tm11.StatusMessage(tm11.generate_message_id(), '0', status_type=tm11.ST_UNSUPPORTED_QUERY, message='The message used an unsupported query format')
        return handlers.create_taxii_response(m, use_https=request.is_secure())
    except Exception as ex:
        logger.debug('Unable to parse inbound message: %s', ex.message)
        m = tm11.StatusMessage(tm11.generate_message_id(), '0', status_type=tm11.ST_BAD_MESSAGE, message='Message received could not be parsed')
        return handlers.create_taxii_response(m, use_https=request.is_secure())
    
    logger.debug('Poll service received TAXII message with id [%s] and type [%s]', make_safe(taxii_message.message_id), make_safe(taxii_message.message_type))
    
    if taxii_message.message_type != tm11.MSG_POLL_REQUEST:
        logger.info('TAXII message with id [%s] was not Poll request [%s]', make_safe(taxii_message.message_id), make_safe(taxii_message.message_type))
        m = tm11.StatusMessage(tm11.generate_message_id(), taxii_message.message_id, status_type=tm11.ST_FAILURE, message='Message sent to Poll service did not have a poll request message type')
        return handlers.create_taxii_response(m, use_https=request.is_secure())    
    
    resp = handlers.poll_get_content(request, taxii_message)
    return resp
def main():
    poll_response = 'file-hash-rep-poll-response.xml'
    f = open(poll_response, 'r')
    msg = tm11.get_message_from_xml(f.read())

    requested_hash = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
    requested_hash_type = 'MD5'

    #Iterate over the content blocks
    for content_block in msg.content_blocks:
        if content_block.content_binding.binding_id != CB_STIX_XML_111:
            raise ValueError('Something other than STIX 1.1.1 was attempted!')

        # Deserialize the STIX_Package
        stix_package = STIXPackage.from_xml(StringIO(content_block.content))
        indicator = get_first_matching_indicator(stix_package, requested_hash,
                                                 requested_hash_type)
        indicated_ttp = get_first_parseable_indicated_ttp(indicator)
        confidence = indicated_ttp.confidence.value
        ttp = get_indicated_ttp(stix_package, indicated_ttp.id_)
        if ttp.title != 'Malicious File':
            raise ValueError('Don\'t know how to handle that TTP')

        if confidence in ('High', 'Medium'):
            print "DO NOT OPEN THE FILE"
        elif confidence in ('Low', 'Unknown'):
            print "THINK TWICE ABOUT OPENING THE FILE"
        elif confidence in ('None', ):
            print "Go ahead!"
        else:
            raise ValueError("Unknown confidence: %s!" % confidence)
Пример #9
0
def get_message_from_httplib_http_response(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    taxii_content_type = http_response.getheader('X-TAXII-Content-Type')
    response_message = http_response.read()

    if taxii_content_type is None:  # Treat it as a Failure Status Message, per the spec

        message = []
        header_tuples = http_response.getheaders()
        for k, v in header_tuples:
            message.append(k + ': ' + v + '\r\n')
        message.append('\r\n')
        message.append(response_message)

        m = ''.join(message)

        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=tm11.ST_FAILURE, message=m)

    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message)
    elif taxii_content_type == VID_TAXII_XML_11: # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)

    return None
def main():
    poll_response = 'file-hash-rep-poll-response.xml'
    f = open(poll_response, 'r')
    msg = tm11.get_message_from_xml(f.read())

    requested_hash = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
    requested_hash_type = 'MD5'

    #Iterate over the content blocks
    for content_block in msg.content_blocks:
        if content_block.content_binding.binding_id != CB_STIX_XML_111:
            raise ValueError('Something other than STIX 1.1.1 was attempted!')

        # Deserialize the STIX_Package
        stix_package = STIXPackage.from_xml(StringIO(content_block.content))
        indicator = get_first_matching_indicator(stix_package, requested_hash, requested_hash_type)
        indicated_ttp = get_first_parseable_indicated_ttp(indicator)
        confidence = indicated_ttp.confidence.value
        ttp = get_indicated_ttp(stix_package, indicated_ttp.id_)
        if ttp.title != 'Malicious File':
            raise ValueError('Don\'t know how to handle that TTP')


        if confidence in ('High','Medium'):
            print "DO NOT OPEN THE FILE"
        elif confidence in ('Low', 'Unknown'):
            print "THINK TWICE ABOUT OPENING THE FILE"
        elif confidence in ('None', ):
            print "Go ahead!"
        else:
            raise ValueError("Unknown confidence: %s!" % confidence)
Пример #11
0
def taxii_discovery_service() -> Response:
    """
    Route for discovery service.
    """

    try:
        discovery_response = SERVER.get_discovery_service(get_message_from_xml(request.data))
    except Exception as e:
        error = f'Could not perform the discovery request: {str(e)}'
        handle_long_running_error(error)
        return make_response(error, 400)

    return taxii_make_response(discovery_response)
Пример #12
0
def taxii_collection_management_service() -> Response:
    """
    Route for collection management.
    """

    try:
        collection_response = SERVER.get_collections(get_message_from_xml(request.data))
    except Exception as e:
        error = f'Could not perform the collection management request: {str(e)}'
        handle_long_running_error(error)
        return make_response(error, 400)

    return taxii_make_response(collection_response)
Пример #13
0
def main():
    parser = argparse.ArgumentParser(description="Poll Client")
    parser.add_argument("--host", dest="host", default="localhost", help="Host where the Poll Service is hosted. Defaults to localhost.")
    parser.add_argument("--port", dest="port", default="8080", help="Port where the Poll Service is hosted. Defaults to 8080.")
    parser.add_argument("--path", dest="path", default="/services/poll/", help="Path where the Poll Service is hosted. Defaults to /services/poll/.")
    parser.add_argument("--feed", dest="feed", default="default", help="Data Feed to poll. Defaults to 'default'.")
    parser.add_argument("--begin_timestamp", dest="begin_ts", default=None, help="The begin timestamp (format: YYYY-MM-DDTHH:MM:SS.ssssss+/-hh:mm) for the poll request. Defaults to None.")
    parser.add_argument("--end_timestamp", dest="end_ts", default=None, help="The end timestamp (format: YYYY-MM-DDTHH:MM:SS.ssssss+/-hh:mm) for the poll request. Defaults to None.")
    parser.add_argument("--content-binding", dest="content_binding", default= t.CB_STIX_XML_10, help="Content binding of the Content Block to send. Defaults to %s" % t.CB_STIX_XML_10 )

    args = parser.parse_args()

    try:
        if args.begin_ts:
            begin_ts = dateutil.parser.parse(args.begin_ts)
            if not begin_ts.tzinfo:
                raise ValueError
        else:
            begin_ts = None

        if args.end_ts:
            end_ts = dateutil.parser.parse(args.end_ts)
            if not end_ts.tzinfo:
                raise ValueError
        else:
            end_ts = None
    except ValueError:
        print "Unable to parse timestamp value. Timestamp should include both date and time information along with a timezone or UTC offset (e.g., YYYY-MM-DDTHH:MM:SS.ssssss+/-hh:mm). Aborting poll."
        sys.exit()

    poll_req = tm11.PollRequest(message_id=tm11.generate_message_id(),
                                 collection_name = args.feed,
                                  exclusive_begin_timestamp_label=begin_ts,
                                  inclusive_end_timestamp_label=end_ts,
                                  subscription_id='1')
    
    poll_req_xml = poll_req.to_xml()
    print "Poll Request: \r\n", poll_req_xml
    client = tc.HttpClient()
    resp = client.callTaxiiService2(args.host, args.path, t.VID_TAXII_XML_10, poll_req_xml, args.port)
    response_message = t.get_message_from_http_response(resp, '0')
    print "Response Message: \r\n", response_message.to_xml()
    
    message = tm11.get_message_from_xml(response_message.to_xml())
    
    
    
    response_message.
Пример #14
0
def taxii_poll_service() -> Response:
    """
    Route for poll service.
    """

    try:
        taxiicontent_type = request.headers['X-TAXII-Content-Type']
        if taxiicontent_type == 'urn:taxii.mitre.org:message:xml:1.1':
            taxii_message = get_message_from_xml(request.data)
        else:
            raise ValueError('Invalid message')
    except Exception as e:
        error = f'Could not perform the polling request: {str(e)}'
        handle_long_running_error(error)
        return make_response(error, 400)

    return SERVER.get_poll_response(taxii_message)
Пример #15
0
def get_message_from_urllib2_httperror(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    taxii_content_type = http_response.info().getheader('X-TAXII-Content-Type')
    response_message = http_response.read()

    if taxii_content_type is None:
        m = str(http_response.info()) + '\r\n' + response_message
        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=tm11.ST_FAILURE, message=m)
    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message)
    elif taxii_content_type == VID_TAXII_XML_11: #It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)

    return None
Пример #16
0
def get_message_from_urllib2_httperror(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    taxii_content_type = http_response.info().getheader('X-TAXII-Content-Type')
    response_message = http_response.read()

    if taxii_content_type is None:
        m = str(http_response.info()) + '\r\n' + response_message
        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=ST_FAILURE, message=m)
    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)

    return None
Пример #17
0
def get_message_from_client_response(resp, in_response_to):
    """ helper func"""

    taxii_content_type = resp.get('X-TAXII-Content-Type', None)
    response_message = resp.content

    if taxii_content_type is None:
        m = str(resp) + '\r\n' + response_message
        return tm11.StatusMessage(message_id='0', in_response_to=in_response_to, status_type=ST_FAILURE, message=m)
    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' % taxii_content_type)

    return None
Пример #18
0
def main():
    input_fns = glob.glob(os.path.join(input_path, '*.xml'))

    for input_fn in input_fns:
        with open(input_fn, 'r') as f:
            text = f.read()

        # parse the file to a TAXII message/object
        msg = tm11.get_message_from_xml(text)

        # create the output files
        basename = os.path.splitext(os.path.basename(input_fn))[0]

        # write XML and text to files.
        xml_out = os.path.join(output_path, basename + ".xml")
        with open(xml_out, 'w') as f:
            f.write(msg.to_xml(pretty_print=True))

        txt_out = os.path.join(output_path, basename + ".txt")
        with open(txt_out, 'w') as f:
            f.write(msg.to_text())
Пример #19
0
def main():
    input_fns = glob.glob(os.path.join(input_path, '*.xml'))

    for input_fn in input_fns:
        with open(input_fn, 'r') as f:
            text = f.read()

        # parse the file to a TAXII message/object
        msg = tm11.get_message_from_xml(text)

        # create the output files
        basename = os.path.splitext(os.path.basename(input_fn))[0]

        # write XML and text to files.
        xml_out = os.path.join(output_path, basename + ".xml")
        with open(xml_out, 'w') as f:
            f.write(msg.to_xml(pretty_print=True))

        txt_out = os.path.join(output_path, basename + ".txt")
        with open(txt_out, 'w') as f:
            f.write(msg.to_text())
Пример #20
0
def get_message_from_urllib_addinfourl(http_response, in_response_to):
    """ This function should not be called by libtaxii users directly. """
    info = http_response.info()

    if hasattr(info, 'getheader'):
        taxii_content_type = info.getheader('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.getheader('Content-Type'))
    else:
        taxii_content_type = info.get('X-TAXII-Content-Type')
        _, params = cgi.parse_header(info.get('Content-Type'))

    encoding = params.get('charset', 'utf-8')
    response_message = six.ensure_text(http_response.read(), errors='replace')

    if taxii_content_type is None:  # Treat it as a Failure Status Message, per the spec

        message = []
        header_dict = six.iteritems(http_response.info().dict)
        for k, v in header_dict:
            message.append(k + ': ' + v + '\r\n')
        message.append('\r\n')
        message.append(response_message)

        m = ''.join(message)

        return tm11.StatusMessage(message_id='0',
                                  in_response_to=in_response_to,
                                  status_type=ST_FAILURE,
                                  message=m)

    elif taxii_content_type == VID_TAXII_XML_10:  # It's a TAXII XML 1.0 message
        return tm10.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_TAXII_XML_11:  # It's a TAXII XML 1.1 message
        return tm11.get_message_from_xml(response_message, encoding)
    elif taxii_content_type == VID_CERT_EU_JSON_10:
        return tm10.get_message_from_json(response_message, encoding)
    else:
        raise ValueError('Unsupported X-TAXII-Content-Type: %s' %
                         taxii_content_type)
Пример #21
0
    def do_POST(s):

        # Get the HTTP bdoy
        varLen = int(s.headers['Content-Length'])
        data = s.rfile.read(varLen)

        # Parse body as TAXII message.
        msg = tm11.get_message_from_xml(data)

        # If it's a poll request, handle it.
        if type(msg) == tm11.PollRequest:
            s.handle_poll_request(msg)
            return

        if type(msg) == tm11.InboxMessage:
            s.handle_inbox_message(msg)
            return

        if type(msg) == tm11.DiscoveryRequest:
            s.handle_discovery_request(msg)
            return

        if type(msg) == tm11.CollectionInformationRequest:
            s.handle_collection_information_request(msg)
            return

        if type(msg) == tm11.ManageCollectionSubscriptionRequest:
            s.handle_manage_collection_subscription_request(msg)
            return

        # Sorry, I only handle inbox and poll requests.

        resp = tm11.StatusMessage(message_id=tm11.generate_message_id(),
                                  in_response_to=msg.message_id,
                                  status_type=tm11.ST_FAILURE,
                                  message="Your request type not supported.")
        s.respond(resp.to_xml())
def round_trip_message(taxii_message, print_xml=False):
    if not isinstance(taxii_message, tm11.TAXIIMessage):
        raise ValueError('taxii_message was not an instance of TAXIIMessage')

    #print '***** Message type = %s; id = %s' % (taxii_message.message_type, taxii_message.message_id)

    xml_string = taxii_message.to_xml()
    valid = tm11.validate_xml(xml_string)
    if valid is not True:
        print 'Bad XML was:'
        try:
            print etree.tostring(taxii_message.to_etree(), pretty_print=True)
        except Exception as e:
            print xml_string
        raise Exception('\tFailure of test #1 - XML not schema valid: %s' % valid)
    
    if print_xml:
        print etree.tostring(taxii_message.to_etree(), pretty_print=True)
    
    msg_from_xml = tm11.get_message_from_xml(xml_string)
    dictionary = taxii_message.to_dict()
    msg_from_dict = tm11.get_message_from_dict(dictionary)
    if taxii_message != msg_from_xml:
        print '\t Failure of test #2 - running equals w/ debug:'
        taxii_message.__eq__(msg_from_xml, True)
        raise Exception('Test #2 failed - taxii_message != msg_from_xml')

    if taxii_message != msg_from_dict:
        print '\t Failure of test #3 - running equals w/ debug:'
        taxii_message.__eq__(msg_from_dict, True)
        raise Exception('Test #3 failed - taxii_message != msg_from_dict')

    if msg_from_xml != msg_from_dict:
        print '\t Failure of test #4 - running equals w/ debug:'
        msg_from_xml.__eq__(msg_from_dict, True)
        raise Exception('Test #4 failed - msg_from_xml != msg_from_dict')
Пример #23
0
def discovery_service(request):
    """Handles TAXII Discovery Service requests"""
    logger = logging.getLogger('yeti.taxii_services.views.discovery_service')
    logger.debug('Entering discovery service')
    
    resp = handlers.validate_taxii_request(request)
    if resp: return resp # if validation fails, return the response
    
    try:
        taxii_message = tm11.get_message_from_xml(request.body)
    except Exception as ex:
        logger.debug('Unable to parse inbound message: %s', ex.message)
        m = tm11.StatusMessage(tm11.generate_message_id(), '0', status_type=tm11.ST_BAD_MESSAGE, message='Message received could not be parsed')
        return handlers.create_taxii_response(m, use_https=request.is_secure())
    
    logger.debug('Discovery service received TAXII message with id [%s] and type [%s]', make_safe(taxii_message.message_id), make_safe(taxii_message.message_type))
    
    if taxii_message.message_type != tm11.MSG_DISCOVERY_REQUEST:
        logger.info('TAXII message with id [%s] was not Discovery request [%s]', make_safe(taxii_message.message_id), make_safe(taxii_message.message_type))
        m = tm11.StatusMessage(tm11.generate_message_id(), taxii_message.message_id, status_type=tm11.ST_FAILURE, message='Message sent to discovery service did not have a discovery request message type')
        return handlers.create_taxii_response(m, use_https=request.is_secure())

    resp = handlers.discovery_get_services(request, taxii_message)
    return resp
Пример #24
0
                   timeout=None)

###############################################################################
# Display HTTP Response #######################################################
###############################################################################
print('HTTP Response Status: ' + str(http_resp.status_code))
print('HTTP Response Header:')
for k, v in sorted(http_resp.headers.iteritems()):
    sep = (28 - len(k)) * ' '
    print('    %s: %s %s' % (k,sep,v))

###############################################################################
# Display TAXII Response ######################################################
###############################################################################
print('HTTP Response Body (TAXII Message): ')
taxii_response = tm11.get_message_from_xml(http_resp.text)
# print etree.tostring(taxii_response.to_etree(), pretty_print=True)
print taxii_response.to_text()

service_options = {}
service_instance_list = taxii_response.service_instances
for service in service_instance_list:
    print service.service_type
    service_options[service.service_type] = service



"""
The Poll service is the mechanism by which a TAXII consumers can pull data from
a TAXII Data Feed. The Poll service can be accessed by transmitting a Poll
request to the /services/poll/ location of this YETI installation. The name of
Пример #25
0
def get_sent_message():
    body = httpretty.last_request().body
    return tm11.get_message_from_xml(body)
Пример #26
0
def test_get_xml_from_unicode_string():
    req = get_message_from_xml(discovery_request_with_encoding_unicode)

    assert req is not None
    assert req.message_id == "331bf15a-76a0-4e29-8444-6e986e514e29"
Пример #27
0
def get_sent_message():
    body = responses.calls[-1].request.body
    print(repr(body))
    return tm11.get_message_from_xml(body)
def test_get_xml_from_unicode_string():
    req = get_message_from_xml(discovery_request_with_encoding_unicode)

    assert req is not None
    assert req.message_id == "331bf15a-76a0-4e29-8444-6e986e514e29"
Пример #29
0
def get_sent_message():
    body = httpretty.last_request().body
    return tm11.get_message_from_xml(body)