示例#1
0
class DateTimeWithPrecision(stix.Entity):
    _binding = common_binding
    _binding_class = _binding.DateTimeWithPrecisionType
    _namespace = 'http://stix.mitre.org/common-1'

    value = fields.DateTimeField("valueOf_", key_name="value")
    precision = fields.TypedField("precision", preset_hook=validate_precision)

    def __init__(self, value=None, precision='second'):
        super(DateTimeWithPrecision, self).__init__()
        self.value = value
        self.precision = precision

    def to_dict(self):
        if self.precision == 'second':
            return utils.dates.serialize_value(self.value)
        return super(DateTimeWithPrecision, self).to_dict()

    @classmethod
    def from_dict(cls, cls_dict):
        if not cls_dict:
            return None
        elif not isinstance(cls_dict, dict):
            obj = cls()
            obj.value = cls_dict
        else:
            obj = super(DateTimeWithPrecision, cls).from_dict(cls_dict)

        return obj
示例#2
0
class Confidence(stix.Entity):
    _namespace = 'http://stix.mitre.org/common-1'
    _binding = common_binding
    _binding_class = common_binding.ConfidenceType

    value = VocabField("Value")
    descriptions = fields.TypedField("Description", StructuredTextList)
    timestamp = fields.DateTimeField("timestamp")
    timestamp_precision = fields.TypedField("timestamp_precision",
                                            preset_hook=validate_precision)
    source = fields.TypedField("Source", type_="stix.common.InformationSource")

    def __init__(self,
                 value=None,
                 timestamp=None,
                 description=None,
                 source=None):
        super(Confidence, self).__init__()

        self.timestamp = timestamp or utils.dates.now()
        self.timestamp_precision = "second"
        self.value = value
        self.description = StructuredTextList(description)
        self.source = source

        # TODO: support confidence_assertion_chain
        # self.confidence_assertion_chain = None

    @property
    def description(self):
        """A single description about the contents or purpose of this object.

        Default Value: ``None``

        Note:
            If this object has more than one description set, this will return
            the description with the lowest ordinality value.

        Returns:
            An instance of :class:`.StructuredText`

        """
        return next(iter(self.descriptions), None)

    @description.setter
    def description(self, value):
        from stix.common.structured_text import StructuredTextList
        if value is None:
            self.descriptions = StructuredTextList()
        else:
            self.descriptions = StructuredTextList(value)

    def add_description(self, description):
        """Adds a description to the ``descriptions`` collection.

        This is the same as calling "foo.descriptions.add(bar)".

        """
        self.descriptions.add(description)
示例#3
0
class Sighting(stix.Entity):
    _namespace = "http://stix.mitre.org/Indicator-2"
    _binding = indicator_binding
    _binding_class = _binding.SightingType

    timestamp = fields.DateTimeField("timestamp")
    timestamp_precision = fields.TypedField("timestamp_precision",
                                            preset_hook=validate_precision)
    descriptions = fields.TypedField("Description", StructuredTextList)
    source = fields.TypedField("Source", InformationSource)
    reference = fields.TypedField("Reference")
    confidence = fields.TypedField("Confidence", Confidence)
    related_observables = fields.TypedField(
        "Related_Observables",
        type_="stix.indicator.sightings.RelatedObservables")

    def __init__(self,
                 timestamp=None,
                 timestamp_precision=None,
                 description=None):
        super(Sighting, self).__init__()

        self.timestamp = timestamp or utils.dates.now()
        self.timestamp_precision = timestamp_precision
        self.descriptions = description
        self.source = None
        self.reference = None
        self.confidence = None

    @property
    def description(self):
        """A single description about the contents or purpose of this object.

        Default Value: ``None``

        Note:
            If this object has more than one description set, this will return
            the description with the lowest ordinality value.

        Returns:
            An instance of :class:`.StructuredText`

        """
        return next(iter(self.descriptions or []), None)

    @description.setter
    def description(self, value):
        self.descriptions = StructuredTextList(value)

    def add_description(self, description):
        """Adds a description to the ``descriptions`` collection.

        This is the same as calling "foo.descriptions.add(bar)".

        """
        self.descriptions.add(description)
示例#4
0
class JournalEntry(stix.Entity):
    _namespace = "http://stix.mitre.org/Incident-1"
    _binding = incident_binding
    _binding_class = incident_binding.JournalEntryType

    value = fields.TypedField("valueOf_", key_name="value")
    author = fields.TypedField("author")
    time = fields.DateTimeField("time")
    time_precision = fields.TypedField("time_precision",
                                       preset_hook=validate_precision)

    def __init__(self, value=None):
        super(JournalEntry, self).__init__()
        self.value = value
        self.time_precision = 'second'
class CampaignRef(stix.Entity):
    _namespace = "http://stix.mitre.org/common-1"
    _binding = common_binding
    _binding_class = common_binding.CampaignReferenceType

    idref = fields.TypedField("idref")
    timestamp = fields.DateTimeField("timestamp")
    names = fields.TypedField("Names", Names)

    def __init__(self, idref=None, timestamp=None):
        super(CampaignRef, self).__init__()

        self.idref = idref
        self.timestamp = timestamp

    def add_name(self, name):
        self.names.append(name)
class DateTimeWithPrecision(entities.Entity):
    _binding = common_binding
    _binding_class = common_binding.DateTimeWithPrecisionType
    _namespace = 'http://cybox.mitre.org/common-2'

    value = fields.DateTimeField("valueOf_", key_name="value")
    precision = fields.TypedField("precision", preset_hook=validate_datetime_precision)

    def __init__(self, value=None, precision='second'):
        super(DateTimeWithPrecision, self).__init__()
        self.value = value
        self.precision = precision

    def to_dict(self):
        if self.precision == 'second':
            return dates.serialize_datetime(self.value)
        return super(DateTimeWithPrecision, self).to_dict()
示例#7
0
class ISAMarkings(dm.MarkingStructure):
    _binding = isa_markings
    _binding_class = _binding.ISAMarkingsType
    _namespace = 'http://www.us-cert.gov/sites/default/files/STIX_Namespace/ISAMarkingsType.v2.xsd'
    _XSI_TYPE = 'isam-v2:ISAMarkingsType'

    isam_version = fields.TypedField("isam_version")
    identifier = fields.TypedField("Identifier", key_name="identifier")
    create_date_time = fields.DateTimeField("CreateDateTime",
                                            key_name="create_date_time")
    responsible_entity = fields.TypedField("ResponsibleEntity",
                                           type_="stix_edh.common.NMTokens",
                                           key_name="responsible_entity")
    auth_ref = fields.TypedField("AuthRef", key_name="auth_ref")

    def __init__(self):
        super(ISAMarkings, self).__init__()
        self.isam_version = '2.0'
示例#8
0
class RelatedPackageRef(GenericRelationship):
    _namespace = "http://stix.mitre.org/common-1"
    _binding = common_binding
    _binding_class = common_binding.RelatedPackageRefType

    idref = fields.IdrefField("idref")
    timestamp = fields.DateTimeField("timestamp")

    def __init__(self, idref=None, timestamp=None, confidence=None,
                 information_source=None, relationship=None):

        super(RelatedPackageRef, self).__init__(
            confidence=confidence,
            information_source=information_source,
            relationship=relationship
        )

        self.idref = idref
        self.timestamp = timestamp
示例#9
0
class Action(entities.Entity):
    _binding = core_binding
    _binding_class = core_binding.ActionType
    _namespace = 'http://cybox.mitre.org/cybox-2'

    id_ = fields.TypedField("id")
    idref = fields.TypedField("idref")
    ordinal_position = fields.TypedField("ordinal_position")
    action_status = fields.TypedField("action_status")
    context = fields.TypedField("context")
    timestamp = fields.DateTimeField("timestamp")
    type_ = VocabField("Type", ActionType)
    name = VocabField("Name", ActionName)
    description = fields.TypedField("Description", StructuredText)
    action_aliases = fields.TypedField("Action_Aliases", ActionAliases)
    action_arguments = fields.TypedField("Action_Arguments", ActionArguments)
    discovery_method = fields.TypedField("Discovery_Method", MeasureSource)
    associated_objects = fields.TypedField("Associated_Objects", AssociatedObjects)
    relationships = fields.TypedField("Relationships", ActionRelationships)
    frequency = fields.TypedField("Frequency", Frequency)
示例#10
0
文件: base.py 项目: sgml/python-stix
class BaseCoreComponent(Entity):
    _ALL_VERSIONS = ()
    _ID_PREFIX = None

    title = fields.TypedField("Title")
    id_ = fields.IdField("id")
    idref = fields.IdrefField("idref")
    descriptions = fields.TypedField(
        "Description",
        type_="stix.common.StructuredTextList",
    )
    short_descriptions = fields.TypedField(
        "Short_Description", type_="stix.common.StructuredTextList")
    version = fields.TypedField("version", preset_hook=_validate_version)
    timestamp = fields.DateTimeField("timestamp")
    handling = fields.TypedField("Handling", type_="stix.data_marking.Marking")

    def __init__(self,
                 id_=None,
                 idref=None,
                 timestamp=None,
                 title=None,
                 description=None,
                 short_description=None):
        from stix.common import StructuredTextList

        super(BaseCoreComponent, self).__init__()

        self.id_ = id_ or idgen.create_id(self._ID_PREFIX)
        self.idref = idref
        self.title = title
        self.descriptions = StructuredTextList(description)
        self.short_descriptions = StructuredTextList(short_description)

        if timestamp:
            self.timestamp = timestamp
        else:
            self.timestamp = utils.dates.now() if not idref else None

    @property
    def description(self):
        """A single description about the contents or purpose of this object.

        Default Value: ``None``

        Note:
            If this object has more than one description set, this will return
            the description with the lowest ordinality value.

        Returns:
            An instance of :class:`.StructuredText`
        """
        return next(iter(self.descriptions), None)

    @description.setter
    def description(self, value):
        self.descriptions = value

    def add_description(self, description):
        """Adds a description to the ``descriptions`` collection.

        This is the same as calling "foo.descriptions.add(bar)".
        """
        self.descriptions.add(description)

    @property
    def short_description(self):
        """A single short description about the contents or purpose of this
        object.

        Default Value: ``None``

        Note:
            If this object has more than one short description set, this will
            return the description with the lowest ordinality value.

        Returns:
            An instance of :class:`.StructuredText`
        """
        return next(iter(self.short_descriptions), None)

    @short_description.setter
    def short_description(self, value):
        self.short_descriptions = value

    def add_short_description(self, description):
        """Adds a description to the ``short_descriptions`` collection.

        This is the same as calling "foo.short_descriptions.add(bar)".
        """
        self.short_descriptions.add(description)
示例#11
0
class STIXPackage(stix.Entity):
    """A STIX Package object.

    Args:
        id_ (optional): An identifier. If ``None``, a value will be generated
            via ``mixbox.idgen.create_id()``. If set, this will unset the
            ``idref`` property.
        idref: **DEPRECATED** An identifier reference. If set this will unset
            the ``id_`` property.
        timestamp: **DEPRECATED** A timestamp value. Can be an instance of
            ``datetime.datetime`` or ``str``.
        header: A Report :class:`.Header` object.
        campaigns: A collection of :class:`.Campaign` objects.
        course_of_action: A collection of :class:`.CourseOfAction` objects.
        exploit_targets: A collection of :class:`.ExploitTarget` objects.
        incidents: A collection of :class:`.Incident` objects.
        indicators: A collection of :class:`.Indicator` objects.
        threat_actors: A collection of :class:`.ThreatActor` objects.
        ttps: A collection of :class:`.TTP` objects.
        related_packages: **DEPRECATED**. A collection of
            :class:`.RelatedPackage` objects.
        reports: A collection of :class:`.Report` objects.

    """
    _binding = stix_core_binding
    _binding_class = _binding.STIXType
    _namespace = 'http://stix.mitre.org/stix-1'
    _version = "1.2"
    _ALL_VERSIONS = ("1.0", "1.0.1", "1.1", "1.1.1", "1.2")

    id_ = fields.IdField("id")
    idref = fields.IdrefField("idref", preset_hook=deprecated.field)
    version = fields.TypedField("version")
    timestamp = fields.DateTimeField("timestamp", preset_hook=deprecated.field)
    stix_header = fields.TypedField("STIX_Header", STIXHeader)
    campaigns = fields.TypedField("Campaigns", Campaigns)
    courses_of_action = fields.TypedField("Courses_Of_Action", CoursesOfAction)
    exploit_targets = fields.TypedField("Exploit_Targets", ExploitTargets)
    observables = fields.TypedField("Observables", Observables)
    indicators = fields.TypedField("Indicators", Indicators)
    incidents = fields.TypedField("Incidents", Incidents)
    threat_actors = fields.TypedField("Threat_Actors", ThreatActors)
    ttps = fields.TypedField("TTPs", TTPs)
    related_packages = fields.TypedField("Related_Packages", RelatedPackages)
    reports = fields.TypedField("Reports", Reports)

    def __init__(self,
                 id_=None,
                 idref=None,
                 timestamp=None,
                 stix_header=None,
                 courses_of_action=None,
                 exploit_targets=None,
                 indicators=None,
                 observables=None,
                 incidents=None,
                 threat_actors=None,
                 ttps=None,
                 campaigns=None,
                 related_packages=None,
                 reports=None):

        super(STIXPackage, self).__init__()

        self.id_ = id_ or idgen.create_id("Package")
        self.idref = idref
        self.version = STIXPackage._version
        self.stix_header = stix_header
        self.campaigns = campaigns or Campaigns()
        self.courses_of_action = courses_of_action or CoursesOfAction()
        self.exploit_targets = exploit_targets or ExploitTargets()
        self.observables = observables or Observables()
        self.indicators = indicators or Indicators()
        self.incidents = incidents or Incidents()
        self.threat_actors = threat_actors or ThreatActors()
        self.ttps = ttps or TTPs()
        self.related_packages = related_packages
        self.reports = reports or Reports()
        self.timestamp = timestamp

    def add_indicator(self, indicator):
        """Adds an :class:`.Indicator` object to the :attr:`indicators`
        collection.

        """
        if self.indicators is None:
            self.indicators = Indicators()
        self.indicators.append(indicator)

    def add_campaign(self, campaign):
        """Adds a :class:`Campaign` object to the :attr:`campaigns` collection.

        """
        if self.campaigns is None:
            self.campaigns = Campaigns()
        self.campaigns.append(campaign)

    def add_observable(self, observable):
        """Adds an ``Observable`` object to the :attr:`observables` collection.

        If `observable` is not an ``Observable`` instance, an effort will be
        made to convert it to one.

        """
        if not self.observables:
            self.observables = Observables(observables=observable)
        else:
            self.observables.add(observable)

    def add_incident(self, incident):
        """Adds an :class:`.Incident` object to the :attr:`incidents`
        collection.

        """
        if self.incidents is None:
            self.incidents = Incidents()
        self.incidents.append(incident)

    def add_threat_actor(self, threat_actor):
        """Adds an :class:`.ThreatActor` object to the :attr:`threat_actors`
        collection.

        """
        if self.threat_actors is None:
            self.threat_actors = ThreatActors()
        self.threat_actors.append(threat_actor)

    def add_course_of_action(self, course_of_action):
        """Adds an :class:`.CourseOfAction` object to the
        :attr:`courses_of_action` collection.

        """
        if self.courses_of_action is None:
            self.courses_of_action = CoursesOfAction()
        self.courses_of_action.append(course_of_action)

    def add_exploit_target(self, exploit_target):
        """Adds an :class:`.ExploitTarget` object to the
        :attr:`exploit_targets` collection.

        """
        if self.exploit_targets is None:
            self.exploit_targets = ExploitTargets()
        self.exploit_targets.append(exploit_target)

    def add_ttp(self, ttp):
        """Adds an :class:`.TTP` object to the :attr:`ttps` collection.

        """
        if self.ttps is None:
            self.ttps = TTPs()
        self.ttps.ttp.append(ttp)

    def add_report(self, report):
        """Adds a :class:`.Report` object to the :attr:`reports` collection.

        """
        if self.reports is None:
            self.reports = Reports()
        self.reports.append(report)

    def add_related_package(self, related_package):
        """Adds a :class:`.RelatedPackage` object to the
        :attr:`related_packages` collection.

        """
        if self.related_packages is None:
            self.related_packages = RelatedPackages()
        self.related_packages.append(related_package)

    def add(self, entity):
        """Adds `entity` to a top-level collection. For example, if `entity` is
        an Indicator object, the `entity` will be added to the ``indicators``
        top-level collection.

        """
        if utils.is_cybox(entity):
            self.add_observable(entity)
            return

        tlo_adds = {
            Campaign: self.add_campaign,
            CourseOfAction: self.add_course_of_action,
            ExploitTarget: self.add_exploit_target,
            Incident: self.add_incident,
            Indicator: self.add_indicator,
            ThreatActor: self.add_threat_actor,
            TTP: self.add_ttp,
            Report: self.add_report,
            Observable: self.add_observable,
        }

        try:
            add = tlo_adds[entity.__class__]
            add(entity)
        except KeyError:
            error = "Cannot add type '{0}' to a top-level collection"
            error = error.format(type(entity))
            raise TypeError(error)

    @classmethod
    def from_xml(cls, xml_file, encoding=None):
        """Parses the `xml_file` file-like object and returns a
        :class:`STIXPackage` instance.

        Args:
            xml_file: A file, file-like object, etree._Element, or
                etree._ElementTree instance.
            encoding: The character encoding of the `xml_file` input. If
                ``None``, an attempt will be made to determine the input
                character encoding. Default is ``None``.

        Returns:
            An instance of :class:`STIXPackage`.

        """
        entity_parser = parser.EntityParser()
        return entity_parser.parse_xml(xml_file, encoding=encoding)
示例#12
0
class Report(stix.Entity):
    """A STIX Report Object.

    Args:
        id_ (optional): An identifier. If ``None``, a value will be generated
            via ``mixbox.idgen.create_id()``. If set, this will unset the
            ``idref`` property.
        idref (optional): An identifier reference. If set this will unset the
            ``id_`` property.
        timestamp (optional): A timestamp value. Can be an instance of
            ``datetime.datetime`` or ``str``.
        header: A Report :class:`.Header` object.
        campaigns: A collection of :class:`.Campaign` objects.
        courses_of_action: A collection of :class:`.CourseOfAction` objects.
        exploit_targets: A collection of :class:`.ExploitTarget` objects.
        incidents: A collection of :class:`.Incident` objects.
        indicators: A collection of :class:`.Indicator` objects.
        threat_actors: A collection of :class:`.ThreatActor` objects.
        ttps: A collection of :class:`.TTP` objects.
        related_reports: A collection of :class:`.RelatedReport` objects.

    """
    _binding = report_binding
    _binding_class = _binding.ReportType
    _namespace = 'http://stix.mitre.org/Report-1'
    _version = "1.0"

    id_ = fields.IdField("id")
    idref = fields.IdrefField("idref")
    timestamp = fields.DateTimeField("timestamp")
    version = fields.TypedField("version")
    header = fields.TypedField("Header", Header)
    campaigns = fields.TypedField("Campaigns", type_="stix.report.Campaigns")
    courses_of_action = fields.TypedField("Courses_Of_Action",
                                          type_="stix.report.CoursesOfAction")
    exploit_targets = fields.TypedField("Exploit_Targets",
                                        type_="stix.report.ExploitTargets")
    observables = fields.TypedField("Observables", Observables)
    indicators = fields.TypedField("Indicators",
                                   type_="stix.report.Indicators")
    incidents = fields.TypedField("Incidents", type_="stix.report.Incidents")
    threat_actors = fields.TypedField("Threat_Actors",
                                      type_="stix.report.ThreatActors")
    ttps = fields.TypedField("TTPs", type_="stix.report.TTPs")
    related_reports = fields.TypedField("Related_Reports",
                                        type_="stix.report.RelatedReports")

    def __init__(self,
                 id_=None,
                 idref=None,
                 timestamp=None,
                 header=None,
                 courses_of_action=None,
                 exploit_targets=None,
                 indicators=None,
                 observables=None,
                 incidents=None,
                 threat_actors=None,
                 ttps=None,
                 campaigns=None,
                 related_reports=None):
        super(Report, self).__init__()
        self.id_ = id_ or idgen.create_id("Report")
        self.idref = idref
        self.version = self._version
        self.header = header
        self.campaigns = campaigns
        self.courses_of_action = courses_of_action
        self.exploit_targets = exploit_targets
        self.observables = observables
        self.indicators = indicators
        self.incidents = incidents
        self.threat_actors = threat_actors
        self.ttps = ttps
        self.related_reports = related_reports

        if timestamp:
            self.timestamp = timestamp
        else:
            self.timestamp = utils.dates.now() if not idref else None

    def add_indicator(self, indicator):
        """Adds an :class:`.Indicator` object to the :attr:`indicators`
        collection.

        """
        if self.indicators is None:
            self.indicators = Indicators()
        self.indicators.append(indicator)

    def add_campaign(self, campaign):
        """Adds a :class:`Campaign` object to the :attr:`campaigns` collection.

        """
        if self.campaigns is None:
            self.campaigns = Campaigns()
        self.campaigns.append(campaign)

    def add_observable(self, observable):
        """Adds an ``Observable`` object to the :attr:`observables` collection.

        If `observable` is not an ``Observable`` instance, an effort will be
        made to convert it to one.

        """
        if not self.observables:
            self.observables = Observables(observables=observable)
        else:
            self.observables.add(observable)

    def add_incident(self, incident):
        """Adds an :class:`.Incident` object to the :attr:`incidents`
        collection.

        """
        if self.incidents is None:
            self.incidents = Incidents()
        self.incidents.append(incident)

    def add_threat_actor(self, threat_actor):
        """Adds an :class:`.ThreatActor` object to the :attr:`threat_actors`
        collection.

        """
        if self.threat_actors is None:
            self.threat_actors = ThreatActors()
        self.threat_actors.append(threat_actor)

    def add_course_of_action(self, course_of_action):
        """Adds an :class:`.CourseOfAction` object to the
        :attr:`courses_of_action` collection.

        """
        if self.courses_of_action is None:
            self.courses_of_action = CoursesOfAction()
        self.courses_of_action.append(course_of_action)

    def add_exploit_target(self, exploit_target):
        """Adds an :class:`.ExploitTarget` object to the
        :attr:`exploit_targets` collection.

        """
        if self.exploit_targets is None:
            self.exploit_targets = ExploitTargets()
        self.exploit_targets.append(exploit_target)

    def add_ttp(self, ttp):
        """Adds an :class:`.TTP` object to the :attr:`ttps` collection.

        """
        if self.ttps is None:
            self.ttps = TTPs()
        self.ttps.append(ttp)

    def add_related_report(self, related_report):
        """Adds an :class:`.RelatedReport` object to the
        :attr:`related_reports` collection.

        """
        if self.related_reports is None:
            self.related_reports = RelatedReports()
        self.related_reports.append(related_report)

    def add(self, entity):
        """Adds `entity` to a top-level collection. For example, if `entity` is
        an Indicator object, the `entity` will be added to the ``indicators``
        top-level collection.

        """
        if utils.is_cybox(entity):
            self.add_observable(entity)
            return

        tlo_adds = {
            Campaign: self.add_campaign,
            CourseOfAction: self.add_course_of_action,
            ExploitTarget: self.add_exploit_target,
            Incident: self.add_incident,
            Indicator: self.add_indicator,
            ThreatActor: self.add_threat_actor,
            TTP: self.add_ttp,
            Observable: self.add_observable,
        }

        try:
            add = tlo_adds[entity.__class__]
            add(entity)
        except KeyError:
            error = "Cannot add type '{0}' to a top-level collection"
            error = error.format(type(entity))
            raise TypeError(error)