diff --git a/.gitignore b/.gitignore
index 8fcbf60..a04a143 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,8 @@ dist/
*.egg-info
.settings/
.project
+.idea
.pydevproject
+.tox
docs/_build
diff --git a/.landscape.yaml b/.landscape.yaml
new file mode 100644
index 0000000..a923692
--- /dev/null
+++ b/.landscape.yaml
@@ -0,0 +1,3 @@
+ignore-paths:
+ - docs
+ - maec/bindings
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..e99e66d
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,19 @@
+os: linux
+language: python
+cache: pip
+dist: xenial
+python:
+ - "2.7"
+ - "3.4"
+ - "3.5"
+ - "3.6"
+ - "3.7"
+ - "3.8"
+install:
+ - pip install -U pip setuptools
+ - pip install tox-travis
+script:
+ - tox
+notifications:
+ email:
+ - stix-commits-list@groups.mitre.org
diff --git a/CHANGES.txt b/CHANGES.txt
new file mode 100644
index 0000000..6c2de9a
--- /dev/null
+++ b/CHANGES.txt
@@ -0,0 +1,56 @@
+Version 4.1.0.17
+2020-11-16
+- Remove deprecation warning for collections module
+
+Version 4.1.0.16
+2019-09-17
+- [#96] Fix problem when installing from Python 2.7
+
+Version 4.1.0.15
+2019-09-06
+- Update project requirements
+
+Version 4.1.0.14
+2018-08-03
+- Drop support for Python 2.6, 3.3
+- [#91] Don't duplicate Action Collections (@jtschichold)
+- [#93] Handle non-ASCII characters in README (@colbyprior)
+- Various packaging, testing, and other non-functional improvements
+
+Version 4.1.0.13
+2016-08-09
+- Add support for Python 3.3+
+- Use 'mixbox' library for features shared with python-cybox and python-stix.
+- [#76] [#77] Fix typo bugs in bundle.py
+
+Version 4.1.0.12
+2015-04-27
+- Added formal vocabulary support (a la python-stix/cybox)
+- [#69] Updated python-cybox dependency to 2.1.0.11
+
+Version 4.1.0.11
+2015-02-20
+- Fixed a deduplicator logic bug
+- Added relative imports for API classes
+
+Version 4.1.0.10
+2014-12-22
+- Various Unicode-related fixes in the bindings [#32]
+- [#58] Namespace collection
+- [#60] Added support for File-like objects in to_xml_file()
+- Various bug fixes
+
+Version 4.1.0.9
+2014-11-26
+- Added __input_namespaces and __input_schemalocations to Package and Bundle
+- [#58] Added tool exception classes
+- [#57] Expanded custom_header support in to_xml_file()
+- Various bug fixes
+
+Version 4.1.0.8
+2014-10-15
+- Performance enhancements in to_xml() serialization (ref: python-stix #163)
+- Greatly expanded documentation (http://maec.readthedocs.org/en/latest/)
+- Added unit tests
+- [#53] Added script options class
+- Various bug fixes
diff --git a/LICENSE.txt b/LICENSE.txt
index 1ee58c7..a7dd435 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,4 +1,4 @@
-Copyright (c) 2013, The MITRE Corporation
+Copyright (c) 2018, The MITRE Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -8,7 +8,7 @@ modification, are permitted provided that the following conditions are met:
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- * Neither the name of The MITRE Corporation nor the
+ * Neither the name of The MITRE Corporation nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
diff --git a/README.rst b/README.rst
index 8c05c09..2ef5d63 100644
--- a/README.rst
+++ b/README.rst
@@ -1,9 +1,26 @@
python-maec
===========
-A Python library for parsing, manipulating, and generating MAEC content.
+A Python library for parsing, manipulating, and generating `Malware Attribute Enumeration and Characterization (MAEC™) `_ v4.1 content.
+
+:Source: https://github.com/MAECProject/python-maec
+:Documentation: https://maec.readthedocs.io/
+:Information: https://maecproject.github.io/
+:Download: https://pypi.python.org/pypi/maec/
+
+|travis badge| |landscape.io badge| |version badge| |downloads badge|
+
+.. |travis badge| image:: https://api.travis-ci.org/MAECProject/python-maec.svg?branch=master
+ :target: https://travis-ci.org/MAECProject/python-maec
+ :alt: Build Status
+.. |landscape.io badge| image:: https://landscape.io/github/MAECProject/python-maec/master/landscape.svg?style=flat
+ :target: https://landscape.io/github/MAECProject/python-maec/master
+ :alt: Code Health
+.. |Version Badge| image:: https://img.shields.io/pypi/v/maec.svg?maxAge=3600
+ :target: https://pypi.python.org/pypi/maec/
+.. |Downloads Badge| image:: https://img.shields.io/pypi/dm/maec.svg?maxAge=3600
+ :target: https://pypi.python.org/pypi/maec/
-For more information about MAEC, see http://maec.mitre.org.
Overview
--------
@@ -18,7 +35,7 @@ There are currently two levels of APIs for dealing with MAEC content:
- A low-level API is provided by auto-generated XML Schema - Python class
bindings. These bindings were generated using `generateDS
- `_. With these, any CybOX
+ `_. With these, any MAEC
content can be parsed from or written to XML, but requires a bit more
knowledge of the actual MAEC schemas. These "binding classes" are all located
in the ``maec.bindings`` package.
@@ -31,8 +48,8 @@ There are currently two levels of APIs for dealing with MAEC content:
Importing from JSON is also supported.
Compatibility
-----------
-The python-maec library is tested and written against python ``2.7.x``. Compatibility with other python versions is neither guaranteed nor implied.
+-------------
+The python-maec library is tested against Python 2.7 and 3.4+.
Versioning
----------
@@ -45,9 +62,27 @@ to indicate new versions of the python-maec library itself.
Installation
------------
-The ``maec`` package depends on the following Python libraries: \* ``lxml`` >=
-3.1.x \* ``python-cybox`` >= 2.1.x.x \* ``setuptools`` (only if installing
-using setup.py)
+The python-maec library can be installed via the distutils setup.py script
+included at the root directory:
+
+ $ python setup.py install
+
+The python-maec library is also hosted on `PyPI
+`_ and can be installed with `pip
+`_:
+
+ $ pip install maec
+
+Dependencies
+------------
+
+The ``maec`` package depends on the following Python libraries:
+
+* ``lxml``
+
+* ``python-cybox``
+
+* ``setuptools`` (only if installing using setup.py)
For Windows installers of the above libraries, we recommend looking here:
http://www.lfd.uci.edu/~gohlke/pythonlibs. python-cybox can be found at
@@ -56,16 +91,19 @@ https://github.com/CybOXProject/python-cybox/releases.
To build ``lxml`` on Ubuntu, you will need the following packages from the
Ubuntu package repository:
-- python-dev
-- libxml2-dev
-- libxslt1-dev
+* python-dev
+
+* libxml2-dev
+
+* libxslt1-dev
+
+* zlib1g-dev
For more information about installing lxml, see
-http://lxml.de/installation.html
+http://lxml.de/installation.html.
Feedback
--------
Bug reports and feature requests are welcome and encouraged. Pull requests are
-especially appreciated. Feel free to use the issue tracker on GitHub or send an
-email directly to maec@mitre.org.
+especially appreciated. Feel free to use the issue tracker on GitHub, join the `MAEC Community Email Discussion List `_, or send an email directly to maec@mitre.org.
diff --git a/docs/_static/cybox.png b/docs/_static/cybox.png
deleted file mode 100644
index d335a3f..0000000
Binary files a/docs/_static/cybox.png and /dev/null differ
diff --git a/docs/_static/maec.png b/docs/_static/maec.png
deleted file mode 100644
index 04c415f..0000000
Binary files a/docs/_static/maec.png and /dev/null differ
diff --git a/docs/_static/stix.png b/docs/_static/stix.png
deleted file mode 100644
index a3db5cd..0000000
Binary files a/docs/_static/stix.png and /dev/null differ
diff --git a/docs/_static/taxii.png b/docs/_static/taxii.png
deleted file mode 100644
index da095ed..0000000
Binary files a/docs/_static/taxii.png and /dev/null differ
diff --git a/docs/_templates/links.html b/docs/_templates/links.html
deleted file mode 100644
index 307eaab..0000000
--- a/docs/_templates/links.html
+++ /dev/null
@@ -1,9 +0,0 @@
-
-
Related Documentation
-
-
-
-
-
-
-
diff --git a/docs/api/__init__.rst b/docs/api/__init__.rst
new file mode 100644
index 0000000..0f87c0c
--- /dev/null
+++ b/docs/api/__init__.rst
@@ -0,0 +1,15 @@
+:mod:`maec` Module
+==================================
+
+.. module:: maec
+
+Classes
+-------
+
+.. autoclass:: Entity
+ :show-inheritance:
+ :members:
+
+.. autoclass:: EntityList
+ :show-inheritance:
+ :members:
\ No newline at end of file
diff --git a/docs/api/analytics/distance.rst b/docs/api/analytics/distance.rst
new file mode 100644
index 0000000..c638a84
--- /dev/null
+++ b/docs/api/analytics/distance.rst
@@ -0,0 +1,19 @@
+:mod:`maec.analytics.distance` Module
+=====================================
+
+.. module:: maec.analytics.distance
+
+Classes
+-------
+
+.. autoclass:: Distance
+ :show-inheritance:
+ :members:
+
+.. autoclass:: StaticFeatureVector
+ :show-inheritance:
+ :members:
+
+.. autoclass:: DynamicFeatureVector
+ :show-inheritance:
+ :members:
diff --git a/docs/api/bundle/action_reference_list.rst b/docs/api/bundle/action_reference_list.rst
new file mode 100644
index 0000000..d708379
--- /dev/null
+++ b/docs/api/bundle/action_reference_list.rst
@@ -0,0 +1,14 @@
+:mod:`maec.bundle.action_reference_list` Module
+===============================================
+
+.. module:: maec.bundle.action_reference_list
+
+Classes
+-------
+
+.. autoclass:: ActionReferenceList
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/av_classification.rst b/docs/api/bundle/av_classification.rst
new file mode 100644
index 0000000..e226449
--- /dev/null
+++ b/docs/api/bundle/av_classification.rst
@@ -0,0 +1,18 @@
+:mod:`maec.bundle.av_classification` Module
+===========================================
+
+.. module:: maec.bundle.av_classification
+
+Classes
+-------
+
+.. autoclass:: AVClassification
+ :show-inheritance:
+ :members:
+
+.. autoclass:: AVClassifications
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/behavior.rst b/docs/api/bundle/behavior.rst
new file mode 100644
index 0000000..e2b8494
--- /dev/null
+++ b/docs/api/bundle/behavior.rst
@@ -0,0 +1,50 @@
+:mod:`maec.bundle.behavior` Module
+==================================
+
+.. module:: maec.bundle.behavior
+
+Classes
+-------
+
+.. autoclass:: Behavior
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehavioralActionEquivalenceReference
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehavioralActionReference
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehavioralAction
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehavioralActions
+ :show-inheritance:
+ :members:
+
+.. autoclass:: PlatformList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CVEVulnerability
+ :show-inheritance:
+ :members:
+
+.. autoclass:: Exploit
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehaviorPurpose
+ :show-inheritance:
+ :members:
+
+.. autoclass:: AssociatedCode
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/behavior_reference.rst b/docs/api/bundle/behavior_reference.rst
new file mode 100644
index 0000000..42e1622
--- /dev/null
+++ b/docs/api/bundle/behavior_reference.rst
@@ -0,0 +1,14 @@
+:mod:`maec.bundle.behavior_reference` Module
+============================================
+
+.. module:: maec.bundle.behavior_reference
+
+Classes
+-------
+
+.. autoclass:: BehaviorReference
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/bundle.rst b/docs/api/bundle/bundle.rst
new file mode 100644
index 0000000..2355ba0
--- /dev/null
+++ b/docs/api/bundle/bundle.rst
@@ -0,0 +1,67 @@
+:mod:`maec.bundle.bundle` Module
+================================
+
+.. module:: maec.bundle.bundle
+
+Classes
+-------
+
+.. autoclass:: Bundle
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ActionList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehaviorList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BaseCollection
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ActionCollection
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehaviorCollection
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectCollection
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CandidateIndicatorCollection
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehaviorCollectionList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ActionCollectionList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectCollectionList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CandidateIndicatorCollectionList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: Collections
+ :show-inheritance:
+ :members:
+
+.. autoclass:: BehaviorReference
+ :show-inheritance:
+ :members:
diff --git a/docs/api/bundle/bundle_reference.rst b/docs/api/bundle/bundle_reference.rst
new file mode 100644
index 0000000..ccae7c5
--- /dev/null
+++ b/docs/api/bundle/bundle_reference.rst
@@ -0,0 +1,14 @@
+:mod:`maec.bundle.bundle_reference` Module
+==========================================
+
+.. module:: maec.bundle.bundle_reference
+
+Classes
+-------
+
+.. autoclass:: BundleReference
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/candidate_indicator.rst b/docs/api/bundle/candidate_indicator.rst
new file mode 100644
index 0000000..1b9ea2d
--- /dev/null
+++ b/docs/api/bundle/candidate_indicator.rst
@@ -0,0 +1,26 @@
+:mod:`maec.bundle.candidate_indicator` Module
+=============================================
+
+.. module:: maec.bundle.candidate_indicator
+
+Classes
+-------
+
+.. autoclass:: CandidateIndicator
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CandidateIndicatorList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CandidateIndicatorComposition
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareEntity
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/capability.rst b/docs/api/bundle/capability.rst
new file mode 100644
index 0000000..cf98118
--- /dev/null
+++ b/docs/api/bundle/capability.rst
@@ -0,0 +1,42 @@
+:mod:`maec.bundle.capability` Module
+====================================
+
+.. module:: maec.bundle.capability
+
+Classes
+-------
+
+.. autoclass:: Capability
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityObjective
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityProperty
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityRelationship
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityObjectiveRelationship
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityReference
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityObjectiveReference
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapabilityList
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/malware_action.rst b/docs/api/bundle/malware_action.rst
new file mode 100644
index 0000000..8110809
--- /dev/null
+++ b/docs/api/bundle/malware_action.rst
@@ -0,0 +1,30 @@
+:mod:`maec.bundle.malware_action` Module
+========================================
+
+.. module:: maec.bundle.malware_action
+
+Classes
+-------
+
+.. autoclass:: MalwareAction
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ActionImplementation
+ :show-inheritance:
+ :members:
+
+.. autoclass:: APICall
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ParameterList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: Parameter
+ :show-inheritance:
+ :members:
+
+
+
diff --git a/docs/api/bundle/object_history.rst b/docs/api/bundle/object_history.rst
new file mode 100644
index 0000000..d03eb5d
--- /dev/null
+++ b/docs/api/bundle/object_history.rst
@@ -0,0 +1,17 @@
+:mod:`maec.bundle.object_history` Module
+========================================
+
+.. module:: maec.bundle.object_history
+
+Classes
+-------
+
+.. autoclass:: ObjectHistory
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectHistoryEntry
+ :show-inheritance:
+ :members:
+
+
diff --git a/docs/api/bundle/object_reference.rst b/docs/api/bundle/object_reference.rst
new file mode 100644
index 0000000..815f465
--- /dev/null
+++ b/docs/api/bundle/object_reference.rst
@@ -0,0 +1,17 @@
+:mod:`maec.bundle.object_reference` Module
+==========================================
+
+.. module:: maec.bundle.object_reference
+
+Classes
+-------
+
+.. autoclass:: ObjectReference
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectReferenceList
+ :show-inheritance:
+ :members:
+
+
diff --git a/docs/api/bundle/process_tree.rst b/docs/api/bundle/process_tree.rst
new file mode 100644
index 0000000..5e8006f
--- /dev/null
+++ b/docs/api/bundle/process_tree.rst
@@ -0,0 +1,17 @@
+:mod:`maec.bundle.process_tree` Module
+======================================
+
+.. module:: maec.bundle.process_tree
+
+Classes
+-------
+
+.. autoclass:: ProcessTree
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ProcessTreeNode
+ :show-inheritance:
+ :members:
+
+
diff --git a/docs/api/index.rst b/docs/api/index.rst
new file mode 100644
index 0000000..a3cb1eb
--- /dev/null
+++ b/docs/api/index.rst
@@ -0,0 +1,57 @@
+API Documentation
+=================
+
+The *python-maec* APIs are the recommended tools for reading, writing, and manipulating MAEC XML documents.
+
+.. note::
+
+ The python-maec APIs are currently under development. As such, API coverage of MAEC data constructs is incomplete; please bear with us as we work toward complete coverage. This documentation also serves to outline current API coverage.
+
+**MAEC** -- Modules located in the base `maec`_ package
+
+.. _maec: https://github.com/MAECProject/python-maec/tree/master/maec
+
+.. toctree::
+ :titlesonly:
+
+ __init__
+
+**MAEC Bundle** -- Modules located in the `maec.bundle`_ package
+
+.. _maec.bundle: https://github.com/MAECProject/python-maec/tree/master/maec/bundle
+
+.. toctree::
+ :titlesonly:
+ :glob:
+
+ bundle/*
+
+**MAEC Package** -- Modules located in the `maec.package`_ package
+
+.. _maec.package: https://github.com/MAECProject/python-maec/tree/master/maec/package
+
+.. toctree::
+ :titlesonly:
+ :glob:
+
+ package/*
+
+**MAEC Utils** -- Modules located in the `maec.utils`_ package
+
+.. _maec.utils: https://github.com/MAECProject/python-maec/tree/master/maec/utils
+
+.. toctree::
+ :titlesonly:
+ :glob:
+
+ utils/*
+
+**MAEC Analytics** -- Modules located in the `maec.analytics`_ package
+
+.. _maec.analytics: https://github.com/MAECProject/python-maec/tree/master/maec/analytics
+
+.. toctree::
+ :titlesonly:
+ :glob:
+
+ analytics/*
diff --git a/docs/api/package/action_equivalence.rst b/docs/api/package/action_equivalence.rst
new file mode 100644
index 0000000..2371fd9
--- /dev/null
+++ b/docs/api/package/action_equivalence.rst
@@ -0,0 +1,15 @@
+:mod:`maec.package.action_equivalence` Module
+=============================================
+
+.. module:: maec.package.action_equivalence
+
+Classes
+-------
+
+.. autoclass:: ActionEquivalence
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ActionEquivalenceList
+ :show-inheritance:
+ :members:
diff --git a/docs/api/package/analysis.rst b/docs/api/package/analysis.rst
new file mode 100644
index 0000000..8c94c61
--- /dev/null
+++ b/docs/api/package/analysis.rst
@@ -0,0 +1,63 @@
+:mod:`maec.package.analysis` Module
+===================================
+
+.. module:: maec.package.analysis
+
+Classes
+-------
+
+.. autoclass:: Analysis
+ :show-inheritance:
+ :members:
+
+.. autoclass:: AnalysisEnvironment
+ :show-inheritance:
+ :members:
+
+.. autoclass:: NetworkInfrastructure
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapturedProtocolList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CapturedProtocol
+ :show-inheritance:
+ :members:
+
+.. autoclass:: AnalysisSystemList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: AnalysisSystem
+ :show-inheritance:
+ :members:
+
+.. autoclass:: InstalledPrograms
+ :show-inheritance:
+ :members:
+
+.. autoclass:: HypervisorHostSystem
+ :show-inheritance:
+ :members:
+
+.. autoclass:: DynamicAnalysisMetadata
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ToolList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: CommentList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: Comment
+ :show-inheritance:
+ :members:
+
+.. autoclass:: Source
+ :show-inheritance:
+ :members:
diff --git a/docs/api/package/grouping_relationship.rst b/docs/api/package/grouping_relationship.rst
new file mode 100644
index 0000000..a51b1cf
--- /dev/null
+++ b/docs/api/package/grouping_relationship.rst
@@ -0,0 +1,31 @@
+:mod:`maec.package.grouping_relationship` Module
+================================================
+
+.. module:: maec.package.grouping_relationship
+
+Classes
+-------
+
+.. autoclass:: GroupingRelationship
+ :show-inheritance:
+ :members:
+
+.. autoclass:: GroupingRelationshipList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ClusteringMetadata
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ClusteringAlgorithmParameters
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ClusterComposition
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ClusterEdgeNodePair
+ :show-inheritance:
+ :members:
diff --git a/docs/api/package/malware_subject.rst b/docs/api/package/malware_subject.rst
new file mode 100644
index 0000000..03497a6
--- /dev/null
+++ b/docs/api/package/malware_subject.rst
@@ -0,0 +1,67 @@
+:mod:`maec.package.malware_subject` Module
+==========================================
+
+.. module:: maec.package.malware_subject
+
+Classes
+-------
+
+.. autoclass:: MalwareSubject
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareSubjectList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareConfigurationDetails
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareConfigurationObfuscationDetails
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareConfigurationObfuscationAlgorithm
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareConfigurationStorageDetails
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareBinaryConfigurationStorageDetails
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareConfigurationParameter
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareDevelopmentEnvironment
+ :show-inheritance:
+ :members:
+
+.. autoclass:: FindingsBundleList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MetaAnalysis
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareSubjectRelationshipList
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MalwareSubjectRelationship
+ :show-inheritance:
+ :members:
+
+.. autoclass:: Analyses
+ :show-inheritance:
+ :members:
+
+.. autoclass:: MinorVariants
+ :show-inheritance:
+ :members:
diff --git a/docs/api/package/malware_subject_reference.rst b/docs/api/package/malware_subject_reference.rst
new file mode 100644
index 0000000..760da5b
--- /dev/null
+++ b/docs/api/package/malware_subject_reference.rst
@@ -0,0 +1,11 @@
+:mod:`maec.package.malware_subject_reference` Module
+====================================================
+
+.. module:: maec.package.malware_subject_reference
+
+Classes
+-------
+
+.. autoclass:: MalwareSubjectReference
+ :show-inheritance:
+ :members:
diff --git a/docs/api/package/object_equivalence.rst b/docs/api/package/object_equivalence.rst
new file mode 100644
index 0000000..a134a50
--- /dev/null
+++ b/docs/api/package/object_equivalence.rst
@@ -0,0 +1,15 @@
+:mod:`maec.package.object_equivalence` Module
+=============================================
+
+.. module:: maec.package.object_equivalence
+
+Classes
+-------
+
+.. autoclass:: ObjectEquivalence
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectEquivalenceList
+ :show-inheritance:
+ :members:
diff --git a/docs/api/package/package.rst b/docs/api/package/package.rst
new file mode 100644
index 0000000..937f82f
--- /dev/null
+++ b/docs/api/package/package.rst
@@ -0,0 +1,11 @@
+:mod:`maec.package.package` Module
+==================================
+
+.. module:: maec.package.package
+
+Classes
+-------
+
+.. autoclass:: Package
+ :show-inheritance:
+ :members:
diff --git a/docs/api/utils/comparator.rst b/docs/api/utils/comparator.rst
new file mode 100644
index 0000000..efdef77
--- /dev/null
+++ b/docs/api/utils/comparator.rst
@@ -0,0 +1,23 @@
+:mod:`maec.utils.comparator` Module
+===================================
+
+.. module:: maec.utils.comparator
+
+Classes
+-------
+
+.. autoclass:: BundleComparator
+ :show-inheritance:
+ :members:
+
+.. autoclass:: SimilarObjectCluster
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ObjectHash
+ :show-inheritance:
+ :members:
+
+.. autoclass:: ComparisonResult
+ :show-inheritance:
+ :members:
diff --git a/docs/api/utils/deduplicator.rst b/docs/api/utils/deduplicator.rst
new file mode 100644
index 0000000..6dfbfcb
--- /dev/null
+++ b/docs/api/utils/deduplicator.rst
@@ -0,0 +1,11 @@
+:mod:`maec.utils.deduplicator` Module
+=====================================
+
+.. module:: maec.utils.deduplicator
+
+Classes
+-------
+
+.. autoclass:: BundleDeduplicator
+ :show-inheritance:
+ :members:
diff --git a/docs/api/utils/merge.rst b/docs/api/utils/merge.rst
new file mode 100644
index 0000000..b4aa256
--- /dev/null
+++ b/docs/api/utils/merge.rst
@@ -0,0 +1,30 @@
+:mod:`maec.utils.merge` Module
+==============================
+
+.. module:: maec.utils.merge
+
+Functions
+---------
+
+.. autofunction:: merge_documents
+
+.. autofunction:: merge_malware_subjects
+
+.. autofunction:: merge_packages
+
+.. autofunction:: update_relationships
+
+.. autofunction:: merge_binned_malware_subjects
+
+.. autofunction:: create_mappings
+
+.. autofunction:: merge_findings_bundles
+
+.. autofunction:: deduplicate_vocabulary_list
+
+.. autofunction:: merge_entities
+
+.. autofunction:: bin_malware_subjects
+
+.. autofunction:: dict_merge
+
diff --git a/docs/api/utils/parser.rst b/docs/api/utils/parser.rst
new file mode 100644
index 0000000..7ac1be9
--- /dev/null
+++ b/docs/api/utils/parser.rst
@@ -0,0 +1,11 @@
+:mod:`maec.utils.parser` Module
+===============================
+
+.. module:: maec.utils.parser
+
+Classes
+-------
+
+.. autoclass:: EntityParser
+ :show-inheritance:
+ :members:
diff --git a/docs/api_vs_bindings/api_snippet.rst b/docs/api_vs_bindings/api_snippet.rst
new file mode 100644
index 0000000..1c9930f
--- /dev/null
+++ b/docs/api_vs_bindings/api_snippet.rst
@@ -0,0 +1,35 @@
+.. code-block:: python
+
+ # Import the required APIs
+ from maec.bundle import Bundle, MalwareAction
+ from maec.utils import IDGenerator, set_id_method
+ from cybox.core import Object, AssociatedObjects, AssociatedObject
+ from cybox.objects.file_object import File
+ from cybox.common import VocabString
+
+ # Instantiate the MAEC/CybOX Entities
+ set_id_method(IDGenerator.METHOD_INT)
+ b = Bundle()
+ a = MalwareAction()
+ ao = AssociatedObject()
+
+ # Build the Associated Object for use in the Action
+ ao.properties = File()
+ ao.properties.file_name = "badware.exe"
+ ao.properties.size_in_bytes = "123456"
+ ao.association_type = VocabString()
+ ao.association_type.value = 'output'
+ ao.association_type.xsi_type = 'maecVocabs:ActionObjectAssociationTypeVocab-1.0'
+
+ # Build the Action and add the Associated Object to it
+ a.name = VocabString()
+ a.name.value = 'create file'
+ a.name.xsi_type = 'maecVocabs:FileActionNameVocab-1.0'
+ a.associated_objects = AssociatedObjects()
+ a.associated_objects.append(ao)
+
+ # Add the Action to the Bundle
+ b.add_action(a)
+
+ # Output the Bundle to stdout
+ print(b.to_xml(include_namespaces = False))
diff --git a/docs/api_vs_bindings/binding_snippet.rst b/docs/api_vs_bindings/binding_snippet.rst
new file mode 100644
index 0000000..ac978aa
--- /dev/null
+++ b/docs/api_vs_bindings/binding_snippet.rst
@@ -0,0 +1,41 @@
+.. code-block:: python
+
+ import sys
+ # Import the required bindings
+ import maec.bindings.maec_bundle as bundle_binding
+ import cybox.bindings.cybox_core as cybox_core_binding
+ import cybox.bindings.cybox_common as cybox_common_binding
+ import cybox.bindings.file_object as file_binding
+
+ # Instantiate the MAEC/CybOX Entities
+ b = bundle_binding.BundleType(id="bundle-1")
+ a = bundle_binding.MalwareActionType(id="action-1")
+ ao = cybox_core_binding.AssociatedObjectType(id="object-1")
+
+ # Build the Associated Object for use in the Action
+ f = file_binding.FileObjectType()
+ f_name = cybox_common_binding.StringObjectPropertyType(valueOf_="badware.exe")
+ f.set_File_Name(f_name)
+ f_size = cybox_common_binding.UnsignedLongObjectPropertyType(valueOf_="123456")
+ f.set_Size_In_Bytes(f_size)
+ f.set_xsi_type = "FileObj:FileObjectType"
+ ao.set_Properties(f)
+ ao_type = cybox_common_binding.ControlledVocabularyStringType(valueOf_="output")
+ ao_type.set_xsi_type("maecVocabs:ActionObjectAssociationTypeVocab-1.0")
+ ao.set_Association_Type(ao_type)
+
+ # Build the Action and add the Associated Object to it
+ a_name = cybox_common_binding.ControlledVocabularyStringType(valueOf_="create file")
+ a_name.set_xsi_type("maecVocabs:FileActionNameVocab-1.0")
+ a.set_Name(a_name)
+ as_objects = cybox_core_binding.AssociatedObjectsType()
+ as_objects.add_Associated_Object(ao)
+ a.set_Associated_Objects(as_objects)
+
+ # Add the Action to the Bundle
+ action_list = bundle_binding.ActionListType()
+ action_list.add_Action(a)
+ b.set_Actions(action_list)
+
+ # Output the Bundle to stdout
+ b.export(sys.stdout, 0)
\ No newline at end of file
diff --git a/docs/api_vs_bindings/index.rst b/docs/api_vs_bindings/index.rst
new file mode 100644
index 0000000..9472188
--- /dev/null
+++ b/docs/api_vs_bindings/index.rst
@@ -0,0 +1,58 @@
+APIs or bindings?
+=================
+
+This page describes both the **APIs** and the **bindings** provided by the *python-maec* library.
+
+Overview
+--------
+
+The python-maec library provides APIs and utilities that aid in the creation, consumption, and processing of Structured Threat Information eXpression (MAEC) content. The APIs that drive much of the functionality of python-maec sit on top of a binding layer that acts as a direct connection between Python and the MAEC XML. Because both the APIs and the bindings allow for the creation and development of MAEC content, developers that are new to python-maec may not understand the differences between the two. This document aims to identify the purpose and uses of the APIs and bindings.
+
+Bindings
+--------
+
+The python-maec library leverages machine generated XML-to-Python bindings for the creation and processing of MAEC content. These bindings are created using the `generateDS`_ utility and can be found under `maec.bindings`_ within the package hierarchy.
+
+The MAEC bindings allow for a direct, complete mapping between Python classes and MAEC XML Schema data structures. That being said, it is possible (though not advised) to use only the MAEC bindings to create MAEC documents. However, because the code is generated from XML Schema without contextual knowledge of relationships or broader organizational/developmental schemes, it is often a cumbersome and laborious task to create even the simplest of MAEC documents.
+
+Developers within the python-maec team felt that the binding code did not lend itself to rapid development or natural navigation of data, and so it was decided that a higher-level API should be created.
+
+.. _generateDS: http://www.rexx.com/~dkuhlman/generateDS.html
+.. _maec.bindings: https://github.com/MAECProject/python-maec/tree/master/maec/bindings
+
+APIs
+----
+
+The python-maec APIs are classes and utilities that leverage the MAEC bindings for the creation and processing of MAEC content. The APIs are designed to behave more naturally when working with MAEC content, allowing developers to conceptualize and interact with MAEC documents as pure Python objects and not XML Schema objects.
+
+The APIs provide validation of inputs, multiple input and output formats, more Pythonic access of data structure internals and interaction with classes, and better interpretation of a developers intent through datatype coercion and implicit instantiation.
+
+.. note::
+
+ The python-maec APIs are under constant development. Our goal is to provide full API coverage of the MAEC data structures, but not all structures are exposed via the APIs yet. Please refer to the :doc:`../api/index` for API coverage details.
+
+Brevity Wins
+------------
+
+The two code examples show the difference in creating and printing a simple MAEC document consisting of only a MAEC Bundle with a single Malware Action using the python-maec and python-cybox bindings. Both examples will produce the same MAEC XML!
+
+.. container:: side-by-side
+
+ .. container::
+
+ **API Example**
+
+ .. include:: api_snippet.rst
+
+ .. container::
+
+ **Binding Example**
+
+ .. include:: binding_snippet.rst
+
+Feedback
+--------
+
+If there is a problem with the APIs or bindings, or if there is functionality missing from the APIs that forces the use of the bindings, let us know in the `python-maec issue tracker`_
+
+.. _python-maec issue tracker: https://github.com/MAECProject/python-maec/issues
diff --git a/docs/conf.py b/docs/conf.py
index 4751ba7..37ffa6e 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,7 +1,10 @@
+import doctest
+import os
+
import maec
project = u'python-maec'
-copyright = u'2014, The MITRE Corporation'
+copyright = u'2018, The MITRE Corporation'
version = maec.__version__
release = version
@@ -9,54 +12,35 @@
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.ifconfig',
- 'sphinx.ext.intersphinx',
- 'sphinxcontrib.napoleon',
+ 'sphinx.ext.viewcode',
+ 'sphinx.ext.napoleon',
]
-intersphinx_mapping = {'http://docs.python.org/': None}
-
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
rst_prolog = """
-.. warning::
-
- This documentation is still a work in progress. If you have any issues or
- questions, please ask on the maec-discussion mailing list or file a bug
- in our `issue tracker`_.
-
-.. _issue tracker: https://github.com/MAECProject/python-maec/issues
-"""
-
-exclude_patterns = ['_build']
-pygments_style = 'sphinx'
-
-html_theme = 'default'
-html_style = '/default.css'
-html_static_path = ['_static']
-htmlhelp_basename = 'python-maecdoc'
-
-html_theme_options = {
- 'codebgcolor': '#EEE',
- 'footerbgcolor': '#FFF',
- 'footertextcolor': '#114684',
- 'headbgcolor': '#E0DBD2',
- 'headtextcolor': '#F15A22',
- 'headlinkcolor': '#114684',
- 'linkcolor': '#706C60',
- 'relbarbgcolor': '#114684',
- 'relbartextcolor': '#F15A22',
- 'sidebarbgcolor': '#FFF',
- 'sidebarlinkcolor': '#706C60',
- 'sidebartextcolor': '#000',
- 'visitedlinkcolor': '#706C60',
-}
-html_sidebars = {"**": ['localtoc.html', 'relations.html', 'sourcelink.html',
-'searchbox.html', 'links.html']}
+**Version**: {0}
+""".format(release)
+
+exclude_patterns = [
+ '_build',
+ 'api_vs_bindings/*_snippet.rst',
+]
+
+on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
+if not on_rtd:
+ import sphinx_rtd_theme
+ html_theme = 'sphinx_rtd_theme'
+ html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
+else:
+ html_theme = 'default'
latex_elements = {}
latex_documents = [
- ('index', 'python-maec.tex', u'python-maec Documentation',
- u'The MITRE Corporation', 'manual'),
+ ('index', 'python-maec.tex', u'python-maec Documentation',
+ u'The MITRE Corporation', 'manual'),
]
+
+doctest_default_flags = doctest.NORMALIZE_WHITESPACE
\ No newline at end of file
diff --git a/docs/contributing.rst b/docs/contributing.rst
new file mode 100644
index 0000000..4c6da98
--- /dev/null
+++ b/docs/contributing.rst
@@ -0,0 +1,15 @@
+Contributing
+============
+
+If you notice a bug, have a suggestion for a new feature, or find that that
+something just isn't behaving the way you'd expect it to, please submit an
+issue to our `issue tracker`_.
+
+If you'd like to contribute code to our repository, you can do so by issuing a
+pull request and we will work with you to try and integrate that code into our
+repository. Users who want to contribute code to the python-maec repository
+should be familiar with git_ and the `GitHub pull request process`_.
+
+.. _issue tracker: https://github.com/MAECProject/python-maec/issues
+.. _git: http://git-scm.com/documentation
+.. _GitHub pull request process: https://help.github.com/articles/using-pull-requests
diff --git a/docs/examples.rst b/docs/examples.rst
new file mode 100644
index 0000000..43fd8c3
--- /dev/null
+++ b/docs/examples.rst
@@ -0,0 +1,249 @@
+.. _examples:
+
+Examples
+========
+
+This page includes some basic examples of creating and parsing MAEC content.
+
+There are a couple things we do in these examples for purposes of demonstration
+that shouldn't be done in production code:
+
+* When calling ``to_xml()``, we use ``include_namespaces=False``. This is to
+ make the example output easier to read, but means the resulting output
+ cannot be successfully parsed. The XML parser doesn't know what namespaces
+ to use if they aren't included. In production code, you should explicitly
+ set ``include_namespaces`` to ``True`` or omit it entirely (``True`` is the
+ default).
+
+* We use ``set_id_method(IDGenerator.METHOD_INT)`` to make IDs for Malware
+ Subjects and Actions easier to read and cross-reference within the XML
+ document. In production code, you should omit this statement, which causes
+ random UUIDs to be created instead, or create explicit IDs yourself for
+ Malware Subjects and Actions.
+
+Creating Packages
+-----------------
+
+The most commonly used MAEC output format is the MAEC Package, which can contain
+one or more Malware Subjects. Malware Subjects (discussed in more detail below)
+encompass all of the data for a single malware instance, including that from
+different types of analysis.
+
+
+.. testcode::
+
+ from mixbox.idgen import IDGenerator, set_id_method
+ set_id_method(IDGenerator.METHOD_INT)
+
+ from maec.package import Package, MalwareSubject
+
+ p = Package()
+ ms = MalwareSubject()
+ p.add_malware_subject(ms)
+
+ print(p.to_xml(include_namespaces=False, encoding=None))
+
+Which outputs:
+
+.. testoutput::
+
+
+
+
+
+
+
+
+Creating Malware Subjects
+-------------------------
+
+The easiest way to create a Malware Subject is to construct one and then set
+various properties on it. The Malware_Instance_Object_Attributes field on a
+Malware Subject MUST be set in order to identify the particular malware instance
+that it is characterizing.
+
+
+.. testcode::
+
+ from mixbox.idgen import IDGenerator, set_id_method
+ set_id_method(IDGenerator.METHOD_INT)
+
+ from cybox.core import Object
+ from cybox.objects.file_object import File
+ from maec.package import MalwareSubject
+
+ ms = MalwareSubject()
+ ms.malware_instance_object_attributes = Object()
+ ms.malware_instance_object_attributes.properties = File()
+ ms.malware_instance_object_attributes.properties.file_name = "malware.exe"
+ ms.malware_instance_object_attributes.properties.file_path = "C:\Windows\Temp\malware.exe"
+ print(ms.to_xml(include_namespaces=False, encoding=None))
+
+Which outputs:
+
+.. testoutput::
+
+
+
+
+ malware.exe
+ C:\Windows\Temp\malware.exe
+
+
+
+
+Creating Bundles
+----------------
+
+In MAEC, the ``Bundle`` represents a container for capturing the results from a
+particular malware analysis that was performed on a malware instance. While a
+``Bundle`` is most commonly included as part of a Malware Subject, it can also
+be used a standalone output format when only malware analysis results for a
+malware instance wish to be shared. We'll cover both cases here.
+
+Creating Standalone Bundles
+---------------------------
+
+Standalone Bundles function very similarly to Malware Subjects. Therefore, the
+easiest way to create a standalone Bundle is to construct one and then set
+various properties on it. The Malware_Instance_Object_Attributes field on a
+standalone Bundle MUST be set in order to identify the particular malware
+instance that it is characterizing.
+
+.. testcode::
+
+ from mixbox.idgen import IDGenerator, set_id_method
+ set_id_method(IDGenerator.METHOD_INT)
+
+ from cybox.core import Object
+ from cybox.objects.file_object import File
+ from maec.bundle import Bundle
+
+ b = Bundle()
+ b.malware_instance_object_attributes = Object()
+ b.malware_instance_object_attributes.properties = File()
+ b.malware_instance_object_attributes.properties.file_name = "malware.exe"
+ b.malware_instance_object_attributes.properties.file_path = "C:\Windows\Temp\malware.exe"
+
+ print(b.to_xml(include_namespaces=False, encoding=None))
+
+Which outputs:
+
+.. testoutput::
+
+
+
+
+ malware.exe
+ C:\Windows\Temp\malware.exe
+
+
+
+
+Creating and adding Bundles to a Malware Subject
+------------------------------------------------
+
+Bundles in a Malware Subject are defined nearly identically to those of the
+standalone variety, with the sole exception that they do not require their
+Malware_Instance_Object_Attributes field to be set, since this would already
+be defined in their parent Malware Subject.
+
+.. testcode::
+
+ from mixbox.idgen import IDGenerator, set_id_method
+ set_id_method(IDGenerator.METHOD_INT)
+
+ from cybox.core import Object
+ from cybox.objects.file_object import File
+
+ from maec.package import MalwareSubject
+ from maec.bundle import Bundle
+
+ ms = MalwareSubject()
+ ms.malware_instance_object_attributes = Object()
+ ms.malware_instance_object_attributes.properties = File()
+ ms.malware_instance_object_attributes.properties.file_name = "malware.exe"
+ ms.malware_instance_object_attributes.properties.file_path = "C:\Windows\Temp\malware.exe"
+
+ b = Bundle()
+ ms.add_findings_bundle(b)
+
+ print(ms.to_xml(include_namespaces=False, encoding=None))
+
+Which outputs:
+
+.. testoutput::
+
+
+
+
+ malware.exe
+ C:\Windows\Temp\malware.exe
+
+
+
+
+
+
+
+
+Creating and adding Actions to a Bundle
+---------------------------------------
+
+MAEC uses its ``MalwareAction`` to capture the low-level dynamic entities, such
+as API calls or their abstractions, performed by malware. A ``MalwareAction`` is
+stored in a Bundle (either standalone or embedded in a Malware Subject, as
+discussed above). As with the other MAEC entities, the easiest way to use the
+``MalwareAction`` is to instantiate it and then set various properties on it as
+needed.
+
+.. testcode::
+
+ from mixbox.idgen import IDGenerator, set_id_method
+ set_id_method(IDGenerator.METHOD_INT)
+
+ from cybox.core import Object, AssociatedObjects, AssociatedObject
+ from cybox.objects.file_object import File
+ from cybox.common import VocabString
+ from maec.bundle import Bundle
+ from maec.bundle import MalwareAction
+
+ b = Bundle()
+ a = MalwareAction()
+ ao = AssociatedObject()
+
+ ao.properties = File()
+ ao.properties.file_name = "badware.exe"
+ ao.properties.size_in_bytes = "123456"
+ ao.association_type = VocabString()
+ ao.association_type.value = 'output'
+ ao.association_type.xsi_type = 'maecVocabs:ActionObjectAssociationTypeVocab-1.0'
+
+ a.name = VocabString()
+ a.name.value = 'create file'
+ a.name.xsi_type = 'maecVocabs:FileActionNameVocab-1.0'
+ a.associated_objects = AssociatedObjects()
+ a.associated_objects.append(ao)
+
+ b.add_action(a)
+
+ print(b.to_xml(include_namespaces = False, encoding=None))
+
+.. testoutput::
+
+
+
+
+ create file
+
+
+
+ badware.exe
+ 123456
+
+ output
+
+
+
+
+
diff --git a/docs/getting_started.rst b/docs/getting_started.rst
new file mode 100644
index 0000000..069c224
--- /dev/null
+++ b/docs/getting_started.rst
@@ -0,0 +1,72 @@
+Getting Started with python-maec
+=================================
+
+.. note::
+
+ The python-maec library is intended for developers who want to add MAEC
+ support to existing programs or create new programs that handle MAEC
+ content. Experience with Python development is assumed.
+
+ Other users should look at existing tools_ that support MAEC.
+
+ Understanding XML, XML Schema, and the MAEC language is also
+ incredibly helpful when using python-maec in an application.
+
+.. _tools: https://cyboxproject.github.io/#convert
+
+First, you should follow the :ref:`installation` procedures.
+
+Your First MAEC Application
+---------------------------
+
+Once you have installed python-maec, you can begin writing Python applications that consume or create STIX content!
+
+.. note::
+
+ The *python-maec* library provides **bindings** and **APIs**, both of which can be used to parse and write MAEC XML files. For in-depth description of the *APIs, bindings, and the differences between the two*, please refer to :doc:`api_vs_bindings/index`
+
+Creating a MAEC Package
+***********************
+
+.. code-block:: python
+
+ from maec.package import Package # Import the MAEC Package API
+ from maec.package import MalwareSubject # Import the MAEC Malware Subject API
+
+ package = Package() # Create an instance of Package
+ malware_subject = MalwareSubject() # Create an instance of MalwareSubject
+ package.add_malware_subject(malware_subject) # Add the Malware Subject to the Package
+
+ print(package.to_xml()) # Print the XML for this MAEC Package
+
+Parsing MAEC XML
+****************
+
+.. code-block:: python
+
+ import maec # Import the python-maec API
+
+ fn = 'sample_maec_package.xml' # generate by running examples\package_generation_example.py
+ maec_objects = maec.parse_xml_instance(fn) # Parse using the from_xml() method
+ api_object = maec_objects['api'] # Get the API object from the parsed objects
+
+Example Scripts
+---------------
+
+The python-maec repository contains several `example scripts`_ that help
+illustrate the capabilities of the APIs. These scripts are simple command line
+utilities that can be executed by passing the name of the script to a Python
+interpreter.
+
+.. code-block:: bash
+
+ $ python package_generation_example.py
+
+.. _example scripts: https://github.com/MAECProject/python-maec/tree/master/examples
+
+
+Writing Your Own Application
+----------------------------
+
+See the :ref:`examples` page for more examples of using python-maec in your
+own application.
diff --git a/docs/index.rst b/docs/index.rst
index 7ef8ccf..47a49af 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -1,17 +1,53 @@
-.. python-maec documentation master file, created by
- sphinx-quickstart on Thu May 1 10:36:32 2014.
- You can adapt this file completely to your liking, but it should at least
- contain the root `toctree` directive.
-
-Welcome to python-maec's documentation!
-=======================================
-
-Contents:
+python-maec |release| Documentation
+====================================
+
+The python-maec library provides an API for developing and consuming Malware
+Attribute Enumeration and Characterization (MAEC) content. Developers can
+leverage the API to create applications that create, consume, translate, or
+otherwise work with MAEC content.
+
+Versions
+--------
+Each version of python-maec is designed to work with a single version of the
+MAEC Language. The table below shows the latest version the library for each
+version of MAEC.
+
+============ ===================
+MAEC Version python-maec Version
+============ ===================
+4.1 4.1.0.17 (`PyPI`__) (`GitHub`__)
+4.0 4.0.1.0 (`PyPI`__) (`GitHub`__)
+3.0 3.0.0b1 (`PyPI`__) (`GitHub`__)
+============ ===================
+
+__ https://pypi.python.org/pypi/maec/4.1.0.17
+__ https://github.com/MAECProject/python-maec/tree/v4.1.0.17
+__ https://pypi.python.org/pypi/maec/4.0.1.0
+__ https://github.com/MAECProject/python-maec/tree/v4.0.1.0
+__ https://pypi.python.org/pypi/maec/3.0.0b1
+__ https://github.com/MAECProject/python-maec/tree/v3.0.0b1
+
+
+Contents
+--------
.. toctree::
:maxdepth: 2
+ getting_started
+ installation
+ overview
+ examples
+ api_vs_bindings/index
+ contributing
+
+API Reference
+=============
+
+.. toctree::
+ :maxdepth: 1
+ api/index
Indices and tables
==================
diff --git a/docs/installation.rst b/docs/installation.rst
new file mode 100644
index 0000000..910e734
--- /dev/null
+++ b/docs/installation.rst
@@ -0,0 +1,124 @@
+.. _installation:
+
+Installation
+============
+
+The installation of python-maec can be accomplished through a few different workflows.
+
+Recommended Installation
+------------------------
+
+Use pypi_ and pip_:
+
+.. code-block:: bash
+
+ $ pip install maec
+
+You might also want to consider using a virtualenv_.
+Please refer to the `pip installation instructions`_ for details regarding the installation of pip.
+
+.. _pypi: https://pypi.python.org/pypi/MAEC/
+.. _pip: http://pip.readthedocs.org/
+.. _pip installation instructions: http://www.pip-installer.org/en/latest/installing.html
+.. _virtualenv: http://virtualenv.readthedocs.org/
+
+
+Dependencies
+------------
+
+The python-maec library relies on some non-standard Python libraries for the processing of MAEC content. Revisions of python-maec may depend on particular versions of dependencies to function correctly. These versions are detailed within the distutils setup.py installation script.
+
+The following libraries are required to use python-maec:
+
+* lxml_ - A Pythonic binding for the C libraries **libxml2** and
+ **libxslt**.
+* python-cybox_ - A library for consuming and producing CybOX content.
+* python-dateutil_ - A library for parsing datetime information.
+
+Each of these can be installed with ``pip`` or by manually downloading packages
+from PyPI. On Windows, you will probably have the most luck using `pre-compiled
+binaries`_ for ``lxml``. On Ubuntu (12.04 or 14.04), you should make sure the
+following packages are installed before attempting to compile ``lxml`` from
+source:
+
+* libxml2-dev
+* libxslt1-dev
+* zlib1g-dev
+
+.. warning::
+
+ Users have encountered errors with versions of libxml2 (a dependency of
+ lxml) prior to version 2.9.1. The default version of libxml2 provided on
+ Ubuntu 12.04 is currently 2.7.8. Users are encouraged to upgrade libxml2
+ manually if they have any issues. Ubuntu 14.04 provides libxml2 version
+ 2.9.1.
+
+.. _lxml: http://lxml.de/
+.. _python-dateutil: http://labix.org/python-dateutil
+.. _python-cybox: https://github.com/CybOXProject/python-cybox
+.. _pre-compiled binaries: http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml
+
+
+Manual Installation
+-------------------
+
+If you are unable to use pip, you can also install python-maec with setuptools_.
+If you don't already have setuptools installed, please install it before
+continuing.
+
+1. Download and install the dependencies_ above. Although setuptools will
+ generally install dependencies automatically, installing the dependencies
+ manually beforehand helps distinguish errors in dependency installation from
+ errors in MAEC installation. Make sure you check to ensure the
+ versions you install are compatible with the version of MAEC you plan
+ to install.
+
+2. Download the desired version of MAEC from PyPI_ or the GitHub releases_
+ page. The steps below assume you are using the |release| release.
+
+3. Extract the downloaded file. This will leave you with a directory named
+ MAEC-|release|.
+
+.. parsed-literal::
+ $ tar -zxf MAEC-|release|.tar.gz
+ $ ls
+ MAEC-|release| MAEC-|release|.tar.gz
+
+OR
+
+.. parsed-literal::
+ $ unzip MAEC-|release|.zip
+ $ ls
+ MAEC-|release| MAEC-|release|.zip
+
+4. Run the installation script.
+
+.. parsed-literal::
+ $ cd MAEC-|release|
+ $ python setup.py install
+
+5. Test the installation.
+
+.. parsed-literal::
+ $ python
+ Python 2.7.6 (default, Mar 22 2015, 22:59:56)
+ [GCC 4.8.2] on linux2
+ Type "help", "copyright", "credits" or "license" for more information.
+ >>> import MAEC
+ >>>
+
+If you don't see an ``ImportError``, the installation was successful.
+
+.. _setuptools: https://pypi.python.org/pypi/setuptools/
+.. _PyPI: https://pypi.python.org/pypi/MAEC/
+.. _releases: https://github.com/MAECProject/python-maec/releases
+
+
+Further Information
+-------------------
+
+If you're new to installing Python packages, you can learn more at the `Python
+Packaging User Guide`_, specifically the `Installing Python Packages`_ section.
+
+.. _Python Packaging User Guide: http://python-packaging-user-guide.readthedocs.org/
+.. _Installing Python Packages: http://python-packaging-user-guide.readthedocs.org/en/latest/tutorial.html#installing-python-packages
diff --git a/docs/overview.rst b/docs/overview.rst
new file mode 100644
index 0000000..cc7d401
--- /dev/null
+++ b/docs/overview.rst
@@ -0,0 +1,19 @@
+Overview
+========
+
+This page provides a quick overview needed to understand the inner workings
+of the python-maec library. If you prefer a more hands-on approach, browse the
+:doc:`examples`.
+
+MAEC Entities
+--------------
+
+Each type within MAEC is represented by a class which derives from
+:class:`maec.Entity`. In general, there is one Python class per MAEC type,
+though in some cases classes which would have identical functionality have
+been reused rather than writing duplicating classes. One example of this is
+that many enumerated values are implemented using the
+:class:`cybox.common.properties.String`, since values aren't checked to make
+sure they are valid enumeration values.
+
+.. note:: Not all MAEC types have yet been implemented.
diff --git a/examples/comparator_example.py b/examples/comparator_example.py
index e64b48e..cc47c92 100644
--- a/examples/comparator_example.py
+++ b/examples/comparator_example.py
@@ -1,8 +1,8 @@
import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
-from maec.bundle.bundle import Bundle
+from maec.bundle import Bundle
# Matching properties dictionary
-match_on_dictionary = {'FileObjectType': ['full_name'],
+match_on_dictionary = {'FileObjectType': ['file_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexObjectType': ['name']}
# Parse in the input Bundle documents and create their python-maec Bundle class representations
diff --git a/examples/package_generation_example.py b/examples/package_generation_example.py
index b458dc1..9386ae9 100644
--- a/examples/package_generation_example.py
+++ b/examples/package_generation_example.py
@@ -6,20 +6,11 @@
# - A single Capability embedded in the Bundle
from cybox.core import AssociatedObjects, AssociatedObject, Object, AssociationType
-from cybox.common import Hash, HashList
+from cybox.common import Hash, HashList, VocabString
from cybox.objects.file_object import File
-from maec.bundle.bundle import Bundle
-from maec.bundle.malware_action import MalwareAction
-from maec.bundle.capability import Capability
-from maec.package.analysis import Analysis
-from maec.package.malware_subject import MalwareSubject
-from maec.package.package import Package
-from cybox.utils import Namespace
-import maec.utils
+from maec.bundle import Bundle, MalwareAction, Capability
+from maec.package import Analysis, MalwareSubject, Package
-# Instantiate the ID generator class (for automatic ID generation) with our example namespace
-NS = Namespace("http://example.com/", "example")
-maec.utils.set_id_namespace(NS)
# Instantiate the Bundle, Package, MalwareSubject, and Analysis classes
bundle = Bundle(defined_subject=False)
package = Package()
@@ -39,12 +30,13 @@
associated_object.properties = File()
associated_object.properties.file_name = 'abcd.dll'
associated_object.properties.size_in_bytes = '123456'
-associated_object.association_type = AssociationType()
+associated_object.association_type = VocabString()
associated_object.association_type.value = 'output'
associated_object.association_type.xsi_type = 'maecVocabs:ActionObjectAssociationTypeVocab-1.0'
# Create the Action from another dictionary
action = MalwareAction()
-action.name = 'create file'
+action.name = VocabString()
+action.name.value = 'create file'
action.name.xsi_type = 'maecVocabs:FileActionNameVocab-1.0'
action.associated_objects = AssociatedObjects()
action.associated_objects.append(associated_object)
@@ -57,8 +49,9 @@
bundle.add_capability(capability)
# Add the Bundle to the Malware Subject
subject.add_findings_bundle(bundle)
+subject.findings_bundles.bundle = [bundle]
# Add the Malware Subject to the Package
package.add_malware_subject(subject)
# Export the Package Bindings Object to an XML file and use the namespaceparser for writing out the namespace definitions
-package.to_xml_file('sample_maec_package.xml', {"http://example.com/":"example"})
+package.to_xml_file('sample_maec_package.xml')
print "Wrote to sample_maec_package.xml"
diff --git a/examples/package_parsing_example.py b/examples/package_parsing_example.py
index ba7c57e..36cf9cf 100644
--- a/examples/package_parsing_example.py
+++ b/examples/package_parsing_example.py
@@ -13,4 +13,4 @@
# For this example, iterate through the Malware Subjects
# in the input Package, and print the ID of each
for malware_subject in maec_package.malware_subjects:
- print malware_subject.id
\ No newline at end of file
+ print malware_subject.id_
\ No newline at end of file
diff --git a/maec/__init__.py b/maec/__init__.py
index 8b34fd2..2ad2570 100644
--- a/maec/__init__.py
+++ b/maec/__init__.py
@@ -1,259 +1,78 @@
-__version__ = "4.1.0.6"
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
-import collections
-import json
-import inspect
-import maec
-from StringIO import StringIO
-import bindings.maec_bundle as bundle_binding
-import bindings.maec_package as package_binding
-from cybox import Entity as cyboxEntity
-from cybox import TypedField
-from cybox.utils import Namespace
-from maec.utils import maecMETA, EntityParser
-
-def get_xmlns_string(ns_set):
- """Build a string with 'xmlns' definitions for every namespace in ns_set.
-
- Arguments:
- - ns_set: a set (or other iterable) of Namespace objects
- """
- xmlns_format = 'xmlns:{0.prefix}="{0.name}"'
- return "\n\t".join([xmlns_format.format(x) for x in ns_set if x])
+from __future__ import absolute_import
+from mixbox.entities import Entity as cyboxEntity
+from mixbox.entities import EntityList
+from mixbox.namespaces import ( get_xmlns_string,
+ make_namespace_subset_from_uris, get_schemaloc_string, lookup_prefix)
+from mixbox.vendor.six import iteritems, string_types
+import maec
+from maec.utils import flip_dict, EntityParser
-def get_schemaloc_string(ns_set):
- """Build a "schemaLocation" string for every namespace in ns_set.
+from .version import __version__ # noqa
- Arguments:
- - ns_set: a set (or other iterable) of Namespace objects
- """
- schemaloc_format = '{0.name} {0.schema_location}'
- # Only include schemas that have a schema_location defined (for instance,
- # 'xsi' does not.
- return " ".join([schemaloc_format.format(x) for x in ns_set
- if x and x.schema_location])
class Entity(cyboxEntity):
"""Base class for all classes in the MAEC SimpleAPI."""
- # By default (unless a particular subclass states otherwise), try to "cast"
- # invalid objects to the correct class using the constructor. Entity
- # subclasses should either provide a "sane" constructor or set this to
- # False.
- _try_cast = True
-
- def __init__(self):
- self._fields = {}
-
- @classmethod
- def _get_vars(cls):
- var_list = []
- for (name, obj) in inspect.getmembers(cls, inspect.isdatadescriptor):
- if isinstance(obj, TypedField):
- var_list.append(obj)
-
- return var_list
-
- def __eq__(self, other):
- # This fixes some strange behavior where an object isn't equal to
- # itself
- if other is self:
- return True
-
- # I'm not sure about this, if we want to compare exact classes or if
- # various subclasses will also do (I think not), but for now I'm going
- # to assume they must be equal. - GTB
- if self.__class__ != other.__class__:
- return False
-
- var_list = self.__class__._get_vars()
-
- # If there are no TypedFields, assume this class hasn't been
- # "TypedField"-ified, so we don't want these to inadvertently return
- # equal.
- if not var_list:
- return False
-
- for f in var_list:
- if not f.comparable:
- continue
- if getattr(self, f.attr_name) != getattr(other, f.attr_name):
- return False
-
- return True
-
- def __ne__(self, other):
- return not self == other
-
- def to_obj(self):
- """Default implementation of a to_obj function.
-
- Subclasses can override this function."""
-
- entity_obj = self._binding_class()
-
- for field in self.__class__._get_vars():
- val = getattr(self, field.attr_name)
-
- if field.multiple:
- if val:
- val = [x.to_obj() for x in val]
- else:
- val = []
- elif isinstance(val, Entity):
- val = val.to_obj()
-
- setattr(entity_obj, field.name, val)
-
- self._finalize_obj(entity_obj)
-
- return entity_obj
-
- def _finalize_obj(self, entity_obj):
- """Subclasses can define additional items in the binding object.
+ def _ns_to_prefix_input_namespaces(self):
+ """The namespace that are extracted during parse are mapped from
+ namespace prefix to namespace. The serialization code expects a mapping
+ from namespace to prefix.
- `entity_obj` should be modified in place.
"""
- pass
+ input_namespaces = getattr(self, '__input_namespaces__', {})
+ return flip_dict(input_namespaces)
- def to_dict(self):
- """Default implementation of a to_dict function.
+ def to_xml_file(self, file, namespace_dict=None, custom_header=None):
+ """Export an object to an XML file. Only supports Package or Bundle
+ objects at the moment.
- Subclasses can override this function."""
+ Args:
+ file: the name of a file or a file-like object to write the output to.
+ namespace_dict: a dictionary of mappings of additional XML namespaces to
+ prefixes.
+ custom_header: a string, list, or dictionary that represents a custom
+ XML header to be written to the output.
- entity_dict = {}
-
- for field in self.__class__._get_vars():
- val = getattr(self, field.attr_name)
-
-
- if field.multiple:
- if val:
- val = [x.to_dict() for x in val]
- else:
- val = []
- elif isinstance(val, Entity):
- val = val.to_dict()
-
- # Only add non-None objects or non-empty lists
- if val is not None and val != []:
- entity_dict[field.key_name] = val
-
- self._finalize_dict(entity_dict)
-
- return entity_dict
-
- def _finalize_dict(self, entity_dict):
- """Subclasses can define additional items in the dictionary.
-
- `entity_dict` should be modified in place.
"""
- pass
-
- @classmethod
- def from_obj(cls, cls_obj=None):
- if not cls_obj:
- return None
-
- entity = cls()
-
- for field in cls._get_vars():
- val = getattr(cls_obj, field.name)
- if field.type_:
- if field.multiple and val is not None:
- val = [field.type_.from_obj(x) for x in val]
- else:
- val = field.type_.from_obj(val)
- setattr(entity, field.attr_name, val)
-
- return entity
-
- @classmethod
- def from_dict(cls, cls_dict=None):
- if cls_dict is None:
- return None
-
- entity = cls()
-
- # Shortcut if an actual dict is not provided:
- if not isinstance(cls_dict, dict):
- value = cls_dict
- # Call the class's constructor
- try:
- return cls(value)
- except TypeError:
- raise TypeError("Could not instantiate a %s from a %s: %s" %
- (cls, type(value), value))
-
- for field in cls._get_vars():
- val = cls_dict.get(field.key_name)
- if field.type_:
- if issubclass(field.type_, EntityList):
- val = field.type_.from_list(val)
- elif field.multiple:
- if val is not None:
- val = [field.type_.from_dict(x) for x in val]
- else:
- val = []
- else:
- val = field.type_.from_dict(val)
-
- else:
- if field.multiple and not val:
- val = []
- setattr(entity, field.attr_name, val)
-
- return entity
-
- def to_xml(self, include_namespaces=True, namespace_dict=None,
- pretty=True):
- """Export an object as an XML String.
-
- :param include_namespaces: whether to include xmlns and
- xsi:schemaLocation attributes on the root element. Set to true by
- default.
- :type include_namespaces: bool
- :param namespace_dict: mapping of additional XML namespaces to prefixes
- :type namespace_dict: dict
- :param pretty: produce readable (``True``) or compact (``False``)
- output. Default is ``True``
- :type pretty: bool
- """
- namespace_def = ""
-
- if include_namespaces:
- # Update the namespace dictionary with namespaces found upon import
- if namespace_dict and hasattr(self, '__input_namespaces__'):
- namespace_dict.update(self.__input_namespaces__)
- elif not namespace_dict and hasattr(self, '__input_namespaces__'):
- namespace_dict = self.__input_namespaces__
- namespace_def = self._get_namespace_def(namespace_dict)
-
- if not pretty:
- namespace_def = namespace_def.replace('\n\t', ' ')
+ if not namespace_dict:
+ namespace_dict = {}
+ else:
+ # Make a copy so we don't pollute the source
+ namespace_dict = namespace_dict.copy()
- s = StringIO()
- self.to_obj().export(s, 0, namespacedef_=namespace_def,
- pretty_print=pretty)
- return s.getvalue()
-
- def to_xml_file(self, filename, namespace_dict=None):
- """Export an object to an XML file. Only supports Package or Bundle objects at the moment."""
# Update the namespace dictionary with namespaces found upon import
- if namespace_dict and hasattr(self, '__input_namespaces__'):
- namespace_dict.update(self.__input_namespaces__)
- elif not namespace_dict and hasattr(self, '__input_namespaces__'):
- namespace_dict = self.__input_namespaces__
- out_file = open(filename, 'w')
+ input_namespaces = self._ns_to_prefix_input_namespaces()
+ namespace_dict.update(input_namespaces)
+
+ # Check whether we're dealing with a filename or file-like Object
+ if isinstance(file, string_types):
+ out_file = open(file, 'w')
+ else:
+ out_file = file
out_file.write("\n")
- self.to_obj().export(out_file, 0, namespacedef_ = self._get_namespace_def(namespace_dict))
+ # Write out the custom header, if included
+ if isinstance(custom_header, list):
+ out_file.write("", "\\-\\->") + "\n")
+ out_file.write("-->\n")
+ elif isinstance(custom_header, dict):
+ out_file.write("", "\\-\\->")
+ sanitized_value = str(value).replace("-->", "\\-\\->")
+ out_file.write(sanitized_key + ": " + sanitized_value + "\n")
+ out_file.write("-->\n")
+ elif isinstance(custom_header, string_types):
+ out_file.write("", "\\-\\->") + "\n")
+ out_file.write("-->\n")
+ out_file.write(self.to_xml(namespace_dict=namespace_dict))
out_file.close()
-
- def to_json(self):
- """Export an object as a JSON string.
- """
- return json.dumps(self.to_dict())
def _get_namespace_def(self, additional_ns_dict=None):
# copy necessary namespaces
@@ -263,32 +82,23 @@ def _get_namespace_def(self, additional_ns_dict=None):
# if there are any other namepaces, include xsi for "schemaLocation"
# also, include the MAEC default vocabularies schema by default
if namespaces:
- namespaces.update([maecMETA.lookup_prefix('xsi')])
- namespaces.update([maecMETA.lookup_prefix('maecVocabs')])
-
- if namespaces and additional_ns_dict:
- namespace_list = [x.name for x in namespaces if x]
- for ns, prefix in additional_ns_dict.iteritems():
- if ns not in namespace_list:
- namespaces.update([Namespace(ns, prefix)])
-
- if not namespaces:
+ namespaces.add(lookup_prefix('xsi'))
+ namespaces.add(lookup_prefix('maecVocabs'))
+
+ ns_set = make_namespace_subset_from_uris(namespaces)
+ if additional_ns_dict:
+ for ns, prefix in iteritems(additional_ns_dict):
+ ns_set.add_namespace_uri(ns, prefix)
+ else:
return ""
- namespaces = sorted(namespaces, key=str)
-
- return ('\n\t' + get_xmlns_string(namespaces) +
- '\n\txsi:schemaLocation="' + get_schemaloc_string(namespaces) +
- '"')
+ return ('\n\t' + ns_set.get_xmlns_string(sort=True, delim='\n\t') +
+ '\n\t' + ns_set.get_schemaloc_string(sort=True, delim='\n\t'))
def _get_namespaces(self, recurse=True):
- nsset = set()
-
# Get all _namespaces for parent classes
- namespaces = [x._namespace for x in self.__class__.__mro__
- if hasattr(x, '_namespace')]
-
- nsset.update([maecMETA.lookup_namespace(ns) for ns in namespaces])
+ nsset = set(x._namespace for x in self.__class__.__mro__
+ if hasattr(x, '_namespace'))
#In case of recursive relationships, don't process this item twice
self.touched = True
@@ -298,148 +108,20 @@ def _get_namespaces(self, recurse=True):
nsset.update(x._get_namespaces())
del self.touched
- return nsset
-
- def _get_children(self):
- #TODO: eventually everything should be in _fields, not the top level
- # of vars()
- for k, v in vars(self).items() + self._fields.items():
- if isinstance(v, Entity) or isinstance(v, cyboxEntity):
- yield v
- elif isinstance(v, list):
- for item in v:
- if isinstance(item, Entity) or isinstance(item, cyboxEntity):
- yield item
-
- @classmethod
- def istypeof(cls, obj):
- """Check if `cls` is the type of `obj`
-
- In the normal case, as implemented here, a simple isinstance check is
- used. However, there are more complex checks possible. For instance,
- EmailAddress.istypeof(obj) checks if obj is an Address object with
- a category of Address.CAT_EMAIL
- """
- return isinstance(obj, cls)
-
-
-class EntityList(collections.MutableSequence, Entity):
- _contained_type = object
-
- # Don't try to cast list types (yet)
- _try_cast = False
-
- def __init__(self, *args):
- super(EntityList, self).__init__()
- self._inner = []
-
- for arg in args:
- if isinstance(arg, list):
- self.extend(arg)
- else:
- self.append(arg)
-
- def __getitem__(self, key):
- return self._inner.__getitem__(key)
-
- def __setitem__(self, key, value):
- if not self._is_valid(value):
- value = self._fix_value(value)
- self._inner.__setitem__(key, value)
-
- def __delitem__(self, key):
- self._inner.__delitem__(key)
-
- def __len__(self):
- return len(self._inner)
-
- def insert(self, idx, value):
- if not self._is_valid(value):
- value = self._fix_value(value)
- self._inner.insert(idx, value)
-
- def _is_valid(self, value):
- """Check if this is a valid object to add to the list.
+ # Add any additional namespaces that may be included in the entity
+ input_ns = self._ns_to_prefix_input_namespaces()
+ for namespace, alias in iteritems(input_ns):
+ nsset.update(namespace)
- Subclasses can override this function, but it's probably better to
- modify the istypeof function on the _contained_type.
- """
- return self._contained_type.istypeof(value)
-
- def _fix_value(self, value):
- """Attempt to coerce value into the correct type.
-
- Subclasses can override this function.
- """
- try:
- new_value = self._contained_type(value)
- except:
- raise ValueError("Can't put '%s' (%s) into a %s" %
- (value, type(value), self.__class__))
- return new_value
-
- # The next four functions can be overridden, but otherwise define the
- # default behavior for EntityList subclasses which define the following
- # class-level members:
- # - _binding_class
- # - _binding_var
- # - _contained_type
-
- def to_obj(self):
- tmp_list = [x.to_obj() for x in self]
-
- list_obj = self._binding_class()
-
- setattr(list_obj, self._binding_var, tmp_list)
-
- return list_obj
-
- def to_list(self):
- return [h.to_dict() for h in self]
-
- # Alias the `to_list` function as `to_dict`
- to_dict = to_list
-
- @classmethod
- def from_obj(cls, list_obj):
- if not list_obj:
- return None
-
- list_ = cls()
-
- for item in getattr(list_obj, cls._binding_var):
- list_.append(cls._contained_type.from_obj(item))
-
- return list_
-
- @classmethod
- def from_list(cls, list_list):
- if not isinstance(list_list, list):
- return None
-
- list_ = cls()
-
- for item in list_list:
- list_.append(cls._contained_type.from_dict(item))
-
- return list_
-
- @classmethod
- def object_from_list(cls, entitylist_list):
- """Convert from list representation to object representation."""
- return cls.from_list(entitylist_list).to_obj()
+ return nsset
- @classmethod
- def list_from_object(cls, entitylist_obj):
- """Convert from object representation to list representation."""
- return cls.from_obj(entitylist_obj).to_list()
def parse_xml_instance(filename, check_version = True):
"""Parse a MAEC instance and return the correct Binding and API objects
Returns a dictionary of MAEC Package or Bundle Binding/API Objects"""
object_dictionary = {}
entity_parser = EntityParser()
-
+
object_dictionary['binding'] = entity_parser.parse_xml_to_obj(filename, check_version)
object_dictionary['api'] = entity_parser.parse_xml(filename, check_version)
diff --git a/maec/analytics/__init__.py b/maec/analytics/__init__.py
new file mode 100644
index 0000000..1932538
--- /dev/null
+++ b/maec/analytics/__init__.py
@@ -0,0 +1,2 @@
+from .distance import Distance, StaticFeatureVector, DynamicFeatureVector
+from .static_features import static_features_dict
\ No newline at end of file
diff --git a/maec/analytics/distance.py b/maec/analytics/distance.py
new file mode 100644
index 0000000..53609b2
--- /dev/null
+++ b/maec/analytics/distance.py
@@ -0,0 +1,613 @@
+# MAEC Distance Measure-related Classes - BETA
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+# See LICENSE.txt for complete terms
+import sys
+try:
+ import numpy
+except ImportError:
+ sys.stdout.write("Error: unable to import required numpy module.\nSee https://pypi.python.org/pypi/numpy.")
+import os
+import subprocess
+import maec
+import itertools
+import math
+from maec.package.package import Package
+from maec.package.malware_subject import MalwareSubject
+from maec.utils.deduplicator import BundleDeduplicator
+from maec.utils.merge import merge_malware_subjects
+from maec.analytics.static_features import static_features_dict
+
+class DynamicFeatureVector(object):
+ '''Generate a feature vector for a Malware Subject based on its dynamic features'''
+ def __init__(self, malware_subject, deduplicator, ignored_object_properties, ignored_actions):
+ self.deduplicator = deduplicator
+ self.dynamic_features = []
+ self.unique_dynamic_features = []
+ self.ignored_object_properties = ignored_object_properties
+ self.ignored_actions = ignored_actions
+ # Extract the features and build the vector
+ self.extract_features(malware_subject)
+ # Calculate the unique features
+ self.get_unique_features()
+
+ def create_action_vector(self, action):
+ '''Create a vector from a single Action'''
+ action_vector = set()
+ # Add the Action Name to the set
+ if action.name:
+ action_vector.add("act:" + action.name.value)
+ # Add the Object values to the set
+ if action.associated_objects:
+ for associated_object in action.associated_objects:
+ if associated_object.properties:
+ object_vector = self.deduplicator.get_object_values(associated_object)
+ updated_vector = set()
+ for entry in object_vector:
+ updated_vector.add(entry.replace(',', ';').rstrip('\n'))
+ action_vector.update(updated_vector)
+ return action_vector
+
+ def create_dynamic_vectors(self, malware_subject):
+ '''Create a vector of unique action/object pairs for an input Malware Subject'''
+ action_vectors = []
+ # Extract the Bundles from the Malware Subject
+ bundles = malware_subject.get_all_bundles()
+ for bundle in bundles:
+ # Create the vector for each Action
+ all_actions = bundle.get_all_actions()
+ for action in all_actions:
+ action_vector = self.create_action_vector(action)
+ if action_vector:
+ action_vectors.append(action_vector)
+ return action_vectors
+
+ def extract_features(self, malware_subject):
+ '''Extract the dynamic features from the Malware Subject'''
+ # Extract the Dynamic (Action) features
+ self.dynamic_features = self.create_dynamic_vectors(malware_subject)
+ # Prune the Dynamic features
+ self.prune_dynamic_features()
+
+ def prune_dynamic_features(self, min_length = 2):
+ '''Prune the dynamic features based on ignored Object properties/Actions'''
+ pruned_dynamic_features = []
+ for dynamic_vector in self.dynamic_features:
+ ignore_vector = False
+ pruned_vector = set()
+ # Do the minimum length check (to prune Actions with no Objects)
+ if len(dynamic_vector) < min_length:
+ continue
+ # Prune any vectors with ignored actions or object properites
+ for entity in dynamic_vector:
+ split_entity = str(entity).split(':')
+ if split_entity[0] == 'act':
+ action_name = split_entity[1]
+ if action_name in self.ignored_actions:
+ ignore_vector = True
+ break
+ else:
+ pruned_vector.add(entity)
+ elif split_entity[0] in self.ignored_object_properties:
+ continue
+ else:
+ pruned_vector.add(entity)
+ if ignore_vector:
+ continue
+ else:
+ pruned_dynamic_features.append(pruned_vector)
+ # Update the existing dynamic feature with the pruned versions
+ self.dynamic_features = pruned_dynamic_features
+
+ def get_unique_features(self):
+ '''Calculates the unique set of dynamic features for the Malware Subject'''
+ self.unique_dynamic_features = [x for x in self.dynamic_features if self.dynamic_features.count(x) == 1]
+
+class StaticFeatureVector(object):
+ '''Generate a feature vector for a Malware Subject based on its static features'''
+ def __init__(self, malware_subject, deduplicator):
+ self.deduplicator = deduplicator
+ self.static_features = {}
+ self.unique_static_features = {}
+ # Extract the features and build the vector
+ self.extract_features(malware_subject)
+ # Calculate the unique features
+ self.get_unique_features()
+
+ def create_object_vector(self, object, static_feature_dict, callback_function = None):
+ '''Create a vector from a single Object'''
+ object_vector = self.deduplicator.get_object_values(object)
+ for entity_string in object_vector:
+ split_string = entity_string.split(':')
+ feature_path = str(split_string[0])
+ feature_value = str(split_string[1]).lower()
+ # Test if this is a feature that we want to keep
+ if feature_path in static_features_dict.keys():
+ feature_dict = static_features_dict[feature_path]
+ feature_name = feature_dict['feature_name']
+ # Set the key in the object feature dictionary
+ if feature_name in static_feature_dict:
+ # Test if multiple values are allowed for this feature
+ if 'options' in feature_dict and 'allow_multiple' in feature_dict['options']:
+ if isinstance(static_feature_dict[feature_name], list):
+ static_feature_dict[feature_name].append(feature_value)
+ else:
+ static_feature_dict[feature_name] = [static_feature_dict[feature_name], feature_value]
+ # If they're not allowed, use a callback function to determine what to do
+ # E.g., if two different tools report the same value differently, this can be used to resolve that
+ # Callback function parameters : feature name, existing feature value, new feature value
+ elif callback_function:
+ existing_value = static_feature_dict[feature_name]
+ static_feature_dict[feature_name] = callback_function(feature_name, existing_value, feature_value)
+
+ else:
+ static_feature_dict[feature_name] = feature_value
+
+ def create_static_vectors(self, malware_subject):
+ '''Create a vector of static features for an input Malware Subject'''
+ static_feature_dict = {}
+ # Extract any feature from the Malware Instance Object Attributes of the Malware Subject
+ if malware_subject.malware_instance_object_attributes and malware_subject.malware_instance_object_attributes.properties:
+ # Add the properties of the Object to the feature dict
+ self.create_object_vector(malware_subject.malware_instance_object_attributes, static_feature_dict)
+ # Extract any feature from the Bundles in the Malware Subject
+ bundles = malware_subject.get_all_bundles()
+ for bundle in bundles:
+ # Test the Bundle's content_type to make sure we're dealing with static analysis tool output
+ if bundle.content_type and bundle.content_type == 'static analysis tool output':
+ # Extract the Objects from the Bundle
+ for obj in bundle.get_all_objects():
+ if obj.properties:
+ # Add the properties of the Object to the feature dict
+ self.create_object_vector(obj, static_feature_dict)
+ if static_feature_dict:
+ return static_feature_dict
+
+ def extract_features(self, malware_subject):
+ '''Extract the static features from the Malware Subject'''
+ # Extract the Static features
+ self.static_features = self.create_static_vectors(malware_subject)
+
+ def get_unique_features(self):
+ '''Calculates the unique set of static features for the Malware Subject'''
+ self.unique_static_features = {}
+ for feature_name, feature_value in self.static_features.items():
+ # Prune any list-type values
+ if isinstance(feature_value, list):
+ pruned_value_list = []
+ for value in feature_value:
+ if value not in pruned_value_list:
+ pruned_value_list.append(value)
+ self.unique_static_features[feature_name] = pruned_value_list
+ else:
+ self.unique_static_features[feature_name] = feature_value
+
+class Distance(object):
+ '''Calculates distance between two or more MAEC entities.
+ Currently supports only Packages or Malware Subjects.'''
+ def __init__(self, maec_entity_list):
+ self.maec_entity_list = maec_entity_list
+ # Options dictionary
+ # currently available options:
+ # use_dynamic_features : True/False. Use dynamic features (Actions) in the distance calculation.
+ # use_static_features : True/False. Use static features (File/PE attributes) in the distance calculation.
+ self.options_dict = {'use_dynamic_features' : True,
+ 'use_static_features' : True}
+ self.deduplicator = BundleDeduplicator()
+ self.feature_vectors = {}
+ self.superset_dynamic_vectors = []
+ self.superset_static_vectors = {}
+ # A list of normalized/merged Malware Subjects
+ self.normalized_subjects = []
+ # Dictionary of distances
+ # Key = Malware Subject ID
+ # Value = dictionary of distances
+ # key = Malware Subject ID
+ # value = distance
+ self.distances = {}
+ # Dictionary of static features to use in the distance calculation
+ # Also, defines how they should be post-processed/compared
+ # NOTE: The default features here are merely a suggestion!
+ # Options:
+ # datatype = Required. The datatype of the values for the feature.
+ # Possible values: hex, hex list, int, int list, float, float list, string.
+ # normalize = Optional. Normalize/scale the data.
+ # True by default.
+ # scale_log = Optional. Use logarithmic scaling for the list of numeric features.
+ # True by default.
+ # bin = Optional. For numerical features, use bins for the distance measure.
+ # number of bins = Optional. Valid only if bin = true. The number of bins to use in binning.
+ # use_raw_value = Optional. Use the raw value for the field, without any post-processing.
+ # All other options are ignored when this setting is used.
+ self.compared_static_features = {'imported_files' : {'datatype' : 'string'},
+ 'section_entropies' : {'datatype' : 'float list', 'scale log' : False},
+ 'section_virtual_sizes' : {'datatype' : 'hex list','scale log' : False},
+ 'address_of_entry_point' : {'datatype' : 'hex', 'scale log' : False, 'bin' : True},
+ 'size_in_bytes' : {'datatype' : 'int', 'bin' : True},
+ 'size_of_initialized_data' : {'datatype' : 'hex', 'scale log' : False, 'bin' : True, 'number of bins' : 5},
+ 'size_of_image' : {'datatype' : 'hex', 'bin' : True}}
+ # List of ignored object attributes, for use in dynamic vector creation
+ self.ignored_object_properties = ['address',
+ 'hashes/simple_hash_value',
+ 'id_',
+ 'type_',
+ 'pid',
+ 'size_in_bytes']
+ # List of ignored actions (not useful/difficult to correlate on), for use in dynamic vector creation
+ self.ignored_actions = ['map view of section',
+ 'create section',
+ 'create thread',
+ 'open section']
+
+ def bin_list(self, numeric_value, numeric_list, n=10):
+ '''Bin a numeric value into a bucket, based on a parent list of values.
+ N = number of buckets to use (default = 10).'''
+ bin_vector = numpy.array([0] * n)
+ # Sanity checking for lists with a single value
+ if len(numeric_list) == 1:
+ bin_vector = numpy.array([0] * n)
+ bin_vector[n-1] = 1
+ return bin_vector
+ max_list = max(numeric_list)
+ min_list = min(numeric_list)
+ bucket_size = (max_list-min_list)/n
+ bin_value = int(math.floor((numeric_value - min_list)/bucket_size))
+ if bin_value == n:
+ bin_value -= 1
+ bin_vector[bin_value] = 1
+ return bin_vector
+
+ def add_log(self, number, log_list):
+ '''Added a log'd (log-ized??) number to a list'''
+ if number != 0:
+ log_list.append(float(math.log(number)))
+ else:
+ log_list.append(float(number))
+
+ def normalize_numeric(self, numeric_value, numeric_list, normalize = True, scale_log = True):
+ '''Scale a numeric value, based on a parent list of values.
+ Return the scaled/normalized form.'''
+ # Sanity check for zeros
+ if numeric_value == 0:
+ return float(0)
+ if normalize:
+ if scale_log:
+ log_list = []
+ for number in numeric_list:
+ self.add_log(number, log_list)
+ return math.log(float(numeric_value))/max(log_list)
+ else:
+ return float(numeric_value)/max(numeric_list)
+ else:
+ return numeric_value
+
+ def normalize_numeric_list(self, value_list, numeric_list, normalize = True, scale_log = True):
+ '''Scale a list of numeric values, based on a parent list of numeric value lists.
+ Return the scaled/normalized form.'''
+ # Find the maximum length of all of the lists
+ max_len = max(len(p) for p in numeric_list)
+ if normalize:
+ # Find the maximum value in all of the lists
+ max_val = max(max(p) for p in numeric_list)
+ if scale_log:
+ log_list = []
+ for vector_entry in value_list:
+ self.add_log(vector_entry, log_list)
+ # Scale the list
+ scaled_list = [float(x)/math.log(max_val) for x in log_list]
+ scaled_vector = numpy.array(scaled_list)
+ # Resize the vector
+ scaled_vector.resize(max_len, refcheck = False)
+ return scaled_vector
+ else:
+ # Scale the list
+ scaled_list = [float(x)/max_val for x in value_list]
+ scaled_vector = numpy.array(scaled_list)
+ # Resize the vector
+ scaled_vector.resize(max_len, refcheck = False)
+ return scaled_vector
+ else:
+ # Resize the vector
+ return value_list.resize(max_len, refcheck = False)
+
+ def build_string_vector(self, string_list, superset_string_list, ignore_case = True):
+ '''Build a vector from an input list of strings and superset list of strings.'''
+ # Flatten the superset list
+ flattened_string_list = self.flatten_vector(superset_string_list)
+ # List of ignored/skipped strings
+ ignored_strings = ['none']
+ # List of unique strings
+ unique_strings = []
+ # First, build up the unique strings
+ for string in flattened_string_list:
+ normalized_string = string
+ # Ignore case if specified
+ if ignore_case:
+ normalized_string = string.lower()
+ if normalized_string not in ignored_strings and normalized_string not in unique_strings:
+ unique_strings.append(normalized_string)
+ # Next, build the actual strings vector
+ string_vector = numpy.array([0] * len(unique_strings))
+ normalized_string_list = string_list
+ # Ignore case if specified
+ if ignore_case:
+ normalized_string_list = [str(x).lower() for x in string_list]
+ for i in range(0, len(unique_strings)):
+ if unique_strings[i] in normalized_string_list:
+ string_vector[i] = 1
+ else:
+ string_vector[i] = 0
+ return string_vector
+
+ def preprocess_entities(self, dereference = True):
+ '''Pre-process the MAEC entities'''
+ malware_subjects = []
+ # Dereference and normalize the Malware Subjects in the Package
+ for entity in self.maec_entity_list:
+ # Test if we're dealing with a package or Malware Subject
+ if isinstance(entity, Package):
+ action_vectors = []
+ for malware_subject in entity.malware_subjects:
+ # Dereference the Bundles in the Malware Subject
+ if dereference:
+ malware_subject.dereference_bundles()
+ # Normalize the Bundles in the Malware Subject
+ malware_subject.normalize_bundles()
+ # Add the Malware Subject to the list
+ malware_subjects.append(malware_subject)
+ elif isinstance(entity, MalwareSubject):
+ # Dereference the Bundles in the Malware Subject
+ if dereference:
+ entity.dereference_bundles()
+ # Normalize the Bundles in the Malware Subject
+ entity.normalize_bundles()
+ # Add the Malware Subject to the list
+ malware_subjects.append(malware_subject)
+ # Merge the Malware Subjects by hash (if possible)
+ return merge_malware_subjects(malware_subjects)
+
+ def generate_feature_vectors(self, merged_subjects):
+ '''Generate a feature vector for the binned Malware Subjects'''
+ for malware_subject in merged_subjects:
+ feature_vector_dict = {'dynamic' : DynamicFeatureVector(malware_subject, self.deduplicator, self.ignored_object_properties, self.ignored_actions),
+ 'static' : StaticFeatureVector(malware_subject, self.deduplicator)}
+ self.feature_vectors[malware_subject.id_] = feature_vector_dict
+
+ def flatten_vector(self, vector_entry_list):
+ '''Generate a single, flattened vector from an input list of vectors or values.'''
+ component_list = []
+ for vector_entry in vector_entry_list:
+ if isinstance(vector_entry, numpy.ndarray) or isinstance(vector_entry, list):
+ for component in vector_entry:
+ component_list.append(component)
+ else:
+ component_list.append(vector_entry)
+ return component_list
+
+ def normalize_vectors(self, vector_1, vector_2):
+ '''Normalize two input vectors so that they have similar composition.'''
+ for i in range(0, len(vector_1)):
+ if type(vector_1[i]) != type(vector_2[i]):
+ if isinstance(vector_1[i], numpy.ndarray) and not isinstance(vector_2[i], numpy.ndarray):
+ vector_2[i] = numpy.array([0] * len(vector_1[i]))
+ elif not isinstance(vector_1[i], numpy.ndarray) and isinstance(vector_2[i], numpy.ndarray):
+ vector_1[i] = numpy.array([0] * len(vector_2[i]))
+
+ def create_static_result_vector(self, static_vector):
+ '''Construct the static result (matching) vector for a corresponding feature vector'''
+ results_vector = []
+ for feature_name in self.compared_static_features:
+ # Test if we wish to use the feature in the comparison
+ if feature_name in static_vector.unique_static_features:
+ # Get the value of the feature
+ feature_value = static_vector.unique_static_features[feature_name]
+ # Get the options dictionary for the feature
+ feature_options_dict = self.compared_static_features[feature_name]
+ feature_items = self.superset_static_vectors[feature_name]
+ # Check if the raw value setting is specified
+ if 'use_raw_value' in feature_options_dict:
+ results_vector.append(feature_value)
+ continue
+ # Determine if numeric values should be logarithmically scaled - true by default
+ scale_log = True
+ if 'scale log' in feature_options_dict:
+ scale_log = feature_options_dict['scale log']
+ # Determine if numeric values should be normalized - true by default
+ normalize = True
+ if 'normalize' in feature_options_dict:
+ normalize = feature_options_dict['normalize']
+ # Normalize the items for the feature based on the specified datatype
+ # Use this to construct the results vector
+ # Normalize on hex values
+ normalized_value = None
+ if feature_options_dict['datatype'] == 'hex':
+ converted_types = [int(x,0) for x in feature_items]
+ normalized_value = self.normalize_numeric(int(feature_value,0), converted_types, normalize, scale_log)
+ # Normalize on lists of hex values
+ if feature_options_dict['datatype'] == 'hex list':
+ converted_types = [numpy.array([int(x, 0) for x in y]) for y in feature_items]
+ normalized_value = self.normalize_numeric_list(numpy.array([int(x,0) for x in feature_value]), converted_types, normalize, scale_log)
+ # Normalize on int values
+ elif feature_options_dict['datatype'] == 'int':
+ converted_types = [int(x) for x in feature_items]
+ normalized_value = self.normalize_numeric(int(feature_value), converted_types, normalize, scale_log)
+ # Normalize on lists of int values
+ elif feature_options_dict['datatype'] == 'int list':
+ converted_types = [numpy.array([int(x) for x in y]) for y in feature_items]
+ normalized_value = self.normalize_numeric_list(numpy.array([int(x) for x in feature_value]), converted_types, normalize, scale_log)
+ # Normalize on float values
+ elif feature_options_dict['datatype'] == 'float':
+ converted_types = [float(x) for x in feature_items]
+ normalized_value = self.normalize_numeric(float(feature_value), converted_types, normalize, scale_log)
+ # Normalize on lists of float values
+ elif feature_options_dict['datatype'] == 'float list':
+ converted_types = [numpy.array([float(x) for x in y]) for y in feature_items]
+ normalized_value = self.normalize_numeric_list(numpy.array([float(x) for x in feature_value]), converted_types, normalize, scale_log)
+ # Normalize on string values
+ elif feature_options_dict['datatype'] == 'string':
+ string_vector = self.build_string_vector(feature_value, feature_items)
+ results_vector.append(string_vector)
+ # Bin any values, if specified in the options dictionary
+ if 'bin' in feature_options_dict and feature_options_dict['bin']:
+ normalized_items = [self.normalize_numeric(x, converted_types, scale_log) for x in converted_types]
+ if 'number of bins' in feature_options_dict:
+ bin = self.bin_list(normalized_value, normalized_items, feature_options_dict['number of bins'])
+ else:
+ bin = self.bin_list(normalized_value, normalized_items)
+ results_vector.append(bin)
+ elif normalized_value is not None:
+ results_vector.append(normalized_value)
+ else:
+ results_vector.append(0)
+ return results_vector
+
+ def create_dynamic_result_vector(self, dynamic_vector):
+ '''Construct the dynamic result (matching) vector for a corresponding feature vector'''
+ # First, construct the results vector for the dynamic vectors
+ results_vector = numpy.array([0] * len(self.superset_dynamic_vectors))
+ i = 0
+ for vector in self.superset_dynamic_vectors:
+ if vector in dynamic_vector.unique_dynamic_features:
+ results_vector[i] = 1
+ i+= 1
+ return results_vector
+
+ def create_superset_vectors(self):
+ '''Calculate vector supersets from the feature vectors'''
+ for feature_vector_dict in self.feature_vectors.values():
+ dynamic_vector = feature_vector_dict['dynamic']
+ static_vector = feature_vector_dict['static']
+ # Build the superset of dynamic vectors
+ for vector in dynamic_vector.unique_dynamic_features:
+ if vector not in self.superset_dynamic_vectors:
+ self.superset_dynamic_vectors.append(vector)
+ # Build the superset of static vectors
+ for feature_name, feature_value in static_vector.unique_static_features.items():
+ if feature_name not in self.superset_static_vectors:
+ self.superset_static_vectors[feature_name] = [feature_value]
+ else:
+ self.superset_static_vectors[feature_name].append(feature_value)
+
+ def euclidean_distance(self, vector_1, vector_2):
+ '''Calculate the Euclidean distance between two input vectors'''
+ distance = 0.0
+ for i in range(0, len(vector_1)):
+ if isinstance(vector_1[i], float):
+ distance += math.pow(vector_1[i] - vector_2[i], 2)
+ elif isinstance(vector_1[i], numpy.ndarray):
+ for vi in range(0, len(vector_1[i])):
+ distance += math.pow(vector_1[i][vi] - vector_2[i][vi], 2)
+ elif isinstance(vector_1[i], int):
+ if vector_1[i] != vector_2[i]:
+ distance += 1.0
+ elif isinstance(vector_1[i], str):
+ if vector_1[i] != vector_2[i]:
+ distance += 1.0
+ return math.sqrt(distance)
+
+ def populate_hashes_mapping(self, malware_subject_list):
+ '''Populate and return the Malware Subject -> Hashes mapping from an input list of Malware Subjects.'''
+ hashes_mapping = {}
+ for malware_subject in malware_subject_list:
+ mal_inst_obj = malware_subject.malware_instance_object_attributes
+ if mal_inst_obj.properties and mal_inst_obj.properties.hashes:
+ hashes_dict = {}
+ for hash in mal_inst_obj.properties.hashes:
+ type = None
+ value = None
+ if hash.type_:
+ type = hash.type_.value
+ if hash.simple_hash_value:
+ value = hash.simple_hash_value.value
+ elif hash.fuzzy_hash_value:
+ value = hash.fuzzy_hash_value.value
+ if type and value:
+ hashes_dict[str(type).lower()] = str(value).lower()
+ hashes_mapping[malware_subject.id_] = hashes_dict
+ return hashes_mapping
+
+ def perform_calculation(self):
+ '''Perform the actual distance calculation.
+ Store the results in the distances dictionary.'''
+ # Determine the different combinations of Malware Subjects
+ combinations = itertools.combinations(self.feature_vectors, r=2)
+ for combination in combinations:
+ if self.options_dict['use_dynamic_features']:
+ dynamic_vectors = (self.feature_vectors[combination[0]]['dynamic_result'],
+ self.feature_vectors[combination[1]]['dynamic_result'])
+ if self.options_dict['use_static_features']:
+ static_vectors = (self.feature_vectors[combination[0]]['static_result'],
+ self.feature_vectors[combination[1]]['static_result'])
+ # Normalize the static vectors (to make them equal length)
+ self.normalize_vectors(static_vectors[0], static_vectors[1])
+ # Generate the combined vectors if necessary and calculate the distance
+ if self.options_dict['use_dynamic_features'] and self.options_dict['use_static_features']:
+ result_vectors = (numpy.array(list(dynamic_vectors[0]) + self.flatten_vector(static_vectors[0])),
+ numpy.array(list(dynamic_vectors[1]) + self.flatten_vector(static_vectors[1])))
+ elif self.options_dict['use_dynamic_features'] and not self.options_dict['use_static_features']:
+ result_vectors = (numpy.array(list(dynamic_vectors[0])),
+ numpy.array(list(dynamic_vectors[1])))
+ elif not self.options_dict['use_dynamic_features'] and self.options_dict['use_static_features']:
+ result_vectors = (self.flatten_vector(static_vectors[0]),
+ self.flatten_vector(static_vectors[1]))
+ distance = self.euclidean_distance(result_vectors[0], result_vectors[1])
+ # Add the result to the distances dictionary
+ for i in range(0,2):
+ opposite = 1 - i
+ if combination[i] not in self.distances:
+ self.distances[combination[i]] = {combination[opposite] : distance}
+ else:
+ self.distances[combination[i]][combination[opposite]] = distance
+
+ def calculate(self):
+ '''Calculate the distances between the input Malware Subjects.'''
+ # Pre-process and merge the entities
+ self.normalized_subjects = self.preprocess_entities()
+ # Generate the feature vectors for the entities
+ self.generate_feature_vectors(self.normalized_subjects)
+ # Build up the supersets of unique vectors
+ self.create_superset_vectors()
+ # Construct the result vectors
+ for feature_vector_dict in self.feature_vectors.values():
+ if self.options_dict['use_dynamic_features']:
+ # Construct the dynamic result vector
+ feature_vector_dict['dynamic_result'] = self.create_dynamic_result_vector(feature_vector_dict['dynamic'])
+ if self.options_dict['use_static_features']:
+ # Construct the static result vector
+ feature_vector_dict['static_result'] = self.create_static_result_vector(feature_vector_dict['static'])
+ # Perform the actual distance calculation
+ self.perform_calculation()
+
+ def print_distances(self, file_object, default_label = 'md5', delimiter = ','):
+ '''Print the distances between the Malware Subjects in delimited matrix format
+ to a File-like object.
+
+ Try to use the MD5s of the Malware Subjects as the default label.
+ Uses commas as the default delimiter, for CSV-like output.'''
+ hashes_mapping = self.populate_hashes_mapping(self.normalized_subjects)
+ distance_strings = []
+ # Generate the header string and individual distance strings
+ header_string = '' + delimiter
+ for malware_subject in self.normalized_subjects:
+ distance_string = ''
+ hashes = hashes_mapping[malware_subject.id_]
+ if default_label in hashes:
+ distance_string += (hashes[default_label] + delimiter)
+ header_string += (hashes[default_label] + delimiter)
+ else:
+ distance_string += (malware_subject.id_ + delimiter)
+ header_string += (malware_subject.id_ + delimiter)
+ for other_malware_subject in self.normalized_subjects:
+ if malware_subject.id_ == other_malware_subject.id_:
+ distance_string += ('0.0' + delimiter)
+ else:
+ distance_string += (str(self.distances[malware_subject.id_][other_malware_subject.id_])
+ + delimiter)
+ distance_strings.append(distance_string.rstrip(delimiter))
+
+ # Print the header and distance strings
+ file_object.write(header_string.rstrip(delimiter) + "\n")
+ for distance_string in distance_strings:
+ file_object.write(distance_string + "\n")
+ file_object.flush()
diff --git a/maec/analytics/static_features.py b/maec/analytics/static_features.py
new file mode 100644
index 0000000..e95ace8
--- /dev/null
+++ b/maec/analytics/static_features.py
@@ -0,0 +1,78 @@
+# MAEC Static Features List
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+static_features_dict = {'file_name' : {'feature_name' : 'file_name'},
+ 'file_path' : {'feature_name' : 'file_path'},
+ 'size_in_bytes' : {'feature_name' : 'size_in_bytes'},
+ 'file_format' : {'feature_name' : 'file_format'},
+ 'peak_entropy' : {'feature_name' : 'peak_entropy'},
+ 'headers/dos_header/e_cblp' : {'feature_name' : 'e_cblp'},
+ 'headers/dos_header/e_cp' : {'feature_name' : 'e_cp'},
+ 'headers/dos_header/e_crlc' : {'feature_name' : 'e_crlc'},
+ 'headers/dos_header/e_cparhdr' : {'feature_name' : 'e_cparhdr'},
+ 'headers/dos_header/e_minalloc' : {'feature_name' : 'e_minalloc'},
+ 'headers/dos_header/e_maxalloc' : {'feature_name' : 'e_maxalloc'},
+ 'headers/dos_header/e_ss' : {'feature_name' : 'e_ss'},
+ 'headers/dos_header/e_sp' : {'feature_name' : 'e_sp'},
+ 'headers/dos_header/e_csum' : {'feature_name' : 'e_csum'},
+ 'headers/dos_header/e_ip' : {'feature_name' : 'e_ip'},
+ 'headers/dos_header/e_cs' : {'feature_name' : 'e_cs'},
+ 'headers/dos_header/e_lfarlc' : {'feature_name' : 'e_lfarlc'},
+ 'headers/dos_header/e_ovro' : {'feature_name' : 'e_ovro'},
+ 'headers/dos_header/e_oemid' : {'feature_name' : 'e_oemid'},
+ 'headers/dos_header/e_oeminfo' : {'feature_name' : 'e_oeminfo'},
+ 'headers/dos_header/e_lfanew' : {'feature_name' : 'e_lfanew'},
+ 'headers/file_header/machine' : {'feature_name' : 'machine'},
+ 'headers/file_header/number_of_sections' : {'feature_name' : 'number_of_sections'},
+ 'headers/file_header/time_date_stamp' : {'feature_name' : 'time_date_stamp'},
+ 'headers/file_header/pointer_to_symbol_table' : {'feature_name' : 'pointer_to_symbol_table'},
+ 'headers/file_header/number_of_symbols' : {'feature_name' : 'number_of_symbols'},
+ 'headers/file_header/size_of_optional_header' : {'feature_name' : 'size_of_optional_header'},
+ 'headers/optional_header/major_linker_version' : {'feature_name' : 'major_linker_version'},
+ 'headers/optional_header/minor_linker_version' : {'feature_name' : 'minor_linker_version'},
+ 'headers/optional_header/size_of_code' : {'feature_name' : 'size_of_code'},
+ 'headers/optional_header/size_of_initialized_data' : {'feature_name' : 'size_of_initialized_data'},
+ 'headers/optional_header/address_of_entry_point' : {'feature_name' : 'address_of_entry_point'},
+ 'headers/optional_header/base_of_code' : {'feature_name' : 'base_of_code'},
+ 'headers/optional_header/base_of_data' : {'feature_name' : 'base_of_data'},
+ 'headers/optional_header/image_base' : {'feature_name' : 'image_base'},
+ 'headers/optional_header/section_alignment' : {'feature_name' : 'section_alignment'},
+ 'headers/optional_header/file_alignment' : {'feature_name' : 'file_alignment'},
+ 'headers/optional_header/major_os_version' : {'feature_name' : 'major_os_version'},
+ 'headers/optional_header/minor_os_version' : {'feature_name' : 'minor_os_version'},
+ 'headers/optional_header/major_image_version' : {'feature_name' : 'major_image_version'},
+ 'headers/optional_header/minor_image_version' : {'feature_name' : 'minor_image_version'},
+ 'headers/optional_header/major_subsystem_version' : {'feature_name' : 'major_subsystem_version'},
+ 'headers/optional_header/minor_subsystem_version' : {'feature_name' : 'minor_subsystem_version'},
+ 'headers/optional_header/win32_version_value' : {'feature_name' : 'win32_version_value'},
+ 'headers/optional_header/size_of_image' : {'feature_name' : 'size_of_image'},
+ 'headers/optional_header/size_of_headers' : {'feature_name' : 'size_of_headers'},
+ 'headers/optional_header/checksum' : {'feature_name' : 'checksum'},
+ 'headers/optional_header/subsystem' : {'feature_name' : 'subsystem'},
+ 'headers/optional_header/size_of_stack_reserve' : {'feature_name' : 'size_of_stack_reserve'},
+ 'headers/optional_header/size_of_stack_commit' : {'feature_name' : 'size_of_stack_commit'},
+ 'headers/optional_header/size_of_heap_reserve' : {'feature_name' : 'size_of_heap_reserve'},
+ 'headers/optional_header/size_of_heap_commit' : {'feature_name' : 'size_of_heap_commit'},
+ 'headers/optional_header/loader_flags' : {'feature_name' : 'loader_flags'},
+ 'headers/optional_header/number_of_rva_and_sizes' : {'feature_name' : 'number_of_rva_and_sizes'},
+ 'imports/file_name' : {'feature_name' : 'imported_files',
+ 'options' : ['allow_multiple']},
+ 'imports/imported_functions/function_name' : {'feature_name' : 'imported_functions',
+ 'options' : ['allow_multiple']},
+ 'resources/type' : {'feature_name' : 'resource_types',
+ 'options' : ['allow_multiple']},
+ 'resources/name' : {'feature_name' : 'resource_names',
+ 'options' : ['allow_multiple']},
+ 'resources/size' : {'feature_name' : 'resource_sizes',
+ 'options' : ['allow_multiple']},
+ 'resources/language' : {'feature_name' : 'resource_languages',
+ 'options' : ['allow_multiple']},
+ 'sections/section_header/name' : {'feature_name' : 'section_names',
+ 'options' : ['allow_multiple']},
+ 'sections/section_header/virtual_size' : {'feature_name' : 'section_virtual_sizes',
+ 'options' : ['allow_multiple']},
+ 'sections/section_header/virtual_address' : {'feature_name' : 'section_virtual_addresses',
+ 'options' : ['allow_multiple']},
+ 'sections/entropy/value' : {'feature_name' : 'section_entropies',
+ 'options' : ['allow_multiple']}}
\ No newline at end of file
diff --git a/maec/bindings/maec_bundle.py b/maec/bindings/maec_bundle.py
index a293ea5..36af803 100644
--- a/maec/bindings/maec_bundle.py
+++ b/maec/bindings/maec_bundle.py
@@ -1,520 +1,14 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-#
-# Generated Mon Apr 29 08:31:10 2013 by generateDS.py version 2.9a.
-#
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
import sys
-import getopt
-import re as re_
+
+from mixbox.binding_utils import *
from cybox.bindings import cybox_core
from cybox.bindings import cybox_common
from cybox.bindings import code_object
from cybox.bindings import process_object
-import base64
-from datetime import datetime, tzinfo, timedelta
-
-etree_ = None
-Verbose_import_ = False
-( XMLParser_import_none, XMLParser_import_lxml,
- XMLParser_import_elementtree
- ) = range(3)
-XMLParser_import_library = None
-try:
- # lxml
- from lxml import etree as etree_
- XMLParser_import_library = XMLParser_import_lxml
- if Verbose_import_:
- print("running with lxml.etree")
-except ImportError:
- try:
- # cElementTree from Python 2.5+
- import xml.etree.cElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with cElementTree on Python 2.5+")
- except ImportError:
- try:
- # ElementTree from Python 2.5+
- import xml.etree.ElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with ElementTree on Python 2.5+")
- except ImportError:
- try:
- # normal cElementTree install
- import cElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with cElementTree")
- except ImportError:
- try:
- # normal ElementTree install
- import elementtree.ElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with ElementTree")
- except ImportError:
- raise ImportError(
- "Failed to import ElementTree from any known place")
-
-def parsexml_(*args, **kwargs):
- if (XMLParser_import_library == XMLParser_import_lxml and
- 'parser' not in kwargs):
- # Use the lxml ElementTree compatible parser so that, e.g.,
- # we ignore comments.
- kwargs['parser'] = etree_.ETCompatXMLParser(huge_tree=True)
- doc = etree_.parse(*args, **kwargs)
- return doc
-
-#
-# User methods
-#
-# Calls to the methods in these classes are generated by generateDS.py.
-# You can replace these methods by re-implementing the following class
-# in a module named generatedssuper.py.
-
-try:
- from generatedssuper import GeneratedsSuper
-except ImportError, exp:
-
- class GeneratedsSuper(object):
- tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
- class _FixedOffsetTZ(tzinfo):
- def __init__(self, offset, name):
- self.__offset = timedelta(minutes = offset)
- self.__name = name
- def utcoffset(self, dt):
- return self.__offset
- def tzname(self, dt):
- return self.__name
- def dst(self, dt):
- return None
- def gds_format_string(self, input_data, input_name=''):
- return input_data
- def gds_validate_string(self, input_data, node, input_name=''):
- return input_data
- def gds_format_base64(self, input_data, input_name=''):
- return base64.b64encode(input_data)
- def gds_validate_base64(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer(self, input_data, input_name=''):
- return '%d' % input_data
- def gds_validate_integer(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_integer_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of integers')
- return input_data
- def gds_format_float(self, input_data, input_name=''):
- return '%f' % input_data
- def gds_validate_float(self, input_data, node, input_name=''):
- return input_data
- def gds_format_float_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_float_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of floats')
- return input_data
- def gds_format_double(self, input_data, input_name=''):
- return '%e' % input_data
- def gds_validate_double(self, input_data, node, input_name=''):
- return input_data
- def gds_format_double_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_double_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of doubles')
- return input_data
- def gds_format_boolean(self, input_data, input_name=''):
- return ('%s' % input_data).lower()
- def gds_validate_boolean(self, input_data, node, input_name=''):
- return input_data
- def gds_format_boolean_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_boolean_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- if value not in ('true', '1', 'false', '0', ):
- raise_parse_error(node,
- 'Requires sequence of booleans '
- '("true", "1", "false", "0")')
- return input_data
- def gds_validate_datetime(self, input_data, node, input_name=''):
- return input_data
- def gds_format_datetime(self, input_data, input_name=''):
- if input_data.microsecond == 0:
- _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S')
- else:
- _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S.%f')
- if input_data.tzinfo is not None:
- tzoff = input_data.tzinfo.utcoffset(input_data)
- if tzoff is not None:
- total_seconds = tzoff.seconds + (86400 * tzoff.days)
- if total_seconds == 0:
- _svalue += 'Z'
- else:
- if total_seconds < 0:
- _svalue += '-'
- total_seconds *= -1
- else:
- _svalue += '+'
- hours = total_seconds // 3600
- minutes = (total_seconds - (hours * 3600)) // 60
- _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
- return _svalue
- def gds_parse_datetime(self, input_data, node, input_name=''):
- tz = None
- if input_data[-1] == 'Z':
- tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
- input_data = input_data[:-1]
- else:
- results = GeneratedsSuper.tzoff_pattern.search(input_data)
- if results is not None:
- tzoff_parts = results.group(2).split(':')
- tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
- if results.group(1) == '-':
- tzoff *= -1
- tz = GeneratedsSuper._FixedOffsetTZ(
- tzoff, results.group(0))
- input_data = input_data[:-6]
- if len(input_data.split('.')) > 1:
- dt = datetime.strptime(
- input_data, '%Y-%m-%dT%H:%M:%S.%f')
- else:
- dt = datetime.strptime(
- input_data, '%Y-%m-%dT%H:%M:%S')
- return dt.replace(tzinfo = tz)
-
- def gds_validate_date(self, input_data, node, input_name=''):
- return input_data
- def gds_format_date(self, input_data, input_name=''):
- _svalue = input_data.strftime('%Y-%m-%d')
- if input_data.tzinfo is not None:
- tzoff = input_data.tzinfo.utcoffset(input_data)
- if tzoff is not None:
- total_seconds = tzoff.seconds + (86400 * tzoff.days)
- if total_seconds == 0:
- _svalue += 'Z'
- else:
- if total_seconds < 0:
- _svalue += '-'
- total_seconds *= -1
- else:
- _svalue += '+'
- hours = total_seconds // 3600
- minutes = (total_seconds - (hours * 3600)) // 60
- _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
- return _svalue
- def gds_parse_date(self, input_data, node, input_name=''):
- tz = None
- if input_data[-1] == 'Z':
- tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
- input_data = input_data[:-1]
- else:
- results = GeneratedsSuper.tzoff_pattern.search(input_data)
- if results is not None:
- tzoff_parts = results.group(2).split(':')
- tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
- if results.group(1) == '-':
- tzoff *= -1
- tz = GeneratedsSuper._FixedOffsetTZ(
- tzoff, results.group(0))
- input_data = input_data[:-6]
- return datetime.strptime(input_data,
- '%Y-%m-%d').replace(tzinfo = tz)
- def gds_str_lower(self, instring):
- return instring.lower()
- def get_path_(self, node):
- path_list = []
- self.get_path_list_(node, path_list)
- path_list.reverse()
- path = '/'.join(path_list)
- return path
- Tag_strip_pattern_ = re_.compile(r'\{.*\}')
- def get_path_list_(self, node, path_list):
- if node is None:
- return
- tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
- if tag:
- path_list.append(tag)
- self.get_path_list_(node.getparent(), path_list)
- def get_class_obj_(self, node, default_class=None):
- class_obj1 = default_class
- if 'xsi' in node.nsmap:
- classname = node.get('{%s}type' % node.nsmap['xsi'])
- if classname is not None:
- names = classname.split(':')
- if len(names) == 2:
- classname = names[1]
- class_obj2 = globals().get(classname)
- if class_obj2 is not None:
- class_obj1 = class_obj2
- return class_obj1
- def gds_build_any(self, node, type_name=None):
- return None
-
-
-#
-# If you have installed IPython you can uncomment and use the following.
-# IPython is available from http://ipython.scipy.org/.
-#
-
-## from IPython.Shell import IPShellEmbed
-## args = ''
-## ipshell = IPShellEmbed(args,
-## banner = 'Dropping into IPython',
-## exit_msg = 'Leaving Interpreter, back to program.')
-
-# Then use the following line where and when you want to drop into the
-# IPython shell:
-# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit')
-
-#
-# Globals
-#
-
-ExternalEncoding = 'utf-8'
-Tag_pattern_ = re_.compile(r'({.*})?(.*)')
-String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
-Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
-
-#
-# Support/utility functions.
-#
-
-def showIndent(outfile, level, pretty_print=True):
- if pretty_print:
- for idx in range(level):
- outfile.write(' ')
-
-def quote_xml(inStr):
- if not inStr:
- return ''
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- return unicode(s1)
-
-def quote_attrib(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- if '"' in s1:
- if "'" in s1:
- s1 = '"%s"' % s1.replace('"', """)
- else:
- s1 = "'%s'" % s1
- else:
- s1 = '"%s"' % s1
- return unicode(s1)
-
-def quote_python(inStr):
- s1 = inStr
- if s1.find("'") == -1:
- if s1.find('\n') == -1:
- return "'%s'" % s1
- else:
- return "'''%s'''" % s1
- else:
- if s1.find('"') != -1:
- s1 = s1.replace('"', '\\"')
- if s1.find('\n') == -1:
- return '"%s"' % s1
- else:
- return '"""%s"""' % s1
-
-def get_all_text_(node):
- if node.text is not None:
- text = node.text
- else:
- text = ''
- for child in node:
- if child.tail is not None:
- text += child.tail
- return text
-
-def find_attr_value_(attr_name, node):
- attrs = node.attrib
- attr_parts = attr_name.split(':')
- value = None
- if len(attr_parts) == 1:
- value = attrs.get(attr_name)
- elif len(attr_parts) == 2:
- prefix, name = attr_parts
- namespace = node.nsmap.get(prefix)
- if namespace is not None:
- value = attrs.get('{%s}%s' % (namespace, name, ))
- return value
-
-
-class GDSParseError(Exception):
- pass
-
-def raise_parse_error(node, msg):
- if XMLParser_import_library == XMLParser_import_lxml:
- msg = '%s (element %s/line %d)' % (
- msg, node.tag, node.sourceline, )
- else:
- msg = '%s (element %s)' % (msg, node.tag, )
- raise GDSParseError(msg)
-
-
-class MixedContainer:
- # Constants for category:
- CategoryNone = 0
- CategoryText = 1
- CategorySimple = 2
- CategoryComplex = 3
- # Constants for content_type:
- TypeNone = 0
- TypeText = 1
- TypeString = 2
- TypeInteger = 3
- TypeFloat = 4
- TypeDecimal = 5
- TypeDouble = 6
- TypeBoolean = 7
- TypeBase64 = 8
- def __init__(self, category, content_type, name, value):
- self.category = category
- self.content_type = content_type
- self.name = name
- self.value = value
- def getCategory(self):
- return self.category
- def getContenttype(self, content_type):
- return self.content_type
- def getValue(self):
- return self.value
- def getName(self):
- return self.name
- def export(self, outfile, level, name, namespace, pretty_print=True):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- outfile.write(self.value)
- elif self.category == MixedContainer.CategorySimple:
- self.exportSimple(outfile, level, name)
- else: # category == MixedContainer.CategoryComplex
- self.value.export(outfile, level, namespace, name, pretty_print)
- def exportSimple(self, outfile, level, name):
- if self.content_type == MixedContainer.TypeString:
- outfile.write('<%s>%s%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeInteger or \
- self.content_type == MixedContainer.TypeBoolean:
- outfile.write('<%s>%d%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeFloat or \
- self.content_type == MixedContainer.TypeDecimal:
- outfile.write('<%s>%f%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeDouble:
- outfile.write('<%s>%g%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeBase64:
- outfile.write('<%s>%s%s>' %
- (self.name, base64.b64encode(self.value), self.name))
- def to_etree(self, element):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- if len(element) > 0:
- if element[-1].tail is None:
- element[-1].tail = self.value
- else:
- element[-1].tail += self.value
- else:
- if element.text is None:
- element.text = self.value
- else:
- element.text += self.value
- elif self.category == MixedContainer.CategorySimple:
- subelement = etree_.SubElement(element, '%s' % self.name)
- subelement.text = self.to_etree_simple()
- else: # category == MixedContainer.CategoryComplex
- self.value.to_etree(element)
- def to_etree_simple(self):
- if self.content_type == MixedContainer.TypeString:
- text = self.value
- elif (self.content_type == MixedContainer.TypeInteger or
- self.content_type == MixedContainer.TypeBoolean):
- text = '%d' % self.value
- elif (self.content_type == MixedContainer.TypeFloat or
- self.content_type == MixedContainer.TypeDecimal):
- text = '%f' % self.value
- elif self.content_type == MixedContainer.TypeDouble:
- text = '%g' % self.value
- elif self.content_type == MixedContainer.TypeBase64:
- text = '%s' % base64.b64encode(self.value)
- return text
- def exportLiteral(self, outfile, level, name):
- if self.category == MixedContainer.CategoryText:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
- % (self.category, self.content_type, self.name, self.value))
- elif self.category == MixedContainer.CategorySimple:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
- % (self.category, self.content_type, self.name, self.value))
- else: # category == MixedContainer.CategoryComplex
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
- (self.category, self.content_type, self.name,))
- self.value.exportLiteral(outfile, level + 1)
- showIndent(outfile, level)
- outfile.write(')\n')
-
-
-class MemberSpec_(object):
- def __init__(self, name='', data_type='', container=0):
- self.name = name
- self.data_type = data_type
- self.container = container
- def set_name(self, name): self.name = name
- def get_name(self): return self.name
- def set_data_type(self, data_type): self.data_type = data_type
- def get_data_type_chain(self): return self.data_type
- def get_data_type(self):
- if isinstance(self.data_type, list):
- if len(self.data_type) > 0:
- return self.data_type[-1]
- else:
- return 'xs:string'
- else:
- return self.data_type
- def set_container(self, container): self.container = container
- def get_container(self): return self.container
-
-def _cast(typ, value):
- if typ is None or value is None:
- return value
- return typ(value)
-
-#
-# Data representation classes.
-#
class BehaviorType(GeneratedsSuper):
"""The BehaviorType is one of the foundational MAEC types, and serves
@@ -587,101 +81,55 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorType'):
if self.status is not None and 'status' not in already_processed:
already_processed.add('status')
- outfile.write(' status=%s' % (quote_attrib(self.status), ))
+ write(' status=%s' % (quote_attrib(self.status), ))
if self.duration is not None and 'duration' not in already_processed:
already_processed.add('duration')
- outfile.write(' duration=%s' % (self.gds_format_string(quote_attrib(self.duration).encode(ExternalEncoding), input_name='duration'), ))
+ write(' duration=%s' % (quote_attrib(self.duration)))
if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
already_processed.add('ordinal_position')
- outfile.write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
+ write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorType', fromsubclass_=False, pretty_print=True):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Purpose is not None:
- self.Purpose.export(outfile, level, 'maecBundle:', name_='Purpose', pretty_print=pretty_print)
+ self.Purpose.export(write, level, 'maecBundle:', name_='Purpose', pretty_print=pretty_print)
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
if self.Discovery_Method is not None:
- self.Discovery_Method.export(outfile, level, 'maecBundle:', name_='Discovery_Method', pretty_print=pretty_print)
+ self.Discovery_Method.export(write, level, 'maecBundle:', name_='Discovery_Method', pretty_print=pretty_print)
if self.Action_Composition is not None:
- self.Action_Composition.export(outfile, level, 'maecBundle:', name_='Action_Composition', pretty_print=pretty_print)
+ self.Action_Composition.export(write, level, 'maecBundle:', name_='Action_Composition', pretty_print=pretty_print)
if self.Associated_Code is not None:
- self.Associated_Code.export(outfile, level, 'maecBundle:', name_='Associated_Code', pretty_print=pretty_print)
+ self.Associated_Code.export(write, level, 'maecBundle:', name_='Associated_Code', pretty_print=pretty_print)
if self.Relationships is not None:
- self.Relationships.export(outfile, level, 'maecBundle:', name_='Relationships', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.status is not None and 'status' not in already_processed:
- already_processed.add('status')
- showIndent(outfile, level)
- outfile.write('status = %s,\n' % (self.status,))
- if self.duration is not None and 'duration' not in already_processed:
- already_processed.add('duration')
- showIndent(outfile, level)
- outfile.write('duration = "%s",\n' % (self.duration,))
- if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
- already_processed.add('ordinal_position')
- showIndent(outfile, level)
- outfile.write('ordinal_position = %d,\n' % (self.ordinal_position,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Purpose is not None:
- outfile.write('Purpose=model_.BehaviorPurposeType(\n')
- self.Purpose.exportLiteral(outfile, level, name_='Purpose')
- outfile.write('),\n')
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
- if self.Discovery_Method is not None:
- outfile.write('Discovery_Method=model_.cybox_common.MeasureSourceType(\n')
- self.Discovery_Method.exportLiteral(outfile, level, name_='Discovery_Method')
- outfile.write('),\n')
- if self.Action_Composition is not None:
- outfile.write('Action_Composition=model_.BehavioralActionsType(\n')
- self.Action_Composition.exportLiteral(outfile, level, name_='Action_Composition')
- outfile.write('),\n')
- if self.Associated_Code is not None:
- outfile.write('Associated_Code=model_.AssociatedCodeType(\n')
- self.Associated_Code.exportLiteral(outfile, level, name_='Associated_Code')
- outfile.write('),\n')
- if self.Relationships is not None:
- outfile.write('Relationships=model_.BehaviorRelationshipListType(\n')
- self.Relationships.exportLiteral(outfile, level, name_='Relationships')
- outfile.write('),\n')
+ self.Relationships.export(write, level, 'maecBundle:', name_='Relationships', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -701,7 +149,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('ordinal_position')
try:
self.ordinal_position = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.ordinal_position <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -820,126 +268,63 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='MAEC_Bundle', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='MAEC_Bundle', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MAEC_Bundle')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MAEC_Bundle')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='MAEC_Bundle'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='MAEC_Bundle'):
if self.defined_subject is not None and 'defined_subject' not in already_processed:
already_processed.add('defined_subject')
- outfile.write(' defined_subject="%s"' % self.gds_format_boolean(self.defined_subject, input_name='defined_subject'))
+ write(' defined_subject="%s"' % self.gds_format_boolean(self.defined_subject, input_name='defined_subject'))
if self.content_type is not None and 'content_type' not in already_processed:
already_processed.add('content_type')
- outfile.write(' content_type=%s' % (quote_attrib(self.content_type), ))
+ write(' content_type=%s' % (quote_attrib(self.content_type), ))
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
+ write(' id=%s' % (quote_attrib(self.id), ))
if self.schema_version is not None and 'schema_version' not in already_processed:
already_processed.add('schema_version')
- outfile.write(' schema_version=%s' % (self.gds_format_string(quote_attrib(self.schema_version).encode(ExternalEncoding), input_name='schema_version'), ))
+ write(' schema_version=%s' % (quote_attrib(self.schema_version)))
if self.timestamp is not None and 'timestamp' not in already_processed:
already_processed.add('timestamp')
- outfile.write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='MAEC_Bundle', fromsubclass_=False, pretty_print=True):
+ write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='MAEC_Bundle', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Malware_Instance_Object_Attributes is not None:
- self.Malware_Instance_Object_Attributes.export(outfile, level, 'maecBundle:', name_='Malware_Instance_Object_Attributes', pretty_print=pretty_print)
- if self.AV_Classifications is not None:
- self.AV_Classifications.export(outfile, level, 'maecBundle:', name_='AV_Classifications', pretty_print=pretty_print)
- if self.Process_Tree is not None:
- self.Process_Tree.export(outfile, level, 'maecBundle:', name_='Process_Tree', pretty_print=pretty_print)
- if self.Capabilities is not None:
- self.Capabilities.export(outfile, level, 'maecBundle:', name_='Capabilities', pretty_print=pretty_print)
- if self.Behaviors is not None:
- self.Behaviors.export(outfile, level, 'maecBundle:', name_='Behaviors', pretty_print=pretty_print)
- if self.Actions is not None:
- self.Actions.export(outfile, level, 'maecBundle:', name_='Actions', pretty_print=pretty_print)
- if self.Objects is not None:
- self.Objects.export(outfile, level, 'maecBundle:', name_='Objects', pretty_print=pretty_print)
- if self.Candidate_Indicators is not None:
- self.Candidate_Indicators.export(outfile, level, 'maecBundle:', name_='Candidate_Indicators', pretty_print=pretty_print)
- if self.Collections is not None:
- self.Collections.export(outfile, level, 'maecBundle:', name_='Collections', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MAEC_Bundle'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.defined_subject is not None and 'defined_subject' not in already_processed:
- already_processed.add('defined_subject')
- showIndent(outfile, level)
- outfile.write('defined_subject = %s,\n' % (self.defined_subject,))
- if self.content_type is not None and 'content_type' not in already_processed:
- already_processed.add('content_type')
- showIndent(outfile, level)
- outfile.write('content_type = %s,\n' % (self.content_type,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- if self.schema_version is not None and 'schema_version' not in already_processed:
- already_processed.add('schema_version')
- showIndent(outfile, level)
- outfile.write('schema_version = "%s",\n' % (self.schema_version,))
- if self.timestamp is not None and 'timestamp' not in already_processed:
- already_processed.add('timestamp')
- showIndent(outfile, level)
- outfile.write('timestamp = "%s",\n' % (self.timestamp,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Malware_Instance_Object_Attributes is not None:
- outfile.write('Malware_Instance_Object_Attributes=model_.cybox_core.ObjectType(\n')
- self.Malware_Instance_Object_Attributes.exportLiteral(outfile, level, name_='Malware_Instance_Object_Attributes')
- outfile.write('),\n')
+ self.Malware_Instance_Object_Attributes.export(write, level, 'maecBundle:', name_='Malware_Instance_Object_Attributes', pretty_print=pretty_print)
if self.AV_Classifications is not None:
- outfile.write('AV_Classifications=model_.AVClassificationsType(\n')
- self.AV_Classifications.exportLiteral(outfile, level, name_='AV_Classifications')
- outfile.write('),\n')
+ self.AV_Classifications.export(write, level, 'maecBundle:', name_='AV_Classifications', pretty_print=pretty_print)
if self.Process_Tree is not None:
- outfile.write('Process_Tree=model_.ProcessTreeType(\n')
- self.Process_Tree.exportLiteral(outfile, level, name_='Process_Tree')
- outfile.write('),\n')
+ self.Process_Tree.export(write, level, 'maecBundle:', name_='Process_Tree', pretty_print=pretty_print)
if self.Capabilities is not None:
- outfile.write('Capabilities=model_.CapabilityListType(\n')
- self.Capabilities.exportLiteral(outfile, level, name_='Capabilities')
- outfile.write('),\n')
+ self.Capabilities.export(write, level, 'maecBundle:', name_='Capabilities', pretty_print=pretty_print)
if self.Behaviors is not None:
- outfile.write('Behaviors=model_.BehaviorListType(\n')
- self.Behaviors.exportLiteral(outfile, level, name_='Behaviors')
- outfile.write('),\n')
+ self.Behaviors.export(write, level, 'maecBundle:', name_='Behaviors', pretty_print=pretty_print)
if self.Actions is not None:
- outfile.write('Actions=model_.ActionListType(\n')
- self.Actions.exportLiteral(outfile, level, name_='Actions')
- outfile.write('),\n')
+ self.Actions.export(write, level, 'maecBundle:', name_='Actions', pretty_print=pretty_print)
if self.Objects is not None:
- outfile.write('Objects=model_.ObjectListType(\n')
- self.Objects.exportLiteral(outfile, level, name_='Objects')
- outfile.write('),\n')
+ self.Objects.export(write, level, 'maecBundle:', name_='Objects', pretty_print=pretty_print)
if self.Candidate_Indicators is not None:
- outfile.write('Candidate_Indicators=model_.CandidateIndicatorListType(\n')
- self.Candidate_Indicators.exportLiteral(outfile, level, name_='Candidate_Indicators')
- outfile.write('),\n')
+ self.Candidate_Indicators.export(write, level, 'maecBundle:', name_='Candidate_Indicators', pretty_print=pretty_print)
if self.Collections is not None:
- outfile.write('Collections=model_.CollectionsType(\n')
- self.Collections.exportLiteral(outfile, level, name_='Collections')
- outfile.write('),\n')
+ self.Collections.export(write, level, 'maecBundle:', name_='Collections', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -972,7 +357,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('timestamp')
try:
self.timestamp = self.gds_parse_datetime(value, node, 'timestamp')
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (timestamp): %s' % exp)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Malware_Instance_Object_Attributes':
@@ -1053,69 +438,44 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='APICallType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='APICallType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='APICallType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='APICallType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='APICallType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='APICallType'):
if self.normalized_function_name is not None and 'normalized_function_name' not in already_processed:
already_processed.add('normalized_function_name')
- outfile.write(' normalized_function_name=%s' % (self.gds_format_string(quote_attrib(self.normalized_function_name).encode(ExternalEncoding), input_name='normalized_function_name'), ))
+ write(' normalized_function_name=%s' % (quote_attrib(self.normalized_function_name)))
if self.function_name is not None and 'function_name' not in already_processed:
already_processed.add('function_name')
- outfile.write(' function_name=%s' % (self.gds_format_string(quote_attrib(self.function_name).encode(ExternalEncoding), input_name='function_name'), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='APICallType', fromsubclass_=False, pretty_print=True):
+ write(' function_name=%s' % (quote_attrib(self.function_name)))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='APICallType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Address is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAddress>%s%sAddress>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Address).encode(ExternalEncoding), input_name='Address'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sAddress>%s%sAddress>%s' % ('maecBundle:', quote_xml(self.Address), 'maecBundle:', eol_))
if self.Return_Value is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sReturn_Value>%s%sReturn_Value>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Return_Value).encode(ExternalEncoding), input_name='Return_Value'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sReturn_Value>%s%sReturn_Value>%s' % ('maecBundle:', quote_xml(self.Return_Value), 'maecBundle:', eol_))
if self.Parameters is not None:
- self.Parameters.export(outfile, level, 'maecBundle:', name_='Parameters', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='APICallType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.normalized_function_name is not None and 'normalized_function_name' not in already_processed:
- already_processed.add('normalized_function_name')
- showIndent(outfile, level)
- outfile.write('normalized_function_name = "%s",\n' % (self.normalized_function_name,))
- if self.function_name is not None and 'function_name' not in already_processed:
- already_processed.add('function_name')
- showIndent(outfile, level)
- outfile.write('function_name = "%s",\n' % (self.function_name,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Address is not None:
- showIndent(outfile, level)
- outfile.write('Address=%s,\n' % quote_python(self.Address).encode(ExternalEncoding))
- if self.Return_Value is not None:
- showIndent(outfile, level)
- outfile.write('Return_Value=%s,\n' % quote_python(self.Return_Value).encode(ExternalEncoding))
- if self.Parameters is not None:
- outfile.write('Parameters=model_.ParameterListType(\n')
- self.Parameters.exportLiteral(outfile, level, name_='Parameters')
- outfile.write('),\n')
+ self.Parameters.export(write, level, 'maecBundle:', name_='Parameters', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1192,76 +552,42 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ActionImplementationType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ActionImplementationType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionImplementationType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionImplementationType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ActionImplementationType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ActionImplementationType'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.add('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
+ write(' type=%s' % (quote_attrib(self.type_), ))
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ActionImplementationType', fromsubclass_=False, pretty_print=True):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ActionImplementationType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Compatible_Platforms is not None:
- self.Compatible_Platforms.export(outfile, level, 'maecBundle:', name_='Compatible_Platforms', pretty_print=pretty_print)
- if self.API_Call is not None:
- self.API_Call.export(outfile, level, 'maecBundle:', name_='API_Call', pretty_print=pretty_print)
- for Code_ in self.Code:
- Code_.export(outfile, level, 'maecBundle:', name_='Code', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionImplementationType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.add('type_')
- showIndent(outfile, level)
- outfile.write('type_ = %s,\n' % (self.type_,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Compatible_Platforms is not None:
- outfile.write('Compatible_Platforms=model_.PlatformListType(\n')
- self.Compatible_Platforms.exportLiteral(outfile, level, name_='Compatible_Platforms')
- outfile.write('),\n')
+ self.Compatible_Platforms.export(write, level, 'maecBundle:', name_='Compatible_Platforms', pretty_print=pretty_print)
if self.API_Call is not None:
- outfile.write('API_Call=model_.APICallType(\n')
- self.API_Call.exportLiteral(outfile, level, name_='API_Call')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Code=[\n')
- level += 1
+ self.API_Call.export(write, level, 'maecBundle:', name_='API_Call', pretty_print=pretty_print)
for Code_ in self.Code:
- outfile.write('model_.code_object.CodeObjectType(\n')
- Code_.exportLiteral(outfile, level, name_='code_object.CodeObjectType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Code_.export(write, level, 'maecBundle:', name_='Code', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1320,50 +646,36 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CVEVulnerabilityType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CVEVulnerabilityType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CVEVulnerabilityType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CVEVulnerabilityType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CVEVulnerabilityType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CVEVulnerabilityType'):
if self.cve_id is not None and 'cve_id' not in already_processed:
already_processed.add('cve_id')
- outfile.write(' cve_id=%s' % (self.gds_format_string(quote_attrib(self.cve_id).encode(ExternalEncoding), input_name='cve_id'), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CVEVulnerabilityType', fromsubclass_=False, pretty_print=True):
+ write(' cve_id=%s' % (quote_attrib(self.cve_id)))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CVEVulnerabilityType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
- def exportLiteral(self, outfile, level, name_='CVEVulnerabilityType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.cve_id is not None and 'cve_id' not in already_processed:
- already_processed.add('cve_id')
- showIndent(outfile, level)
- outfile.write('cve_id = "%s",\n' % (self.cve_id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1417,66 +729,46 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BaseCollectionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BaseCollectionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BaseCollectionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BaseCollectionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BaseCollectionType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BaseCollectionType'):
if self.name is not None and 'name' not in already_processed:
already_processed.add('name')
- outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
+ write(' name=%s' % (quote_attrib(self.name)))
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.add('xsi:type')
- outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
- outfile.write(' xsi:type="%s"' % self.extensiontype_)
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BaseCollectionType', fromsubclass_=False, pretty_print=True):
+ write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
+ write(' xsi:type="%s"' % self.extensiontype_)
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BaseCollectionType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Affinity_Type is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAffinity_Type>%s%sAffinity_Type>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Affinity_Type).encode(ExternalEncoding), input_name='Affinity_Type'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sAffinity_Type>%s%sAffinity_Type>%s' % ('maecBundle:', quote_xml(self.Affinity_Type), 'maecBundle:', eol_))
if self.Affinity_Degree is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAffinity_Degree>%s%sAffinity_Degree>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Affinity_Degree).encode(ExternalEncoding), input_name='Affinity_Degree'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sAffinity_Degree>%s%sAffinity_Degree>%s' % ('maecBundle:', quote_xml(self.Affinity_Degree), 'maecBundle:', eol_))
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
- def exportLiteral(self, outfile, level, name_='BaseCollectionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.name is not None and 'name' not in already_processed:
- already_processed.add('name')
- showIndent(outfile, level)
- outfile.write('name = "%s",\n' % (self.name,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Affinity_Type is not None:
- showIndent(outfile, level)
- outfile.write('Affinity_Type=%s,\n' % quote_python(self.Affinity_Type).encode(ExternalEncoding))
- if self.Affinity_Degree is not None:
- showIndent(outfile, level)
- outfile.write('Affinity_Degree=%s,\n' % quote_python(self.Affinity_Degree).encode(ExternalEncoding))
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1538,57 +830,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorRelationshipType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorRelationshipType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorRelationshipType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorRelationshipType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorRelationshipType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorRelationshipType'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.add('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorRelationshipType', fromsubclass_=False, pretty_print=True):
+ write(' type=%s' % (quote_attrib(self.type_), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorRelationshipType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Behavior_Reference_ in self.Behavior_Reference:
- Behavior_Reference_.export(outfile, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorRelationshipType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.add('type_')
- showIndent(outfile, level)
- outfile.write('type_ = %s,\n' % (self.type_,))
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Behavior_Reference=[\n')
- level += 1
- for Behavior_Reference_ in self.Behavior_Reference:
- outfile.write('model_.BehaviorReferenceType(\n')
- Behavior_Reference_.exportLiteral(outfile, level, name_='BehaviorReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Behavior_Reference_.export(write, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1633,52 +903,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='AVClassificationsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='AVClassificationsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AVClassificationsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AVClassificationsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='AVClassificationsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='AVClassificationsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='AVClassificationsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='AVClassificationsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for AV_Classification_ in self.AV_Classification:
- AV_Classification_.export(outfile, level, 'maecBundle:', name_='AV_Classification', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AVClassificationsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('AV_Classification=[\n')
- level += 1
- for AV_Classification_ in self.AV_Classification:
- outfile.write('model_.AVClassificationType(\n')
- AV_Classification_.exportLiteral(outfile, level, name_='AVClassificationType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ AV_Classification_.export(write, level, 'maecBundle:', name_='AV_Classification', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1725,55 +976,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ParameterType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ParameterType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ParameterType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ParameterType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ParameterType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ParameterType'):
if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
already_processed.add('ordinal_position')
- outfile.write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
+ write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
if self.name is not None and 'name' not in already_processed:
already_processed.add('name')
- outfile.write(' name=%s' % (self.gds_format_string(quote_attrib(self.name).encode(ExternalEncoding), input_name='name'), ))
+ write(' name=%s' % (quote_attrib(self.name)))
if self.value is not None and 'value' not in already_processed:
already_processed.add('value')
- outfile.write(' value=%s' % (self.gds_format_string(quote_attrib(self.value).encode(ExternalEncoding), input_name='value'), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ParameterType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='ParameterType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
- already_processed.add('ordinal_position')
- showIndent(outfile, level)
- outfile.write('ordinal_position = %d,\n' % (self.ordinal_position,))
- if self.name is not None and 'name' not in already_processed:
- already_processed.add('name')
- showIndent(outfile, level)
- outfile.write('name = "%s",\n' % (self.name,))
- if self.value is not None and 'value' not in already_processed:
- already_processed.add('value')
- showIndent(outfile, level)
- outfile.write('value = "%s",\n' % (self.value,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' value=%s' % (quote_attrib(self.value)))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ParameterType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1785,7 +1016,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('ordinal_position')
try:
self.ordinal_position = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.ordinal_position <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -1827,52 +1058,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ParameterListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ParameterListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ParameterListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ParameterListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ParameterListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ParameterListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ParameterListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ParameterListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Parameter_ in self.Parameter:
- Parameter_.export(outfile, level, 'maecBundle:', name_='Parameter', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ParameterListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Parameter=[\n')
- level += 1
- for Parameter_ in self.Parameter:
- outfile.write('model_.ParameterType(\n')
- Parameter_.exportLiteral(outfile, level, name_='ParameterType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Parameter_.export(write, level, 'maecBundle:', name_='Parameter', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1914,52 +1126,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='AssociatedCodeType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='AssociatedCodeType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AssociatedCodeType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AssociatedCodeType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='AssociatedCodeType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='AssociatedCodeType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='AssociatedCodeType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='AssociatedCodeType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Code_Snippet_ in self.Code_Snippet:
- Code_Snippet_.export(outfile, level, 'maecBundle:', name_='Code_Snippet', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AssociatedCodeType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Code_Snippet=[\n')
- level += 1
- for Code_Snippet_ in self.Code_Snippet:
- outfile.write('model_.code_object.CodeObjectType(\n')
- Code_Snippet_.exportLiteral(outfile, level, name_='code_object.CodeObjectType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Code_Snippet_.export(write, level, 'maecBundle:', name_='Code_Snippet', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2000,51 +1193,36 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorPurposeType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorPurposeType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorPurposeType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorPurposeType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorPurposeType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorPurposeType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorPurposeType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorPurposeType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
if self.Vulnerability_Exploit is not None:
- self.Vulnerability_Exploit.export(outfile, level, 'maecBundle:', name_='Vulnerability_Exploit', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorPurposeType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
- if self.Vulnerability_Exploit is not None:
- outfile.write('Vulnerability_Exploit=model_.ExploitType(\n')
- self.Vulnerability_Exploit.exportLiteral(outfile, level, name_='Vulnerability_Exploit')
- outfile.write('),\n')
+ self.Vulnerability_Exploit.export(write, level, 'maecBundle:', name_='Vulnerability_Exploit', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2090,52 +1268,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='PlatformListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='PlatformListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='PlatformListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='PlatformListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='PlatformListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='PlatformListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='PlatformListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='PlatformListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Platform_ in self.Platform:
- Platform_.export(outfile, level, 'maecBundle:', name_='Platform', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='PlatformListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Platform=[\n')
- level += 1
- for Platform_ in self.Platform:
- outfile.write('model_.cybox_common.PlatformSpecificationType(\n')
- Platform_.exportLiteral(outfile, level, name_='cybox_common.PlatformSpecificationType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Platform_.export(write, level, 'maecBundle:', name_='Platform', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2196,68 +1355,40 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ExploitType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ExploitType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ExploitType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ExploitType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ExploitType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ExploitType'):
if self.known_vulnerability is not None and 'known_vulnerability' not in already_processed:
already_processed.add('known_vulnerability')
- outfile.write(' known_vulnerability="%s"' % self.gds_format_boolean(self.known_vulnerability, input_name='known_vulnerability'))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ExploitType', fromsubclass_=False, pretty_print=True):
+ write(' known_vulnerability="%s"' % self.gds_format_boolean(self.known_vulnerability, input_name='known_vulnerability'))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ExploitType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.CVE is not None:
- self.CVE.export(outfile, level, 'maecBundle:', name_='CVE', pretty_print=pretty_print)
+ self.CVE.export(write, level, 'maecBundle:', name_='CVE', pretty_print=pretty_print)
for CWE_ID_ in self.CWE_ID:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sCWE_ID>%s%sCWE_ID>%s' % ('maecBundle:', self.gds_format_string(quote_xml(CWE_ID_).encode(ExternalEncoding), input_name='CWE_ID'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sCWE_ID>%s%sCWE_ID>%s' % ('maecBundle:', quote_xml(CWE_ID_), 'maecBundle:', eol_))
if self.Targeted_Platforms is not None:
- self.Targeted_Platforms.export(outfile, level, 'maecBundle:', name_='Targeted_Platforms', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ExploitType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.known_vulnerability is not None and 'known_vulnerability' not in already_processed:
- already_processed.add('known_vulnerability')
- showIndent(outfile, level)
- outfile.write('known_vulnerability = %s,\n' % (self.known_vulnerability,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.CVE is not None:
- outfile.write('CVE=model_.CVEVulnerabilityType(\n')
- self.CVE.exportLiteral(outfile, level, name_='CVE')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('CWE_ID=[\n')
- level += 1
- for CWE_ID_ in self.CWE_ID:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(CWE_ID_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- if self.Targeted_Platforms is not None:
- outfile.write('Targeted_Platforms=model_.PlatformListType(\n')
- self.Targeted_Platforms.exportLiteral(outfile, level, name_='Targeted_Platforms')
- outfile.write('),\n')
+ self.Targeted_Platforms.export(write, level, 'maecBundle:', name_='Targeted_Platforms', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2315,52 +1446,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorRelationshipListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorRelationshipListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorRelationshipListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorRelationshipListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorRelationshipListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorRelationshipListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorRelationshipListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorRelationshipListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Relationship_ in self.Relationship:
- Relationship_.export(outfile, level, 'maecBundle:', name_='Relationship', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorRelationshipListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Relationship=[\n')
- level += 1
- for Relationship_ in self.Relationship:
- outfile.write('model_.BehaviorRelationshipType(\n')
- Relationship_.exportLiteral(outfile, level, name_='BehaviorRelationshipType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Relationship_.export(write, level, 'maecBundle:', name_='Relationship', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2429,91 +1541,39 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehavioralActionsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehavioralActionsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehavioralActionsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehavioralActionsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Action_Collection_ in self.Action_Collection:
- Action_Collection_.export(outfile, level, 'maecBundle:', name_='Action_Collection', pretty_print=pretty_print)
- for Action_ in self.Action:
- Action_.export(outfile, level, 'maecBundle:', name_='Action', pretty_print=pretty_print)
- for Action_Reference_ in self.Action_Reference:
- Action_Reference_.export(outfile, level, 'maecBundle:', name_='Action_Reference', pretty_print=pretty_print)
- for Action_Equivalence_Reference_ in self.Action_Equivalence_Reference:
- Action_Equivalence_Reference_.export(outfile, level, 'maecBundle:', name_='Action_Equivalence_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehavioralActionsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Action_Collection=[\n')
- level += 1
- for Action_Collection_ in self.Action_Collection:
- outfile.write('model_.ActionCollectionType(\n')
- Action_Collection_.exportLiteral(outfile, level, name_='ActionCollectionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Action=[\n')
- level += 1
+ Action_Collection_.export(write, level, 'maecBundle:', name_='Action_Collection', pretty_print=pretty_print)
for Action_ in self.Action:
- outfile.write('model_.BehavioralActionType(\n')
- Action_.exportLiteral(outfile, level, name_='BehavioralActionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Action_Reference=[\n')
- level += 1
+ Action_.export(write, level, 'maecBundle:', name_='Action', pretty_print=pretty_print)
for Action_Reference_ in self.Action_Reference:
- outfile.write('model_.BehavioralActionReferenceType(\n')
- Action_Reference_.exportLiteral(outfile, level, name_='BehavioralActionReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Action_Equivalence_Reference=[\n')
- level += 1
+ Action_Reference_.export(write, level, 'maecBundle:', name_='Action_Reference', pretty_print=pretty_print)
for Action_Equivalence_Reference_ in self.Action_Equivalence_Reference:
- outfile.write('model_.BehavioralActionEquivalenceReferenceType(\n')
- Action_Equivalence_Reference_.exportLiteral(outfile, level, name_='BehavioralActionEquivalenceReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Action_Equivalence_Reference_.export(write, level, 'maecBundle:', name_='Action_Equivalence_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2527,7 +1587,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
obj_.build(child_)
self.Action_Collection.append(obj_)
elif nodeName_ == 'Action':
- obj_ = MalwareActionType.factory()
+ obj_ = BehavioralActionType.factory()
obj_.build(child_)
self.Action.append(obj_)
elif nodeName_ == 'Action_Reference':
@@ -2566,52 +1626,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Behavior_ in self.Behavior:
- Behavior_.export(outfile, level, 'maecBundle:', name_='Behavior', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Behavior=[\n')
- level += 1
- for Behavior_ in self.Behavior:
- outfile.write('model_.BehaviorType(\n')
- Behavior_.exportLiteral(outfile, level, name_='BehaviorType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Behavior_.export(write, level, 'maecBundle:', name_='Behavior', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2652,52 +1693,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ActionListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ActionListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ActionListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ActionListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ActionListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ActionListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Action_ in self.Action:
- Action_.export(outfile, level, 'maecBundle:', name_='Action', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Action=[\n')
- level += 1
- for Action_ in self.Action:
- outfile.write('model_.MalwareActionType(\n')
- Action_.exportLiteral(outfile, level, name_='MalwareActionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Action_.export(write, level, 'maecBundle:', name_='Action', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2738,52 +1760,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ObjectListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ObjectListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ObjectListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ObjectListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ObjectListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ObjectListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Object_ in self.Object:
- Object_.export(outfile, level, 'maecBundle:', name_='Object', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ObjectListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Object=[\n')
- level += 1
- for Object_ in self.Object:
- outfile.write('model_.cybox_core.ObjectType(\n')
- Object_.exportLiteral(outfile, level, name_='cybox_core.ObjectType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Object_.export(write, level, 'maecBundle:', name_='Object', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2823,41 +1826,29 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorReferenceType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorReferenceType'):
if self.behavior_idref is not None and 'behavior_idref' not in already_processed:
already_processed.add('behavior_idref')
- outfile.write(' behavior_idref=%s' % (quote_attrib(self.behavior_idref), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='BehaviorReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.behavior_idref is not None and 'behavior_idref' not in already_processed:
- already_processed.add('behavior_idref')
- showIndent(outfile, level)
- outfile.write('behavior_idref = %s,\n' % (self.behavior_idref,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' behavior_idref=%s' % (quote_attrib(self.behavior_idref), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2897,41 +1888,29 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ObjectReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ObjectReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ObjectReferenceType'):
- if self.object_idref is not None and 'object_idref' not in already_processed:
- already_processed.add('object_idref')
- outfile.write(' object_idref=%s' % (quote_attrib(self.object_idref), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ObjectReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='ObjectReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ObjectReferenceType'):
if self.object_idref is not None and 'object_idref' not in already_processed:
already_processed.add('object_idref')
- showIndent(outfile, level)
- outfile.write('object_idref = %s,\n' % (self.object_idref,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' object_idref=%s' % (quote_attrib(self.object_idref), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ObjectReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2982,48 +1961,32 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionEquivalenceReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehavioralActionEquivalenceReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehavioralActionEquivalenceReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehavioralActionEquivalenceReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionEquivalenceReferenceType'):
- if self.action_equivalence_idref is not None and 'action_equivalence_idref' not in already_processed:
- already_processed.add('action_equivalence_idref')
- outfile.write(' action_equivalence_idref=%s' % (quote_attrib(self.action_equivalence_idref), ))
- if self.behavioral_ordering is not None and 'behavioral_ordering' not in already_processed:
- already_processed.add('behavioral_ordering')
- outfile.write(' behavioral_ordering="%s"' % self.gds_format_integer(self.behavioral_ordering, input_name='behavioral_ordering'))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionEquivalenceReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='BehavioralActionEquivalenceReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionEquivalenceReferenceType'):
if self.action_equivalence_idref is not None and 'action_equivalence_idref' not in already_processed:
already_processed.add('action_equivalence_idref')
- showIndent(outfile, level)
- outfile.write('action_equivalence_idref = %s,\n' % (self.action_equivalence_idref,))
+ write(' action_equivalence_idref=%s' % (quote_attrib(self.action_equivalence_idref), ))
if self.behavioral_ordering is not None and 'behavioral_ordering' not in already_processed:
already_processed.add('behavioral_ordering')
- showIndent(outfile, level)
- outfile.write('behavioral_ordering = %d,\n' % (self.behavioral_ordering,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' behavioral_ordering="%s"' % self.gds_format_integer(self.behavioral_ordering, input_name='behavioral_ordering'))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehavioralActionEquivalenceReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3039,7 +2002,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('behavioral_ordering')
try:
self.behavioral_ordering = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.behavioral_ordering <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -3074,52 +2037,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorReferenceListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorReferenceListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorReferenceListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorReferenceListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorReferenceListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorReferenceListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorReferenceListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorReferenceListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Behavior_Reference_ in self.Behavior_Reference:
- Behavior_Reference_.export(outfile, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorReferenceListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Behavior_Reference=[\n')
- level += 1
- for Behavior_Reference_ in self.Behavior_Reference:
- outfile.write('model_.BehaviorReferenceType(\n')
- Behavior_Reference_.exportLiteral(outfile, level, name_='BehaviorReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Behavior_Reference_.export(write, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3160,52 +2104,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ActionReferenceListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ActionReferenceListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionReferenceListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionReferenceListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ActionReferenceListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ActionReferenceListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ActionReferenceListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ActionReferenceListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Action_Reference_ in self.Action_Reference:
- Action_Reference_.export(outfile, level, 'maecBundle:', name_='Action_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionReferenceListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Action_Reference=[\n')
- level += 1
- for Action_Reference_ in self.Action_Reference:
- outfile.write('model_.cybox_core.ActionReferenceType(\n')
- Action_Reference_.exportLiteral(outfile, level, name_='cybox_core.ActionReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Action_Reference_.export(write, level, 'maecBundle:', name_='Action_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3247,52 +2172,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ObjectReferenceListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ObjectReferenceListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectReferenceListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectReferenceListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ObjectReferenceListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ObjectReferenceListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ObjectReferenceListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ObjectReferenceListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Object_Reference_ in self.Object_Reference:
- Object_Reference_.export(outfile, level, 'maecBundle:', name_='Object_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ObjectReferenceListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Object_Reference=[\n')
- level += 1
- for Object_Reference_ in self.Object_Reference:
- outfile.write('model_.ObjectReferenceType(\n')
- Object_Reference_.exportLiteral(outfile, level, name_='ObjectReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Object_Reference_.export(write, level, 'maecBundle:', name_='Object_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3370,101 +2276,57 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CandidateIndicatorType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CandidateIndicatorType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorType'):
if self.version is not None and 'version' not in already_processed:
already_processed.add('version')
- outfile.write(' version=%s' % (self.gds_format_string(quote_attrib(self.version).encode(ExternalEncoding), input_name='version'), ))
+ write(' version=%s' % (quote_attrib(self.version)))
if self.creation_datetime is not None and 'creation_datetime' not in already_processed:
already_processed.add('creation_datetime')
- outfile.write(' creation_datetime="%s"' % self.gds_format_datetime(self.creation_datetime, input_name='creation_datetime'))
+ write(' creation_datetime="%s"' % self.gds_format_datetime(self.creation_datetime, input_name='creation_datetime'))
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
+ write(' id=%s' % (quote_attrib(self.id), ))
if self.lastupdate_datetime is not None and 'lastupdate_datetime' not in already_processed:
already_processed.add('lastupdate_datetime')
- outfile.write(' lastupdate_datetime="%s"' % self.gds_format_datetime(self.lastupdate_datetime, input_name='lastupdate_datetime'))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorType', fromsubclass_=False, pretty_print=True):
+ write(' lastupdate_datetime="%s"' % self.gds_format_datetime(self.lastupdate_datetime, input_name='lastupdate_datetime'))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Importance is not None:
- self.Importance.export(outfile, level, 'maecBundle:', name_='Importance', pretty_print=pretty_print)
+ self.Importance.export(write, level, 'maecBundle:', name_='Importance', pretty_print=pretty_print)
if self.Numeric_Importance is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sNumeric_Importance>%s%sNumeric_Importance>%s' % ('maecBundle:', self.gds_format_integer(self.Numeric_Importance, input_name='Numeric_Importance'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sNumeric_Importance>%s%sNumeric_Importance>%s' % ('maecBundle:', self.gds_format_integer(self.Numeric_Importance, input_name='Numeric_Importance'), 'maecBundle:', eol_))
if self.Author is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAuthor>%s%sAuthor>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Author).encode(ExternalEncoding), input_name='Author'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sAuthor>%s%sAuthor>%s' % ('maecBundle:', quote_xml(self.Author), 'maecBundle:', eol_))
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
if self.Malware_Entity is not None:
- self.Malware_Entity.export(outfile, level, 'maecBundle:', name_='Malware_Entity', pretty_print=pretty_print)
+ self.Malware_Entity.export(write, level, 'maecBundle:', name_='Malware_Entity', pretty_print=pretty_print)
if self.Composition is not None:
- self.Composition.export(outfile, level, 'maecBundle:', name_='Composition', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CandidateIndicatorType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.version is not None and 'version' not in already_processed:
- already_processed.add('version')
- showIndent(outfile, level)
- outfile.write('version = "%s",\n' % (self.version,))
- if self.creation_datetime is not None and 'creation_datetime' not in already_processed:
- already_processed.add('creation_datetime')
- showIndent(outfile, level)
- outfile.write('creation_datetime = "%s",\n' % (self.creation_datetime,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- if self.lastupdate_datetime is not None and 'lastupdate_datetime' not in already_processed:
- already_processed.add('lastupdate_datetime')
- showIndent(outfile, level)
- outfile.write('lastupdate_datetime = "%s",\n' % (self.lastupdate_datetime,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Importance is not None:
- outfile.write('Importance=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Importance.exportLiteral(outfile, level, name_='Importance')
- outfile.write('),\n')
- if self.Numeric_Importance is not None:
- showIndent(outfile, level)
- outfile.write('Numeric_Importance=%d,\n' % self.Numeric_Importance)
- if self.Author is not None:
- showIndent(outfile, level)
- outfile.write('Author=%s,\n' % quote_python(self.Author).encode(ExternalEncoding))
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
- if self.Malware_Entity is not None:
- outfile.write('Malware_Entity=model_.MalwareEntityType(\n')
- self.Malware_Entity.exportLiteral(outfile, level, name_='Malware_Entity')
- outfile.write('),\n')
- if self.Composition is not None:
- outfile.write('Composition=model_.CandidateIndicatorCompositionType(\n')
- self.Composition.exportLiteral(outfile, level, name_='Composition')
- outfile.write('),\n')
+ self.Composition.export(write, level, 'maecBundle:', name_='Composition', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3480,7 +2342,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('creation_datetime')
try:
self.creation_datetime = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (creation_datetime): %s' % exp)
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
@@ -3491,7 +2353,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('lastupdate_datetime')
try:
self.lastupdate_datetime = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (lastupdate_datetime): %s' % exp)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Importance':
@@ -3502,7 +2364,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
if ival_ <= 0:
raise_parse_error(child_, 'requires positiveInteger')
@@ -3553,52 +2415,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CandidateIndicatorListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CandidateIndicatorListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Candidate_Indicator_ in self.Candidate_Indicator:
- Candidate_Indicator_.export(outfile, level, 'maecBundle:', name_='Candidate_Indicator', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CandidateIndicatorListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Candidate_Indicator=[\n')
- level += 1
- for Candidate_Indicator_ in self.Candidate_Indicator:
- outfile.write('model_.CandidateIndicatorType(\n')
- Candidate_Indicator_.exportLiteral(outfile, level, name_='CandidateIndicatorType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Candidate_Indicator_.export(write, level, 'maecBundle:', name_='Candidate_Indicator', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3645,57 +2488,39 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='MalwareEntityType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='MalwareEntityType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareEntityType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareEntityType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='MalwareEntityType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='MalwareEntityType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='MalwareEntityType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='MalwareEntityType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Type is not None:
- self.Type.export(outfile, level, 'maecBundle:', name_='Type', pretty_print=pretty_print)
- if self.Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sName>%s%sName>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Name).encode(ExternalEncoding), input_name='Name'), 'maecBundle:', eol_))
- if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
- def exportLiteral(self, outfile, level, name_='MalwareEntityType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Type is not None:
- outfile.write('Type=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Type.exportLiteral(outfile, level, name_='Type')
- outfile.write('),\n')
+ self.Type.export(write, level, 'maecBundle:', name_='Type', pretty_print=pretty_print)
if self.Name is not None:
- showIndent(outfile, level)
- outfile.write('Name=%s,\n' % quote_python(self.Name).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sName>%s%sName>%s' % ('maecBundle:', quote_xml(self.Name), 'maecBundle:', eol_))
if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3752,63 +2577,39 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CollectionsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CollectionsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CollectionsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CollectionsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CollectionsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CollectionsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CollectionsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CollectionsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Behavior_Collections is not None:
- self.Behavior_Collections.export(outfile, level, 'maecBundle:', name_='Behavior_Collections', pretty_print=pretty_print)
+ self.Behavior_Collections.export(write, level, 'maecBundle:', name_='Behavior_Collections', pretty_print=pretty_print)
if self.Action_Collections is not None:
- self.Action_Collections.export(outfile, level, 'maecBundle:', name_='Action_Collections', pretty_print=pretty_print)
+ self.Action_Collections.export(write, level, 'maecBundle:', name_='Action_Collections', pretty_print=pretty_print)
if self.Object_Collections is not None:
- self.Object_Collections.export(outfile, level, 'maecBundle:', name_='Object_Collections', pretty_print=pretty_print)
+ self.Object_Collections.export(write, level, 'maecBundle:', name_='Object_Collections', pretty_print=pretty_print)
if self.Candidate_Indicator_Collections is not None:
- self.Candidate_Indicator_Collections.export(outfile, level, 'maecBundle:', name_='Candidate_Indicator_Collections', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CollectionsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Behavior_Collections is not None:
- outfile.write('Behavior_Collections=model_.BehaviorCollectionListType(\n')
- self.Behavior_Collections.exportLiteral(outfile, level, name_='Behavior_Collections')
- outfile.write('),\n')
- if self.Action_Collections is not None:
- outfile.write('Action_Collections=model_.ActionCollectionListType(\n')
- self.Action_Collections.exportLiteral(outfile, level, name_='Action_Collections')
- outfile.write('),\n')
- if self.Object_Collections is not None:
- outfile.write('Object_Collections=model_.ObjectCollectionListType(\n')
- self.Object_Collections.exportLiteral(outfile, level, name_='Object_Collections')
- outfile.write('),\n')
- if self.Candidate_Indicator_Collections is not None:
- outfile.write('Candidate_Indicator_Collections=model_.CandidateIndicatorCollectionListType(\n')
- self.Candidate_Indicator_Collections.exportLiteral(outfile, level, name_='Candidate_Indicator_Collections')
- outfile.write('),\n')
+ self.Candidate_Indicator_Collections.export(write, level, 'maecBundle:', name_='Candidate_Indicator_Collections', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3859,41 +2660,29 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BundleReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BundleReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BundleReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BundleReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BundleReferenceType'):
- if self.bundle_idref is not None and 'bundle_idref' not in already_processed:
- already_processed.add('bundle_idref')
- outfile.write(' bundle_idref=%s' % (quote_attrib(self.bundle_idref), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BundleReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='BundleReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BundleReferenceType'):
if self.bundle_idref is not None and 'bundle_idref' not in already_processed:
already_processed.add('bundle_idref')
- showIndent(outfile, level)
- outfile.write('bundle_idref = %s,\n' % (self.bundle_idref,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' bundle_idref=%s' % (quote_attrib(self.bundle_idref), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BundleReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3931,45 +2720,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ProcessTreeType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ProcessTreeType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ProcessTreeType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ProcessTreeType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ProcessTreeType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ProcessTreeType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ProcessTreeType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ProcessTreeType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Root_Process is not None:
- self.Root_Process.export(outfile, level, 'maecBundle:', name_='Root_Process', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ProcessTreeType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Root_Process is not None:
- outfile.write('Root_Process=model_.ProcessTreeNodeType(\n')
- self.Root_Process.exportLiteral(outfile, level, name_='Root_Process')
- outfile.write('),\n')
+ self.Root_Process.export(write, level, 'maecBundle:', name_='Root_Process', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4044,96 +2821,41 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorCompositionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorCompositionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CandidateIndicatorCompositionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CandidateIndicatorCompositionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorCompositionType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorCompositionType'):
if self.operator is not None and 'operator' not in already_processed:
already_processed.add('operator')
- outfile.write(' operator=%s' % (quote_attrib(self.operator), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorCompositionType', fromsubclass_=False, pretty_print=True):
+ write(' operator=%s' % (quote_attrib(self.operator), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorCompositionType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Behavior_Reference_ in self.Behavior_Reference:
- Behavior_Reference_.export(outfile, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
- for Action_Reference_ in self.Action_Reference:
- Action_Reference_.export(outfile, level, 'maecBundle:', name_='Action_Reference', pretty_print=pretty_print)
- for Object_Reference_ in self.Object_Reference:
- Object_Reference_.export(outfile, level, 'maecBundle:', name_='Object_Reference', pretty_print=pretty_print)
- for Sub_Composition_ in self.Sub_Composition:
- Sub_Composition_.export(outfile, level, 'maecBundle:', name_='Sub_Composition', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CandidateIndicatorCompositionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.operator is not None and 'operator' not in already_processed:
- already_processed.add('operator')
- showIndent(outfile, level)
- outfile.write('operator = %s,\n' % (self.operator,))
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Behavior_Reference=[\n')
- level += 1
- for Behavior_Reference_ in self.Behavior_Reference:
- outfile.write('model_.BehaviorReferenceType(\n')
- Behavior_Reference_.exportLiteral(outfile, level, name_='BehaviorReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Action_Reference=[\n')
- level += 1
+ Behavior_Reference_.export(write, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
for Action_Reference_ in self.Action_Reference:
- outfile.write('model_.cybox_core.ActionReferenceType(\n')
- Action_Reference_.exportLiteral(outfile, level, name_='cybox_core.ActionReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Object_Reference=[\n')
- level += 1
+ Action_Reference_.export(write, level, 'maecBundle:', name_='Action_Reference', pretty_print=pretty_print)
for Object_Reference_ in self.Object_Reference:
- outfile.write('model_.ObjectReferenceType(\n')
- Object_Reference_.exportLiteral(outfile, level, name_='ObjectReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Sub_Composition=[\n')
- level += 1
+ Object_Reference_.export(write, level, 'maecBundle:', name_='Object_Reference', pretty_print=pretty_print)
for Sub_Composition_ in self.Sub_Composition:
- outfile.write('model_.CandidateIndicatorCompositionType(\n')
- Sub_Composition_.exportLiteral(outfile, level, name_='CandidateIndicatorCompositionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Sub_Composition_.export(write, level, 'maecBundle:', name_='Sub_Composition', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4193,54 +2915,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CandidateIndicatorCollectionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CandidateIndicatorCollectionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorCollectionType'):
- super(CandidateIndicatorCollectionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='CandidateIndicatorCollectionType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorCollectionType'):
+ super(CandidateIndicatorCollectionType, self).exportAttributes(write, level, already_processed, namespace_, name_='CandidateIndicatorCollectionType')
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionType', fromsubclass_=False, pretty_print=True):
- super(CandidateIndicatorCollectionType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionType', fromsubclass_=False, pretty_print=True):
+ super(CandidateIndicatorCollectionType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Candidate_Indicator_List is not None:
- self.Candidate_Indicator_List.export(outfile, level, 'maecBundle:', name_='Candidate_Indicator_List', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CandidateIndicatorCollectionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- super(CandidateIndicatorCollectionType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(CandidateIndicatorCollectionType, self).exportLiteralChildren(outfile, level, name_)
- if self.Candidate_Indicator_List is not None:
- outfile.write('Candidate_Indicator_List=model_.CandidateIndicatorListType(\n')
- self.Candidate_Indicator_List.exportLiteral(outfile, level, name_='Candidate_Indicator_List')
- outfile.write('),\n')
+ self.Candidate_Indicator_List.export(write, level, 'maecBundle:', name_='Candidate_Indicator_List', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4287,52 +2992,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CandidateIndicatorCollectionListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CandidateIndicatorCollectionListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorCollectionListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CandidateIndicatorCollectionListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CandidateIndicatorCollectionListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Candidate_Indicator_Collection_ in self.Candidate_Indicator_Collection:
- Candidate_Indicator_Collection_.export(outfile, level, 'maecBundle:', name_='Candidate_Indicator_Collection', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CandidateIndicatorCollectionListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Candidate_Indicator_Collection=[\n')
- level += 1
- for Candidate_Indicator_Collection_ in self.Candidate_Indicator_Collection:
- outfile.write('model_.CandidateIndicatorCollectionType(\n')
- Candidate_Indicator_Collection_.exportLiteral(outfile, level, name_='CandidateIndicatorCollectionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Candidate_Indicator_Collection_.export(write, level, 'maecBundle:', name_='Candidate_Indicator_Collection', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4374,52 +3060,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorCollectionListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorCollectionListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorCollectionListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorCollectionListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorCollectionListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorCollectionListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorCollectionListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorCollectionListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Behavior_Collection_ in self.Behavior_Collection:
- Behavior_Collection_.export(outfile, level, 'maecBundle:', name_='Behavior_Collection', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorCollectionListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Behavior_Collection=[\n')
- level += 1
- for Behavior_Collection_ in self.Behavior_Collection:
- outfile.write('model_.BehaviorCollectionType(\n')
- Behavior_Collection_.exportLiteral(outfile, level, name_='BehaviorCollectionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Behavior_Collection_.export(write, level, 'maecBundle:', name_='Behavior_Collection', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4460,52 +3127,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ActionCollectionListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ActionCollectionListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionCollectionListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionCollectionListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ActionCollectionListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ActionCollectionListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ActionCollectionListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ActionCollectionListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Action_Collection_ in self.Action_Collection:
- Action_Collection_.export(outfile, level, 'maecBundle:', name_='Action_Collection', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionCollectionListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Action_Collection=[\n')
- level += 1
- for Action_Collection_ in self.Action_Collection:
- outfile.write('model_.ActionCollectionType(\n')
- Action_Collection_.exportLiteral(outfile, level, name_='ActionCollectionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Action_Collection_.export(write, level, 'maecBundle:', name_='Action_Collection', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4546,52 +3194,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ObjectCollectionListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ObjectCollectionListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectCollectionListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectCollectionListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ObjectCollectionListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ObjectCollectionListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ObjectCollectionListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ObjectCollectionListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Object_Collection_ in self.Object_Collection:
- Object_Collection_.export(outfile, level, 'maecBundle:', name_='Object_Collection', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ObjectCollectionListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Object_Collection=[\n')
- level += 1
- for Object_Collection_ in self.Object_Collection:
- outfile.write('model_.ObjectCollectionType(\n')
- Object_Collection_.exportLiteral(outfile, level, name_='ObjectCollectionType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Object_Collection_.export(write, level, 'maecBundle:', name_='Object_Collection', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4639,59 +3268,41 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='AVClassificationType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='AVClassificationType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AVClassificationType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AVClassificationType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='AVClassificationType'):
- super(AVClassificationType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AVClassificationType')
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='AVClassificationType', fromsubclass_=False, pretty_print=True):
- super(AVClassificationType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='AVClassificationType'):
+ super(AVClassificationType, self).exportAttributes(write, level, already_processed, namespace_, name_='AVClassificationType')
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='AVClassificationType', fromsubclass_=False, pretty_print=True):
+ super(AVClassificationType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Engine_Version is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sEngine_Version>%s%sEngine_Version>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Engine_Version).encode(ExternalEncoding), input_name='Engine_Version'), 'maecBundle:', eol_))
- if self.Definition_Version is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDefinition_Version>%s%sDefinition_Version>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Definition_Version).encode(ExternalEncoding), input_name='Definition_Version'), 'maecBundle:', eol_))
- if self.Classification_Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sClassification_Name>%s%sClassification_Name>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Classification_Name).encode(ExternalEncoding), input_name='Classification_Name'), 'maecBundle:', eol_))
- def exportLiteral(self, outfile, level, name_='AVClassificationType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- super(AVClassificationType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(AVClassificationType, self).exportLiteralChildren(outfile, level, name_)
- if self.Engine_Version is not None:
- showIndent(outfile, level)
- outfile.write('Engine_Version=%s,\n' % quote_python(self.Engine_Version).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sEngine_Version>%s%sEngine_Version>%s' % ('maecBundle:', quote_xml(self.Engine_Version), 'maecBundle:', eol_))
if self.Definition_Version is not None:
- showIndent(outfile, level)
- outfile.write('Definition_Version=%s,\n' % quote_python(self.Definition_Version).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sDefinition_Version>%s%sDefinition_Version>%s' % ('maecBundle:', quote_xml(self.Definition_Version), 'maecBundle:', eol_))
if self.Classification_Name is not None:
- showIndent(outfile, level)
- outfile.write('Classification_Name=%s,\n' % quote_python(self.Classification_Name).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sClassification_Name>%s%sClassification_Name>%s' % ('maecBundle:', quote_xml(self.Classification_Name), 'maecBundle:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4771,90 +3382,47 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ProcessTreeNodeType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ProcessTreeNodeType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ProcessTreeNodeType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ProcessTreeNodeType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ProcessTreeNodeType'):
- super(ProcessTreeNodeType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ProcessTreeNodeType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ProcessTreeNodeType'):
+ super(ProcessTreeNodeType, self).exportAttributes(write, level, already_processed, namespace_, name_='ProcessTreeNodeType')
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
+ write(' id=%s' % (quote_attrib(self.id), ))
if self.parent_action_idref is not None and 'parent_action_idref' not in already_processed:
already_processed.add('parent_action_idref')
- outfile.write(' parent_action_idref=%s' % (quote_attrib(self.parent_action_idref), ))
+ write(' parent_action_idref=%s' % (quote_attrib(self.parent_action_idref), ))
if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
already_processed.add('ordinal_position')
- outfile.write(' ordinal_position=%s' % (quote_attrib(self.ordinal_position), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ProcessTreeNodeType', fromsubclass_=False, pretty_print=True):
- super(ProcessTreeNodeType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write(' ordinal_position=%s' % (quote_attrib(self.ordinal_position), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ProcessTreeNodeType', fromsubclass_=False, pretty_print=True):
+ super(ProcessTreeNodeType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Initiated_Actions is not None:
- self.Initiated_Actions.export(outfile, level, 'maecBundle:', name_='Initiated_Actions', pretty_print=pretty_print)
- for Spawned_Process_ in self.Spawned_Process:
- Spawned_Process_.export(outfile, level, 'maecBundle:', name_='Spawned_Process', pretty_print=pretty_print)
- for Injected_Process_ in self.Injected_Process:
- Injected_Process_.export(outfile, level, 'maecBundle:', name_='Injected_Process', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ProcessTreeNodeType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- if self.parent_action_idref is not None and 'parent_action_idref' not in already_processed:
- already_processed.add('parent_action_idref')
- showIndent(outfile, level)
- outfile.write('parent_action_idref = %s,\n' % (self.parent_action_idref,))
- super(ProcessTreeNodeType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(ProcessTreeNodeType, self).exportLiteralChildren(outfile, level, name_)
- if self.Initiated_Actions is not None:
- outfile.write('Initiated_Actions=model_.ActionReferenceListType(\n')
- self.Initiated_Actions.exportLiteral(outfile, level, name_='Initiated_Actions')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Spawned_Process=[\n')
- level += 1
+ self.Initiated_Actions.export(write, level, 'maecBundle:', name_='Initiated_Actions', pretty_print=pretty_print)
for Spawned_Process_ in self.Spawned_Process:
- outfile.write('model_.ProcessTreeNodeType(\n')
- Spawned_Process_.exportLiteral(outfile, level, name_='ProcessTreeNodeType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Injected_Process=[\n')
- level += 1
+ Spawned_Process_.export(write, level, 'maecBundle:', name_='Spawned_Process', pretty_print=pretty_print)
for Injected_Process_ in self.Injected_Process:
- outfile.write('model_.ProcessTreeNodeType(\n')
- Injected_Process_.exportLiteral(outfile, level, name_='ProcessTreeNodeType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Injected_Process_.export(write, level, 'maecBundle:', name_='Injected_Process', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4918,45 +3486,31 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehavioralActionReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehavioralActionReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehavioralActionReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionReferenceType'):
- super(BehavioralActionReferenceType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='BehavioralActionReferenceType')
- if self.behavioral_ordering is not None and 'behavioral_ordering' not in already_processed:
- already_processed.add('behavioral_ordering')
- outfile.write(' behavioral_ordering="%s"' % self.gds_format_integer(self.behavioral_ordering, input_name='behavioral_ordering'))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionReferenceType', fromsubclass_=False, pretty_print=True):
- super(BehavioralActionReferenceType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
- pass
- def exportLiteral(self, outfile, level, name_='BehavioralActionReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionReferenceType'):
+ super(BehavioralActionReferenceType, self).exportAttributes(write, level, already_processed, namespace_, name_='BehavioralActionReferenceType')
if self.behavioral_ordering is not None and 'behavioral_ordering' not in already_processed:
already_processed.add('behavioral_ordering')
- showIndent(outfile, level)
- outfile.write('behavioral_ordering = %d,\n' % (self.behavioral_ordering,))
- super(BehavioralActionReferenceType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(BehavioralActionReferenceType, self).exportLiteralChildren(outfile, level, name_)
+ write(' behavioral_ordering="%s"' % self.gds_format_integer(self.behavioral_ordering, input_name='behavioral_ordering'))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehavioralActionReferenceType', fromsubclass_=False, pretty_print=True):
+ super(BehavioralActionReferenceType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4968,7 +3522,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('behavioral_ordering')
try:
self.behavioral_ordering = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.behavioral_ordering <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -5009,54 +3563,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ObjectCollectionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ObjectCollectionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectCollectionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectCollectionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ObjectCollectionType'):
- super(ObjectCollectionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectCollectionType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ObjectCollectionType'):
+ super(ObjectCollectionType, self).exportAttributes(write, level, already_processed, namespace_, name_='ObjectCollectionType')
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ObjectCollectionType', fromsubclass_=False, pretty_print=True):
- super(ObjectCollectionType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ObjectCollectionType', fromsubclass_=False, pretty_print=True):
+ super(ObjectCollectionType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Object_List is not None:
- self.Object_List.export(outfile, level, 'maecBundle:', name_='Object_List', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ObjectCollectionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- super(ObjectCollectionType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(ObjectCollectionType, self).exportLiteralChildren(outfile, level, name_)
- if self.Object_List is not None:
- outfile.write('Object_List=model_.ObjectListType(\n')
- self.Object_List.exportLiteral(outfile, level, name_='Object_List')
- outfile.write('),\n')
+ self.Object_List.export(write, level, 'maecBundle:', name_='Object_List', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5108,54 +3645,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='ActionCollectionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='ActionCollectionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionCollectionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionCollectionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='ActionCollectionType'):
- super(ActionCollectionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ActionCollectionType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='ActionCollectionType'):
+ super(ActionCollectionType, self).exportAttributes(write, level, already_processed, namespace_, name_='ActionCollectionType')
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='ActionCollectionType', fromsubclass_=False, pretty_print=True):
- super(ActionCollectionType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='ActionCollectionType', fromsubclass_=False, pretty_print=True):
+ super(ActionCollectionType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Action_List is not None:
- self.Action_List.export(outfile, level, 'maecBundle:', name_='Action_List', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionCollectionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- super(ActionCollectionType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(ActionCollectionType, self).exportLiteralChildren(outfile, level, name_)
- if self.Action_List is not None:
- outfile.write('Action_List=model_.ActionListType(\n')
- self.Action_List.exportLiteral(outfile, level, name_='Action_List')
- outfile.write('),\n')
+ self.Action_List.export(write, level, 'maecBundle:', name_='Action_List', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5208,58 +3728,39 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehaviorCollectionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehaviorCollectionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorCollectionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehaviorCollectionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehaviorCollectionType'):
- super(BehaviorCollectionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='BehaviorCollectionType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehaviorCollectionType'):
+ super(BehaviorCollectionType, self).exportAttributes(write, level, already_processed, namespace_, name_='BehaviorCollectionType')
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehaviorCollectionType', fromsubclass_=False, pretty_print=True):
- super(BehaviorCollectionType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehaviorCollectionType', fromsubclass_=False, pretty_print=True):
+ super(BehaviorCollectionType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Purpose is not None:
- outfile.write('<%sPurpose>%s%sPurpose>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Purpose).encode(ExternalEncoding), input_name='Purpose'), 'maecBundle:', eol_))
- if self.Behavior_List is not None:
- self.Behavior_List.export(outfile, level, 'maecBundle:', name_='Behavior_List', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehaviorCollectionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- super(BehaviorCollectionType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(BehaviorCollectionType, self).exportLiteralChildren(outfile, level, name_)
- if self.Purpose is not None:
- outfile.write('Purpose=%s,\n' % quote_python(self.Purpose).encode(ExternalEncoding))
+ write('<%sPurpose>%s%sPurpose>%s' % ('maecBundle:', quote_xml(self.Purpose), 'maecBundle:', eol_))
if self.Behavior_List is not None:
- outfile.write('Behavior_List=model_.BehaviorListType(\n')
- self.Behavior_List.exportLiteral(outfile, level, name_='Behavior_List')
- outfile.write('),\n')
+ self.Behavior_List.export(write, level, 'maecBundle:', name_='Behavior_List', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5320,51 +3821,38 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='MalwareActionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='MalwareActionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareActionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareActionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='MalwareActionType'):
- super(MalwareActionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareActionType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='MalwareActionType'):
+ super(MalwareActionType, self).exportAttributes(write, level, already_processed, namespace_, name_='MalwareActionType')
if self.extensiontype_ is not None and 'xsi:type' not in already_processed:
already_processed.add('xsi:type')
- outfile.write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
- outfile.write(' xsi:type="%s"' % self.extensiontype_)
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='MalwareActionType', fromsubclass_=False, pretty_print=True):
- super(MalwareActionType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
+ write(' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"')
+ write(' xsi:type="%s"' % self.extensiontype_)
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='MalwareActionType', fromsubclass_=False, pretty_print=True):
+ super(MalwareActionType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Implementation is not None:
- self.Implementation.export(outfile, level, 'maecBundle:', name_='Implementation', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareActionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- super(MalwareActionType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(MalwareActionType, self).exportLiteralChildren(outfile, level, name_)
- if self.Implementation is not None:
- outfile.write('Implementation=model_.ActionImplementationType(\n')
- self.Implementation.exportLiteral(outfile, level, name_='Implementation')
- outfile.write('),\n')
+ self.Implementation.export(write, level, 'maecBundle:', name_='Implementation', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5411,44 +3899,31 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='BehavioralActionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
- already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='BehavioralActionType')
- if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionType'):
- super(BehavioralActionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='BehavioralActionType')
- if self.behavioral_ordering is not None and 'behavioral_ordering' not in already_processed:
- already_processed.add('behavioral_ordering')
- outfile.write(' behavioral_ordering="%s"' % self.gds_format_integer(self.behavioral_ordering, input_name='behavioral_ordering'))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='BehavioralActionType', fromsubclass_=False, pretty_print=True):
- super(BehavioralActionType, self).exportChildren(outfile, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='BehavioralActionType'):
- level += 1
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
+ self.exportAttributes(write, level, already_processed, namespace_, name_='BehavioralActionType')
if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='BehavioralActionType'):
+ super(BehavioralActionType, self).exportAttributes(write, level, already_processed, namespace_, name_='BehavioralActionType')
if self.behavioral_ordering is not None and 'behavioral_ordering' not in already_processed:
already_processed.add('behavioral_ordering')
- showIndent(outfile, level)
- outfile.write('behavioral_ordering = %d,\n' % (self.behavioral_ordering,))
- super(BehavioralActionType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(BehavioralActionType, self).exportLiteralChildren(outfile, level, name_)
+ write(' behavioral_ordering="%s"' % self.gds_format_integer(self.behavioral_ordering, input_name='behavioral_ordering'))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='BehavioralActionType', fromsubclass_=False, pretty_print=True):
+ super(BehavioralActionType, self).exportChildren(write, level, 'maecBundle:', name_, True, pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5460,7 +3935,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('behavioral_ordering')
try:
self.behavioral_ordering = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.behavioral_ordering <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -5548,122 +4023,49 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityType'):
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
+ write(' id=%s' % (quote_attrib(self.id), ))
if self.name is not None and 'name' not in already_processed:
already_processed.add('name')
- outfile.write(' name=%s' % (quote_attrib(self.name), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityType', fromsubclass_=False, pretty_print=True):
+ write(' name=%s' % (quote_attrib(self.name), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
for Property_ in self.Property:
- Property_.export(outfile, level, 'maecBundle:', name_='Property', pretty_print=pretty_print)
+ Property_.export(write, level, 'maecBundle:', name_='Property', pretty_print=pretty_print)
for Strategic_Objective_ in self.Strategic_Objective:
- Strategic_Objective_.export(outfile, level, 'maecBundle:', name_='Strategic_Objective', pretty_print=pretty_print)
+ Strategic_Objective_.export(write, level, 'maecBundle:', name_='Strategic_Objective', pretty_print=pretty_print)
for Tactical_Objective_ in self.Tactical_Objective:
- Tactical_Objective_.export(outfile, level, 'maecBundle:', name_='Tactical_Objective', pretty_print=pretty_print)
+ Tactical_Objective_.export(write, level, 'maecBundle:', name_='Tactical_Objective', pretty_print=pretty_print)
for Behavior_Reference_ in self.Behavior_Reference:
- Behavior_Reference_.export(outfile, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
+ Behavior_Reference_.export(write, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
for Relationship_ in self.Relationship:
- Relationship_.export(outfile, level, 'maecBundle:', name_='Relationship', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapabilityType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- if self.name is not None and 'name' not in already_processed:
- already_processed.add('name')
- showIndent(outfile, level)
- outfile.write('name = %s,\n' % (self.name,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
- showIndent(outfile, level)
- outfile.write('Property=[\n')
- level += 1
- for Property_ in self.Property:
- outfile.write('model_.CapabilityPropertyType(\n')
- Property_.exportLiteral(outfile, level, name_='CapabilityPropertyType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Strategic_Objective=[\n')
- level += 1
- for Strategic_Objective_ in self.Strategic_Objective:
- outfile.write('model_.CapabilityObjectiveType(\n')
- Strategic_Objective_.exportLiteral(outfile, level, name_='CapabilityObjectiveType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Tactical_Objective=[\n')
- level += 1
- for Tactical_Objective_ in self.Tactical_Objective:
- outfile.write('model_.CapabilityObjectiveType(\n')
- Tactical_Objective_.exportLiteral(outfile, level, name_='CapabilityObjectiveType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Behavior_Reference=[\n')
- level += 1
- for Behavior_Reference_ in self.Behavior_Reference:
- outfile.write('model_.BehaviorReferenceType(\n')
- Behavior_Reference_.exportLiteral(outfile, level, name_='BehaviorReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Relationship=[\n')
- level += 1
- for Relationship_ in self.Relationship:
- outfile.write('model_.CapabilityRelationshipType(\n')
- Relationship_.exportLiteral(outfile, level, name_='CapabilityRelationshipType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Relationship_.export(write, level, 'maecBundle:', name_='Relationship', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5740,58 +4142,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Capability_ in self.Capability:
- Capability_.export(outfile, level, 'maecBundle:', name_='Capability', pretty_print=pretty_print)
+ Capability_.export(write, level, 'maecBundle:', name_='Capability', pretty_print=pretty_print)
for Capability_Reference_ in self.Capability_Reference:
- Capability_Reference_.export(outfile, level, 'maecBundle:', name_='Capability_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapabilityListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Capability is not None:
- outfile.write('Capability=model_.CapabilityType(\n')
- self.Capability.exportLiteral(outfile, level, name_='Capability')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Capability_Reference=[\n')
- level += 1
- for Capability_Reference_ in self.Capability_Reference:
- outfile.write('model_.CapabilityReferenceType(\n')
- Capability_Reference_.exportLiteral(outfile, level, name_='CapabilityReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Capability_Reference_.export(write, level, 'maecBundle:', name_='Capability_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5835,41 +4214,29 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityReferenceType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityReferenceType'):
if self.capability_idref is not None and 'capability_idref' not in already_processed:
already_processed.add('capability_idref')
- outfile.write(' capability_idref=%s' % (quote_attrib(self.capability_idref), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='CapabilityReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.capability_idref is not None and 'capability_idref' not in already_processed:
- already_processed.add('capability_idref')
- showIndent(outfile, level)
- outfile.write('capability_idref = %s,\n' % (self.capability_idref,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' capability_idref=%s' % (quote_attrib(self.capability_idref), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5942,95 +4309,44 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityObjectiveType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityObjectiveType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityObjectiveType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityObjectiveType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityObjectiveType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityObjectiveType'):
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityObjectiveType', fromsubclass_=False, pretty_print=True):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityObjectiveType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Name is not None:
- self.Name.export(outfile, level, 'maecBundle:', name_='Name', pretty_print=pretty_print)
- if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', self.gds_format_string(quote_xml(self.Description).encode(ExternalEncoding), input_name='Description'), 'maecBundle:', eol_))
- for Property_ in self.Property:
- Property_.export(outfile, level, 'maecBundle:', name_='Property', pretty_print=pretty_print)
- for Behavior_Reference_ in self.Behavior_Reference:
- Behavior_Reference_.export(outfile, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
- for Relationship_ in self.Relationship:
- Relationship_.export(outfile, level, 'maecBundle:', name_='Relationship', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapabilityObjectiveType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Name is not None:
- outfile.write('Name=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Name.exportLiteral(outfile, level, name_='Name')
- outfile.write('),\n')
+ self.Name.export(write, level, 'maecBundle:', name_='Name', pretty_print=pretty_print)
if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%s,\n' % quote_python(self.Description).encode(ExternalEncoding))
- showIndent(outfile, level)
- outfile.write('Property=[\n')
- level += 1
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % ('maecBundle:', quote_xml(self.Description), 'maecBundle:', eol_))
for Property_ in self.Property:
- outfile.write('model_.CapabilityPropertyType(\n')
- Property_.exportLiteral(outfile, level, name_='CapabilityPropertyType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Behavior_Reference=[\n')
- level += 1
+ Property_.export(write, level, 'maecBundle:', name_='Property', pretty_print=pretty_print)
for Behavior_Reference_ in self.Behavior_Reference:
- outfile.write('model_.BehaviorReferenceType(\n')
- Behavior_Reference_.exportLiteral(outfile, level, name_='BehaviorReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Relationship=[\n')
- level += 1
+ Behavior_Reference_.export(write, level, 'maecBundle:', name_='Behavior_Reference', pretty_print=pretty_print)
for Relationship_ in self.Relationship:
- outfile.write('model_.CapabilityObjectiveRelationshipType(\n')
- Relationship_.exportLiteral(outfile, level, name_='CapabilityObjectiveRelationshipType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Relationship_.export(write, level, 'maecBundle:', name_='Relationship', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -6095,58 +4411,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityRelationshipType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityRelationshipType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityRelationshipType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityRelationshipType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityRelationshipType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityRelationshipType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityRelationshipType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityRelationshipType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Relationship_Type is not None:
- self.Relationship_Type.export(outfile, level, 'maecBundle:', name_='Relationship_Type', pretty_print=pretty_print)
- for Capability_Reference_ in self.Capability_Reference:
- Capability_Reference_.export(outfile, level, 'maecBundle:', name_='Capability_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapabilityRelationshipType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Relationship_Type is not None:
- outfile.write('Relationship_Type=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Relationship_Type.exportLiteral(outfile, level, name_='Relationship_Type')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Capability_Reference=[\n')
- level += 1
+ self.Relationship_Type.export(write, level, 'maecBundle:', name_='Relationship_Type', pretty_print=pretty_print)
for Capability_Reference_ in self.Capability_Reference:
- outfile.write('model_.CapabilityType(\n')
- Capability_Reference_.exportLiteral(outfile, level, name_='CapabilityType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Capability_Reference_.export(write, level, 'maecBundle:', name_='Capability_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -6197,58 +4490,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityObjectiveRelationshipType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityObjectiveRelationshipType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityObjectiveRelationshipType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityObjectiveRelationshipType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityObjectiveRelationshipType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityObjectiveRelationshipType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityObjectiveRelationshipType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityObjectiveRelationshipType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Relationship_Type is not None:
- self.Relationship_Type.export(outfile, level, 'maecBundle:', name_='Relationship_Type', pretty_print=pretty_print)
+ self.Relationship_Type.export(write, level, 'maecBundle:', name_='Relationship_Type', pretty_print=pretty_print)
for Objective_Reference_ in self.Objective_Reference:
- Objective_Reference_.export(outfile, level, 'maecBundle:', name_='Objective_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapabilityObjectiveRelationshipType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Relationship_Type is not None:
- outfile.write('Relationship_Type=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Relationship_Type.exportLiteral(outfile, level, name_='Relationship_Type')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Objective_Reference=[\n')
- level += 1
- for Objective_Reference_ in self.Objective_Reference:
- outfile.write('model_.CapabilityObjectiveReferenceType(\n')
- Objective_Reference_.exportLiteral(outfile, level, name_='CapabilityObjectiveReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Objective_Reference_.export(write, level, 'maecBundle:', name_='Objective_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -6293,41 +4563,29 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityObjectiveReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityObjectiveReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityObjectiveReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityObjectiveReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityObjectiveReferenceType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityObjectiveReferenceType'):
if self.objective_idref is not None and 'objective_idref' not in already_processed:
already_processed.add('objective_idref')
- outfile.write(' objective_idref=%s' % (quote_attrib(self.objective_idref), ))
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityObjectiveReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='CapabilityObjectiveReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.objective_idref is not None and 'objective_idref' not in already_processed:
- already_processed.add('objective_idref')
- showIndent(outfile, level)
- outfile.write('objective_idref = %s,\n' % (self.objective_idref,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' objective_idref=%s' % (quote_attrib(self.objective_idref), ))
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityObjectiveReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -6371,51 +4629,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecBundle:', name_='CapabilityPropertyType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecBundle:', name_='CapabilityPropertyType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapabilityPropertyType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapabilityPropertyType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecBundle:', name_='CapabilityPropertyType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecBundle:', name_='CapabilityPropertyType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecBundle:', name_='CapabilityPropertyType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecBundle:', name_='CapabilityPropertyType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Name is not None:
- self.Name.export(outfile, level, 'maecBundle:', name_='Name', pretty_print=pretty_print)
+ self.Name.export(write, level, 'maecBundle:', name_='Name', pretty_print=pretty_print)
if self.Value is not None:
- self.Value.export(outfile, level, 'maecBundle:', name_='Value', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapabilityPropertyType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Name is not None:
- outfile.write('Name=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Name.exportLiteral(outfile, level, name_='Name')
- outfile.write('),\n')
- if self.Value is not None:
- outfile.write('Value=model_.cybox_common.StringObjectPropertyType(\n')
- self.Value.exportLiteral(outfile, level, name_='Value')
- outfile.write('),\n')
+ self.Value.export(write, level, 'maecBundle:', name_='Value', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -6439,14 +4681,20 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
"""
def usage():
- print USAGE_TEXT
+ print(USAGE_TEXT)
sys.exit(1)
+def get_root_tag(node):
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
+ rootClass = GDSClassesMapping.get(tag)
+ if rootClass is None:
+ rootClass = globals().get(tag)
+ return tag, rootClass
+
def parse(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Bundle'
- rootClass = BundleType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -6460,8 +4708,7 @@ def parse(inFileName):
def parseEtree(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Bundle'
- rootClass = BundleType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -6474,11 +4721,10 @@ def parseEtree(inFileName):
return rootObj, rootElement
def parseString(inString):
- from StringIO import StringIO
+ from mixbox.vendor.six import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
- rootTag = 'MAEC_Bundle'
- rootClass = BundleType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -6491,8 +4737,7 @@ def parseString(inString):
def parseLiteral(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Bundle'
- rootClass = BundleType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -6562,4 +4807,52 @@ def main():
"ActionCollectionListType",
"ObjectCollectionListType",
"AVClassificationType"
- ]
\ No newline at end of file
+ ]
+
+GDSClassesMapping = {
+ "MalwareActionType": MalwareActionType,
+ "MAEC_Bundle": BundleType,
+ "BehaviorType": BehaviorType,
+ "BehaviorCollectionType": BehaviorCollectionType,
+ "ActionCollectionType": ActionCollectionType,
+ "APICallType": APICallType,
+ "ActionImplementationType": ActionImplementationType,
+ "CVEVulnerabilityType": CVEVulnerabilityType,
+ "ObjectCollectionType": ObjectCollectionType,
+ "BaseCollectionType": BaseCollectionType,
+ "BehaviorRelationshipType": BehaviorRelationshipType,
+ "AVClassificationsType": AVClassificationsType,
+ "ParameterType": ParameterType,
+ "ParameterListType": ParameterListType,
+ "AssociatedCodeType": AssociatedCodeType,
+ "BehaviorPurposeType": BehaviorPurposeType,
+ "PlatformListType": PlatformListType,
+ "ExploitType": ExploitType,
+ "BehaviorRelationshipListType": BehaviorRelationshipListType,
+ "BehavioralActionsType": BehavioralActionsType,
+ "BehaviorListType": BehaviorListType,
+ "ActionListType": ActionListType,
+ "ObjectListType": ObjectListType,
+ "BehaviorReferenceType": BehaviorReferenceType,
+ "ObjectReferenceType": ObjectReferenceType,
+ "BehavioralActionType": BehavioralActionType,
+ "BehavioralActionReferenceType": BehavioralActionReferenceType,
+ "BehavioralActionEquivalenceReferenceType": BehavioralActionEquivalenceReferenceType,
+ "BehaviorReferenceListType": BehaviorReferenceListType,
+ "ActionReferenceListType": ActionReferenceListType,
+ "ObjectReferenceListType": ObjectReferenceListType,
+ "CandidateIndicatorType": CandidateIndicatorType,
+ "CandidateIndicatorListType": CandidateIndicatorListType,
+ "MalwareEntityType": MalwareEntityType,
+ "CollectionsType": CollectionsType,
+ "BundleReferenceType": BundleReferenceType,
+ "ProcessTreeType": ProcessTreeType,
+ "ProcessTreeNodeType": ProcessTreeNodeType,
+ "CandidateIndicatorCompositionType": CandidateIndicatorCompositionType,
+ "CandidateIndicatorCollectionType": CandidateIndicatorCollectionType,
+ "CandidateIndicatorCollectionListType": CandidateIndicatorCollectionListType,
+ "BehaviorCollectionListType": BehaviorCollectionListType,
+ "ActionCollectionListType": ActionCollectionListType,
+ "ObjectCollectionListType": ObjectCollectionListType,
+ "AVClassificationType": AVClassificationType
+}
diff --git a/maec/bindings/maec_container.py b/maec/bindings/maec_container.py
index 988fa68..dfe855c 100644
--- a/maec/bindings/maec_container.py
+++ b/maec/bindings/maec_container.py
@@ -1,517 +1,11 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-#
-# Generated Mon Apr 29 08:31:25 2013 by generateDS.py version 2.9a.
-#
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
import sys
-import getopt
-import re as re_
-
-from maec.bindings import maec_package as maec_package_schema
-import base64
-from datetime import datetime, tzinfo, timedelta
-
-etree_ = None
-Verbose_import_ = False
-( XMLParser_import_none, XMLParser_import_lxml,
- XMLParser_import_elementtree
- ) = range(3)
-XMLParser_import_library = None
-try:
- # lxml
- from lxml import etree as etree_
- XMLParser_import_library = XMLParser_import_lxml
- if Verbose_import_:
- print("running with lxml.etree")
-except ImportError:
- try:
- # cElementTree from Python 2.5+
- import xml.etree.cElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with cElementTree on Python 2.5+")
- except ImportError:
- try:
- # ElementTree from Python 2.5+
- import xml.etree.ElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with ElementTree on Python 2.5+")
- except ImportError:
- try:
- # normal cElementTree install
- import cElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with cElementTree")
- except ImportError:
- try:
- # normal ElementTree install
- import elementtree.ElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with ElementTree")
- except ImportError:
- raise ImportError(
- "Failed to import ElementTree from any known place")
-
-def parsexml_(*args, **kwargs):
- if (XMLParser_import_library == XMLParser_import_lxml and
- 'parser' not in kwargs):
- # Use the lxml ElementTree compatible parser so that, e.g.,
- # we ignore comments.
- kwargs['parser'] = etree_.ETCompatXMLParser(huge_tree=True)
- doc = etree_.parse(*args, **kwargs)
- return doc
-
-#
-# User methods
-#
-# Calls to the methods in these classes are generated by generateDS.py.
-# You can replace these methods by re-implementing the following class
-# in a module named generatedssuper.py.
-
-try:
- from generatedssuper import GeneratedsSuper
-except ImportError, exp:
-
- class GeneratedsSuper(object):
- tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
- class _FixedOffsetTZ(tzinfo):
- def __init__(self, offset, name):
- self.__offset = timedelta(minutes = offset)
- self.__name = name
- def utcoffset(self, dt):
- return self.__offset
- def tzname(self, dt):
- return self.__name
- def dst(self, dt):
- return None
- def gds_format_string(self, input_data, input_name=''):
- return input_data
- def gds_validate_string(self, input_data, node, input_name=''):
- return input_data
- def gds_format_base64(self, input_data, input_name=''):
- return base64.b64encode(input_data)
- def gds_validate_base64(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer(self, input_data, input_name=''):
- return '%d' % input_data
- def gds_validate_integer(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_integer_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of integers')
- return input_data
- def gds_format_float(self, input_data, input_name=''):
- return '%f' % input_data
- def gds_validate_float(self, input_data, node, input_name=''):
- return input_data
- def gds_format_float_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_float_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of floats')
- return input_data
- def gds_format_double(self, input_data, input_name=''):
- return '%e' % input_data
- def gds_validate_double(self, input_data, node, input_name=''):
- return input_data
- def gds_format_double_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_double_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of doubles')
- return input_data
- def gds_format_boolean(self, input_data, input_name=''):
- return ('%s' % input_data).lower()
- def gds_validate_boolean(self, input_data, node, input_name=''):
- return input_data
- def gds_format_boolean_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_boolean_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- if value not in ('true', '1', 'false', '0', ):
- raise_parse_error(node,
- 'Requires sequence of booleans '
- '("true", "1", "false", "0")')
- return input_data
- def gds_validate_datetime(self, input_data, node, input_name=''):
- return input_data
- def gds_format_datetime(self, input_data, input_name=''):
- if input_data.microsecond == 0:
- _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S')
- else:
- _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S.%f')
- if input_data.tzinfo is not None:
- tzoff = input_data.tzinfo.utcoffset(input_data)
- if tzoff is not None:
- total_seconds = tzoff.seconds + (86400 * tzoff.days)
- if total_seconds == 0:
- _svalue += 'Z'
- else:
- if total_seconds < 0:
- _svalue += '-'
- total_seconds *= -1
- else:
- _svalue += '+'
- hours = total_seconds // 3600
- minutes = (total_seconds - (hours * 3600)) // 60
- _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
- return _svalue
- def gds_parse_datetime(self, input_data, node, input_name=''):
- tz = None
- if input_data[-1] == 'Z':
- tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
- input_data = input_data[:-1]
- else:
- results = GeneratedsSuper.tzoff_pattern.search(input_data)
- if results is not None:
- tzoff_parts = results.group(2).split(':')
- tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
- if results.group(1) == '-':
- tzoff *= -1
- tz = GeneratedsSuper._FixedOffsetTZ(
- tzoff, results.group(0))
- input_data = input_data[:-6]
- if len(input_data.split('.')) > 1:
- dt = datetime.strptime(
- input_data, '%Y-%m-%dT%H:%M:%S.%f')
- else:
- dt = datetime.strptime(
- input_data, '%Y-%m-%dT%H:%M:%S')
- return dt.replace(tzinfo = tz)
-
- def gds_validate_date(self, input_data, node, input_name=''):
- return input_data
- def gds_format_date(self, input_data, input_name=''):
- _svalue = input_data.strftime('%Y-%m-%d')
- if input_data.tzinfo is not None:
- tzoff = input_data.tzinfo.utcoffset(input_data)
- if tzoff is not None:
- total_seconds = tzoff.seconds + (86400 * tzoff.days)
- if total_seconds == 0:
- _svalue += 'Z'
- else:
- if total_seconds < 0:
- _svalue += '-'
- total_seconds *= -1
- else:
- _svalue += '+'
- hours = total_seconds // 3600
- minutes = (total_seconds - (hours * 3600)) // 60
- _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
- return _svalue
- def gds_parse_date(self, input_data, node, input_name=''):
- tz = None
- if input_data[-1] == 'Z':
- tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
- input_data = input_data[:-1]
- else:
- results = GeneratedsSuper.tzoff_pattern.search(input_data)
- if results is not None:
- tzoff_parts = results.group(2).split(':')
- tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
- if results.group(1) == '-':
- tzoff *= -1
- tz = GeneratedsSuper._FixedOffsetTZ(
- tzoff, results.group(0))
- input_data = input_data[:-6]
- return datetime.strptime(input_data,
- '%Y-%m-%d').replace(tzinfo = tz)
- def gds_str_lower(self, instring):
- return instring.lower()
- def get_path_(self, node):
- path_list = []
- self.get_path_list_(node, path_list)
- path_list.reverse()
- path = '/'.join(path_list)
- return path
- Tag_strip_pattern_ = re_.compile(r'\{.*\}')
- def get_path_list_(self, node, path_list):
- if node is None:
- return
- tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
- if tag:
- path_list.append(tag)
- self.get_path_list_(node.getparent(), path_list)
- def get_class_obj_(self, node, default_class=None):
- class_obj1 = default_class
- if 'xsi' in node.nsmap:
- classname = node.get('{%s}type' % node.nsmap['xsi'])
- if classname is not None:
- names = classname.split(':')
- if len(names) == 2:
- classname = names[1]
- class_obj2 = globals().get(classname)
- if class_obj2 is not None:
- class_obj1 = class_obj2
- return class_obj1
- def gds_build_any(self, node, type_name=None):
- return None
-
-
-#
-# If you have installed IPython you can uncomment and use the following.
-# IPython is available from http://ipython.scipy.org/.
-#
-
-## from IPython.Shell import IPShellEmbed
-## args = ''
-## ipshell = IPShellEmbed(args,
-## banner = 'Dropping into IPython',
-## exit_msg = 'Leaving Interpreter, back to program.')
-
-# Then use the following line where and when you want to drop into the
-# IPython shell:
-# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit')
-
-#
-# Globals
-#
-
-ExternalEncoding = 'utf-8'
-Tag_pattern_ = re_.compile(r'({.*})?(.*)')
-String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
-Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
-
-#
-# Support/utility functions.
-#
-
-def showIndent(outfile, level, pretty_print=True):
- if pretty_print:
- for idx in range(level):
- outfile.write(' ')
-
-def quote_xml(inStr):
- if not inStr:
- return ''
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- return unicode(s1)
-
-def quote_attrib(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- if '"' in s1:
- if "'" in s1:
- s1 = '"%s"' % s1.replace('"', """)
- else:
- s1 = "'%s'" % s1
- else:
- s1 = '"%s"' % s1
- return unicode(s1)
-
-def quote_python(inStr):
- s1 = inStr
- if s1.find("'") == -1:
- if s1.find('\n') == -1:
- return "'%s'" % s1
- else:
- return "'''%s'''" % s1
- else:
- if s1.find('"') != -1:
- s1 = s1.replace('"', '\\"')
- if s1.find('\n') == -1:
- return '"%s"' % s1
- else:
- return '"""%s"""' % s1
-
-def get_all_text_(node):
- if node.text is not None:
- text = node.text
- else:
- text = ''
- for child in node:
- if child.tail is not None:
- text += child.tail
- return text
-
-def find_attr_value_(attr_name, node):
- attrs = node.attrib
- attr_parts = attr_name.split(':')
- value = None
- if len(attr_parts) == 1:
- value = attrs.get(attr_name)
- elif len(attr_parts) == 2:
- prefix, name = attr_parts
- namespace = node.nsmap.get(prefix)
- if namespace is not None:
- value = attrs.get('{%s}%s' % (namespace, name, ))
- return value
-
-
-class GDSParseError(Exception):
- pass
-
-def raise_parse_error(node, msg):
- if XMLParser_import_library == XMLParser_import_lxml:
- msg = '%s (element %s/line %d)' % (
- msg, node.tag, node.sourceline, )
- else:
- msg = '%s (element %s)' % (msg, node.tag, )
- raise GDSParseError(msg)
-
-class MixedContainer:
- # Constants for category:
- CategoryNone = 0
- CategoryText = 1
- CategorySimple = 2
- CategoryComplex = 3
- # Constants for content_type:
- TypeNone = 0
- TypeText = 1
- TypeString = 2
- TypeInteger = 3
- TypeFloat = 4
- TypeDecimal = 5
- TypeDouble = 6
- TypeBoolean = 7
- TypeBase64 = 8
- def __init__(self, category, content_type, name, value):
- self.category = category
- self.content_type = content_type
- self.name = name
- self.value = value
- def getCategory(self):
- return self.category
- def getContenttype(self, content_type):
- return self.content_type
- def getValue(self):
- return self.value
- def getName(self):
- return self.name
- def export(self, outfile, level, name, namespace, pretty_print=True):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- outfile.write(self.value)
- elif self.category == MixedContainer.CategorySimple:
- self.exportSimple(outfile, level, name)
- else: # category == MixedContainer.CategoryComplex
- self.value.export(outfile, level, namespace, name, pretty_print)
- def exportSimple(self, outfile, level, name):
- if self.content_type == MixedContainer.TypeString:
- outfile.write('<%s>%s%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeInteger or \
- self.content_type == MixedContainer.TypeBoolean:
- outfile.write('<%s>%d%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeFloat or \
- self.content_type == MixedContainer.TypeDecimal:
- outfile.write('<%s>%f%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeDouble:
- outfile.write('<%s>%g%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeBase64:
- outfile.write('<%s>%s%s>' %
- (self.name, base64.b64encode(self.value), self.name))
- def to_etree(self, element):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- if len(element) > 0:
- if element[-1].tail is None:
- element[-1].tail = self.value
- else:
- element[-1].tail += self.value
- else:
- if element.text is None:
- element.text = self.value
- else:
- element.text += self.value
- elif self.category == MixedContainer.CategorySimple:
- subelement = etree_.SubElement(element, '%s' % self.name)
- subelement.text = self.to_etree_simple()
- else: # category == MixedContainer.CategoryComplex
- self.value.to_etree(element)
- def to_etree_simple(self):
- if self.content_type == MixedContainer.TypeString:
- text = self.value
- elif (self.content_type == MixedContainer.TypeInteger or
- self.content_type == MixedContainer.TypeBoolean):
- text = '%d' % self.value
- elif (self.content_type == MixedContainer.TypeFloat or
- self.content_type == MixedContainer.TypeDecimal):
- text = '%f' % self.value
- elif self.content_type == MixedContainer.TypeDouble:
- text = '%g' % self.value
- elif self.content_type == MixedContainer.TypeBase64:
- text = '%s' % base64.b64encode(self.value)
- return text
- def exportLiteral(self, outfile, level, name):
- if self.category == MixedContainer.CategoryText:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
- % (self.category, self.content_type, self.name, self.value))
- elif self.category == MixedContainer.CategorySimple:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
- % (self.category, self.content_type, self.name, self.value))
- else: # category == MixedContainer.CategoryComplex
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
- (self.category, self.content_type, self.name,))
- self.value.exportLiteral(outfile, level + 1)
- showIndent(outfile, level)
- outfile.write(')\n')
+from mixbox.binding_utils import *
-
-class MemberSpec_(object):
- def __init__(self, name='', data_type='', container=0):
- self.name = name
- self.data_type = data_type
- self.container = container
- def set_name(self, name): self.name = name
- def get_name(self): return self.name
- def set_data_type(self, data_type): self.data_type = data_type
- def get_data_type_chain(self): return self.data_type
- def get_data_type(self):
- if isinstance(self.data_type, list):
- if len(self.data_type) > 0:
- return self.data_type[-1]
- else:
- return 'xs:string'
- else:
- return self.data_type
- def set_container(self, container): self.container = container
- def get_container(self): return self.container
-
-def _cast(typ, value):
- if typ is None or value is None:
- return value
- return typ(value)
-
-#
-# Data representation classes.
-#
+from maec.bindings import maec_package as maec_package_schema
class ContainerType(GeneratedsSuper):
"""The ContainerType encompasses all forms of MAEC data. Currently,
@@ -550,64 +44,41 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecContainer:', name_='MAEC_Container', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecContainer:', name_='MAEC_Container', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MAEC_Container')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MAEC_Container')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecContainer:', name_='MAEC_Container'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecContainer:', name_='MAEC_Container'):
if self.timestamp is not None and 'timestamp' not in already_processed:
already_processed.add('timestamp')
- outfile.write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
+ write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
+ write(' id=%s' % (quote_attrib(self.id), ))
if self.schema_version is not None and 'schema_version' not in already_processed:
already_processed.add('schema_version')
- outfile.write(' schema_version="%s"' % self.schema_version)
- def exportChildren(self, outfile, level, namespace_='maecContainer:', name_='MAEC_Container', fromsubclass_=False, pretty_print=True):
+ write(' schema_version="%s"' % self.schema_version)
+ def exportChildren(self, write, level, namespace_='maecContainer:', name_='MAEC_Container', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Packages is not None:
- self.Packages.export(outfile, level, 'maecContainer:', name_='Packages', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MAEC_Container'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.timestamp is not None and 'timestamp' not in already_processed:
- already_processed.add('timestamp')
- showIndent(outfile, level)
- outfile.write('timestamp = "%s",\n' % (self.timestamp,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- if self.schema_version is not None and 'schema_version' not in already_processed:
- already_processed.add('schema_version')
- showIndent(outfile, level)
- outfile.write('schema_version = %s,\n' % (self.schema_version))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Packages is not None:
- outfile.write('Packages=model_.PackageListType(\n')
- self.Packages.exportLiteral(outfile, level, name_='Packages')
- outfile.write('),\n')
+ self.Packages.export(write, level, 'maecContainer:', name_='Packages', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -619,7 +90,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('timestamp')
try:
self.timestamp = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (timestamp): %s' % exp)
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
@@ -662,52 +133,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecContainer:', name_='PackageListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecContainer:', name_='PackageListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='PackageListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='PackageListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecContainer:', name_='PackageListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecContainer:', name_='PackageListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecContainer:', name_='PackageListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecContainer:', name_='PackageListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Package_ in self.Package:
- Package_.export(outfile, level, 'maecContainer:', name_='Package', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='PackageListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Package=[\n')
- level += 1
- for Package_ in self.Package:
- outfile.write('model_.maec_package_schema.PackageType(\n')
- Package_.exportLiteral(outfile, level, name_='maec_package_schema.PackageType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Package_.export(write, level, 'maecContainer:', name_='Package', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -727,14 +179,20 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
"""
def usage():
- print USAGE_TEXT
+ print(USAGE_TEXT)
sys.exit(1)
+def get_root_tag(node):
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
+ rootClass = GDSClassesMapping.get(tag)
+ if rootClass is None:
+ rootClass = globals().get(tag)
+ return tag, rootClass
+
def parse(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Container'
- rootClass = ContainerType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -748,8 +206,7 @@ def parse(inFileName):
def parseEtree(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Container'
- rootClass = ContainerType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -762,11 +219,10 @@ def parseEtree(inFileName):
return rootObj, rootElement
def parseString(inString):
- from StringIO import StringIO
+ from mixbox.vendor.six import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
- rootTag = 'MAEC_Container'
- rootClass = ContainerType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -779,8 +235,7 @@ def parseString(inString):
def parseLiteral(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Container'
- rootClass = ContainerType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -807,4 +262,9 @@ def main():
__all__ = [
"ContainerType",
"PackageListType"
- ]
\ No newline at end of file
+ ]
+
+GDSClassesMapping = {
+ "ContainerType": ContainerType,
+ "PackageListType": PackageListType
+}
diff --git a/maec/bindings/maec_package.py b/maec/bindings/maec_package.py
index f77c38f..a87e803 100644
--- a/maec/bindings/maec_package.py
+++ b/maec/bindings/maec_package.py
@@ -1,13 +1,9 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-#
-# Generated Mon Apr 29 08:30:56 2013 by generateDS.py version 2.9a.
-#
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
import sys
-import getopt
-import re as re_
+
+from mixbox.binding_utils import *
from maec.bindings import maec_bundle as maec_bundle_schema
from maec.bindings import mmdef_1_2 as metadatasharing
@@ -16,508 +12,6 @@
from cybox.bindings import cybox_common
from cybox.bindings import file_object
from cybox.bindings import uri_object
-import base64
-from datetime import datetime, tzinfo, timedelta
-
-etree_ = None
-Verbose_import_ = False
-( XMLParser_import_none, XMLParser_import_lxml,
- XMLParser_import_elementtree
- ) = range(3)
-XMLParser_import_library = None
-try:
- # lxml
- from lxml import etree as etree_
- XMLParser_import_library = XMLParser_import_lxml
- if Verbose_import_:
- print("running with lxml.etree")
-except ImportError:
- try:
- # cElementTree from Python 2.5+
- import xml.etree.cElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with cElementTree on Python 2.5+")
- except ImportError:
- try:
- # ElementTree from Python 2.5+
- import xml.etree.ElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with ElementTree on Python 2.5+")
- except ImportError:
- try:
- # normal cElementTree install
- import cElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with cElementTree")
- except ImportError:
- try:
- # normal ElementTree install
- import elementtree.ElementTree as etree_
- XMLParser_import_library = XMLParser_import_elementtree
- if Verbose_import_:
- print("running with ElementTree")
- except ImportError:
- raise ImportError(
- "Failed to import ElementTree from any known place")
-
-def parsexml_(*args, **kwargs):
- if (XMLParser_import_library == XMLParser_import_lxml and
- 'parser' not in kwargs):
- # Use the lxml ElementTree compatible parser so that, e.g.,
- # we ignore comments.
- kwargs['parser'] = etree_.ETCompatXMLParser(huge_tree=True)
- doc = etree_.parse(*args, **kwargs)
- return doc
-
-#
-# User methods
-#
-# Calls to the methods in these classes are generated by generateDS.py.
-# You can replace these methods by re-implementing the following class
-# in a module named generatedssuper.py.
-
-try:
- from generatedssuper import GeneratedsSuper
-except ImportError, exp:
-
- class GeneratedsSuper(object):
- tzoff_pattern = re_.compile(r'(\+|-)((0\d|1[0-3]):[0-5]\d|14:00)$')
- class _FixedOffsetTZ(tzinfo):
- def __init__(self, offset, name):
- self.__offset = timedelta(minutes = offset)
- self.__name = name
- def utcoffset(self, dt):
- return self.__offset
- def tzname(self, dt):
- return self.__name
- def dst(self, dt):
- return None
- def gds_format_string(self, input_data, input_name=''):
- return input_data
- def gds_validate_string(self, input_data, node, input_name=''):
- return input_data
- def gds_format_base64(self, input_data, input_name=''):
- return base64.b64encode(input_data)
- def gds_validate_base64(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer(self, input_data, input_name=''):
- return '%d' % input_data
- def gds_validate_integer(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_integer_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of integers')
- return input_data
- def gds_format_float(self, input_data, input_name=''):
- return '%f' % input_data
- def gds_validate_float(self, input_data, node, input_name=''):
- return input_data
- def gds_format_float_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_float_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of floats')
- return input_data
- def gds_format_double(self, input_data, input_name=''):
- return '%e' % input_data
- def gds_validate_double(self, input_data, node, input_name=''):
- return input_data
- def gds_format_double_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_double_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of doubles')
- return input_data
- def gds_format_boolean(self, input_data, input_name=''):
- return ('%s' % input_data).lower()
- def gds_validate_boolean(self, input_data, node, input_name=''):
- return input_data
- def gds_format_boolean_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_boolean_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- if value not in ('true', '1', 'false', '0', ):
- raise_parse_error(node,
- 'Requires sequence of booleans '
- '("true", "1", "false", "0")')
- return input_data
- def gds_validate_datetime(self, input_data, node, input_name=''):
- return input_data
- def gds_format_datetime(self, input_data, input_name=''):
- if input_data.microsecond == 0:
- _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S')
- else:
- _svalue = input_data.strftime('%Y-%m-%dT%H:%M:%S.%f')
- if input_data.tzinfo is not None:
- tzoff = input_data.tzinfo.utcoffset(input_data)
- if tzoff is not None:
- total_seconds = tzoff.seconds + (86400 * tzoff.days)
- if total_seconds == 0:
- _svalue += 'Z'
- else:
- if total_seconds < 0:
- _svalue += '-'
- total_seconds *= -1
- else:
- _svalue += '+'
- hours = total_seconds // 3600
- minutes = (total_seconds - (hours * 3600)) // 60
- _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
- return _svalue
- def gds_parse_datetime(self, input_data, node, input_name=''):
- tz = None
- if input_data[-1] == 'Z':
- tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
- input_data = input_data[:-1]
- else:
- results = GeneratedsSuper.tzoff_pattern.search(input_data)
- if results is not None:
- tzoff_parts = results.group(2).split(':')
- tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
- if results.group(1) == '-':
- tzoff *= -1
- tz = GeneratedsSuper._FixedOffsetTZ(
- tzoff, results.group(0))
- input_data = input_data[:-6]
- if len(input_data.split('.')) > 1:
- dt = datetime.strptime(
- input_data, '%Y-%m-%dT%H:%M:%S.%f')
- else:
- dt = datetime.strptime(
- input_data, '%Y-%m-%dT%H:%M:%S')
- return dt.replace(tzinfo = tz)
-
- def gds_validate_date(self, input_data, node, input_name=''):
- return input_data
- def gds_format_date(self, input_data, input_name=''):
- _svalue = input_data.strftime('%Y-%m-%d')
- if input_data.tzinfo is not None:
- tzoff = input_data.tzinfo.utcoffset(input_data)
- if tzoff is not None:
- total_seconds = tzoff.seconds + (86400 * tzoff.days)
- if total_seconds == 0:
- _svalue += 'Z'
- else:
- if total_seconds < 0:
- _svalue += '-'
- total_seconds *= -1
- else:
- _svalue += '+'
- hours = total_seconds // 3600
- minutes = (total_seconds - (hours * 3600)) // 60
- _svalue += '{0:02d}:{1:02d}'.format(hours, minutes)
- return _svalue
- def gds_parse_date(self, input_data, node, input_name=''):
- tz = None
- if input_data[-1] == 'Z':
- tz = GeneratedsSuper._FixedOffsetTZ(0, 'GMT')
- input_data = input_data[:-1]
- else:
- results = GeneratedsSuper.tzoff_pattern.search(input_data)
- if results is not None:
- tzoff_parts = results.group(2).split(':')
- tzoff = int(tzoff_parts[0]) * 60 + int(tzoff_parts[1])
- if results.group(1) == '-':
- tzoff *= -1
- tz = GeneratedsSuper._FixedOffsetTZ(
- tzoff, results.group(0))
- input_data = input_data[:-6]
- return datetime.strptime(input_data,
- '%Y-%m-%d').replace(tzinfo = tz)
- def gds_str_lower(self, instring):
- return instring.lower()
- def get_path_(self, node):
- path_list = []
- self.get_path_list_(node, path_list)
- path_list.reverse()
- path = '/'.join(path_list)
- return path
- Tag_strip_pattern_ = re_.compile(r'\{.*\}')
- def get_path_list_(self, node, path_list):
- if node is None:
- return
- tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
- if tag:
- path_list.append(tag)
- self.get_path_list_(node.getparent(), path_list)
- def get_class_obj_(self, node, default_class=None):
- class_obj1 = default_class
- if 'xsi' in node.nsmap:
- classname = node.get('{%s}type' % node.nsmap['xsi'])
- if classname is not None:
- names = classname.split(':')
- if len(names) == 2:
- classname = names[1]
- class_obj2 = globals().get(classname)
- if class_obj2 is not None:
- class_obj1 = class_obj2
- return class_obj1
- def gds_build_any(self, node, type_name=None):
- return None
-
-
-#
-# If you have installed IPython you can uncomment and use the following.
-# IPython is available from http://ipython.scipy.org/.
-#
-
-## from IPython.Shell import IPShellEmbed
-## args = ''
-## ipshell = IPShellEmbed(args,
-## banner = 'Dropping into IPython',
-## exit_msg = 'Leaving Interpreter, back to program.')
-
-# Then use the following line where and when you want to drop into the
-# IPython shell:
-# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit')
-
-#
-# Globals
-#
-
-ExternalEncoding = 'utf-8'
-Tag_pattern_ = re_.compile(r'({.*})?(.*)')
-String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
-Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
-
-#
-# Support/utility functions.
-#
-
-def showIndent(outfile, level, pretty_print=True):
- if pretty_print:
- for idx in range(level):
- outfile.write(' ')
-
-def quote_xml(inStr):
- if not inStr:
- return ''
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- return unicode(s1)
-
-def quote_attrib(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- if '"' in s1:
- if "'" in s1:
- s1 = '"%s"' % s1.replace('"', """)
- else:
- s1 = "'%s'" % s1
- else:
- s1 = '"%s"' % s1
- return unicode(s1)
-
-def quote_python(inStr):
- s1 = inStr
- if s1.find("'") == -1:
- if s1.find('\n') == -1:
- return "'%s'" % s1
- else:
- return "'''%s'''" % s1
- else:
- if s1.find('"') != -1:
- s1 = s1.replace('"', '\\"')
- if s1.find('\n') == -1:
- return '"%s"' % s1
- else:
- return '"""%s"""' % s1
-
-def get_all_text_(node):
- if node.text is not None:
- text = node.text
- else:
- text = ''
- for child in node:
- if child.tail is not None:
- text += child.tail
- return text
-
-def find_attr_value_(attr_name, node):
- attrs = node.attrib
- attr_parts = attr_name.split(':')
- value = None
- if len(attr_parts) == 1:
- value = attrs.get(attr_name)
- elif len(attr_parts) == 2:
- prefix, name = attr_parts
- namespace = node.nsmap.get(prefix)
- if namespace is not None:
- value = attrs.get('{%s}%s' % (namespace, name, ))
- return value
-
-
-class GDSParseError(Exception):
- pass
-
-def raise_parse_error(node, msg):
- if XMLParser_import_library == XMLParser_import_lxml:
- msg = '%s (element %s/line %d)' % (
- msg, node.tag, node.sourceline, )
- else:
- msg = '%s (element %s)' % (msg, node.tag, )
- raise GDSParseError(msg)
-
-
-class MixedContainer:
- # Constants for category:
- CategoryNone = 0
- CategoryText = 1
- CategorySimple = 2
- CategoryComplex = 3
- # Constants for content_type:
- TypeNone = 0
- TypeText = 1
- TypeString = 2
- TypeInteger = 3
- TypeFloat = 4
- TypeDecimal = 5
- TypeDouble = 6
- TypeBoolean = 7
- TypeBase64 = 8
- def __init__(self, category, content_type, name, value):
- self.category = category
- self.content_type = content_type
- self.name = name
- self.value = value
- def getCategory(self):
- return self.category
- def getContenttype(self, content_type):
- return self.content_type
- def getValue(self):
- return self.value
- def getName(self):
- return self.name
- def export(self, outfile, level, name, namespace, pretty_print=True):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- outfile.write(self.value)
- elif self.category == MixedContainer.CategorySimple:
- self.exportSimple(outfile, level, name)
- else: # category == MixedContainer.CategoryComplex
- self.value.export(outfile, level, namespace, name, pretty_print)
- def exportSimple(self, outfile, level, name):
- if self.content_type == MixedContainer.TypeString:
- outfile.write('<%s>%s%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeInteger or \
- self.content_type == MixedContainer.TypeBoolean:
- outfile.write('<%s>%d%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeFloat or \
- self.content_type == MixedContainer.TypeDecimal:
- outfile.write('<%s>%f%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeDouble:
- outfile.write('<%s>%g%s>' %
- (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeBase64:
- outfile.write('<%s>%s%s>' %
- (self.name, base64.b64encode(self.value), self.name))
- def to_etree(self, element):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- if len(element) > 0:
- if element[-1].tail is None:
- element[-1].tail = self.value
- else:
- element[-1].tail += self.value
- else:
- if element.text is None:
- element.text = self.value
- else:
- element.text += self.value
- elif self.category == MixedContainer.CategorySimple:
- subelement = etree_.SubElement(element, '%s' % self.name)
- subelement.text = self.to_etree_simple()
- else: # category == MixedContainer.CategoryComplex
- self.value.to_etree(element)
- def to_etree_simple(self):
- if self.content_type == MixedContainer.TypeString:
- text = self.value
- elif (self.content_type == MixedContainer.TypeInteger or
- self.content_type == MixedContainer.TypeBoolean):
- text = '%d' % self.value
- elif (self.content_type == MixedContainer.TypeFloat or
- self.content_type == MixedContainer.TypeDecimal):
- text = '%f' % self.value
- elif self.content_type == MixedContainer.TypeDouble:
- text = '%g' % self.value
- elif self.content_type == MixedContainer.TypeBase64:
- text = '%s' % base64.b64encode(self.value)
- return text
- def exportLiteral(self, outfile, level, name):
- if self.category == MixedContainer.CategoryText:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
- % (self.category, self.content_type, self.name, self.value))
- elif self.category == MixedContainer.CategorySimple:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n'
- % (self.category, self.content_type, self.name, self.value))
- else: # category == MixedContainer.CategoryComplex
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
- (self.category, self.content_type, self.name,))
- self.value.exportLiteral(outfile, level + 1)
- showIndent(outfile, level)
- outfile.write(')\n')
-
-
-class MemberSpec_(object):
- def __init__(self, name='', data_type='', container=0):
- self.name = name
- self.data_type = data_type
- self.container = container
- def set_name(self, name): self.name = name
- def get_name(self): return self.name
- def set_data_type(self, data_type): self.data_type = data_type
- def get_data_type_chain(self): return self.data_type
- def get_data_type(self):
- if isinstance(self.data_type, list):
- if len(self.data_type) > 0:
- return self.data_type[-1]
- else:
- return 'xs:string'
- else:
- return self.data_type
- def set_container(self, container): self.container = container
- def get_container(self): return self.container
-
-def _cast(typ, value):
- if typ is None or value is None:
- return value
- return typ(value)
-
-#
-# Data representation classes.
-#
class AnalysisEnvironmentType(GeneratedsSuper):
"""The AnalysisEnvironmentType provides mechanisms for characterizing
@@ -550,57 +44,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='AnalysisEnvironmentType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='AnalysisEnvironmentType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AnalysisEnvironmentType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AnalysisEnvironmentType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='AnalysisEnvironmentType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='AnalysisEnvironmentType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='AnalysisEnvironmentType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='AnalysisEnvironmentType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Hypervisor_Host_System is not None:
- self.Hypervisor_Host_System.export(outfile, level, 'maecPackage:', name_='Hypervisor_Host_System', pretty_print=pretty_print)
+ self.Hypervisor_Host_System.export(write, level, 'maecPackage:', name_='Hypervisor_Host_System', pretty_print=pretty_print)
if self.Analysis_Systems is not None:
- self.Analysis_Systems.export(outfile, level, 'maecPackage:', name_='Analysis_Systems', pretty_print=pretty_print)
+ self.Analysis_Systems.export(write, level, 'maecPackage:', name_='Analysis_Systems', pretty_print=pretty_print)
if self.Network_Infrastructure is not None:
- self.Network_Infrastructure.export(outfile, level, 'maecPackage:', name_='Network_Infrastructure', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AnalysisEnvironmentType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Hypervisor_Host_System is not None:
- outfile.write('Hypervisor_Host_System=model_.HypervisorHostSystemType(\n')
- self.Hypervisor_Host_System.exportLiteral(outfile, level, name_='Hypervisor_Host_System')
- outfile.write('),\n')
- if self.Analysis_Systems is not None:
- outfile.write('Analysis_Systems=model_.AnalysisSystemListType(\n')
- self.Analysis_Systems.exportLiteral(outfile, level, name_='Analysis_Systems')
- outfile.write('),\n')
- if self.Network_Infrastructure is not None:
- outfile.write('Network_Infrastructure=model_.NetworkInfrastructureType(\n')
- self.Network_Infrastructure.exportLiteral(outfile, level, name_='Network_Infrastructure')
- outfile.write('),\n')
+ self.Network_Infrastructure.export(write, level, 'maecPackage:', name_='Network_Infrastructure', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -661,69 +135,46 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='SourceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='SourceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='SourceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='SourceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='SourceType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='SourceType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='SourceType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='SourceType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sName>%s%sName>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Name).encode(ExternalEncoding), input_name='Name'), 'maecPackage:', eol_))
- if self.Method is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sMethod>%s%sMethod>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Method).encode(ExternalEncoding), input_name='Method'), 'maecPackage:', eol_))
- if self.Reference is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sReference>%s%sReference>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Reference).encode(ExternalEncoding), input_name='Reference'), 'maecPackage:', eol_))
- if self.Organization is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sOrganization>%s%sOrganization>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Organization).encode(ExternalEncoding), input_name='Organization'), 'maecPackage:', eol_))
- if self.URL is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sURL>%s%sURL>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.URL).encode(ExternalEncoding), input_name='URL'), 'maecPackage:', eol_))
- def exportLiteral(self, outfile, level, name_='SourceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Name is not None:
- showIndent(outfile, level)
- outfile.write('Name=%s,\n' % quote_python(self.Name).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sName>%s%sName>%s' % ('maecPackage:', quote_xml(self.Name), 'maecPackage:', eol_))
if self.Method is not None:
- showIndent(outfile, level)
- outfile.write('Method=%s,\n' % quote_python(self.Method).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sMethod>%s%sMethod>%s' % ('maecPackage:', quote_xml(self.Method), 'maecPackage:', eol_))
if self.Reference is not None:
- showIndent(outfile, level)
- outfile.write('Reference=%s,\n' % quote_python(self.Reference).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sReference>%s%sReference>%s' % ('maecPackage:', quote_xml(self.Reference), 'maecPackage:', eol_))
if self.Organization is not None:
- showIndent(outfile, level)
- outfile.write('Organization=%s,\n' % quote_python(self.Organization).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sOrganization>%s%sOrganization>%s' % ('maecPackage:', quote_xml(self.Organization), 'maecPackage:', eol_))
if self.URL is not None:
- showIndent(outfile, level)
- outfile.write('URL=%s,\n' % quote_python(self.URL).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sURL>%s%sURL>%s' % ('maecPackage:', quote_xml(self.URL), 'maecPackage:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -781,52 +232,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='CommentListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='CommentListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CommentListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CommentListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='CommentListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='CommentListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='CommentListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='CommentListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Comment_ in self.Comment:
- Comment_.export(outfile, level, 'maecPackage:', name_='Comment', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CommentListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Comment=[\n')
- level += 1
- for Comment_ in self.Comment:
- outfile.write('model_.CommentType(\n')
- Comment_.exportLiteral(outfile, level, name_='CommentType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Comment_.export(write, level, 'maecPackage:', name_='Comment', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -868,52 +300,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='AnalysisSystemListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='AnalysisSystemListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AnalysisSystemListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AnalysisSystemListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='AnalysisSystemListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='AnalysisSystemListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='AnalysisSystemListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='AnalysisSystemListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Analysis_System_ in self.Analysis_System:
- Analysis_System_.export(outfile, level, 'maecPackage:', name_='Analysis_System', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AnalysisSystemListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Analysis_System=[\n')
- level += 1
- for Analysis_System_ in self.Analysis_System:
- outfile.write('model_.AnalysisSystemType(\n')
- Analysis_System_.exportLiteral(outfile, level, name_='AnalysisSystemType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Analysis_System_.export(write, level, 'maecPackage:', name_='Analysis_System', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -955,52 +368,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ToolListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ToolListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ToolListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ToolListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ToolListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ToolListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ToolListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ToolListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Tool_ in self.Tool:
- Tool_.export(outfile, level, 'maecPackage:', name_='Tool', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ToolListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Tool=[\n')
- level += 1
- for Tool_ in self.Tool:
- outfile.write('model_.cybox_common.ToolInformationType(\n')
- Tool_.exportLiteral(outfile, level, name_='cybox_common.ToolInformationType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Tool_.export(write, level, 'maecPackage:', name_='Tool', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1045,57 +439,40 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='DynamicAnalysisMetadataType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='DynamicAnalysisMetadataType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='DynamicAnalysisMetadataType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='DynamicAnalysisMetadataType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='DynamicAnalysisMetadataType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='DynamicAnalysisMetadataType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='DynamicAnalysisMetadataType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='DynamicAnalysisMetadataType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Command_Line is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sCommand_Line>%s%sCommand_Line>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Command_Line).encode(ExternalEncoding), input_name='Command_Line'), 'maecPackage:', eol_))
- if self.Analysis_Duration is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAnalysis_Duration>%s%sAnalysis_Duration>%s' % ('maecPackage:', self.gds_format_float(self.Analysis_Duration, input_name='Analysis_Duration'), 'maecPackage:', eol_))
- if self.Exit_Code is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sExit_Code>%s%sExit_Code>%s' % ('maecPackage:', self.gds_format_integer(self.Exit_Code, input_name='Exit_Code'), 'maecPackage:', eol_))
- def exportLiteral(self, outfile, level, name_='DynamicAnalysisMetadataType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Command_Line is not None:
- showIndent(outfile, level)
- outfile.write('Command_Line=%s,\n' % quote_python(self.Command_Line).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sCommand_Line>%s%sCommand_Line>%s' % ('maecPackage:', quote_xml(self.Command_Line), 'maecPackage:', eol_))
if self.Analysis_Duration is not None:
- showIndent(outfile, level)
- outfile.write('Analysis_Duration=%f,\n' % self.Analysis_Duration)
+ showIndent(write, level, pretty_print)
+ write('<%sAnalysis_Duration>%s%sAnalysis_Duration>%s' % ('maecPackage:', self.gds_format_float(self.Analysis_Duration, input_name='Analysis_Duration'), 'maecPackage:', eol_))
if self.Exit_Code is not None:
- showIndent(outfile, level)
- outfile.write('Exit_Code=%d,\n' % self.Exit_Code)
+ showIndent(write, level, pretty_print)
+ write('<%sExit_Code>%s%sExit_Code>%s' % ('maecPackage:', self.gds_format_integer(self.Exit_Code, input_name='Exit_Code'), 'maecPackage:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1112,7 +489,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
fval_ = float(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
fval_ = self.gds_validate_float(fval_, node, 'Analysis_Duration')
self.Analysis_Duration = fval_
@@ -1120,7 +497,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'Exit_Code')
self.Exit_Code = ival_
@@ -1143,13 +520,13 @@ class AnalysisType(GeneratedsSuper):
the analysis was last updated."""
subclass = None
superclass = None
- def __init__(self, start_datetime=None, complete_datetime=None, method=None, ordinal_position=None, lastupdate_datetime=None, type_=None, id=None, Source=None, Analysts=None, Summary=None, Comments=None, Findings_Bundle_Reference=None, Tools=None, Dynamic_Analysis_Metadata=None, Analysis_Environment=None, Report=None):
+ def __init__(self, start_datetime=None, complete_datetime=None, method=None, ordinal_position=None, lastupdate_datetime=None, type=None, id=None, Source=None, Analysts=None, Summary=None, Comments=None, Findings_Bundle_Reference=None, Tools=None, Dynamic_Analysis_Metadata=None, Analysis_Environment=None, Report=None):
self.start_datetime = _cast(None, start_datetime)
self.complete_datetime = _cast(None, complete_datetime)
self.method = _cast(None, method)
self.ordinal_position = _cast(int, ordinal_position)
self.lastupdate_datetime = _cast(None, lastupdate_datetime)
- self.type_ = _cast(None, type_)
+ self.type = _cast(None, type)
self.id = _cast(None, id)
self.Source = Source
self.Analysts = Analysts
@@ -1199,8 +576,8 @@ def get_ordinal_position(self): return self.ordinal_position
def set_ordinal_position(self, ordinal_position): self.ordinal_position = ordinal_position
def get_lastupdate_datetime(self): return self.lastupdate_datetime
def set_lastupdate_datetime(self, lastupdate_datetime): self.lastupdate_datetime = lastupdate_datetime
- def get_type(self): return self.type_
- def set_type(self, type_): self.type_ = type_
+ def get_type(self): return self.type
+ def set_type(self, type): self.type = type
def get_id(self): return self.id
def set_id(self, id): self.id = id
def hasContent_(self):
@@ -1218,140 +595,69 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='AnalysisType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='AnalysisType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AnalysisType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AnalysisType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='AnalysisType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='AnalysisType'):
if self.start_datetime is not None and 'start_datetime' not in already_processed:
already_processed.add('start_datetime')
- outfile.write(' start_datetime="%s"' % self.start_datetime)
+ write(' start_datetime="%s"' % self.start_datetime)
if self.complete_datetime is not None and 'complete_datetime' not in already_processed:
already_processed.add('complete_datetime')
- outfile.write(' complete_datetime="%s"' % self.complete_datetime)
+ write(' complete_datetime="%s"' % self.complete_datetime)
if self.method is not None and 'method' not in already_processed:
already_processed.add('method')
- outfile.write(' method=%s' % (quote_attrib(self.method), ))
+ write(' method=%s' % (quote_attrib(self.method), ))
if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
already_processed.add('ordinal_position')
- outfile.write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
+ write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
if self.lastupdate_datetime is not None and 'lastupdate_datetime' not in already_processed:
already_processed.add('lastupdate_datetime')
- outfile.write(' lastupdate_datetime="%s"' % self.lastupdate_datetime)
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.add('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
+ write(' lastupdate_datetime="%s"' % self.lastupdate_datetime)
+ if self.type is not None and 'type' not in already_processed:
+ already_processed.add('type')
+ write(' type=%s' % (quote_attrib(self.type), ))
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='AnalysisType', fromsubclass_=False, pretty_print=True):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='AnalysisType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Source is not None:
- self.Source.export(outfile, level, 'maecPackage:', name_='Source', pretty_print=pretty_print)
+ self.Source.export(write, level, 'maecPackage:', name_='Source', pretty_print=pretty_print)
if self.Analysts is not None:
- self.Analysts.export(outfile, level, 'maecPackage:', name_='Analysts', pretty_print=pretty_print)
+ self.Analysts.export(write, level, 'maecPackage:', name_='Analysts', pretty_print=pretty_print)
if self.Summary is not None:
- self.Summary.export(outfile, level, 'maecPackage:', name_='Summary', pretty_print=pretty_print)
+ self.Summary.export(write, level, 'maecPackage:', name_='Summary', pretty_print=pretty_print)
if self.Comments is not None:
- self.Comments.export(outfile, level, 'maecPackage:', name_='Comments', pretty_print=pretty_print)
+ self.Comments.export(write, level, 'maecPackage:', name_='Comments', pretty_print=pretty_print)
for Findings_Bundle_Reference_ in self.Findings_Bundle_Reference:
- Findings_Bundle_Reference_.export(outfile, level, 'maecPackage:', name_='Findings_Bundle_Reference', pretty_print=pretty_print)
- if self.Tools is not None:
- self.Tools.export(outfile, level, 'maecPackage:', name_='Tools', pretty_print=pretty_print)
- if self.Dynamic_Analysis_Metadata is not None:
- self.Dynamic_Analysis_Metadata.export(outfile, level, 'maecPackage:', name_='Dynamic_Analysis_Metadata', pretty_print=pretty_print)
- if self.Analysis_Environment is not None:
- self.Analysis_Environment.export(outfile, level, 'maecPackage:', name_='Analysis_Environment', pretty_print=pretty_print)
- if self.Report is not None:
- self.Report.export(outfile, level, 'maecPackage:', name_='Report', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AnalysisType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.start_datetime is not None and 'start_datetime' not in already_processed:
- already_processed.add('start_datetime')
- showIndent(outfile, level)
- outfile.write('start_datetime = "%s",\n' % (self.start_datetime,))
- if self.complete_datetime is not None and 'complete_datetime' not in already_processed:
- already_processed.add('complete_datetime')
- showIndent(outfile, level)
- outfile.write('complete_datetime = "%s",\n' % (self.complete_datetime,))
- if self.method is not None and 'method' not in already_processed:
- already_processed.add('method')
- showIndent(outfile, level)
- outfile.write('method = %s,\n' % (self.method,))
- if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
- already_processed.add('ordinal_position')
- showIndent(outfile, level)
- outfile.write('ordinal_position = %d,\n' % (self.ordinal_position,))
- if self.lastupdate_datetime is not None and 'lastupdate_datetime' not in already_processed:
- already_processed.add('lastupdate_datetime')
- showIndent(outfile, level)
- outfile.write('lastupdate_datetime = "%s",\n' % (self.lastupdate_datetime,))
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.add('type_')
- showIndent(outfile, level)
- outfile.write('type_ = %s,\n' % (self.type_,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Source is not None:
- outfile.write('Source=model_.SourceType(\n')
- self.Source.exportLiteral(outfile, level, name_='Source')
- outfile.write('),\n')
- if self.Analysts is not None:
- outfile.write('Analysts=model_.cybox_common.PersonnelType(\n')
- self.Analysts.exportLiteral(outfile, level, name_='Analysts')
- outfile.write('),\n')
- if self.Summary is not None:
- outfile.write('Summary=model_.cybox_common.StructuredTextType(\n')
- self.Summary.exportLiteral(outfile, level, name_='Summary')
- outfile.write('),\n')
- if self.Comments is not None:
- outfile.write('Comments=model_.CommentListType(\n')
- self.Comments.exportLiteral(outfile, level, name_='Comments')
- outfile.write('),\n')
- if self.Findings_Bundle_Reference is not None:
- outfile.write('Findings_Bundle_Reference=model_.maec_bundle_schema.BundleReferenceType(\n')
- self.Findings_Bundle_Reference.exportLiteral(outfile, level, name_='Findings_Bundle_Reference')
- outfile.write('),\n')
+ Findings_Bundle_Reference_.export(write, level, 'maecPackage:', name_='Findings_Bundle_Reference', pretty_print=pretty_print)
if self.Tools is not None:
- outfile.write('Tools=model_.ToolListType(\n')
- self.Tools.exportLiteral(outfile, level, name_='Tools')
- outfile.write('),\n')
+ self.Tools.export(write, level, 'maecPackage:', name_='Tools', pretty_print=pretty_print)
if self.Dynamic_Analysis_Metadata is not None:
- outfile.write('Dynamic_Analysis_Metadata=model_.DynamicAnalysisMetadataType(\n')
- self.Dynamic_Analysis_Metadata.exportLiteral(outfile, level, name_='Dynamic_Analysis_Metadata')
- outfile.write('),\n')
+ self.Dynamic_Analysis_Metadata.export(write, level, 'maecPackage:', name_='Dynamic_Analysis_Metadata', pretty_print=pretty_print)
if self.Analysis_Environment is not None:
- outfile.write('Analysis_Environment=model_.AnalysisEnvironmentType(\n')
- self.Analysis_Environment.exportLiteral(outfile, level, name_='Analysis_Environment')
- outfile.write('),\n')
+ self.Analysis_Environment.export(write, level, 'maecPackage:', name_='Analysis_Environment', pretty_print=pretty_print)
if self.Report is not None:
- outfile.write('Report=model_.cybox_common.StructuredTextType(\n')
- self.Report.exportLiteral(outfile, level, name_='Report')
- outfile.write('),\n')
+ self.Report.export(write, level, 'maecPackage:', name_='Report', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1363,14 +669,14 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('start_datetime')
try:
self.start_datetime = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (start_datetime): %s' % exp)
value = find_attr_value_('complete_datetime', node)
if value is not None and 'complete_datetime' not in already_processed:
already_processed.add('complete_datetime')
try:
self.complete_datetime = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (complete_datetime): %s' % exp)
value = find_attr_value_('method', node)
if value is not None and 'method' not in already_processed:
@@ -1381,7 +687,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('ordinal_position')
try:
self.ordinal_position = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.ordinal_position <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -1390,12 +696,12 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('lastupdate_datetime')
try:
self.lastupdate_datetime = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (lastupdate_datetime): %s' % exp)
value = find_attr_value_('type', node)
if value is not None and 'type' not in already_processed:
already_processed.add('type')
- self.type_ = value
+ self.type = value
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
already_processed.add('id')
@@ -1466,52 +772,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='AnalysisListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='AnalysisListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AnalysisListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AnalysisListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='AnalysisListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='AnalysisListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='AnalysisListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='AnalysisListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Analysis_ in self.Analysis:
- Analysis_.export(outfile, level, 'maecPackage:', name_='Analysis', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AnalysisListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Analysis=[\n')
- level += 1
- for Analysis_ in self.Analysis:
- outfile.write('model_.AnalysisType(\n')
- Analysis_.exportLiteral(outfile, level, name_='AnalysisType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Analysis_.export(write, level, 'maecPackage:', name_='Analysis', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1554,52 +841,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='InstalledProgramsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='InstalledProgramsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='InstalledProgramsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='InstalledProgramsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='InstalledProgramsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='InstalledProgramsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='InstalledProgramsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='InstalledProgramsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Program_ in self.Program:
- Program_.export(outfile, level, 'maecPackage:', name_='Program', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='InstalledProgramsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Program=[\n')
- level += 1
- for Program_ in self.Program:
- outfile.write('model_.cybox_common.PlatformSpecificationType(\n')
- Program_.exportLiteral(outfile, level, name_='cybox_common.PlatformSpecificationType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Program_.export(write, level, 'maecPackage:', name_='Program', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1661,70 +929,43 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MAEC_Package', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MAEC_Package', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MAEC_Package')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MAEC_Package')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MAEC_Package'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MAEC_Package'):
if self.timestamp is not None and 'timestamp' not in already_processed:
already_processed.add('timestamp')
- outfile.write(' timestamp="%s"' % self.timestamp)
+ write(' timestamp="%s"' % self.timestamp)
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
+ write(' id=%s' % (quote_attrib(self.id), ))
if self.schema_version is not None and 'schema_version' not in already_processed:
already_processed.add('schema_version')
- outfile.write(' schema_version="%s"' % self.schema_version)
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MAEC_Package', fromsubclass_=False, pretty_print=True):
+ write(' schema_version="%s"' % self.schema_version)
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MAEC_Package', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Malware_Subjects is not None:
- self.Malware_Subjects.export(outfile, level, 'maecPackage:', name_='Malware_Subjects', pretty_print=pretty_print)
+ self.Malware_Subjects.export(write, level, 'maecPackage:', name_='Malware_Subjects', pretty_print=pretty_print)
if self.Grouping_Relationships is not None:
- self.Grouping_Relationships.export(outfile, level, 'maecPackage:', name_='Grouping_Relationships', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MAEC_Package'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.timestamp is not None and 'timestamp' not in already_processed:
- already_processed.add('timestamp')
- showIndent(outfile, level)
- outfile.write('timestamp = "%s",\n' % (self.timestamp,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- if self.schema_version is not None and 'schema_version' not in already_processed:
- already_processed.add('schema_version')
- showIndent(outfile, level)
- outfile.write('schema_version = %s,\n' % (self.schema_version,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Malware_Subjects is not None:
- outfile.write('Malware_Subjects=model_.MalwareSubjectListType(\n')
- self.Malware_Subjects.exportLiteral(outfile, level, name_='Malware_Subjects')
- outfile.write('),\n')
- if self.Grouping_Relationships is not None:
- outfile.write('Grouping_Relationships=model_.GroupingRelationshipListType(\n')
- self.Grouping_Relationships.exportLiteral(outfile, level, name_='Grouping_Relationships')
- outfile.write('),\n')
+ self.Grouping_Relationships.export(write, level, 'maecPackage:', name_='Grouping_Relationships', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1736,7 +977,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('timestamp')
try:
self.timestamp = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (timestamp): %s' % exp)
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
@@ -1771,7 +1012,7 @@ def __init__(self, id=None, Malware_Instance_Object_Attributes=None, Label=None,
self.Malware_Instance_Object_Attributes = Malware_Instance_Object_Attributes
self.Configuration_Details = Configuration_Details
self.Minor_Variants = Minor_Variants
- self.Development_Environment = Development_Environment
+ self.Development_Environment = Development_Environment
self.Field_Data = Field_Data
self.Analyses = Analyses
self.Findings_Bundles = Findings_Bundles
@@ -1832,88 +1073,53 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareSubjectType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareSubjectType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectType'):
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectType', fromsubclass_=False, pretty_print=True):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Malware_Instance_Object_Attributes is not None:
- self.Malware_Instance_Object_Attributes.export(outfile, level, 'maecPackage:', name_='Malware_Instance_Object_Attributes', pretty_print=pretty_print)
+ self.Malware_Instance_Object_Attributes.export(write, level, 'maecPackage:', name_='Malware_Instance_Object_Attributes', pretty_print=pretty_print)
for Label_ in self.Label:
- Label_.export(outfile, level, 'maecPackage:', name_='Label', pretty_print=pretty_print)
+ Label_.export(write, level, 'maecPackage:', name_='Label', pretty_print=pretty_print)
if self.Configuration_Details is not None:
- self.Configuration_Details.export(outfile, level, 'maecPackage:', name_='Configuration_Details', pretty_print=pretty_print)
+ self.Configuration_Details.export(write, level, 'maecPackage:', name_='Configuration_Details', pretty_print=pretty_print)
if self.Minor_Variants is not None:
- self.Minor_Variants.export(outfile, level, 'maecPackage:', name_='Minor_Variants', pretty_print=pretty_print)
+ self.Minor_Variants.export(write, level, 'maecPackage:', name_='Minor_Variants', pretty_print=pretty_print)
if self.Development_Environment is not None:
- self.Development_Environment.export(outfile, level, 'maecPackage:', name_='Development_Environment', pretty_print=pretty_print)
+ self.Development_Environment.export(write, level, 'maecPackage:', name_='Development_Environment', pretty_print=pretty_print)
if self.Field_Data is not None:
- self.Field_Data.export(outfile, level, 'maecPackage:', name_='Field_Data', pretty_print=pretty_print)
+ self.Field_Data.export(write, level, 'maecPackage:', name_='Field_Data', pretty_print=pretty_print)
if self.Analyses is not None:
- self.Analyses.export(outfile, level, 'maecPackage:', name_='Analyses', pretty_print=pretty_print)
+ self.Analyses.export(write, level, 'maecPackage:', name_='Analyses', pretty_print=pretty_print)
if self.Findings_Bundles is not None:
- self.Findings_Bundles.export(outfile, level, 'maecPackage:', name_='Findings_Bundles', pretty_print=pretty_print)
+ self.Findings_Bundles.export(write, level, 'maecPackage:', name_='Findings_Bundles', pretty_print=pretty_print)
if self.Relationships is not None:
- self.Relationships.export(outfile, level, 'maecPackage:', name_='Relationships', pretty_print=pretty_print)
+ self.Relationships.export(write, level, 'maecPackage:', name_='Relationships', pretty_print=pretty_print)
for Compatible_Platform_ in self.Compatible_Platform:
- Compatible_Platform_.export(outfile, level, 'maecPackage:', name_='Compatible_Platform', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareSubjectType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Malware_Instance_Object_Attributes is not None:
- outfile.write('Malware_Instance_Object_Attributes=model_.cybox_core.ObjectType(\n')
- self.Malware_Instance_Object_Attributes.exportLiteral(outfile, level, name_='Malware_Instance_Object_Attributes')
- outfile.write('),\n')
- if self.Minor_Variants is not None:
- outfile.write('Minor_Variants=model_.MinorVariantListType(\n')
- self.Minor_Variants.exportLiteral(outfile, level, name_='Minor_Variants')
- outfile.write('),\n')
- if self.Field_Data is not None:
- outfile.write('Field_Data=model_.metadatasharing.fieldDataEntry(\n')
- self.Field_Data.exportLiteral(outfile, level, name_='Field_Data')
- outfile.write('),\n')
- if self.Analyses is not None:
- outfile.write('Analyses=model_.AnalysisListType(\n')
- self.Analyses.exportLiteral(outfile, level, name_='Analyses')
- outfile.write('),\n')
- if self.Findings_Bundles is not None:
- outfile.write('Findings_Bundles=model_.FindingsBundleListType(\n')
- self.Findings_Bundles.exportLiteral(outfile, level, name_='Findings_Bundles')
- outfile.write('),\n')
- if self.Relationships is not None:
- outfile.write('Relationships=model_.MalwareSubjectRelationshipListType(\n')
- self.Relationships.exportLiteral(outfile, level, name_='Relationships')
- outfile.write('),\n')
+ Compatible_Platform_.export(write, level, 'maecPackage:', name_='Compatible_Platform', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -1994,51 +1200,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MetaAnalysisType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MetaAnalysisType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MetaAnalysisType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MetaAnalysisType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MetaAnalysisType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MetaAnalysisType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MetaAnalysisType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MetaAnalysisType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Action_Equivalences is not None:
- self.Action_Equivalences.export(outfile, level, 'maecPackage:', name_='Action_Equivalences', pretty_print=pretty_print)
+ self.Action_Equivalences.export(write, level, 'maecPackage:', name_='Action_Equivalences', pretty_print=pretty_print)
if self.Object_Equivalences is not None:
- self.Object_Equivalences.export(outfile, level, 'maecPackage:', name_='Object_Equivalences', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MetaAnalysisType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Action_Equivalences is not None:
- outfile.write('Action_Equivalences=model_.ActionEquivalenceListType(\n')
- self.Action_Equivalences.exportLiteral(outfile, level, name_='Action_Equivalences')
- outfile.write('),\n')
- if self.Object_Equivalences is not None:
- outfile.write('Object_Equivalences=model_.ObjectEquivalenceListType(\n')
- self.Object_Equivalences.exportLiteral(outfile, level, name_='Object_Equivalences')
- outfile.write('),\n')
+ self.Object_Equivalences.export(write, level, 'maecPackage:', name_='Object_Equivalences', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2089,58 +1279,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareSubjectRelationshipType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareSubjectRelationshipType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectRelationshipType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectRelationshipType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Type is not None:
- self.Type.export(outfile, level, 'maecPackage:', name_='Type', pretty_print=pretty_print)
+ self.Type.export(write, level, 'maecPackage:', name_='Type', pretty_print=pretty_print)
for Malware_Subject_Reference_ in self.Malware_Subject_Reference:
- Malware_Subject_Reference_.export(outfile, level, 'maecPackage:', name_='Malware_Subject_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareSubjectRelationshipType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Type is not None:
- outfile.write('Type=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Type.exportLiteral(outfile, level, name_='Type')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Malware_Subject_Reference=[\n')
- level += 1
- for Malware_Subject_Reference_ in self.Malware_Subject_Reference:
- outfile.write('model_.MalwareSubjectReferenceType(\n')
- Malware_Subject_Reference_.exportLiteral(outfile, level, name_='MalwareSubjectReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Malware_Subject_Reference_.export(write, level, 'maecPackage:', name_='Malware_Subject_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2187,52 +1354,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareSubjectRelationshipListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareSubjectRelationshipListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectRelationshipListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectRelationshipListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectRelationshipListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Relationship_ in self.Relationship:
- Relationship_.export(outfile, level, 'maecPackage:', name_='Relationship', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareSubjectRelationshipListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Relationship=[\n')
- level += 1
- for Relationship_ in self.Relationship:
- outfile.write('model_.MalwareSubjectRelationshipType(\n')
- Relationship_.exportLiteral(outfile, level, name_='MalwareSubjectRelationshipType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Relationship_.export(write, level, 'maecPackage:', name_='Relationship', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2272,41 +1420,29 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectReferenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectReferenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareSubjectReferenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareSubjectReferenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectReferenceType'):
- if self.malware_subject_idref is not None and 'malware_subject_idref' not in already_processed:
- already_processed.add('malware_subject_idref')
- outfile.write(' malware_subject_idref=%s' % (quote_attrib(self.malware_subject_idref), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectReferenceType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='MalwareSubjectReferenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectReferenceType'):
if self.malware_subject_idref is not None and 'malware_subject_idref' not in already_processed:
already_processed.add('malware_subject_idref')
- showIndent(outfile, level)
- outfile.write('malware_subject_idref = %s,\n' % (self.malware_subject_idref,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' malware_subject_idref=%s' % (quote_attrib(self.malware_subject_idref), ))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectReferenceType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2347,52 +1483,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareSubjectListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareSubjectListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareSubjectListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareSubjectListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareSubjectListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Malware_Subject_ in self.Malware_Subject:
- Malware_Subject_.export(outfile, level, 'maecPackage:', name_='Malware_Subject', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareSubjectListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Malware_Subject=[\n')
- level += 1
- for Malware_Subject_ in self.Malware_Subject:
- outfile.write('model_.MalwareSubjectType(\n')
- Malware_Subject_.exportLiteral(outfile, level, name_='MalwareSubjectType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Malware_Subject_.export(write, level, 'maecPackage:', name_='Malware_Subject', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2435,52 +1552,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MinorVariantListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MinorVariantListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MinorVariantListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MinorVariantListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MinorVariantListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MinorVariantListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MinorVariantListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MinorVariantListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Minor_Variant_ in self.Minor_Variant:
- Minor_Variant_.export(outfile, level, 'maecPackage:', name_='Minor_Variant', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MinorVariantListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Minor_Variant=[\n')
- level += 1
- for Minor_Variant_ in self.Minor_Variant:
- outfile.write('model_.cybox_core.ObjectType(\n')
- Minor_Variant_.exportLiteral(outfile, level, name_='cybox_core.ObjectType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Minor_Variant_.export(write, level, 'maecPackage:', name_='Minor_Variant', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2536,70 +1634,38 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='FindingsBundleListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='FindingsBundleListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='FindingsBundleListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='FindingsBundleListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='FindingsBundleListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='FindingsBundleListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='FindingsBundleListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='FindingsBundleListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Meta_Analysis is not None:
- self.Meta_Analysis.export(outfile, level, 'maecPackage:', name_='Meta_Analysis', pretty_print=pretty_print)
- for Bundle_ in self.Bundle:
- Bundle_.export(outfile, level, 'maecPackage:', name_='Bundle', pretty_print=pretty_print)
- for Bundle_External_Reference_ in self.Bundle_External_Reference:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sBundle_External_Reference>%s%sBundle_External_Reference>%s' % ('maecPackage:', self.gds_format_string(quote_xml(Bundle_External_Reference_).encode(ExternalEncoding), input_name='Bundle_External_Reference'), 'maecPackage:', eol_))
- def exportLiteral(self, outfile, level, name_='FindingsBundleListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Meta_Analysis is not None:
- outfile.write('Meta_Analysis=model_.MetaAnalysisType(\n')
- self.Meta_Analysis.exportLiteral(outfile, level, name_='Meta_Analysis')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Bundle=[\n')
- level += 1
+ self.Meta_Analysis.export(write, level, 'maecPackage:', name_='Meta_Analysis', pretty_print=pretty_print)
for Bundle_ in self.Bundle:
- outfile.write('model_.maec_bundle_schema.BundleType(\n')
- Bundle_.exportLiteral(outfile, level, name_='maec_bundle_schema.BundleType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('Bundle_External_Reference=[\n')
- level += 1
+ Bundle_.export(write, level, 'maecPackage:', name_='Bundle', pretty_print=pretty_print)
for Bundle_External_Reference_ in self.Bundle_External_Reference:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(Bundle_External_Reference_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ showIndent(write, level, pretty_print)
+ write('<%sBundle_External_Reference>%s%sBundle_External_Reference>%s' % ('maecPackage:', self.gds_format_string(quote_xml(Bundle_External_Reference_).encode(ExternalEncoding), input_name='Bundle_External_Reference'), 'maecPackage:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2657,63 +1723,41 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='GroupingRelationshipType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='GroupingRelationshipType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='GroupingRelationshipType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='GroupingRelationshipType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='GroupingRelationshipType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='GroupingRelationshipType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='GroupingRelationshipType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='GroupingRelationshipType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Type is not None:
- self.Type.export(outfile, level, 'maecPackage:', name_='Type', pretty_print=pretty_print)
+ self.Type.export(write, level, 'maecPackage:', name_='Type', pretty_print=pretty_print)
if self.Malware_Family_Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sMalware_Family_Name>%s%sMalware_Family_Name>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Malware_Family_Name).encode(ExternalEncoding), input_name='Malware_Family_Name'), 'maecPackage:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sMalware_Family_Name>%s%sMalware_Family_Name>%s' % ('maecPackage:', quote_xml(self.Malware_Family_Name), 'maecPackage:', eol_))
if self.Malware_Toolkit_Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sMalware_Toolkit_Name>%s%sMalware_Toolkit_Name>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Malware_Toolkit_Name).encode(ExternalEncoding), input_name='Malware_Toolkit_Name'), 'maecPackage:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sMalware_Toolkit_Name>%s%sMalware_Toolkit_Name>%s' % ('maecPackage:', quote_xml(self.Malware_Toolkit_Name), 'maecPackage:', eol_))
if self.Clustering_Metadata is not None:
- self.Clustering_Metadata.export(outfile, level, 'maecPackage:', name_='Clustering_Metadata', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='GroupingRelationshipType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Type is not None:
- outfile.write('Type=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Type.exportLiteral(outfile, level, name_='Type')
- outfile.write('),\n')
- if self.Malware_Family_Name is not None:
- showIndent(outfile, level)
- outfile.write('Malware_Family_Name=%s,\n' % quote_python(self.Malware_Family_Name).encode(ExternalEncoding))
- if self.Malware_Toolkit_Name is not None:
- showIndent(outfile, level)
- outfile.write('Malware_Toolkit_Name=%s,\n' % quote_python(self.Malware_Toolkit_Name).encode(ExternalEncoding))
- if self.Clustering_Metadata is not None:
- outfile.write('Clustering_Metadata=model_.ClusteringMetadataType(\n')
- self.Clustering_Metadata.exportLiteral(outfile, level, name_='Clustering_Metadata')
- outfile.write('),\n')
+ self.Clustering_Metadata.export(write, level, 'maecPackage:', name_='Clustering_Metadata', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2767,52 +1811,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='GroupingRelationshipListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='GroupingRelationshipListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='GroupingRelationshipListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='GroupingRelationshipListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='GroupingRelationshipListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='GroupingRelationshipListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='GroupingRelationshipListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='GroupingRelationshipListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Grouping_Relationship_ in self.Grouping_Relationship:
- Grouping_Relationship_.export(outfile, level, 'maecPackage:', name_='Grouping_Relationship', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='GroupingRelationshipListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Grouping_Relationship=[\n')
- level += 1
- for Grouping_Relationship_ in self.Grouping_Relationship:
- outfile.write('model_.GroupingRelationshipType(\n')
- Grouping_Relationship_.exportLiteral(outfile, level, name_='GroupingRelationshipType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Grouping_Relationship_.export(write, level, 'maecPackage:', name_='Grouping_Relationship', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2869,75 +1894,47 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ClusteringMetadataType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ClusteringMetadataType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ClusteringMetadataType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ClusteringMetadataType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ClusteringMetadataType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ClusteringMetadataType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ClusteringMetadataType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ClusteringMetadataType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Algorithm_Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAlgorithm_Name>%s%sAlgorithm_Name>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Algorithm_Name).encode(ExternalEncoding), input_name='Algorithm_Name'), 'maecPackage:', eol_))
- if self.Algorithm_Version is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sAlgorithm_Version>%s%sAlgorithm_Version>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Algorithm_Version).encode(ExternalEncoding), input_name='Algorithm_Version'), 'maecPackage:', eol_))
- if self.Algorithm_Parameters is not None:
- self.Algorithm_Parameters.export(outfile, level, 'maecPackage:', name_='Algorithm_Parameters', pretty_print=pretty_print)
- if self.Cluster_Size is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sCluster_Size>%s%sCluster_Size>%s' % ('maecPackage:', self.gds_format_integer(self.Cluster_Size, input_name='Cluster_Size'), 'maecPackage:', eol_))
- if self.Cluster_Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sCluster_Description>%s%sCluster_Description>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Cluster_Description).encode(ExternalEncoding), input_name='Cluster_Description'), 'maecPackage:', eol_))
- if self.Cluster_Composition is not None:
- self.Cluster_Composition.export(outfile, level, 'maecPackage:', name_='Cluster_Composition', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ClusteringMetadataType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Algorithm_Name is not None:
- showIndent(outfile, level)
- outfile.write('Algorithm_Name=%s,\n' % quote_python(self.Algorithm_Name).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sAlgorithm_Name>%s%sAlgorithm_Name>%s' % ('maecPackage:', quote_xml(self.Algorithm_Name), 'maecPackage:', eol_))
if self.Algorithm_Version is not None:
- showIndent(outfile, level)
- outfile.write('Algorithm_Version=%s,\n' % quote_python(self.Algorithm_Version).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sAlgorithm_Version>%s%sAlgorithm_Version>%s' % ('maecPackage:', quote_xml(self.Algorithm_Version), 'maecPackage:', eol_))
if self.Algorithm_Parameters is not None:
- outfile.write('Algorithm_Parameters=model_.ClusteringAlgorithmParametersType(\n')
- self.Algorithm_Parameters.exportLiteral(outfile, level, name_='Algorithm_Parameters')
- outfile.write('),\n')
+ self.Algorithm_Parameters.export(write, level, 'maecPackage:', name_='Algorithm_Parameters', pretty_print=pretty_print)
if self.Cluster_Size is not None:
- showIndent(outfile, level)
- outfile.write('Cluster_Size=%d,\n' % self.Cluster_Size)
+ showIndent(write, level, pretty_print)
+ write('<%sCluster_Size>%s%sCluster_Size>%s' % ('maecPackage:', self.gds_format_integer(self.Cluster_Size, input_name='Cluster_Size'), 'maecPackage:', eol_))
if self.Cluster_Description is not None:
- showIndent(outfile, level)
- outfile.write('Cluster_Description=%s,\n' % quote_python(self.Cluster_Description).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sCluster_Description>%s%sCluster_Description>%s' % ('maecPackage:', quote_xml(self.Cluster_Description), 'maecPackage:', eol_))
if self.Cluster_Composition is not None:
- outfile.write('Cluster_Composition=model_.ClusterCompositionType(\n')
- self.Cluster_Composition.exportLiteral(outfile, level, name_='Cluster_Composition')
- outfile.write('),\n')
+ self.Cluster_Composition.export(write, level, 'maecPackage:', name_='Cluster_Composition', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -2962,7 +1959,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
if ival_ <= 0:
raise_parse_error(child_, 'requires positiveInteger')
@@ -3021,63 +2018,40 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ClusterEdgeNodePairType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ClusterEdgeNodePairType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ClusterEdgeNodePairType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ClusterEdgeNodePairType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ClusterEdgeNodePairType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ClusterEdgeNodePairType'):
if self.similarity_distance is not None and 'similarity_distance' not in already_processed:
already_processed.add('similarity_distance')
- outfile.write(' similarity_distance="%s"' % self.gds_format_float(self.similarity_distance, input_name='similarity_distance'))
+ write(' similarity_distance="%s"' % self.gds_format_float(self.similarity_distance, input_name='similarity_distance'))
if self.similarity_index is not None and 'similarity_index' not in already_processed:
already_processed.add('similarity_index')
- outfile.write(' similarity_index="%s"' % self.gds_format_float(self.similarity_index, input_name='similarity_index'))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ClusterEdgeNodePairType', fromsubclass_=False, pretty_print=True):
+ write(' similarity_index="%s"' % self.gds_format_float(self.similarity_index, input_name='similarity_index'))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ClusterEdgeNodePairType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Malware_Subject_Node_A is not None:
- self.Malware_Subject_Node_A.export(outfile, level, 'maecPackage:', name_='Malware_Subject_Node_A', pretty_print=pretty_print)
+ self.Malware_Subject_Node_A.export(write, level, 'maecPackage:', name_='Malware_Subject_Node_A', pretty_print=pretty_print)
if self.Malware_Subject_Node_B is not None:
- self.Malware_Subject_Node_B.export(outfile, level, 'maecPackage:', name_='Malware_Subject_Node_B', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ClusterEdgeNodePairType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.similarity_distance is not None and 'similarity_distance' not in already_processed:
- already_processed.add('similarity_distance')
- showIndent(outfile, level)
- outfile.write('similarity_distance = %f,\n' % (self.similarity_distance,))
- if self.similarity_index is not None and 'similarity_index' not in already_processed:
- already_processed.add('similarity_index')
- showIndent(outfile, level)
- outfile.write('similarity_index = %f,\n' % (self.similarity_index,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Malware_Subject_Node_A is not None:
- outfile.write('Malware_Subject_Node_A=model_.MalwareSubjectReferenceType(\n')
- self.Malware_Subject_Node_A.exportLiteral(outfile, level, name_='Malware_Subject_Node_A')
- outfile.write('),\n')
- if self.Malware_Subject_Node_B is not None:
- outfile.write('Malware_Subject_Node_B=model_.MalwareSubjectReferenceType(\n')
- self.Malware_Subject_Node_B.exportLiteral(outfile, level, name_='Malware_Subject_Node_B')
- outfile.write('),\n')
+ self.Malware_Subject_Node_B.export(write, level, 'maecPackage:', name_='Malware_Subject_Node_B', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3089,14 +2063,14 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('similarity_distance')
try:
self.similarity_distance = float(value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad float/double attribute (similarity_distance): %s' % exp)
value = find_attr_value_('similarity_index', node)
if value is not None and 'similarity_index' not in already_processed:
already_processed.add('similarity_index')
try:
self.similarity_index = float(value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad float/double attribute (similarity_index): %s' % exp)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'Malware_Subject_Node_A':
@@ -3143,57 +2117,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ClusterCompositionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ClusterCompositionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ClusterCompositionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ClusterCompositionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ClusterCompositionType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ClusterCompositionType'):
if self.score_type is not None and 'score_type' not in already_processed:
already_processed.add('score_type')
- outfile.write(' score_type=%s' % (self.gds_format_string(quote_attrib(self.score_type).encode(ExternalEncoding), input_name='score_type'), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ClusterCompositionType', fromsubclass_=False, pretty_print=True):
+ write(' score_type=%s' % (quote_attrib(self.score_type)))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ClusterCompositionType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Edge_Node_Pair_ in self.Edge_Node_Pair:
- Edge_Node_Pair_.export(outfile, level, 'maecPackage:', name_='Edge_Node_Pair', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ClusterCompositionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.score_type is not None and 'score_type' not in already_processed:
- already_processed.add('score_type')
- showIndent(outfile, level)
- outfile.write('score_type = "%s",\n' % (self.score_type,))
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Edge_Node_Pair=[\n')
- level += 1
- for Edge_Node_Pair_ in self.Edge_Node_Pair:
- outfile.write('model_.ClusterEdgeNodePairType(\n')
- Edge_Node_Pair_.exportLiteral(outfile, level, name_='ClusterEdgeNodePairType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Edge_Node_Pair_.export(write, level, 'maecPackage:', name_='Edge_Node_Pair', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3237,51 +2189,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ClusteringAlgorithmParametersType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ClusteringAlgorithmParametersType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ClusteringAlgorithmParametersType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ClusteringAlgorithmParametersType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ClusteringAlgorithmParametersType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ClusteringAlgorithmParametersType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ClusteringAlgorithmParametersType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ClusteringAlgorithmParametersType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Distance_Threshold is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDistance_Threshold>%s%sDistance_Threshold>%s' % ('maecPackage:', self.gds_format_float(self.Distance_Threshold, input_name='Distance_Threshold'), 'maecPackage:', eol_))
- if self.Number_of_Iterations is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sNumber_of_Iterations>%s%sNumber_of_Iterations>%s' % ('maecPackage:', self.gds_format_integer(self.Number_of_Iterations, input_name='Number_of_Iterations'), 'maecPackage:', eol_))
- def exportLiteral(self, outfile, level, name_='ClusteringAlgorithmParametersType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Distance_Threshold is not None:
- showIndent(outfile, level)
- outfile.write('Distance_Threshold=%f,\n' % self.Distance_Threshold)
+ showIndent(write, level, pretty_print)
+ write('<%sDistance_Threshold>%s%sDistance_Threshold>%s' % ('maecPackage:', self.gds_format_float(self.Distance_Threshold, input_name='Distance_Threshold'), 'maecPackage:', eol_))
if self.Number_of_Iterations is not None:
- showIndent(outfile, level)
- outfile.write('Number_of_Iterations=%d,\n' % self.Number_of_Iterations)
+ showIndent(write, level, pretty_print)
+ write('<%sNumber_of_Iterations>%s%sNumber_of_Iterations>%s' % ('maecPackage:', self.gds_format_integer(self.Number_of_Iterations, input_name='Number_of_Iterations'), 'maecPackage:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3294,7 +2232,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
fval_ = float(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
fval_ = self.gds_validate_float(fval_, node, 'Distance_Threshold')
self.Distance_Threshold = fval_
@@ -3302,7 +2240,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
if ival_ <= 0:
raise_parse_error(child_, 'requires positiveInteger')
@@ -3332,45 +2270,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='NetworkInfrastructureType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='NetworkInfrastructureType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='NetworkInfrastructureType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='NetworkInfrastructureType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='NetworkInfrastructureType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='NetworkInfrastructureType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='NetworkInfrastructureType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='NetworkInfrastructureType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Captured_Protocols is not None:
- self.Captured_Protocols.export(outfile, level, 'maecPackage:', name_='Captured_Protocols', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='NetworkInfrastructureType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Captured_Protocols is not None:
- outfile.write('Captured_Protocols=model_.CapturedProtocolListType(\n')
- self.Captured_Protocols.exportLiteral(outfile, level, name_='Captured_Protocols')
- outfile.write('),\n')
+ self.Captured_Protocols.export(write, level, 'maecPackage:', name_='Captured_Protocols', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3421,57 +2347,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ActionEquivalenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ActionEquivalenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionEquivalenceType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionEquivalenceType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ActionEquivalenceType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ActionEquivalenceType'):
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ActionEquivalenceType', fromsubclass_=False, pretty_print=True):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ActionEquivalenceType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Action_Reference_ in self.Action_Reference:
- Action_Reference_.export(outfile, level, 'maecPackage:', name_='Action_Reference', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionEquivalenceType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Action_Reference=[\n')
- level += 1
- for Action_Reference_ in self.Action_Reference:
- outfile.write('model_.cybox_core.ActionReferenceType(\n')
- Action_Reference_.exportLiteral(outfile, level, name_='cybox_core.ActionReferenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Action_Reference_.export(write, level, 'maecPackage:', name_='Action_Reference', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3516,52 +2420,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ActionEquivalenceListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ActionEquivalenceListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ActionEquivalenceListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ActionEquivalenceListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ActionEquivalenceListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ActionEquivalenceListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ActionEquivalenceListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ActionEquivalenceListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Action_Equivalence_ in self.Action_Equivalence:
- Action_Equivalence_.export(outfile, level, 'maecPackage:', name_='Action_Equivalence', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ActionEquivalenceListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Action_Equivalence=[\n')
- level += 1
- for Action_Equivalence_ in self.Action_Equivalence:
- outfile.write('model_.ActionEquivalenceType(\n')
- Action_Equivalence_.exportLiteral(outfile, level, name_='ActionEquivalenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Action_Equivalence_.export(write, level, 'maecPackage:', name_='Action_Equivalence', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3604,52 +2489,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='CapturedProtocolListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='CapturedProtocolListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapturedProtocolListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapturedProtocolListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='CapturedProtocolListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='CapturedProtocolListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='CapturedProtocolListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='CapturedProtocolListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Protocol_ in self.Protocol:
- Protocol_.export(outfile, level, 'maecPackage:', name_='Protocol', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='CapturedProtocolListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Protocol=[\n')
- level += 1
- for Protocol_ in self.Protocol:
- outfile.write('model_.CapturedProtocolType(\n')
- Protocol_.exportLiteral(outfile, level, name_='CapturedProtocolType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Protocol_.export(write, level, 'maecPackage:', name_='Protocol', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3706,62 +2572,38 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='CapturedProtocolType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='CapturedProtocolType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CapturedProtocolType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CapturedProtocolType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='CapturedProtocolType'):
- if self.layer7_protocol is not None and 'layer7_protocol' not in already_processed:
- already_processed.add('layer7_protocol')
- outfile.write(' layer7_protocol=%s' % (quote_attrib(self.layer7_protocol), ))
- if self.port_number is not None and 'port_number' not in already_processed:
- already_processed.add('port_number')
- outfile.write(' port_number="%s"' % self.gds_format_integer(self.port_number, input_name='port_number'))
- if self.interaction_level is not None and 'interaction_level' not in already_processed:
- already_processed.add('interaction_level')
- outfile.write(' interaction_level=%s' % (quote_attrib(self.interaction_level), ))
- if self.layer4_protocol is not None and 'layer4_protocol' not in already_processed:
- already_processed.add('layer4_protocol')
- outfile.write(' layer4_protocol=%s' % (quote_attrib(self.layer4_protocol), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='CapturedProtocolType', fromsubclass_=False, pretty_print=True):
- pass
- def exportLiteral(self, outfile, level, name_='CapturedProtocolType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='CapturedProtocolType'):
if self.layer7_protocol is not None and 'layer7_protocol' not in already_processed:
already_processed.add('layer7_protocol')
- showIndent(outfile, level)
- outfile.write('layer7_protocol = %s,\n' % (self.layer7_protocol,))
+ write(' layer7_protocol=%s' % (quote_attrib(self.layer7_protocol), ))
if self.port_number is not None and 'port_number' not in already_processed:
already_processed.add('port_number')
- showIndent(outfile, level)
- outfile.write('port_number = %d,\n' % (self.port_number,))
+ write(' port_number="%s"' % self.gds_format_integer(self.port_number, input_name='port_number'))
if self.interaction_level is not None and 'interaction_level' not in already_processed:
already_processed.add('interaction_level')
- showIndent(outfile, level)
- outfile.write('interaction_level = %s,\n' % (self.interaction_level,))
+ write(' interaction_level=%s' % (quote_attrib(self.interaction_level), ))
if self.layer4_protocol is not None and 'layer4_protocol' not in already_processed:
already_processed.add('layer4_protocol')
- showIndent(outfile, level)
- outfile.write('layer4_protocol = %s,\n' % (self.layer4_protocol,))
- def exportLiteralChildren(self, outfile, level, name_):
+ write(' layer4_protocol=%s' % (quote_attrib(self.layer4_protocol), ))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='CapturedProtocolType', fromsubclass_=False, pretty_print=True):
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3777,7 +2619,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('port_number')
try:
self.port_number = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.port_number <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -3820,52 +2662,33 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ObjectEquivalenceListType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ObjectEquivalenceListType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectEquivalenceListType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectEquivalenceListType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ObjectEquivalenceListType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ObjectEquivalenceListType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ObjectEquivalenceListType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ObjectEquivalenceListType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Object_Equivalence_ in self.Object_Equivalence:
- Object_Equivalence_.export(outfile, level, 'maecPackage:', name_='Object_Equivalence', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ObjectEquivalenceListType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Object_Equivalence=[\n')
- level += 1
- for Object_Equivalence_ in self.Object_Equivalence:
- outfile.write('model_.ObjectEquivalenceType(\n')
- Object_Equivalence_.exportLiteral(outfile, level, name_='ObjectEquivalenceType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Object_Equivalence_.export(write, level, 'maecPackage:', name_='Object_Equivalence', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3907,44 +2730,31 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='ObjectEquivalenceType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='ObjectEquivalenceType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
- already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectEquivalenceType')
- if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='ObjectEquivalenceType'):
- super(ObjectEquivalenceType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='ObjectEquivalenceType')
- if self.id is not None and 'id' not in already_processed:
- already_processed.add('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='ObjectEquivalenceType', fromsubclass_=False, pretty_print=True):
- super(ObjectEquivalenceType, self).exportChildren(outfile, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='ObjectEquivalenceType'):
- level += 1
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ObjectEquivalenceType')
if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='ObjectEquivalenceType'):
+ super(ObjectEquivalenceType, self).exportAttributes(write, level, already_processed, namespace_, name_='ObjectEquivalenceType')
if self.id is not None and 'id' not in already_processed:
already_processed.add('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- super(ObjectEquivalenceType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(ObjectEquivalenceType, self).exportLiteralChildren(outfile, level, name_)
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='ObjectEquivalenceType', fromsubclass_=False, pretty_print=True):
+ super(ObjectEquivalenceType, self).exportChildren(write, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -3985,47 +2795,34 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='HypervisorHostSystemType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='HypervisorHostSystemType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='HypervisorHostSystemType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='HypervisorHostSystemType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='HypervisorHostSystemType'):
- super(HypervisorHostSystemType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='HypervisorHostSystemType')
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='HypervisorHostSystemType', fromsubclass_=False, pretty_print=True):
- super(HypervisorHostSystemType, self).exportChildren(outfile, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='HypervisorHostSystemType'):
+ super(HypervisorHostSystemType, self).exportAttributes(write, level, already_processed, namespace_, name_='HypervisorHostSystemType')
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='HypervisorHostSystemType', fromsubclass_=False, pretty_print=True):
+ super(HypervisorHostSystemType, self).exportChildren(write, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.VM_Hypervisor is not None:
- self.VM_Hypervisor.export(outfile, level, 'maecPackage:', name_='VM_Hypervisor', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='HypervisorHostSystemType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- super(HypervisorHostSystemType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(HypervisorHostSystemType, self).exportLiteralChildren(outfile, level, name_)
- if self.VM_Hypervisor is not None:
- outfile.write('VM_Hypervisor=model_.cybox_common.PlatformSpecificationType(\n')
- self.VM_Hypervisor.exportLiteral(outfile, level, name_='VM_Hypervisor')
- outfile.write('),\n')
+ self.VM_Hypervisor.export(write, level, 'maecPackage:', name_='VM_Hypervisor', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4066,47 +2863,34 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='AnalysisSystemType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='AnalysisSystemType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='AnalysisSystemType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='AnalysisSystemType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='AnalysisSystemType'):
- super(AnalysisSystemType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='AnalysisSystemType')
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='AnalysisSystemType', fromsubclass_=False, pretty_print=True):
- super(AnalysisSystemType, self).exportChildren(outfile, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='AnalysisSystemType'):
+ super(AnalysisSystemType, self).exportAttributes(write, level, already_processed, namespace_, name_='AnalysisSystemType')
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='AnalysisSystemType', fromsubclass_=False, pretty_print=True):
+ super(AnalysisSystemType, self).exportChildren(write, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Installed_Programs is not None:
- self.Installed_Programs.export(outfile, level, 'maecPackage:', name_='Installed_Programs', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='AnalysisSystemType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- super(AnalysisSystemType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(AnalysisSystemType, self).exportLiteralChildren(outfile, level, name_)
- if self.Installed_Programs is not None:
- outfile.write('Installed_Programs=model_.InstalledProgramsType(\n')
- self.Installed_Programs.exportLiteral(outfile, level, name_='Installed_Programs')
- outfile.write('),\n')
+ self.Installed_Programs.export(write, level, 'maecPackage:', name_='Installed_Programs', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4157,58 +2941,38 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='CommentType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='CommentType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CommentType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CommentType')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='CommentType'):
- super(CommentType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='CommentType')
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='CommentType'):
+ super(CommentType, self).exportAttributes(write, level, already_processed, namespace_, name_='CommentType')
if self.timestamp is not None and 'timestamp' not in already_processed:
already_processed.add('timestamp')
- outfile.write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
+ write(' timestamp="%s"' % self.gds_format_datetime(self.timestamp, input_name='timestamp'))
if self.author is not None and 'author' not in already_processed:
already_processed.add('author')
- outfile.write(' author=%s' % (self.gds_format_string(quote_attrib(self.author).encode(ExternalEncoding), input_name='author'), ))
+ write(' author=%s' % (quote_attrib(self.author)))
if self.observation_name is not None and 'observation_name' not in already_processed:
already_processed.add('observation_name')
- outfile.write(' observation_name=%s' % (self.gds_format_string(quote_attrib(self.observation_name).encode(ExternalEncoding), input_name='observation_name'), ))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='CommentType', fromsubclass_=False, pretty_print=True):
- super(CommentType, self).exportChildren(outfile, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
- pass
- def exportLiteral(self, outfile, level, name_='CommentType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.timestamp is not None and 'timestamp' not in already_processed:
- already_processed.add('timestamp')
- showIndent(outfile, level)
- outfile.write('timestamp = "%s",\n' % (self.timestamp,))
- if self.author is not None and 'author' not in already_processed:
- already_processed.add('author')
- showIndent(outfile, level)
- outfile.write('author = "%s",\n' % (self.author,))
- super(CommentType, self).exportLiteralAttributes(outfile, level, already_processed, name_)
- def exportLiteralChildren(self, outfile, level, name_):
- super(CommentType, self).exportLiteralChildren(outfile, level, name_)
+ write(' observation_name=%s' % (quote_attrib(self.observation_name)))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='CommentType', fromsubclass_=False, pretty_print=True):
+ super(CommentType, self).exportChildren(write, level, 'maecPackage:', name_, True, pretty_print=pretty_print)
pass
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
self.valueOf_ = get_all_text_(node)
@@ -4221,7 +2985,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('timestamp')
try:
self.timestamp = value
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad date-time attribute (timestamp): %s' % exp)
value = find_attr_value_('author', node)
if value is not None and 'author' not in already_processed:
@@ -4274,64 +3038,44 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareExceptionType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareExceptionType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareExceptionType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareExceptionType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
- else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareExceptionType'):
- super(MalwareExceptionType, self).exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareExceptionType')
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
+ else:
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareExceptionType'):
+ super(MalwareExceptionType, self).exportAttributes(write, level, already_processed, namespace_, name_='MalwareExceptionType')
if self.is_fatal is not None and 'is_fatal' not in already_processed:
already_processed.add('is_fatal')
- outfile.write(' is_fatal="%s"' % self.gds_format_boolean(self.is_fatal, input_name='is_fatal'))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareExceptionType', fromsubclass_=False, pretty_print=True):
- super(MalwareExceptionType, self).exportChildren(outfile, level, namespace_, name_, True, pretty_print=pretty_print)
+ write(' is_fatal="%s"' % self.gds_format_boolean(self.is_fatal, input_name='is_fatal'))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareExceptionType', fromsubclass_=False, pretty_print=True):
+ super(MalwareExceptionType, self).exportChildren(write, level, namespace_, name_, True, pretty_print=pretty_print)
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Exception_Code is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sException_Code>%s%sException_Code>%s' % (namespace_, self.gds_format_string(quote_xml(self.Exception_Code).encode(ExternalEncoding), input_name='Exception_Code'), namespace_, eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sException_Code>%s%sException_Code>%s' % (namespace_, quote_xml(self.Exception_Code), namespace_, eol_))
if self.Faulting_Address is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sFaulting_Address>%s%sFaulting_Address>%s' % (namespace_, self.gds_format_string(quote_xml(self.Faulting_Address).encode(ExternalEncoding), input_name='Faulting_Address'), namespace_, eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sFaulting_Address>%s%sFaulting_Address>%s' % (namespace_, quote_xml(self.Faulting_Address), namespace_, eol_))
if self.Description is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sDescription>%s%sDescription>%s' % (namespace_, self.gds_format_integer(self.Description, input_name='Description'), namespace_, eol_))
- def exportLiteral(self, outfile, level, name_='MalwareExceptionType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.is_fatal is not None and 'is_fatal' not in already_processed:
- already_processed.add('is_fatal')
- showIndent(outfile, level)
- outfile.write('is_fatal = %s,\n' % (self.is_fatal,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Exception_Code is not None:
- showIndent(outfile, level)
- outfile.write('Exception_Code=%s,\n' % quote_python(self.Exception_Code).encode(ExternalEncoding))
- if self.Faulting_Address is not None:
- showIndent(outfile, level)
- outfile.write('Faulting_Address=%s,\n' % quote_python(self.Faulting_Address).encode(ExternalEncoding))
- if self.Description is not None:
- showIndent(outfile, level)
- outfile.write('Description=%d,\n' % self.Description)
+ showIndent(write, level, pretty_print)
+ write('<%sDescription>%s%sDescription>%s' % (namespace_, self.gds_format_integer(self.Description, input_name='Description'), namespace_, eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4361,7 +3105,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'Description')
self.Description = ival_
@@ -4400,55 +3144,35 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareDevelopmentEnvironmentType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareDevelopmentEnvironmentType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareDevelopmentEnvironmentType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareDevelopmentEnvironmentType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareDevelopmentEnvironmentType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareDevelopmentEnvironmentType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareDevelopmentEnvironmentType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareDevelopmentEnvironmentType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Tools is not None:
- self.Tools.export(outfile, level, namespace_, name_='Tools', pretty_print=pretty_print)
- for Debugging_File_ in self.Debugging_File:
- Debugging_File_.export(outfile, level, namespace_, name_='Debugging_File', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareDevelopmentEnvironmentType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Tools is not None:
- showIndent(outfile, level)
- outfile.write('Tools=%s,\n' % quote_python(self.Tools).encode(ExternalEncoding))
- showIndent(outfile, level)
- outfile.write('Debugging_File=[\n')
- level += 1
+ self.Tools.export(write, level, namespace_, name_='Tools', pretty_print=pretty_print)
for Debugging_File_ in self.Debugging_File:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(Debugging_File_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Debugging_File_.export(write, level, namespace_, name_='Debugging_File', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4494,51 +3218,36 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationParameterType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationParameterType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareConfigurationParameterType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareConfigurationParameterType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationParameterType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationParameterType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationParameterType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationParameterType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Name is not None:
- self.Name.export(outfile, level, 'maecPackage:', name_='Name', pretty_print=pretty_print)
+ self.Name.export(write, level, 'maecPackage:', name_='Name', pretty_print=pretty_print)
if self.Value is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sValue>%s%sValue>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Value).encode(ExternalEncoding), input_name='Value'), 'maecPackage:', eol_))
- def exportLiteral(self, outfile, level, name_='MalwareConfigurationParameterType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Name is not None:
- outfile.write('Name=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Name.exportLiteral(outfile, level, name_='Name')
- outfile.write('),\n')
- if self.Value is not None:
- showIndent(outfile, level)
- outfile.write('Value=%s,\n' % quote_python(self.Value).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sValue>%s%sValue>%s' % ('maecPackage:', quote_xml(self.Value), 'maecPackage:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4592,64 +3301,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationDetailsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationDetailsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareConfigurationDetailsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareConfigurationDetailsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationDetailsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationDetailsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationDetailsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationDetailsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Storage is not None:
- self.Storage.export(outfile, level, 'maecPackage:', name_='Storage', pretty_print=pretty_print)
+ self.Storage.export(write, level, 'maecPackage:', name_='Storage', pretty_print=pretty_print)
if self.Obfuscation is not None:
- self.Obfuscation.export(outfile, level, 'maecPackage:', name_='Obfuscation', pretty_print=pretty_print)
+ self.Obfuscation.export(write, level, 'maecPackage:', name_='Obfuscation', pretty_print=pretty_print)
for Configuration_Parameter_ in self.Configuration_Parameter:
- Configuration_Parameter_.export(outfile, level, 'maecPackage:', name_='Configuration_Parameter', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareConfigurationDetailsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Storage is not None:
- outfile.write('Storage=model_.MalwareConfigurationStorageDetailsType(\n')
- self.Storage.exportLiteral(outfile, level, name_='Storage')
- outfile.write('),\n')
- if self.Obfuscation is not None:
- outfile.write('Obfuscation=model_.MalwareConfigurationObfuscationDetailsType(\n')
- self.Obfuscation.exportLiteral(outfile, level, name_='Obfuscation')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('Configuration_Parameter=[\n')
- level += 1
- for Configuration_Parameter_ in self.Configuration_Parameter:
- outfile.write('model_.MalwareConfigurationParameterType(\n')
- Configuration_Parameter_.exportLiteral(outfile, level, name_='MalwareConfigurationParameterType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Configuration_Parameter_.export(write, level, 'maecPackage:', name_='Configuration_Parameter', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4710,64 +3392,38 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationDetailsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationDetailsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareConfigurationObfuscationDetailsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareConfigurationObfuscationDetailsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationDetailsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationDetailsType'):
if self.is_encoded is not None and 'is_encoded' not in already_processed:
already_processed.add('is_encoded')
- outfile.write(' is_encoded="%s"' % self.gds_format_boolean(self.is_encoded, input_name='is_encoded'))
+ write(' is_encoded="%s"' % self.gds_format_boolean(self.is_encoded, input_name='is_encoded'))
if self.is_encrypted is not None and 'is_encrypted' not in already_processed:
already_processed.add('is_encrypted')
- outfile.write(' is_encrypted="%s"' % self.gds_format_boolean(self.is_encrypted, input_name='is_encrypted'))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationDetailsType', fromsubclass_=False, pretty_print=True):
+ write(' is_encrypted="%s"' % self.gds_format_boolean(self.is_encrypted, input_name='is_encrypted'))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationDetailsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
for Algorithm_Details_ in self.Algorithm_Details:
- Algorithm_Details_.export(outfile, level, 'maecPackage:', name_='Algorithm_Details', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareConfigurationObfuscationDetailsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.is_encoded is not None and 'is_encoded' not in already_processed:
- already_processed.add('is_encoded')
- showIndent(outfile, level)
- outfile.write('is_encoded = %s,\n' % (self.is_encoded,))
- if self.is_encrypted is not None and 'is_encrypted' not in already_processed:
- already_processed.add('is_encrypted')
- showIndent(outfile, level)
- outfile.write('is_encrypted = %s,\n' % (self.is_encrypted,))
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('Algorithm_Details=[\n')
- level += 1
- for Algorithm_Details_ in self.Algorithm_Details:
- outfile.write('model_.MalwareConfigurationObfuscationAlgorithmType(\n')
- Algorithm_Details_.exportLiteral(outfile, level, name_='MalwareConfigurationObfuscationAlgorithmType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ Algorithm_Details_.export(write, level, 'maecPackage:', name_='Algorithm_Details', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4832,56 +3488,38 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationAlgorithmType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationAlgorithmType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareConfigurationObfuscationAlgorithmType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareConfigurationObfuscationAlgorithmType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationAlgorithmType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationAlgorithmType'):
if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
already_processed.add('ordinal_position')
- outfile.write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationAlgorithmType', fromsubclass_=False, pretty_print=True):
+ write(' ordinal_position="%s"' % self.gds_format_integer(self.ordinal_position, input_name='ordinal_position'))
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationObfuscationAlgorithmType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Key is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sKey>%s%sKey>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Key).encode(ExternalEncoding), input_name='Key'), 'maecPackage:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sKey>%s%sKey>%s' % ('maecPackage:', quote_xml(self.Key), 'maecPackage:', eol_))
if self.Algorithm_Name is not None:
- self.Algorithm_Name.export(outfile, level, 'maecPackage:', name_='Algorithm_Name', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareConfigurationObfuscationAlgorithmType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.ordinal_position is not None and 'ordinal_position' not in already_processed:
- already_processed.add('ordinal_position')
- showIndent(outfile, level)
- outfile.write('ordinal_position = %d,\n' % (self.ordinal_position,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Key is not None:
- showIndent(outfile, level)
- outfile.write('Key=%s,\n' % quote_python(self.Key).encode(ExternalEncoding))
- if self.Algorithm_Name is not None:
- outfile.write('Algorithm_Name=model_.cybox_common.ControlledVocabularyStringType(\n')
- self.Algorithm_Name.exportLiteral(outfile, level, name_='Algorithm_Name')
- outfile.write('),\n')
+ self.Algorithm_Name.export(write, level, 'maecPackage:', name_='Algorithm_Name', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -4893,7 +3531,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.add('ordinal_position')
try:
self.ordinal_position = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
if self.ordinal_position <= 0:
raise_parse_error(node, 'Invalid PositiveInteger')
@@ -4943,64 +3581,37 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationStorageDetailsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationStorageDetailsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareConfigurationStorageDetailsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareConfigurationStorageDetailsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationStorageDetailsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareConfigurationStorageDetailsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareConfigurationStorageDetailsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareConfigurationStorageDetailsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.Malware_Binary is not None:
- self.Malware_Binary.export(outfile, level, 'maecPackage:', name_='Malware_Binary', pretty_print=pretty_print)
- if self.File is not None:
- self.File.export(outfile, level, 'maecPackage:', name_='File', pretty_print=pretty_print)
- for URL_ in self.URL:
- URL_.export(outfile, level, 'maecPackage:', name_='URL', pretty_print=pretty_print)
- def exportLiteral(self, outfile, level, name_='MalwareConfigurationStorageDetailsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.Malware_Binary is not None:
- outfile.write('Malware_Binary=model_.MalwareBinaryConfigurationStorageDetailsType(\n')
- self.Malware_Binary.exportLiteral(outfile, level, name_='Malware_Binary')
- outfile.write('),\n')
+ self.Malware_Binary.export(write, level, 'maecPackage:', name_='Malware_Binary', pretty_print=pretty_print)
if self.File is not None:
- outfile.write('File=model_.file_object.FileObjectType(\n')
- self.File.exportLiteral(outfile, level, name_='File')
- outfile.write('),\n')
- showIndent(outfile, level)
- outfile.write('URL=[\n')
- level += 1
+ self.File.export(write, level, 'maecPackage:', name_='File', pretty_print=pretty_print)
for URL_ in self.URL:
- outfile.write('model_.uri_object.URIObjectType(\n')
- URL_.exportLiteral(outfile, level, name_='uri_object.URIObjectType')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
+ URL_.export(write, level, 'maecPackage:', name_='URL', pretty_print=pretty_print)
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5054,57 +3665,40 @@ def hasContent_(self):
return True
else:
return False
- def export(self, outfile, level, namespace_='maecPackage:', name_='MalwareBinaryConfigurationStorageDetailsType', namespacedef_='', pretty_print=True):
+ def export(self, write, level, namespace_='maecPackage:', name_='MalwareBinaryConfigurationStorageDetailsType', namespacedef_='', pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
- showIndent(outfile, level, pretty_print)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ showIndent(write, level, pretty_print)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = set()
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='MalwareBinaryConfigurationStorageDetailsType')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='MalwareBinaryConfigurationStorageDetailsType')
if self.hasContent_():
- outfile.write('>%s' % (eol_, ))
- self.exportChildren(outfile, level + 1, namespace_, name_, pretty_print=pretty_print)
- showIndent(outfile, level, pretty_print)
- outfile.write('%s%s>%s' % (namespace_, name_, eol_))
+ write('>%s' % (eol_, ))
+ self.exportChildren(write, level + 1, namespace_, name_, pretty_print=pretty_print)
+ showIndent(write, level, pretty_print)
+ write('%s%s>%s' % (namespace_, name_, eol_))
else:
- outfile.write('/>%s' % (eol_, ))
- def exportAttributes(self, outfile, level, already_processed, namespace_='maecPackage:', name_='MalwareBinaryConfigurationStorageDetailsType'):
+ write('/>%s' % (eol_, ))
+ def exportAttributes(self, write, level, already_processed, namespace_='maecPackage:', name_='MalwareBinaryConfigurationStorageDetailsType'):
pass
- def exportChildren(self, outfile, level, namespace_='maecPackage:', name_='MalwareBinaryConfigurationStorageDetailsType', fromsubclass_=False, pretty_print=True):
+ def exportChildren(self, write, level, namespace_='maecPackage:', name_='MalwareBinaryConfigurationStorageDetailsType', fromsubclass_=False, pretty_print=True):
if pretty_print:
eol_ = '\n'
else:
eol_ = ''
if self.File_Offset is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sFile_Offset>%s%sFile_Offset>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.File_Offset).encode(ExternalEncoding), input_name='File_Offset'), 'maecPackage:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sFile_Offset>%s%sFile_Offset>%s' % ('maecPackage:', quote_xml(self.File_Offset), 'maecPackage:', eol_))
if self.Section_Name is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sSection_Name>%s%sSection_Name>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Section_Name).encode(ExternalEncoding), input_name='Section_Name'), 'maecPackage:', eol_))
+ showIndent(write, level, pretty_print)
+ write('<%sSection_Name>%s%sSection_Name>%s' % ('maecPackage:', quote_xml(self.Section_Name), 'maecPackage:', eol_))
if self.Section_Offset is not None:
- showIndent(outfile, level, pretty_print)
- outfile.write('<%sSection_Offset>%s%sSection_Offset>%s' % ('maecPackage:', self.gds_format_string(quote_xml(self.Section_Offset).encode(ExternalEncoding), input_name='Section_Offset'), 'maecPackage:', eol_))
- def exportLiteral(self, outfile, level, name_='MalwareBinaryConfigurationStorageDetailsType'):
- level += 1
- already_processed = set()
- self.exportLiteralAttributes(outfile, level, already_processed, name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.File_Offset is not None:
- showIndent(outfile, level)
- outfile.write('File_Offset=%s,\n' % quote_python(self.File_Offset).encode(ExternalEncoding))
- if self.Section_Name is not None:
- showIndent(outfile, level)
- outfile.write('Section_Name=%s,\n' % quote_python(self.Section_Name).encode(ExternalEncoding))
- if self.Section_Offset is not None:
- showIndent(outfile, level)
- outfile.write('Section_Offset=%s,\n' % quote_python(self.Section_Offset).encode(ExternalEncoding))
+ showIndent(write, level, pretty_print)
+ write('<%sSection_Offset>%s%sSection_Offset>%s' % ('maecPackage:', quote_xml(self.Section_Offset), 'maecPackage:', eol_))
def build(self, node):
+ self.__sourcenode__ = node
already_processed = set()
self.buildAttributes(node, node.attrib, already_processed)
for child in node:
@@ -5132,14 +3726,20 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
"""
def usage():
- print USAGE_TEXT
+ print(USAGE_TEXT)
sys.exit(1)
+def get_root_tag(node):
+ tag = Tag_pattern_.match(node.tag).groups()[-1]
+ rootClass = GDSClassesMapping.get(tag)
+ if rootClass is None:
+ rootClass = globals().get(tag)
+ return tag, rootClass
+
def parse(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Package'
- rootClass = PackageType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -5153,8 +3753,7 @@ def parse(inFileName):
def parseEtree(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Package'
- rootClass = PackageType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -5167,11 +3766,10 @@ def parseEtree(inFileName):
return rootObj, rootElement
def parseString(inString):
- from StringIO import StringIO
+ from mixbox.vendor.six import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
- rootTag = 'MAEC_Package'
- rootClass = PackageType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -5184,8 +3782,7 @@ def parseString(inString):
def parseLiteral(inFileName):
doc = parsexml_(inFileName)
rootNode = doc.getroot()
- rootTag = 'MAEC_Package'
- rootClass = PackageType
+ rootTag, rootClass = get_root_tag(rootNode)
rootObj = rootClass.factory()
rootObj.build(rootNode)
# Enable Python to collect the space used by the DOM.
@@ -5244,4 +3841,41 @@ def main():
"CapturedProtocolType",
"ObjectEquivalenceType",
"ObjectEquivalenceListType"
- ]
\ No newline at end of file
+ ]
+
+GDSClassesMapping = {
+ "AnalysisEnvironmentType": AnalysisEnvironmentType,
+ "SourceType": SourceType,
+ "CommentListType": CommentListType,
+ "AnalysisSystemListType": AnalysisSystemListType,
+ "ToolListType": ToolListType,
+ "CommentType": CommentType,
+ "AnalysisSystemType": AnalysisSystemType,
+ "HypervisorHostSystemType": HypervisorHostSystemType,
+ "DynamicAnalysisMetadataType": DynamicAnalysisMetadataType,
+ "AnalysisType": AnalysisType,
+ "AnalysisListType": AnalysisListType,
+ "InstalledProgramsType": InstalledProgramsType,
+ "MAEC_Package": PackageType,
+ "MalwareSubjectType": MalwareSubjectType,
+ "MetaAnalysisType": MetaAnalysisType,
+ "MalwareSubjectRelationshipType": MalwareSubjectRelationshipType,
+ "MalwareSubjectRelationshipListType": MalwareSubjectRelationshipListType,
+ "MalwareSubjectReferenceType": MalwareSubjectReferenceType,
+ "MalwareSubjectListType": MalwareSubjectListType,
+ "MinorVariantListType": MinorVariantListType,
+ "FindingsBundleListType": FindingsBundleListType,
+ "GroupingRelationshipType": GroupingRelationshipType,
+ "GroupingRelationshipListType": GroupingRelationshipListType,
+ "ClusteringMetadataType": ClusteringMetadataType,
+ "ClusterEdgeNodePairType": ClusterEdgeNodePairType,
+ "ClusterCompositionType": ClusterCompositionType,
+ "ClusteringAlgorithmParametersType": ClusteringAlgorithmParametersType,
+ "NetworkInfrastructureType": NetworkInfrastructureType,
+ "ActionEquivalenceType": ActionEquivalenceType,
+ "ActionEquivalenceListType": ActionEquivalenceListType,
+ "CapturedProtocolListType": CapturedProtocolListType,
+ "CapturedProtocolType": CapturedProtocolType,
+ "ObjectEquivalenceType": ObjectEquivalenceType,
+ "ObjectEquivalenceListType": ObjectEquivalenceListType
+}
diff --git a/maec/bindings/mmdef_1_2.py b/maec/bindings/mmdef_1_2.py
index 03328bc..b70d006 100644
--- a/maec/bindings/mmdef_1_2.py
+++ b/maec/bindings/mmdef_1_2.py
@@ -1,342 +1,10 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-#
-# Generated Wed Feb 01 11:30:10 2012 by generateDS.py version 2.7b.
-#
+# -*- coding: utf-8 -*-
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
import sys
-import getopt
-import re as re_
-
-etree_ = None
-Verbose_import_ = False
-( XMLParser_import_none, XMLParser_import_lxml,
- XMLParser_import_elementtree
- ) = range(3)
-XMLParser_import_library = None
-try:
- # lxml
- from lxml import etree as etree_
- XMLParser_import_library = XMLParser_import_lxml
- if Verbose_import_:
- print("running with lxml.etree")
-except ImportError:
- if Verbose_import_:
- print 'Error: LXML version 2.3+ required for parsing files'
-
-def parsexml_(*args, **kwargs):
- if (XMLParser_import_library == XMLParser_import_lxml and
- 'parser' not in kwargs):
- # Use the lxml ElementTree compatible parser so that, e.g.,
- # we ignore comments.
- kwargs['parser'] = etree_.ETCompatXMLParser(huge_tree=True)
- doc = etree_.parse(*args, **kwargs)
- return doc
-
-#
-# User methods
-#
-# Calls to the methods in these classes are generated by generateDS.py.
-# You can replace these methods by re-implementing the following class
-# in a module named generatedssuper.py.
-
-try:
- from generatedssuper import GeneratedsSuper
-except ImportError, exp:
-
- class GeneratedsSuper(object):
- def gds_format_string(self, input_data, input_name=''):
- return input_data
- def gds_validate_string(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer(self, input_data, input_name=''):
- return '%d' % input_data
- def gds_validate_integer(self, input_data, node, input_name=''):
- return input_data
- def gds_format_integer_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_integer_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of integers')
- return input_data
- def gds_format_float(self, input_data, input_name=''):
- return '%f' % input_data
- def gds_validate_float(self, input_data, node, input_name=''):
- return input_data
- def gds_format_float_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_float_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of floats')
- return input_data
- def gds_format_double(self, input_data, input_name=''):
- return '%e' % input_data
- def gds_validate_double(self, input_data, node, input_name=''):
- return input_data
- def gds_format_double_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_double_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- try:
- fvalue = float(value)
- except (TypeError, ValueError), exp:
- raise_parse_error(node, 'Requires sequence of doubles')
- return input_data
- def gds_format_boolean(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_boolean(self, input_data, node, input_name=''):
- return input_data
- def gds_format_boolean_list(self, input_data, input_name=''):
- return '%s' % input_data
- def gds_validate_boolean_list(self, input_data, node, input_name=''):
- values = input_data.split()
- for value in values:
- if value not in ('true', '1', 'false', '0', ):
- raise_parse_error(node, 'Requires sequence of booleans ("true", "1", "false", "0")')
- return input_data
- def gds_str_lower(self, instring):
- return instring.lower()
- def get_path_(self, node):
- path_list = []
- self.get_path_list_(node, path_list)
- path_list.reverse()
- path = '/'.join(path_list)
- return path
- Tag_strip_pattern_ = re_.compile(r'\{.*\}')
- def get_path_list_(self, node, path_list):
- if node is None:
- return
- tag = GeneratedsSuper.Tag_strip_pattern_.sub('', node.tag)
- if tag:
- path_list.append(tag)
- self.get_path_list_(node.getparent(), path_list)
- def get_class_obj_(self, node, default_class=None):
- class_obj1 = default_class
- if 'xsi' in node.nsmap:
- classname = node.get('{%s}type' % node.nsmap['xsi'])
- if classname is not None:
- names = classname.split(':')
- if len(names) == 2:
- classname = names[1]
- class_obj2 = globals().get(classname)
- if class_obj2 is not None:
- class_obj1 = class_obj2
- return class_obj1
- def gds_build_any(self, node, type_name=None):
- return None
-
-
-#
-# If you have installed IPython you can uncomment and use the following.
-# IPython is available from http://ipython.scipy.org/.
-#
-
-## from IPython.Shell import IPShellEmbed
-## args = ''
-## ipshell = IPShellEmbed(args,
-## banner = 'Dropping into IPython',
-## exit_msg = 'Leaving Interpreter, back to program.')
-
-# Then use the following line where and when you want to drop into the
-# IPython shell:
-# ipshell(' -- Entering ipshell.\nHit Ctrl-D to exit')
-
-#
-# Globals
-#
-
-ExternalEncoding = 'utf-8'
-Tag_pattern_ = re_.compile(r'({.*})?(.*)')
-String_cleanup_pat_ = re_.compile(r"[\n\r\s]+")
-Namespace_extract_pat_ = re_.compile(r'{(.*)}(.*)')
-
-#
-# Support/utility functions.
-#
-
-def showIndent(outfile, level):
- for idx in range(level):
- outfile.write(' ')
-
-def quote_xml(inStr):
- if not inStr:
- return ''
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- return unicode(s1)
-
-def quote_attrib(inStr):
- s1 = (isinstance(inStr, basestring) and inStr or
- '%s' % inStr)
- s1 = s1.replace('&', '&')
- s1 = s1.replace('<', '<')
- s1 = s1.replace('>', '>')
- if '"' in s1:
- if "'" in s1:
- s1 = '"%s"' % s1.replace('"', """)
- else:
- s1 = "'%s'" % s1
- else:
- s1 = '"%s"' % s1
- return unicode(s1)
-
-def quote_python(inStr):
- s1 = inStr
- if s1.find("'") == -1:
- if s1.find('\n') == -1:
- return "'%s'" % s1
- else:
- return "'''%s'''" % s1
- else:
- if s1.find('"') != -1:
- s1 = s1.replace('"', '\\"')
- if s1.find('\n') == -1:
- return '"%s"' % s1
- else:
- return '"""%s"""' % s1
-
-def get_all_text_(node):
- if node.text is not None:
- text = node.text
- else:
- text = ''
- for child in node:
- if child.tail is not None:
- text += child.tail
- return text
-def find_attr_value_(attr_name, node):
- attrs = node.attrib
- attr_parts = attr_name.split(':')
- value = None
- if len(attr_parts) == 1:
- value = attrs.get(attr_name)
- elif len(attr_parts) == 2:
- prefix, name = attr_parts
- namespace = node.nsmap.get(prefix)
- if namespace is not None:
- value = attrs.get('{%s}%s' % (namespace, name, ))
- return value
-
-
-class GDSParseError(Exception):
- pass
-
-def raise_parse_error(node, msg):
- if XMLParser_import_library == XMLParser_import_lxml:
- msg = '%s (element %s/line %d)' % (msg, node.tag, node.sourceline, )
- else:
- msg = '%s (element %s)' % (msg, node.tag, )
- raise GDSParseError(msg)
-
-
-class MixedContainer:
- # Constants for category:
- CategoryNone = 0
- CategoryText = 1
- CategorySimple = 2
- CategoryComplex = 3
- # Constants for content_type:
- TypeNone = 0
- TypeText = 1
- TypeString = 2
- TypeInteger = 3
- TypeFloat = 4
- TypeDecimal = 5
- TypeDouble = 6
- TypeBoolean = 7
- def __init__(self, category, content_type, name, value):
- self.category = category
- self.content_type = content_type
- self.name = name
- self.value = value
- def getCategory(self):
- return self.category
- def getContenttype(self, content_type):
- return self.content_type
- def getValue(self):
- return self.value
- def getName(self):
- return self.name
- def export(self, outfile, level, name, namespace):
- if self.category == MixedContainer.CategoryText:
- # Prevent exporting empty content as empty lines.
- if self.value.strip():
- outfile.write(self.value)
- elif self.category == MixedContainer.CategorySimple:
- self.exportSimple(outfile, level, name)
- else: # category == MixedContainer.CategoryComplex
- self.value.export(outfile, level, namespace,name)
- def exportSimple(self, outfile, level, name):
- if self.content_type == MixedContainer.TypeString:
- outfile.write('<%s>%s%s>' % (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeInteger or \
- self.content_type == MixedContainer.TypeBoolean:
- outfile.write('<%s>%d%s>' % (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeFloat or \
- self.content_type == MixedContainer.TypeDecimal:
- outfile.write('<%s>%f%s>' % (self.name, self.value, self.name))
- elif self.content_type == MixedContainer.TypeDouble:
- outfile.write('<%s>%g%s>' % (self.name, self.value, self.name))
- def exportLiteral(self, outfile, level, name):
- if self.category == MixedContainer.CategoryText:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
- (self.category, self.content_type, self.name, self.value))
- elif self.category == MixedContainer.CategorySimple:
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s", "%s"),\n' % \
- (self.category, self.content_type, self.name, self.value))
- else: # category == MixedContainer.CategoryComplex
- showIndent(outfile, level)
- outfile.write('model_.MixedContainer(%d, %d, "%s",\n' % \
- (self.category, self.content_type, self.name,))
- self.value.exportLiteral(outfile, level + 1)
- showIndent(outfile, level)
- outfile.write(')\n')
-
-
-class MemberSpec_(object):
- def __init__(self, name='', data_type='', container=0):
- self.name = name
- self.data_type = data_type
- self.container = container
- def set_name(self, name): self.name = name
- def get_name(self): return self.name
- def set_data_type(self, data_type): self.data_type = data_type
- def get_data_type_chain(self): return self.data_type
- def get_data_type(self):
- if isinstance(self.data_type, list):
- if len(self.data_type) > 0:
- return self.data_type[-1]
- else:
- return 'xs:string'
- else:
- return self.data_type
- def set_container(self, container): self.container = container
- def get_container(self): return self.container
-
-def _cast(typ, value):
- if typ is None or value is None:
- return value
- return typ(value)
-
-#
-# Data representation classes.
-#
+from mixbox.binding_utils import *
class malwareMetaData(GeneratedsSuper):
"""This is the top level element for the xml document. Required
@@ -457,46 +125,46 @@ def get_version(self): return self.version
def set_version(self, version): self.version = version
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='malwareMetaData', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='malwareMetaData', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='malwareMetaData')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='malwareMetaData')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='malwareMetaData'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='malwareMetaData'):
if self.version is not None and 'version' not in already_processed:
already_processed.append('version')
- outfile.write(' version="%s"' % self.gds_format_float(self.version, input_name='version'))
+ write(' version="%s"' % self.gds_format_float(self.version, input_name='version'))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='malwareMetaData', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='malwareMetaData', fromsubclass_=False):
if self.company is not None:
- showIndent(outfile, level)
- outfile.write('<%scompany>%s%scompany>\n' % (namespace_, self.gds_format_string(quote_xml(self.company).encode(ExternalEncoding), input_name='company'), namespace_))
+ showIndent(write, level)
+ write('<%scompany>%s%scompany>\n' % (namespace_, quote_xml(self.company), namespace_))
if self.author is not None:
- showIndent(outfile, level)
- outfile.write('<%sauthor>%s%sauthor>\n' % (namespace_, self.gds_format_string(quote_xml(self.author).encode(ExternalEncoding), input_name='author'), namespace_))
+ showIndent(write, level)
+ write('<%sauthor>%s%sauthor>\n' % (namespace_, quote_xml(self.author), namespace_))
if self.comment is not None:
- showIndent(outfile, level)
- outfile.write('<%scomment>%s%scomment>\n' % (namespace_, self.gds_format_string(quote_xml(self.comment).encode(ExternalEncoding), input_name='comment'), namespace_))
+ showIndent(write, level)
+ write('<%scomment>%s%scomment>\n' % (namespace_, quote_xml(self.comment), namespace_))
if self.timestamp is not None:
- showIndent(outfile, level)
- outfile.write('<%stimestamp>%s%stimestamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.timestamp).encode(ExternalEncoding), input_name='timestamp'), namespace_))
+ showIndent(write, level)
+ write('<%stimestamp>%s%stimestamp>\n' % (namespace_, quote_xml(self.timestamp), namespace_))
if self.objects is not None:
- self.objects.export(outfile, level, namespace_, name_='objects')
+ self.objects.export(write, level, namespace_, name_='objects')
if self.objectProperties is not None:
- self.objectProperties.export(outfile, level, namespace_, name_='objectProperties')
+ self.objectProperties.export(write, level, namespace_, name_='objectProperties')
if self.relationships is not None:
- self.relationships.export(outfile, level, namespace_, name_='relationships')
+ self.relationships.export(write, level, namespace_, name_='relationships')
if self.fieldData is not None:
- self.fieldData.export(outfile, level, namespace_, name_='fieldData')
+ self.fieldData.export(write, level, namespace_, name_='fieldData')
def hasContent_(self):
if (
self.company is not None or
@@ -511,58 +179,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='malwareMetaData'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.version is not None and 'version' not in already_processed:
- already_processed.append('version')
- showIndent(outfile, level)
- outfile.write('version = %f,\n' % (self.version,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.company is not None:
- showIndent(outfile, level)
- outfile.write('company=%s,\n' % quote_python(self.company).encode(ExternalEncoding))
- if self.author is not None:
- showIndent(outfile, level)
- outfile.write('author=%s,\n' % quote_python(self.author).encode(ExternalEncoding))
- if self.comment is not None:
- showIndent(outfile, level)
- outfile.write('comment=%s,\n' % quote_python(self.comment).encode(ExternalEncoding))
- if self.timestamp is not None:
- showIndent(outfile, level)
- outfile.write('timestamp=%s,\n' % quote_python(self.timestamp).encode(ExternalEncoding))
- if self.objects is not None:
- showIndent(outfile, level)
- outfile.write('objects=model_.objects(\n')
- self.objects.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.objectProperties is not None:
- showIndent(outfile, level)
- outfile.write('objectProperties=model_.objectProperties(\n')
- self.objectProperties.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.relationships is not None:
- showIndent(outfile, level)
- outfile.write('relationships=model_.relationships(\n')
- self.relationships.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.fieldData is not None:
- showIndent(outfile, level)
- outfile.write('fieldData=model_.fieldData(\n')
- self.fieldData.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -573,7 +191,7 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.append('version')
try:
self.version = float(value)
- except ValueError, exp:
+ except ValueError as exp:
raise ValueError('Bad float/double attribute (version): %s' % exp)
value = find_attr_value_('id', node)
if value is not None and 'id' not in already_processed:
@@ -721,43 +339,43 @@ def get_taggant(self): return self.taggant
def set_taggant(self, taggant): self.taggant = taggant
def add_taggant(self, value): self.taggant.append(value)
def insert_taggant(self, index, value): self.taggant[index] = value
- def export(self, outfile, level, namespace_='', name_='objects', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='objects', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='objects')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='objects')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='objects'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='objects'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='objects', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='objects', fromsubclass_=False):
for file_ in self.file:
- file_.export(outfile, level, namespace_, name_='file')
+ file_.export(write, level, namespace_, name_='file')
for uri_ in self.uri:
- uri_.export(outfile, level, namespace_, name_='uri')
+ uri_.export(write, level, namespace_, name_='uri')
for domain_ in self.domain:
- domain_.export(outfile, level, namespace_, name_='domain')
+ domain_.export(write, level, namespace_, name_='domain')
for registry_ in self.registry:
- registry_.export(outfile, level, namespace_, name_='registry')
+ registry_.export(write, level, namespace_, name_='registry')
for ip_ in self.ip:
- ip_.export(outfile, level, namespace_, name_='ip')
+ ip_.export(write, level, namespace_, name_='ip')
for asn_ in self.asn:
- asn_.export(outfile, level, namespace_, name_='asn')
+ asn_.export(write, level, namespace_, name_='asn')
for entity_ in self.entity:
- entity_.export(outfile, level, namespace_, name_='entity')
+ entity_.export(write, level, namespace_, name_='entity')
for classification_ in self.classification:
- classification_.export(outfile, level, namespace_, name_='classification')
+ classification_.export(write, level, namespace_, name_='classification')
for softwarePackage_ in self.softwarePackage:
- softwarePackage_.export(outfile, level, namespace_, name_='softwarePackage')
+ softwarePackage_.export(write, level, namespace_, name_='softwarePackage')
for digitalSignature_ in self.digitalSignature:
- digitalSignature_.export(outfile, level, namespace_, name_='digitalSignature')
+ digitalSignature_.export(write, level, namespace_, name_='digitalSignature')
for taggant_ in self.taggant:
- taggant_.export(outfile, level, namespace_, name_='taggant')
+ taggant_.export(write, level, namespace_, name_='taggant')
def hasContent_(self):
if (
self.file or
@@ -775,147 +393,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='objects'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('file=[\n')
- level += 1
- for file_ in self.file:
- showIndent(outfile, level)
- outfile.write('model_.fileObject(\n')
- file_.exportLiteral(outfile, level, name_='fileObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('uri=[\n')
- level += 1
- for uri_ in self.uri:
- showIndent(outfile, level)
- outfile.write('model_.uriObject(\n')
- uri_.exportLiteral(outfile, level, name_='uriObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('domain=[\n')
- level += 1
- for domain_ in self.domain:
- showIndent(outfile, level)
- outfile.write('model_.domainObject(\n')
- domain_.exportLiteral(outfile, level, name_='domainObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('registry=[\n')
- level += 1
- for registry_ in self.registry:
- showIndent(outfile, level)
- outfile.write('model_.registryObject(\n')
- registry_.exportLiteral(outfile, level, name_='registryObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('ip=[\n')
- level += 1
- for ip_ in self.ip:
- showIndent(outfile, level)
- outfile.write('model_.IPObject(\n')
- ip_.exportLiteral(outfile, level, name_='IPObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('asn=[\n')
- level += 1
- for asn_ in self.asn:
- showIndent(outfile, level)
- outfile.write('model_.ASNObject(\n')
- asn_.exportLiteral(outfile, level, name_='ASNObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('entity=[\n')
- level += 1
- for entity_ in self.entity:
- showIndent(outfile, level)
- outfile.write('model_.entityObject(\n')
- entity_.exportLiteral(outfile, level, name_='entityObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('classification=[\n')
- level += 1
- for classification_ in self.classification:
- showIndent(outfile, level)
- outfile.write('model_.classificationObject(\n')
- classification_.exportLiteral(outfile, level, name_='classificationObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('softwarePackage=[\n')
- level += 1
- for softwarePackage_ in self.softwarePackage:
- showIndent(outfile, level)
- outfile.write('model_.softwarePackageObject(\n')
- softwarePackage_.exportLiteral(outfile, level, name_='softwarePackageObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('digitalSignature=[\n')
- level += 1
- for digitalSignature_ in self.digitalSignature:
- showIndent(outfile, level)
- outfile.write('model_.digitalSignatureObject(\n')
- digitalSignature_.exportLiteral(outfile, level, name_='digitalSignatureObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('taggant=[\n')
- level += 1
- for taggant_ in self.taggant:
- showIndent(outfile, level)
- outfile.write('model_.taggantObject(\n')
- taggant_.exportLiteral(outfile, level, name_='taggantObject')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -990,23 +469,23 @@ def get_objectProperty(self): return self.objectProperty
def set_objectProperty(self, objectProperty): self.objectProperty = objectProperty
def add_objectProperty(self, value): self.objectProperty.append(value)
def insert_objectProperty(self, index, value): self.objectProperty[index] = value
- def export(self, outfile, level, namespace_='', name_='objectProperties', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='objectProperties', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='objectProperties')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='objectProperties')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='objectProperties'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='objectProperties'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='objectProperties', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='objectProperties', fromsubclass_=False):
for objectProperty_ in self.objectProperty:
- objectProperty_.export(outfile, level, namespace_, name_='objectProperty')
+ objectProperty_.export(write, level, namespace_, name_='objectProperty')
def hasContent_(self):
if (
self.objectProperty
@@ -1014,27 +493,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='objectProperties'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('objectProperty=[\n')
- level += 1
- for objectProperty_ in self.objectProperty:
- showIndent(outfile, level)
- outfile.write('model_.objectProperty(\n')
- objectProperty_.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -1068,23 +528,23 @@ def get_relationship(self): return self.relationship
def set_relationship(self, relationship): self.relationship = relationship
def add_relationship(self, value): self.relationship.append(value)
def insert_relationship(self, index, value): self.relationship[index] = value
- def export(self, outfile, level, namespace_='', name_='relationships', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='relationships', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='relationships')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='relationships')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='relationships'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='relationships'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='relationships', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='relationships', fromsubclass_=False):
for relationship_ in self.relationship:
- relationship_.export(outfile, level, namespace_, name_='relationship')
+ relationship_.export(write, level, namespace_, name_='relationship')
def hasContent_(self):
if (
self.relationship
@@ -1092,27 +552,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='relationships'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('relationship=[\n')
- level += 1
- for relationship_ in self.relationship:
- showIndent(outfile, level)
- outfile.write('model_.relationship(\n')
- relationship_.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -1146,23 +587,23 @@ def get_fieldDataEntry(self): return self.fieldDataEntry
def set_fieldDataEntry(self, fieldDataEntry): self.fieldDataEntry = fieldDataEntry
def add_fieldDataEntry(self, value): self.fieldDataEntry.append(value)
def insert_fieldDataEntry(self, index, value): self.fieldDataEntry[index] = value
- def export(self, outfile, level, namespace_='', name_='fieldData', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='fieldData', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='fieldData')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='fieldData')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='fieldData'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='fieldData'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='fieldData', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='fieldData', fromsubclass_=False):
for fieldDataEntry_ in self.fieldDataEntry:
- fieldDataEntry_.export(outfile, level, namespace_, name_='fieldDataEntry')
+ fieldDataEntry_.export(write, level, namespace_, name_='fieldDataEntry')
def hasContent_(self):
if (
self.fieldDataEntry
@@ -1170,27 +611,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='fieldData'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('fieldDataEntry=[\n')
- level += 1
- for fieldDataEntry_ in self.fieldDataEntry:
- showIndent(outfile, level)
- outfile.write('model_.fieldDataEntry(\n')
- fieldDataEntry_.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -1354,105 +776,105 @@ def get_taggant(self): return self.taggant
def set_taggant(self, taggant): self.taggant = taggant
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='fileObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='fileObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='fileObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='fileObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='fileObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='fileObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='', name_='fileObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='', name_='fileObject', fromsubclass_=False):
if self.md5 is not None:
- self.md5.export(outfile, level, namespace_, name_='md5', )
+ self.md5.export(write, level, namespace_, name_='md5', )
if self.sha1 is not None:
- self.sha1.export(outfile, level, namespace_, name_='sha1')
+ self.sha1.export(write, level, namespace_, name_='sha1')
if self.sha256 is not None:
- self.sha256.export(outfile, level, namespace_, name_='sha256')
+ self.sha256.export(write, level, namespace_, name_='sha256')
if self.sha512 is not None:
- self.sha512.export(outfile, level, namespace_, name_='sha512')
+ self.sha512.export(write, level, namespace_, name_='sha512')
if self.size is not None:
- showIndent(outfile, level)
- outfile.write('<%ssize>%s%ssize>\n' % (namespace_, self.gds_format_integer(self.size, input_name='size'), namespace_))
+ showIndent(write, level)
+ write('<%ssize>%s%ssize>\n' % (namespace_, self.gds_format_integer(self.size, input_name='size'), namespace_))
if self.crc32 is not None:
- showIndent(outfile, level)
- outfile.write('<%scrc32>%s%scrc32>\n' % (namespace_, self.gds_format_string(quote_xml(self.crc32).encode(ExternalEncoding), input_name='crc32'), namespace_))
+ showIndent(write, level)
+ write('<%scrc32>%s%scrc32>\n' % (namespace_, quote_xml(self.crc32), namespace_))
for fileType_ in self.fileType:
- showIndent(outfile, level)
- outfile.write('<%sfileType>%s%sfileType>\n' % (namespace_, self.gds_format_string(quote_xml(fileType_).encode(ExternalEncoding), input_name='fileType'), namespace_))
+ showIndent(write, level)
+ write('<%sfileType>%s%sfileType>\n' % (namespace_, quote_xml(fileType_), namespace_))
for extraHash_ in self.extraHash:
- extraHash_.export(outfile, level, namespace_, name_='extraHash')
+ extraHash_.export(write, level, namespace_, name_='extraHash')
for filename_ in self.filename:
- showIndent(outfile, level)
- outfile.write('<%sfilename>%s%sfilename>\n' % (namespace_, self.gds_format_string(quote_xml(filename_).encode(ExternalEncoding), input_name='filename'), namespace_))
+ showIndent(write, level)
+ write('<%sfilename>%s%sfilename>\n' % (namespace_, quote_xml(filename_), namespace_))
for normalizedNativePath_ in self.normalizedNativePath:
- showIndent(outfile, level)
- outfile.write('<%snormalizedNativePath>%s%snormalizedNativePath>\n' % (namespace_, self.gds_format_string(quote_xml(normalizedNativePath_).encode(ExternalEncoding), input_name='normalizedNativePath'), namespace_))
+ showIndent(write, level)
+ write('<%snormalizedNativePath>%s%snormalizedNativePath>\n' % (namespace_, quote_xml(normalizedNativePath_), namespace_))
for filenameWithinInstaller_ in self.filenameWithinInstaller:
- showIndent(outfile, level)
- outfile.write('<%sfilenameWithinInstaller>%s%sfilenameWithinInstaller>\n' % (namespace_, self.gds_format_string(quote_xml(filenameWithinInstaller_).encode(ExternalEncoding), input_name='filenameWithinInstaller'), namespace_))
+ showIndent(write, level)
+ write('<%sfilenameWithinInstaller>%s%sfilenameWithinInstaller>\n' % (namespace_, quote_xml(filenameWithinInstaller_), namespace_))
for folderWithinInstaller_ in self.folderWithinInstaller:
- showIndent(outfile, level)
- outfile.write('<%sfolderWithinInstaller>%s%sfolderWithinInstaller>\n' % (namespace_, self.gds_format_string(quote_xml(folderWithinInstaller_).encode(ExternalEncoding), input_name='folderWithinInstaller'), namespace_))
+ showIndent(write, level)
+ write('<%sfolderWithinInstaller>%s%sfolderWithinInstaller>\n' % (namespace_, quote_xml(folderWithinInstaller_), namespace_))
if self.vendor is not None:
- showIndent(outfile, level)
- outfile.write('<%svendor>%s%svendor>\n' % (namespace_, self.gds_format_string(quote_xml(self.vendor).encode(ExternalEncoding), input_name='vendor'), namespace_))
+ showIndent(write, level)
+ write('<%svendor>%s%svendor>\n' % (namespace_, quote_xml(self.vendor), namespace_))
for internalName_ in self.internalName:
- showIndent(outfile, level)
- outfile.write('<%sinternalName>%s%sinternalName>\n' % (namespace_, self.gds_format_string(quote_xml(internalName_).encode(ExternalEncoding), input_name='internalName'), namespace_))
+ showIndent(write, level)
+ write('<%sinternalName>%s%sinternalName>\n' % (namespace_, quote_xml(internalName_), namespace_))
for language_ in self.language:
- showIndent(outfile, level)
- outfile.write('<%slanguage>%s%slanguage>\n' % (namespace_, self.gds_format_string(quote_xml(language_).encode(ExternalEncoding), input_name='language'), namespace_))
+ showIndent(write, level)
+ write('<%slanguage>%s%slanguage>\n' % (namespace_, quote_xml(language_), namespace_))
if self.productName is not None:
- showIndent(outfile, level)
- outfile.write('<%sproductName>%s%sproductName>\n' % (namespace_, self.gds_format_string(quote_xml(self.productName).encode(ExternalEncoding), input_name='productName'), namespace_))
+ showIndent(write, level)
+ write('<%sproductName>%s%sproductName>\n' % (namespace_, quote_xml(self.productName), namespace_))
if self.fileVersion is not None:
- showIndent(outfile, level)
- outfile.write('<%sfileVersion>%s%sfileVersion>\n' % (namespace_, self.gds_format_string(quote_xml(self.fileVersion).encode(ExternalEncoding), input_name='fileVersion'), namespace_))
+ showIndent(write, level)
+ write('<%sfileVersion>%s%sfileVersion>\n' % (namespace_, quote_xml(self.fileVersion), namespace_))
if self.productVersion is not None:
- showIndent(outfile, level)
- outfile.write('<%sproductVersion>%s%sproductVersion>\n' % (namespace_, self.gds_format_string(quote_xml(self.productVersion).encode(ExternalEncoding), input_name='productVersion'), namespace_))
+ showIndent(write, level)
+ write('<%sproductVersion>%s%sproductVersion>\n' % (namespace_, quote_xml(self.productVersion), namespace_))
if self.developmentEnvironment is not None:
- showIndent(outfile, level)
- outfile.write('<%sdevelopmentEnvironment>%s%sdevelopmentEnvironment>\n' % (namespace_, self.gds_format_string(quote_xml(self.developmentEnvironment).encode(ExternalEncoding), input_name='developmentEnvironment'), namespace_))
+ showIndent(write, level)
+ write('<%sdevelopmentEnvironment>%s%sdevelopmentEnvironment>\n' % (namespace_, quote_xml(self.developmentEnvironment), namespace_))
if self.checksum is not None:
- self.checksum.export(outfile, level, namespace_, name_='checksum')
+ self.checksum.export(write, level, namespace_, name_='checksum')
if self.architecture is not None:
- showIndent(outfile, level)
- outfile.write('<%sarchitecture>%s%sarchitecture>\n' % (namespace_, self.gds_format_string(quote_xml(self.architecture).encode(ExternalEncoding), input_name='architecture'), namespace_))
+ showIndent(write, level)
+ write('<%sarchitecture>%s%sarchitecture>\n' % (namespace_, quote_xml(self.architecture), namespace_))
if self.buildTimeDateStamp is not None:
- showIndent(outfile, level)
- outfile.write('<%sbuildTimeDateStamp>%s%sbuildTimeDateStamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.buildTimeDateStamp).encode(ExternalEncoding), input_name='buildTimeDateStamp'), namespace_))
+ showIndent(write, level)
+ write('<%sbuildTimeDateStamp>%s%sbuildTimeDateStamp>\n' % (namespace_, quote_xml(self.buildTimeDateStamp), namespace_))
if self.compilerVersion is not None:
- showIndent(outfile, level)
- outfile.write('<%scompilerVersion>%s%scompilerVersion>\n' % (namespace_, self.gds_format_string(quote_xml(self.compilerVersion).encode(ExternalEncoding), input_name='compilerVersion'), namespace_))
+ showIndent(write, level)
+ write('<%scompilerVersion>%s%scompilerVersion>\n' % (namespace_, quote_xml(self.compilerVersion), namespace_))
if self.linkerVersion is not None:
- showIndent(outfile, level)
- outfile.write('<%slinkerVersion>%s%slinkerVersion>\n' % (namespace_, self.gds_format_float(self.linkerVersion, input_name='linkerVersion'), namespace_))
+ showIndent(write, level)
+ write('<%slinkerVersion>%s%slinkerVersion>\n' % (namespace_, self.gds_format_float(self.linkerVersion, input_name='linkerVersion'), namespace_))
if self.minOSVersionCPE is not None:
- showIndent(outfile, level)
- outfile.write('<%sminOSVersionCPE>%s%sminOSVersionCPE>\n' % (namespace_, self.gds_format_string(quote_xml(self.minOSVersionCPE).encode(ExternalEncoding), input_name='minOSVersionCPE'), namespace_))
+ showIndent(write, level)
+ write('<%sminOSVersionCPE>%s%sminOSVersionCPE>\n' % (namespace_, quote_xml(self.minOSVersionCPE), namespace_))
if self.numberOfSections is not None:
- showIndent(outfile, level)
- outfile.write('<%snumberOfSections>%s%snumberOfSections>\n' % (namespace_, self.gds_format_integer(self.numberOfSections, input_name='numberOfSections'), namespace_))
+ showIndent(write, level)
+ write('<%snumberOfSections>%s%snumberOfSections>\n' % (namespace_, self.gds_format_integer(self.numberOfSections, input_name='numberOfSections'), namespace_))
if self.MIMEType is not None:
- showIndent(outfile, level)
- outfile.write('<%sMIMEType>%s%sMIMEType>\n' % (namespace_, self.gds_format_string(quote_xml(self.MIMEType).encode(ExternalEncoding), input_name='MIMEType'), namespace_))
+ showIndent(write, level)
+ write('<%sMIMEType>%s%sMIMEType>\n' % (namespace_, quote_xml(self.MIMEType), namespace_))
if self.requiredPrivilege is not None:
- showIndent(outfile, level)
- outfile.write('<%srequiredPrivilege>%s%srequiredPrivilege>\n' % (namespace_, self.gds_format_string(quote_xml(self.requiredPrivilege).encode(ExternalEncoding), input_name='requiredPrivilege'), namespace_))
+ showIndent(write, level)
+ write('<%srequiredPrivilege>%s%srequiredPrivilege>\n' % (namespace_, quote_xml(self.requiredPrivilege), namespace_))
if self.digitalSignature is not None:
- self.digitalSignature.export(outfile, level, namespace_, name_='digitalSignature')
+ self.digitalSignature.export(write, level, namespace_, name_='digitalSignature')
if self.taggant is not None:
- self.taggant.export(outfile, level, namespace_, name_='taggant')
+ self.taggant.export(write, level, namespace_, name_='taggant')
def hasContent_(self):
if (
self.md5 is not None or
@@ -1489,180 +911,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='fileObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.md5 is not None:
- showIndent(outfile, level)
- outfile.write('md5=model_.xs_hexBinary(\n')
- self.md5.exportLiteral(outfile, level, name_='md5')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.sha1 is not None:
- showIndent(outfile, level)
- outfile.write('sha1=model_.xs_hexBinary(\n')
- self.sha1.exportLiteral(outfile, level, name_='sha1')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.sha256 is not None:
- showIndent(outfile, level)
- outfile.write('sha256=model_.xs_hexBinary(\n')
- self.sha256.exportLiteral(outfile, level, name_='sha256')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.sha512 is not None:
- showIndent(outfile, level)
- outfile.write('sha512=model_.xs_hexBinary(\n')
- self.sha512.exportLiteral(outfile, level, name_='sha512')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.size is not None:
- showIndent(outfile, level)
- outfile.write('size=%d,\n' % self.size)
- if self.crc32 is not None:
- showIndent(outfile, level)
- outfile.write('crc32=%s,\n' % quote_python(self.crc32).encode(ExternalEncoding))
- showIndent(outfile, level)
- outfile.write('fileType=[\n')
- level += 1
- for fileType_ in self.fileType:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(fileType_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('extraHash=[\n')
- level += 1
- for extraHash_ in self.extraHash:
- showIndent(outfile, level)
- outfile.write('model_.extraHash(\n')
- extraHash_.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('filename=[\n')
- level += 1
- for filename_ in self.filename:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(filename_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('normalizedNativePath=[\n')
- level += 1
- for normalizedNativePath_ in self.normalizedNativePath:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(normalizedNativePath_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('filenameWithinInstaller=[\n')
- level += 1
- for filenameWithinInstaller_ in self.filenameWithinInstaller:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(filenameWithinInstaller_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('folderWithinInstaller=[\n')
- level += 1
- for folderWithinInstaller_ in self.folderWithinInstaller:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(folderWithinInstaller_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- if self.vendor is not None:
- showIndent(outfile, level)
- outfile.write('vendor=%s,\n' % quote_python(self.vendor).encode(ExternalEncoding))
- showIndent(outfile, level)
- outfile.write('internalName=[\n')
- level += 1
- for internalName_ in self.internalName:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(internalName_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- showIndent(outfile, level)
- outfile.write('language=[\n')
- level += 1
- for language_ in self.language:
- showIndent(outfile, level)
- outfile.write('%s,\n' % quote_python(language_).encode(ExternalEncoding))
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- if self.productName is not None:
- showIndent(outfile, level)
- outfile.write('productName=%s,\n' % quote_python(self.productName).encode(ExternalEncoding))
- if self.fileVersion is not None:
- showIndent(outfile, level)
- outfile.write('fileVersion=%s,\n' % quote_python(self.fileVersion).encode(ExternalEncoding))
- if self.productVersion is not None:
- showIndent(outfile, level)
- outfile.write('productVersion=%s,\n' % quote_python(self.productVersion).encode(ExternalEncoding))
- if self.developmentEnvironment is not None:
- showIndent(outfile, level)
- outfile.write('developmentEnvironment=%s,\n' % quote_python(self.developmentEnvironment).encode(ExternalEncoding))
- if self.checksum is not None:
- showIndent(outfile, level)
- outfile.write('checksum=model_.xs_hexBinary(\n')
- self.checksum.exportLiteral(outfile, level, name_='checksum')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.architecture is not None:
- showIndent(outfile, level)
- outfile.write('architecture=%s,\n' % quote_python(self.architecture).encode(ExternalEncoding))
- if self.buildTimeDateStamp is not None:
- showIndent(outfile, level)
- outfile.write('buildTimeDateStamp=%s,\n' % quote_python(self.buildTimeDateStamp).encode(ExternalEncoding))
- if self.compilerVersion is not None:
- showIndent(outfile, level)
- outfile.write('compilerVersion=%s,\n' % quote_python(self.compilerVersion).encode(ExternalEncoding))
- if self.linkerVersion is not None:
- showIndent(outfile, level)
- outfile.write('linkerVersion=%f,\n' % self.linkerVersion)
- if self.minOSVersionCPE is not None:
- showIndent(outfile, level)
- outfile.write('minOSVersionCPE=%s,\n' % quote_python(self.minOSVersionCPE).encode(ExternalEncoding))
- if self.numberOfSections is not None:
- showIndent(outfile, level)
- outfile.write('numberOfSections=%d,\n' % self.numberOfSections)
- if self.MIMEType is not None:
- showIndent(outfile, level)
- outfile.write('MIMEType=%s,\n' % quote_python(self.MIMEType).encode(ExternalEncoding))
- if self.requiredPrivilege is not None:
- showIndent(outfile, level)
- outfile.write('requiredPrivilege=%s,\n' % quote_python(self.requiredPrivilege).encode(ExternalEncoding))
- if self.digitalSignature is not None:
- showIndent(outfile, level)
- outfile.write('digitalSignature=model_.digitalSignatureObject(\n')
- self.digitalSignature.exportLiteral(outfile, level, name_='digitalSignature')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.taggant is not None:
- showIndent(outfile, level)
- outfile.write('taggant=model_.taggantObject(\n')
- self.taggant.exportLiteral(outfile, level, name_='taggant')
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -1693,7 +943,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'size')
self.size = ival_
@@ -1773,7 +1023,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
fval_ = float(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires float or double: %s' % exp)
fval_ = self.gds_validate_float(fval_, node, 'linkerVersion')
self.linkerVersion = fval_
@@ -1785,7 +1035,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'numberOfSections')
self.numberOfSections = ival_
@@ -1827,23 +1077,23 @@ def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='extraHash', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='extraHash', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='extraHash')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='extraHash')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='extraHash'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='extraHash'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='extraHash', fromsubclass_=False):
+ write(' type=%s' % (quote_attrib(self.type_)))
+ def exportChildren(self, write, level, namespace_='', name_='extraHash', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -1852,21 +1102,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='extraHash'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -1907,29 +1144,29 @@ def get_valueName(self): return self.valueName
def set_valueName(self, valueName): self.valueName = valueName
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='registryObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='registryObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='registryObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='registryObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='registryObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='registryObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='registryObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='registryObject', fromsubclass_=False):
if self.key is not None:
- showIndent(outfile, level)
- outfile.write('<%skey>%s%skey>\n' % (namespace_, self.gds_format_string(quote_xml(self.key).encode(ExternalEncoding), input_name='key'), namespace_))
+ showIndent(write, level)
+ write('<%skey>%s%skey>\n' % (namespace_, quote_xml(self.key), namespace_))
if self.valueName is not None:
- showIndent(outfile, level)
- outfile.write('<%svalueName>%s%svalueName>\n' % (namespace_, self.gds_format_string(quote_xml(self.valueName).encode(ExternalEncoding), input_name='valueName'), namespace_))
+ showIndent(write, level)
+ write('<%svalueName>%s%svalueName>\n' % (namespace_, quote_xml(self.valueName), namespace_))
def hasContent_(self):
if (
self.key is not None or
@@ -1938,24 +1175,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='registryObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.key is not None:
- showIndent(outfile, level)
- outfile.write('key=%s,\n' % quote_python(self.key).encode(ExternalEncoding))
- if self.valueName is not None:
- showIndent(outfile, level)
- outfile.write('valueName=%s,\n' % quote_python(self.valueName).encode(ExternalEncoding))
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -1998,26 +1219,26 @@ def get_name(self): return self.name
def set_name(self, name): self.name = name
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='entityObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='entityObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='entityObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='entityObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='entityObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='entityObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='entityObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='entityObject', fromsubclass_=False):
if self.name is not None:
- showIndent(outfile, level)
- outfile.write('<%sname>%s%sname>\n' % (namespace_, self.gds_format_string(quote_xml(self.name).encode(ExternalEncoding), input_name='name'), namespace_))
+ showIndent(write, level)
+ write('<%sname>%s%sname>\n' % (namespace_, quote_xml(self.name), namespace_))
def hasContent_(self):
if (
self.name is not None
@@ -2025,21 +1246,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='entityObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.name is not None:
- showIndent(outfile, level)
- outfile.write('name=%s,\n' % quote_python(self.name).encode(ExternalEncoding))
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2103,44 +1311,44 @@ def get_ipProtocol(self): return self.ipProtocol
def set_ipProtocol(self, ipProtocol): self.ipProtocol = ipProtocol
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='uriObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='uriObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='uriObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='uriObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='uriObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='uriObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='', name_='uriObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='', name_='uriObject', fromsubclass_=False):
if self.uriString is not None:
- showIndent(outfile, level)
- outfile.write('<%suriString>%s%suriString>\n' % (namespace_, self.gds_format_string(quote_xml(self.uriString).encode(ExternalEncoding), input_name='uriString'), namespace_))
+ showIndent(write, level)
+ write('<%suriString>%s%suriString>\n' % (namespace_, quote_xml(self.uriString), namespace_))
if self.protocol is not None:
- showIndent(outfile, level)
- outfile.write('<%sprotocol>%s%sprotocol>\n' % (namespace_, self.gds_format_string(quote_xml(self.protocol).encode(ExternalEncoding), input_name='protocol'), namespace_))
+ showIndent(write, level)
+ write('<%sprotocol>%s%sprotocol>\n' % (namespace_, quote_xml(self.protocol), namespace_))
if self.hostname is not None:
- showIndent(outfile, level)
- outfile.write('<%shostname>%s%shostname>\n' % (namespace_, self.gds_format_string(quote_xml(self.hostname).encode(ExternalEncoding), input_name='hostname'), namespace_))
+ showIndent(write, level)
+ write('<%shostname>%s%shostname>\n' % (namespace_, quote_xml(self.hostname), namespace_))
if self.domain is not None:
- showIndent(outfile, level)
- outfile.write('<%sdomain>%s%sdomain>\n' % (namespace_, self.gds_format_string(quote_xml(self.domain).encode(ExternalEncoding), input_name='domain'), namespace_))
+ showIndent(write, level)
+ write('<%sdomain>%s%sdomain>\n' % (namespace_, quote_xml(self.domain), namespace_))
if self.port is not None:
- showIndent(outfile, level)
- outfile.write('<%sport>%s%sport>\n' % (namespace_, self.gds_format_integer(self.port, input_name='port'), namespace_))
+ showIndent(write, level)
+ write('<%sport>%s%sport>\n' % (namespace_, self.gds_format_integer(self.port, input_name='port'), namespace_))
if self.path is not None:
- showIndent(outfile, level)
- outfile.write('<%spath>%s%spath>\n' % (namespace_, self.gds_format_string(quote_xml(self.path).encode(ExternalEncoding), input_name='path'), namespace_))
+ showIndent(write, level)
+ write('<%spath>%s%spath>\n' % (namespace_, quote_xml(self.path), namespace_))
if self.ipProtocol is not None:
- showIndent(outfile, level)
- outfile.write('<%sipProtocol>%s%sipProtocol>\n' % (namespace_, self.gds_format_string(quote_xml(self.ipProtocol).encode(ExternalEncoding), input_name='ipProtocol'), namespace_))
+ showIndent(write, level)
+ write('<%sipProtocol>%s%sipProtocol>\n' % (namespace_, quote_xml(self.ipProtocol), namespace_))
def hasContent_(self):
if (
self.uriString is not None or
@@ -2154,39 +1362,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='uriObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.uriString is not None:
- showIndent(outfile, level)
- outfile.write('uriString=%s,\n' % quote_python(self.uriString).encode(ExternalEncoding))
- if self.protocol is not None:
- showIndent(outfile, level)
- outfile.write('protocol=%s,\n' % quote_python(self.protocol).encode(ExternalEncoding))
- if self.hostname is not None:
- showIndent(outfile, level)
- outfile.write('hostname=%s,\n' % quote_python(self.hostname).encode(ExternalEncoding))
- if self.domain is not None:
- showIndent(outfile, level)
- outfile.write('domain=%s,\n' % quote_python(self.domain).encode(ExternalEncoding))
- if self.port is not None:
- showIndent(outfile, level)
- outfile.write('port=%d,\n' % self.port)
- if self.path is not None:
- showIndent(outfile, level)
- outfile.write('path=%s,\n' % quote_python(self.path).encode(ExternalEncoding))
- if self.ipProtocol is not None:
- showIndent(outfile, level)
- outfile.write('ipProtocol=%s,\n' % quote_python(self.ipProtocol).encode(ExternalEncoding))
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2219,7 +1396,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'port')
self.port = ival_
@@ -2262,27 +1439,27 @@ def set_id(self, id): self.id = id
def validate_IPRange(self, value):
# Validate type IPRange, a restriction on xs:string.
pass
- def export(self, outfile, level, namespace_='', name_='IPObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='IPObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='IPObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='IPObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='IPObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='IPObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='', name_='IPObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='', name_='IPObject', fromsubclass_=False):
if self.startAddress is not None:
- self.startAddress.export(outfile, level, namespace_, name_='startAddress', )
+ self.startAddress.export(write, level, namespace_, name_='startAddress', )
if self.endAddress is not None:
- self.endAddress.export(outfile, level, namespace_, name_='endAddress', )
+ self.endAddress.export(write, level, namespace_, name_='endAddress', )
def hasContent_(self):
if (
self.startAddress is not None or
@@ -2291,30 +1468,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='IPObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.startAddress is not None:
- showIndent(outfile, level)
- outfile.write('startAddress=model_.IPAddress(\n')
- self.startAddress.exportLiteral(outfile, level, name_='startAddress')
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.endAddress is not None:
- showIndent(outfile, level)
- outfile.write('endAddress=model_.IPAddress(\n')
- self.endAddress.exportLiteral(outfile, level, name_='endAddress')
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2358,23 +1513,23 @@ def validate_IPTypeEnum(self, value):
pass
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='IPAddress', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='IPAddress', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='IPAddress')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='IPAddress')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='IPAddress'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='IPAddress'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
- def exportChildren(self, outfile, level, namespace_='', name_='IPAddress', fromsubclass_=False):
+ write(' type=%s' % (quote_attrib(self.type_), ))
+ def exportChildren(self, write, level, namespace_='', name_='IPAddress', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -2383,21 +1538,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='IPAddress'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -2433,26 +1575,26 @@ def get_domain(self): return self.domain
def set_domain(self, domain): self.domain = domain
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='domainObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='domainObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='domainObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='domainObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='domainObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='domainObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='domainObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='domainObject', fromsubclass_=False):
if self.domain is not None:
- showIndent(outfile, level)
- outfile.write('<%sdomain>%s%sdomain>\n' % (namespace_, self.gds_format_string(quote_xml(self.domain).encode(ExternalEncoding), input_name='domain'), namespace_))
+ showIndent(write, level)
+ write('<%sdomain>%s%sdomain>\n' % (namespace_, quote_xml(self.domain), namespace_))
def hasContent_(self):
if (
self.domain is not None
@@ -2460,21 +1602,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='domainObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.domain is not None:
- showIndent(outfile, level)
- outfile.write('domain=%s,\n' % quote_python(self.domain).encode(ExternalEncoding))
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2514,26 +1643,26 @@ def get_as_number(self): return self.as_number
def set_as_number(self, as_number): self.as_number = as_number
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='ASNObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='ASNObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='ASNObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='ASNObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='ASNObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='ASNObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id="%s"' % self.gds_format_integer(self.id, input_name='id'))
- def exportChildren(self, outfile, level, namespace_='', name_='ASNObject', fromsubclass_=False):
+ write(' id="%s"' % self.gds_format_integer(self.id, input_name='id'))
+ def exportChildren(self, write, level, namespace_='', name_='ASNObject', fromsubclass_=False):
if self.as_number is not None:
- showIndent(outfile, level)
- outfile.write('<%sas-number>%s%sas-number>\n' % (namespace_, self.gds_format_integer(self.as_number, input_name='as-number'), namespace_))
+ showIndent(write, level)
+ write('<%sas-number>%s%sas-number>\n' % (namespace_, self.gds_format_integer(self.as_number, input_name='as-number'), namespace_))
def hasContent_(self):
if (
self.as_number is not None
@@ -2541,21 +1670,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='ASNObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = %d,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.as_number is not None:
- showIndent(outfile, level)
- outfile.write('as_number=%d,\n' % self.as_number)
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2566,14 +1682,14 @@ def buildAttributes(self, node, attrs, already_processed):
already_processed.append('id')
try:
self.id = int(value)
- except ValueError, exp:
+ except ValueError as exp:
raise_parse_error(node, 'Bad integer attribute: %s' % exp)
def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
if nodeName_ == 'as-number':
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'as_number')
self.as_number = ival_
@@ -2621,37 +1737,37 @@ def validate_ClassificationTypeEnum(self, value):
pass
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='classificationObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='classificationObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='classificationObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='classificationObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='classificationObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='classificationObject'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
+ write(' type=%s' % (quote_attrib(self.type_), ))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='classificationObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='classificationObject', fromsubclass_=False):
if self.classificationName is not None:
- showIndent(outfile, level)
- outfile.write('<%sclassificationName>%s%sclassificationName>\n' % ('mmdef:', self.gds_format_string(quote_xml(self.classificationName).encode(ExternalEncoding), input_name='classificationName'), 'mmdef:'))
+ showIndent(write, level)
+ write('<%sclassificationName>%s%sclassificationName>\n' % ('mmdef:', quote_xml(self.classificationName), 'mmdef:'))
if self.companyName is not None:
- showIndent(outfile, level)
- outfile.write('<%scompanyName>%s%scompanyName>\n' % ('mmdef:', self.gds_format_string(quote_xml(self.companyName).encode(ExternalEncoding), input_name='companyName'), 'mmdef:'))
+ showIndent(write, level)
+ write('<%scompanyName>%s%scompanyName>\n' % ('mmdef:', quote_xml(self.companyName), 'mmdef:'))
if self.category is not None:
- showIndent(outfile, level)
- outfile.write('<%scategory>%s%scategory>\n' % ('mmdef:', self.gds_format_string(quote_xml(self.category).encode(ExternalEncoding), input_name='category'), 'mmdef:'))
+ showIndent(write, level)
+ write('<%scategory>%s%scategory>\n' % ('mmdef:', quote_xml(self.category), 'mmdef:'))
if self.classificationDetails is not None:
- self.classificationDetails.export(outfile, level, namespace_, name_='classificationDetails')
+ self.classificationDetails.export(write, level, namespace_, name_='classificationDetails')
def hasContent_(self):
if (
self.classificationName is not None or
@@ -2662,37 +1778,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='classificationObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.classificationName is not None:
- showIndent(outfile, level)
- outfile.write('classificationName=%s,\n' % quote_python(self.classificationName).encode(ExternalEncoding))
- if self.companyName is not None:
- showIndent(outfile, level)
- outfile.write('companyName=%s,\n' % quote_python(self.companyName).encode(ExternalEncoding))
- if self.category is not None:
- showIndent(outfile, level)
- outfile.write('category=%s,\n' % quote_python(self.category).encode(ExternalEncoding))
- if self.classificationDetails is not None:
- showIndent(outfile, level)
- outfile.write('classificationDetails=model_.classificationDetails(\n')
- self.classificationDetails.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2754,36 +1841,36 @@ def get_product(self): return self.product
def set_product(self, product): self.product = product
def get_productVersion(self): return self.productVersion
def set_productVersion(self, productVersion): self.productVersion = productVersion
- def export(self, outfile, level, namespace_='', name_='classificationDetails', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='classificationDetails', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='classificationDetails')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='classificationDetails')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='classificationDetails'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='classificationDetails'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='classificationDetails', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='classificationDetails', fromsubclass_=False):
if self.definitionVersion is not None:
- showIndent(outfile, level)
- outfile.write('<%sdefinitionVersion>%s%sdefinitionVersion>\n' % (namespace_, self.gds_format_string(quote_xml(self.definitionVersion).encode(ExternalEncoding), input_name='definitionVersion'), namespace_))
+ showIndent(write, level)
+ write('<%sdefinitionVersion>%s%sdefinitionVersion>\n' % (namespace_, quote_xml(self.definitionVersion), namespace_))
if self.detectionAddedTimeStamp is not None:
- showIndent(outfile, level)
- outfile.write('<%sdetectionAddedTimeStamp>%s%sdetectionAddedTimeStamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.detectionAddedTimeStamp).encode(ExternalEncoding), input_name='detectionAddedTimeStamp'), namespace_))
+ showIndent(write, level)
+ write('<%sdetectionAddedTimeStamp>%s%sdetectionAddedTimeStamp>\n' % (namespace_, quote_xml(self.detectionAddedTimeStamp), namespace_))
if self.detectionShippedTimeStamp is not None:
- showIndent(outfile, level)
- outfile.write('<%sdetectionShippedTimeStamp>%s%sdetectionShippedTimeStamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.detectionShippedTimeStamp).encode(ExternalEncoding), input_name='detectionShippedTimeStamp'), namespace_))
+ showIndent(write, level)
+ write('<%sdetectionShippedTimeStamp>%s%sdetectionShippedTimeStamp>\n' % (namespace_, quote_xml(self.detectionShippedTimeStamp), namespace_))
if self.product is not None:
- showIndent(outfile, level)
- outfile.write('<%sproduct>%s%sproduct>\n' % (namespace_, self.gds_format_string(quote_xml(self.product).encode(ExternalEncoding), input_name='product'), namespace_))
+ showIndent(write, level)
+ write('<%sproduct>%s%sproduct>\n' % (namespace_, quote_xml(self.product), namespace_))
if self.productVersion is not None:
- showIndent(outfile, level)
- outfile.write('<%sproductVersion>%s%sproductVersion>\n' % (namespace_, self.gds_format_string(quote_xml(self.productVersion).encode(ExternalEncoding), input_name='productVersion'), namespace_))
+ showIndent(write, level)
+ write('<%sproductVersion>%s%sproductVersion>\n' % (namespace_, quote_xml(self.productVersion), namespace_))
def hasContent_(self):
if (
self.definitionVersion is not None or
@@ -2795,30 +1882,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='classificationDetails'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.definitionVersion is not None:
- showIndent(outfile, level)
- outfile.write('definitionVersion=%s,\n' % quote_python(self.definitionVersion).encode(ExternalEncoding))
- if self.detectionAddedTimeStamp is not None:
- showIndent(outfile, level)
- outfile.write('detectionAddedTimeStamp=%s,\n' % quote_python(self.detectionAddedTimeStamp).encode(ExternalEncoding))
- if self.detectionShippedTimeStamp is not None:
- showIndent(outfile, level)
- outfile.write('detectionShippedTimeStamp=%s,\n' % quote_python(self.detectionShippedTimeStamp).encode(ExternalEncoding))
- if self.product is not None:
- showIndent(outfile, level)
- outfile.write('product=%s,\n' % quote_python(self.product).encode(ExternalEncoding))
- if self.productVersion is not None:
- showIndent(outfile, level)
- outfile.write('productVersion=%s,\n' % quote_python(self.productVersion).encode(ExternalEncoding))
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -2948,45 +2013,45 @@ def get_importance(self): return self.importance
def set_importance(self, importance): self.importance = importance
def get_location(self): return self.location
def set_location(self, location): self.location = location
- def export(self, outfile, level, namespace_='', name_='fieldDataEntry', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='fieldDataEntry', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='fieldDataEntry')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='fieldDataEntry')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='fieldDataEntry'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='fieldDataEntry'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='fieldDataEntry', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='fieldDataEntry', fromsubclass_=False):
if self.references is not None:
- self.references.export(outfile, level, namespace_, name_='references', )
+ self.references.export(write, level, namespace_, name_='references', )
if self.startDate is not None:
- showIndent(outfile, level)
- outfile.write('<%sstartDate>%s%sstartDate>\n' % (namespace_, self.gds_format_string(quote_xml(self.startDate).encode(ExternalEncoding), input_name='startDate'), namespace_))
+ showIndent(write, level)
+ write('<%sstartDate>%s%sstartDate>\n' % (namespace_, quote_xml(self.startDate), namespace_))
if self.endDate is not None:
- showIndent(outfile, level)
- outfile.write('<%sendDate>%s%sendDate>\n' % (namespace_, self.gds_format_string(quote_xml(self.endDate).encode(ExternalEncoding), input_name='endDate'), namespace_))
+ showIndent(write, level)
+ write('<%sendDate>%s%sendDate>\n' % (namespace_, quote_xml(self.endDate), namespace_))
if self.firstSeenDate is not None:
- showIndent(outfile, level)
- outfile.write('<%sfirstSeenDate>%s%sfirstSeenDate>\n' % (namespace_, self.gds_format_string(quote_xml(self.firstSeenDate).encode(ExternalEncoding), input_name='firstSeenDate'), namespace_))
+ showIndent(write, level)
+ write('<%sfirstSeenDate>%s%sfirstSeenDate>\n' % (namespace_, quote_xml(self.firstSeenDate), namespace_))
if self.origin is not None:
- showIndent(outfile, level)
- outfile.write('<%sorigin>%s%sorigin>\n' % (namespace_, self.gds_format_string(quote_xml(self.origin).encode(ExternalEncoding), input_name='origin'), namespace_))
+ showIndent(write, level)
+ write('<%sorigin>%s%sorigin>\n' % (namespace_, quote_xml(self.origin), namespace_))
if self.commonality is not None:
- showIndent(outfile, level)
- outfile.write('<%scommonality>%s%scommonality>\n' % (namespace_, self.gds_format_integer(self.commonality, input_name='commonality'), namespace_))
+ showIndent(write, level)
+ write('<%scommonality>%s%scommonality>\n' % (namespace_, self.gds_format_integer(self.commonality, input_name='commonality'), namespace_))
for volume_ in self.volume:
- volume_.export(outfile, level, namespace_, name_='volume')
+ volume_.export(write, level, namespace_, name_='volume')
if self.importance is not None:
- showIndent(outfile, level)
- outfile.write('<%simportance>%s%simportance>\n' % (namespace_, self.gds_format_integer(self.importance, input_name='importance'), namespace_))
+ showIndent(write, level)
+ write('<%simportance>%s%simportance>\n' % (namespace_, self.gds_format_integer(self.importance, input_name='importance'), namespace_))
if self.location is not None:
- self.location.export(outfile, level, namespace_, name_='location')
+ self.location.export(write, level, namespace_, name_='location')
def hasContent_(self):
if (
self.references is not None or
@@ -3002,57 +2067,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='fieldDataEntry'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- if self.references is not None:
- showIndent(outfile, level)
- outfile.write('references=model_.references(\n')
- self.references.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.startDate is not None:
- showIndent(outfile, level)
- outfile.write('startDate=%s,\n' % quote_python(self.startDate).encode(ExternalEncoding))
- if self.endDate is not None:
- showIndent(outfile, level)
- outfile.write('endDate=%s,\n' % quote_python(self.endDate).encode(ExternalEncoding))
- if self.firstSeenDate is not None:
- showIndent(outfile, level)
- outfile.write('firstSeenDate=%s,\n' % quote_python(self.firstSeenDate).encode(ExternalEncoding))
- if self.origin is not None:
- showIndent(outfile, level)
- outfile.write('origin=%s,\n' % quote_python(self.origin).encode(ExternalEncoding))
- if self.commonality is not None:
- showIndent(outfile, level)
- outfile.write('commonality=%d,\n' % self.commonality)
- showIndent(outfile, level)
- outfile.write('volume=[\n')
- level += 1
- for volume_ in self.volume:
- showIndent(outfile, level)
- outfile.write('model_.volume(\n')
- volume_.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
- if self.importance is not None:
- showIndent(outfile, level)
- outfile.write('importance=%d,\n' % self.importance)
- if self.location is not None:
- showIndent(outfile, level)
- outfile.write('location=model_.location(\n')
- self.location.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -3085,7 +2101,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'commonality')
self.commonality = ival_
@@ -3098,7 +2114,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
sval_ = child_.text
try:
ival_ = int(sval_)
- except (TypeError, ValueError), exp:
+ except (TypeError, ValueError) as exp:
raise_parse_error(child_, 'requires integer: %s' % exp)
ival_ = self.gds_validate_integer(ival_, node, 'importance')
self.importance = ival_
@@ -3129,23 +2145,23 @@ def get_ref(self): return self.ref
def set_ref(self, ref): self.ref = ref
def add_ref(self, value): self.ref.append(value)
def insert_ref(self, index, value): self.ref[index] = value
- def export(self, outfile, level, namespace_='', name_='references', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='references', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='references')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='references')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='references'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='references'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='references', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='references', fromsubclass_=False):
for ref_ in self.ref:
- ref_.export(outfile, level, namespace_, name_='ref')
+ ref_.export(write, level, namespace_, name_='ref')
def hasContent_(self):
if (
self.ref
@@ -3153,27 +2169,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='references'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('ref=[\n')
- level += 1
- for ref_ in self.ref:
- showIndent(outfile, level)
- outfile.write('model_.reference(\n')
- ref_.exportLiteral(outfile, level, name_='reference')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -3208,23 +2205,23 @@ def validate_VolumeUnitsEnum(self, value):
pass
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='volume', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='volume', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='volume')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='volume')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='volume'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='volume'):
if self.units is not None and 'units' not in already_processed:
already_processed.append('units')
- outfile.write(' units=%s' % (quote_attrib(self.units), ))
- def exportChildren(self, outfile, level, namespace_='', name_='volume', fromsubclass_=False):
+ write(' units=%s' % (quote_attrib(self.units), ))
+ def exportChildren(self, write, level, namespace_='', name_='volume', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -3233,21 +2230,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='volume'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.units is not None and 'units' not in already_processed:
- already_processed.append('units')
- showIndent(outfile, level)
- outfile.write('units = "%s",\n' % (self.units,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -3284,23 +2268,23 @@ def validate_LocationTypeEnum(self, value):
pass
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='location', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='location', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='location')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='location')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='location'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='location'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
- def exportChildren(self, outfile, level, namespace_='', name_='location', fromsubclass_=False):
+ write(' type=%s' % (quote_attrib(self.type_), ))
+ def exportChildren(self, write, level, namespace_='', name_='location', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -3309,21 +2293,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='location'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -3355,21 +2326,21 @@ def factory(*args_, **kwargs_):
factory = staticmethod(factory)
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='reference', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='reference', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='reference')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='reference')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='reference'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='reference'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='reference', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='reference', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -3378,18 +2349,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='reference'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -3422,23 +2383,23 @@ def validate_PropertyTypeEnum(self, value):
pass
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='property', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='property', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='property')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='property')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='property'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='property'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
- def exportChildren(self, outfile, level, namespace_='', name_='property', fromsubclass_=False):
+ write(' type=%s' % (quote_attrib(self.type_), ))
+ def exportChildren(self, write, level, namespace_='', name_='property', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -3447,21 +2408,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='property'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -3514,30 +2462,30 @@ def add_property(self, value): self.property.append(value)
def insert_property(self, index, value): self.property[index] = value
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='objectProperty', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='objectProperty', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='objectProperty')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='objectProperty')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='objectProperty'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='objectProperty'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='', name_='objectProperty', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='', name_='objectProperty', fromsubclass_=False):
if self.references is not None:
- self.references.export(outfile, level, namespace_, name_='references', )
+ self.references.export(write, level, namespace_, name_='references', )
if self.timestamp is not None:
- showIndent(outfile, level)
- outfile.write('<%stimestamp>%s%stimestamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.timestamp).encode(ExternalEncoding), input_name='timestamp'), namespace_))
+ showIndent(write, level)
+ write('<%stimestamp>%s%stimestamp>\n' % (namespace_, quote_xml(self.timestamp), namespace_))
for property_ in self.property:
- property_.export(outfile, level, namespace_, name_='property')
+ property_.export(write, level, namespace_, name_='property')
def hasContent_(self):
if (
self.references is not None or
@@ -3547,39 +2495,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='objectProperty'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.references is not None:
- showIndent(outfile, level)
- outfile.write('references=model_.references(\n')
- self.references.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.timestamp is not None:
- showIndent(outfile, level)
- outfile.write('timestamp=%s,\n' % quote_python(self.timestamp).encode(ExternalEncoding))
- showIndent(outfile, level)
- outfile.write('property=[\n')
- level += 1
- for property_ in self.property:
- showIndent(outfile, level)
- outfile.write('model_.property(\n')
- property_.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -3647,33 +2564,33 @@ def validate_RelationshipTypeEnum(self, value):
pass
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='relationship', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='relationship', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='relationship')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='relationship')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='relationship'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='relationship'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (quote_attrib(self.type_), ))
+ write(' type=%s' % (quote_attrib(self.type_), ))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (quote_attrib(self.id), ))
- def exportChildren(self, outfile, level, namespace_='', name_='relationship', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id), ))
+ def exportChildren(self, write, level, namespace_='', name_='relationship', fromsubclass_=False):
if self.source is not None:
- self.source.export(outfile, level, namespace_, name_='source', )
+ self.source.export(write, level, namespace_, name_='source', )
if self.target is not None:
- self.target.export(outfile, level, namespace_, name_='target', )
+ self.target.export(write, level, namespace_, name_='target', )
if self.timestamp is not None:
- showIndent(outfile, level)
- outfile.write('<%stimestamp>%s%stimestamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.timestamp).encode(ExternalEncoding), input_name='timestamp'), namespace_))
+ showIndent(write, level)
+ write('<%stimestamp>%s%stimestamp>\n' % (namespace_, quote_xml(self.timestamp), namespace_))
def hasContent_(self):
if (
self.source is not None or
@@ -3683,37 +2600,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='relationship'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = %s,\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.source is not None:
- showIndent(outfile, level)
- outfile.write('source=model_.source(\n')
- self.source.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.target is not None:
- showIndent(outfile, level)
- outfile.write('target=model_.target(\n')
- self.target.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
- if self.timestamp is not None:
- showIndent(outfile, level)
- outfile.write('timestamp=%s,\n' % quote_python(self.timestamp).encode(ExternalEncoding))
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -3763,23 +2651,23 @@ def get_ref(self): return self.ref
def set_ref(self, ref): self.ref = ref
def add_ref(self, value): self.ref.append(value)
def insert_ref(self, index, value): self.ref[index] = value
- def export(self, outfile, level, namespace_='', name_='source', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='source', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='source')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='source')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='source'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='source'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='source', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='source', fromsubclass_=False):
for ref_ in self.ref:
- ref_.export(outfile, level, namespace_, name_='ref')
+ ref_.export(write, level, namespace_, name_='ref')
def hasContent_(self):
if (
self.ref
@@ -3787,27 +2675,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='source'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('ref=[\n')
- level += 1
- for ref_ in self.ref:
- showIndent(outfile, level)
- outfile.write('model_.reference(\n')
- ref_.exportLiteral(outfile, level, name_='reference')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -3841,23 +2710,23 @@ def get_ref(self): return self.ref
def set_ref(self, ref): self.ref = ref
def add_ref(self, value): self.ref.append(value)
def insert_ref(self, index, value): self.ref[index] = value
- def export(self, outfile, level, namespace_='', name_='target', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='target', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='target')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='target')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='target'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='target'):
pass
- def exportChildren(self, outfile, level, namespace_='', name_='target', fromsubclass_=False):
+ def exportChildren(self, write, level, namespace_='', name_='target', fromsubclass_=False):
for ref_ in self.ref:
- ref_.export(outfile, level, namespace_, name_='ref')
+ ref_.export(write, level, namespace_, name_='ref')
def hasContent_(self):
if (
self.ref
@@ -3865,27 +2734,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='target'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- pass
- def exportLiteralChildren(self, outfile, level, name_):
- showIndent(outfile, level)
- outfile.write('ref=[\n')
- level += 1
- for ref_ in self.ref:
- showIndent(outfile, level)
- outfile.write('model_.reference(\n')
- ref_.exportLiteral(outfile, level, name_='reference')
- showIndent(outfile, level)
- outfile.write('),\n')
- level -= 1
- showIndent(outfile, level)
- outfile.write('],\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -3940,46 +2790,46 @@ def get_CPEname(self): return self.CPEname
def set_CPEname(self, CPEname): self.CPEname = CPEname
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='softwarePackageObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='softwarePackageObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='softwarePackageObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='softwarePackageObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='softwarePackageObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='softwarePackageObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='softwarePackageObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='softwarePackageObject', fromsubclass_=False):
if self.vendor is not None:
- showIndent(outfile, level)
- outfile.write('<%svendor>%s%svendor>\n' % (namespace_, self.gds_format_string(quote_xml(self.vendor).encode(ExternalEncoding), input_name='vendor'), namespace_))
+ showIndent(write, level)
+ write('<%svendor>%s%svendor>\n' % (namespace_, quote_xml(self.vendor), namespace_))
if self.productgroup is not None:
- showIndent(outfile, level)
- outfile.write('<%sproductgroup>%s%sproductgroup>\n' % (namespace_, self.gds_format_string(quote_xml(self.productgroup).encode(ExternalEncoding), input_name='productgroup'), namespace_))
+ showIndent(write, level)
+ write('<%sproductgroup>%s%sproductgroup>\n' % (namespace_, quote_xml(self.productgroup), namespace_))
if self.product is not None:
- showIndent(outfile, level)
- outfile.write('<%sproduct>%s%sproduct>\n' % (namespace_, self.gds_format_string(quote_xml(self.product).encode(ExternalEncoding), input_name='product'), namespace_))
+ showIndent(write, level)
+ write('<%sproduct>%s%sproduct>\n' % (namespace_, quote_xml(self.product), namespace_))
if self.version is not None:
- showIndent(outfile, level)
- outfile.write('<%sversion>%s%sversion>\n' % (namespace_, self.gds_format_string(quote_xml(self.version).encode(ExternalEncoding), input_name='version'), namespace_))
+ showIndent(write, level)
+ write('<%sversion>%s%sversion>\n' % (namespace_, quote_xml(self.version), namespace_))
if self.update is not None:
- showIndent(outfile, level)
- outfile.write('<%supdate>%s%supdate>\n' % (namespace_, self.gds_format_string(quote_xml(self.update).encode(ExternalEncoding), input_name='update'), namespace_))
+ showIndent(write, level)
+ write('<%supdate>%s%supdate>\n' % (namespace_, quote_xml(self.update), namespace_))
if self.edition is not None:
- showIndent(outfile, level)
- outfile.write('<%sedition>%s%sedition>\n' % (namespace_, self.gds_format_string(quote_xml(self.edition).encode(ExternalEncoding), input_name='edition'), namespace_))
+ showIndent(write, level)
+ write('<%sedition>%s%sedition>\n' % (namespace_, quote_xml(self.edition), namespace_))
if self.language is not None:
- showIndent(outfile, level)
- outfile.write('<%slanguage>%s%slanguage>\n' % (namespace_, self.gds_format_string(quote_xml(self.language).encode(ExternalEncoding), input_name='language'), namespace_))
+ showIndent(write, level)
+ write('<%slanguage>%s%slanguage>\n' % (namespace_, quote_xml(self.language), namespace_))
if self.CPEname is not None:
- self.CPEname.export(outfile, level, namespace_, name_='CPEname')
+ self.CPEname.export(write, level, namespace_, name_='CPEname')
def hasContent_(self):
if (
self.vendor is not None or
@@ -3994,45 +2844,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='softwarePackageObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.vendor is not None:
- showIndent(outfile, level)
- outfile.write('vendor=%s,\n' % quote_python(self.vendor).encode(ExternalEncoding))
- if self.productgroup is not None:
- showIndent(outfile, level)
- outfile.write('productgroup=%s,\n' % quote_python(self.productgroup).encode(ExternalEncoding))
- if self.product is not None:
- showIndent(outfile, level)
- outfile.write('product=%s,\n' % quote_python(self.product).encode(ExternalEncoding))
- if self.version is not None:
- showIndent(outfile, level)
- outfile.write('version=%s,\n' % quote_python(self.version).encode(ExternalEncoding))
- if self.update is not None:
- showIndent(outfile, level)
- outfile.write('update=%s,\n' % quote_python(self.update).encode(ExternalEncoding))
- if self.edition is not None:
- showIndent(outfile, level)
- outfile.write('edition=%s,\n' % quote_python(self.edition).encode(ExternalEncoding))
- if self.language is not None:
- showIndent(outfile, level)
- outfile.write('language=%s,\n' % quote_python(self.language).encode(ExternalEncoding))
- if self.CPEname is not None:
- showIndent(outfile, level)
- outfile.write('CPEname=model_.CPEname(\n')
- self.CPEname.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -4100,23 +2913,23 @@ def get_cpeVersion(self): return self.cpeVersion
def set_cpeVersion(self, cpeVersion): self.cpeVersion = cpeVersion
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='CPEname', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='CPEname', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='CPEname')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='CPEname')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='CPEname'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='CPEname'):
if self.cpeVersion is not None and 'cpeVersion' not in already_processed:
already_processed.append('cpeVersion')
- outfile.write(' cpeVersion=%s' % (self.gds_format_string(quote_attrib(self.cpeVersion).encode(ExternalEncoding), input_name='cpeVersion'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='CPEname', fromsubclass_=False):
+ write(' cpeVersion=%s' % (quote_attrib(self.cpeVersion)))
+ def exportChildren(self, write, level, namespace_='', name_='CPEname', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -4125,21 +2938,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='CPEname'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.cpeVersion is not None and 'cpeVersion' not in already_processed:
- already_processed.append('cpeVersion')
- showIndent(outfile, level)
- outfile.write('cpeVersion = "%s",\n' % (self.cpeVersion,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -4189,40 +2989,40 @@ def get_type(self): return self.type_
def set_type(self, type_): self.type_ = type_
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='digitalSignatureObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='digitalSignatureObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='digitalSignatureObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='digitalSignatureObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='digitalSignatureObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='digitalSignatureObject'):
if self.type_ is not None and 'type_' not in already_processed:
already_processed.append('type_')
- outfile.write(' type=%s' % (self.gds_format_string(quote_attrib(self.type_).encode(ExternalEncoding), input_name='type'), ))
+ write(' type=%s' % (quote_attrib(self.type_)))
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='digitalSignatureObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='digitalSignatureObject', fromsubclass_=False):
if self.certificateIssuer is not None:
- showIndent(outfile, level)
- outfile.write('<%scertificateIssuer>%s%scertificateIssuer>\n' % (namespace_, self.gds_format_string(quote_xml(self.certificateIssuer).encode(ExternalEncoding), input_name='certificateIssuer'), namespace_))
+ showIndent(write, level)
+ write('<%scertificateIssuer>%s%scertificateIssuer>\n' % (namespace_, quote_xml(self.certificateIssuer), namespace_))
if self.certificateSubject is not None:
- showIndent(outfile, level)
- outfile.write('<%scertificateSubject>%s%scertificateSubject>\n' % (namespace_, self.gds_format_string(quote_xml(self.certificateSubject).encode(ExternalEncoding), input_name='certificateSubject'), namespace_))
+ showIndent(write, level)
+ write('<%scertificateSubject>%s%scertificateSubject>\n' % (namespace_, quote_xml(self.certificateSubject), namespace_))
if self.certificateValidity is not None:
- showIndent(outfile, level)
- outfile.write('<%scertificateValidity>%s%scertificateValidity>\n' % (namespace_, self.gds_format_boolean(self.gds_str_lower(str(self.certificateValidity)), input_name='certificateValidity'), namespace_))
+ showIndent(write, level)
+ write('<%scertificateValidity>%s%scertificateValidity>\n' % (namespace_, self.gds_format_boolean(self.gds_str_lower(str(self.certificateValidity)), input_name='certificateValidity'), namespace_))
if self.certificateRevocationTimestamp is not None:
- showIndent(outfile, level)
- outfile.write('<%scertificateRevocationTimestamp>%s%scertificateRevocationTimestamp>\n' % (namespace_, self.gds_format_string(quote_xml(self.certificateRevocationTimestamp).encode(ExternalEncoding), input_name='certificateRevocationTimestamp'), namespace_))
+ showIndent(write, level)
+ write('<%scertificateRevocationTimestamp>%s%scertificateRevocationTimestamp>\n' % (namespace_, quote_xml(self.certificateRevocationTimestamp), namespace_))
if self.signingTimestamp is not None:
- self.signingTimestamp.export(outfile, level, namespace_, name_='signingTimestamp')
+ self.signingTimestamp.export(write, level, namespace_, name_='signingTimestamp')
def hasContent_(self):
if (
self.certificateIssuer is not None or
@@ -4234,40 +3034,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='digitalSignatureObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.type_ is not None and 'type_' not in already_processed:
- already_processed.append('type_')
- showIndent(outfile, level)
- outfile.write('type_ = "%s",\n' % (self.type_,))
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.certificateIssuer is not None:
- showIndent(outfile, level)
- outfile.write('certificateIssuer=%s,\n' % quote_python(self.certificateIssuer).encode(ExternalEncoding))
- if self.certificateSubject is not None:
- showIndent(outfile, level)
- outfile.write('certificateSubject=%s,\n' % quote_python(self.certificateSubject).encode(ExternalEncoding))
- if self.certificateValidity is not None:
- showIndent(outfile, level)
- outfile.write('certificateValidity=%s,\n' % self.certificateValidity)
- if self.certificateRevocationTimestamp is not None:
- showIndent(outfile, level)
- outfile.write('certificateRevocationTimestamp=%s,\n' % quote_python(self.certificateRevocationTimestamp).encode(ExternalEncoding))
- if self.signingTimestamp is not None:
- showIndent(outfile, level)
- outfile.write('signingTimestamp=model_.signingTimestamp(\n')
- self.signingTimestamp.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -4327,23 +3095,23 @@ def get_valid(self): return self.valid
def set_valid(self, valid): self.valid = valid
def get_valueOf_(self): return self.valueOf_
def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
- def export(self, outfile, level, namespace_='', name_='signingTimestamp', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='signingTimestamp', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='signingTimestamp')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='signingTimestamp')
if self.hasContent_():
- outfile.write('>')
- outfile.write(str(self.valueOf_).encode(ExternalEncoding))
- self.exportChildren(outfile, level + 1, namespace_, name_)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>')
+ write(quote_xml(self.valueOf_))
+ self.exportChildren(write, level + 1, namespace_, name_)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='signingTimestamp'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='signingTimestamp'):
if self.valid is not None and 'valid' not in already_processed:
already_processed.append('valid')
- outfile.write(' valid="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.valid)), input_name='valid'))
- def exportChildren(self, outfile, level, namespace_='', name_='signingTimestamp', fromsubclass_=False):
+ write(' valid="%s"' % self.gds_format_boolean(self.gds_str_lower(str(self.valid)), input_name='valid'))
+ def exportChildren(self, write, level, namespace_='', name_='signingTimestamp', fromsubclass_=False):
pass
def hasContent_(self):
if (
@@ -4352,21 +3120,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='signingTimestamp'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- showIndent(outfile, level)
- outfile.write('valueOf_ = """%s""",\n' % (self.valueOf_,))
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.valid is not None and 'valid' not in already_processed:
- already_processed.append('valid')
- showIndent(outfile, level)
- outfile.write('valid = %s,\n' % (self.valid,))
- def exportLiteralChildren(self, outfile, level, name_):
- pass
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
self.valueOf_ = get_all_text_(node)
for child in node:
@@ -4414,31 +3169,31 @@ def get_signingTimestamp(self): return self.signingTimestamp
def set_signingTimestamp(self, signingTimestamp): self.signingTimestamp = signingTimestamp
def get_id(self): return self.id
def set_id(self, id): self.id = id
- def export(self, outfile, level, namespace_='', name_='taggantObject', namespacedef_=''):
- showIndent(outfile, level)
- outfile.write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
+ def export(self, write, level, namespace_='', name_='taggantObject', namespacedef_=''):
+ showIndent(write, level)
+ write('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
already_processed = []
- self.exportAttributes(outfile, level, already_processed, namespace_, name_='taggantObject')
+ self.exportAttributes(write, level, already_processed, namespace_, name_='taggantObject')
if self.hasContent_():
- outfile.write('>\n')
- self.exportChildren(outfile, level + 1, namespace_, name_)
- showIndent(outfile, level)
- outfile.write('%s%s>\n' % (namespace_, name_))
+ write('>\n')
+ self.exportChildren(write, level + 1, namespace_, name_)
+ showIndent(write, level)
+ write('%s%s>\n' % (namespace_, name_))
else:
- outfile.write('/>\n')
- def exportAttributes(self, outfile, level, already_processed, namespace_='', name_='taggantObject'):
+ write('/>\n')
+ def exportAttributes(self, write, level, already_processed, namespace_='', name_='taggantObject'):
if self.id is not None and 'id' not in already_processed:
already_processed.append('id')
- outfile.write(' id=%s' % (self.gds_format_string(quote_attrib(self.id).encode(ExternalEncoding), input_name='id'), ))
- def exportChildren(self, outfile, level, namespace_='', name_='taggantObject', fromsubclass_=False):
+ write(' id=%s' % (quote_attrib(self.id)))
+ def exportChildren(self, write, level, namespace_='', name_='taggantObject', fromsubclass_=False):
if self.vendorID is not None:
- showIndent(outfile, level)
- outfile.write('<%svendorID>%s%svendorID>\n' % (namespace_, self.gds_format_string(quote_xml(self.vendorID).encode(ExternalEncoding), input_name='vendorID'), namespace_))
+ showIndent(write, level)
+ write('<%svendorID>%s%svendorID>\n' % (namespace_, quote_xml(self.vendorID), namespace_))
if self.taggantValidity is not None:
- showIndent(outfile, level)
- outfile.write('<%staggantValidity>%s%staggantValidity>\n' % (namespace_, self.gds_format_boolean(self.gds_str_lower(str(self.taggantValidity)), input_name='taggantValidity'), namespace_))
+ showIndent(write, level)
+ write('<%staggantValidity>%s%staggantValidity>\n' % (namespace_, self.gds_format_boolean(self.gds_str_lower(str(self.taggantValidity)), input_name='taggantValidity'), namespace_))
if self.signingTimestamp is not None:
- self.signingTimestamp.export(outfile, level, namespace_, name_='signingTimestamp')
+ self.signingTimestamp.export(write, level, namespace_, name_='signingTimestamp')
def hasContent_(self):
if (
self.vendorID is not None or
@@ -4448,30 +3203,8 @@ def hasContent_(self):
return True
else:
return False
- def exportLiteral(self, outfile, level, name_='taggantObject'):
- level += 1
- self.exportLiteralAttributes(outfile, level, [], name_)
- if self.hasContent_():
- self.exportLiteralChildren(outfile, level, name_)
- def exportLiteralAttributes(self, outfile, level, already_processed, name_):
- if self.id is not None and 'id' not in already_processed:
- already_processed.append('id')
- showIndent(outfile, level)
- outfile.write('id = "%s",\n' % (self.id,))
- def exportLiteralChildren(self, outfile, level, name_):
- if self.vendorID is not None:
- showIndent(outfile, level)
- outfile.write('vendorID=%s,\n' % quote_python(self.vendorID).encode(ExternalEncoding))
- if self.taggantValidity is not None:
- showIndent(outfile, level)
- outfile.write('taggantValidity=%s,\n' % self.taggantValidity)
- if self.signingTimestamp is not None:
- showIndent(outfile, level)
- outfile.write('signingTimestamp=model_.signingTimestamp(\n')
- self.signingTimestamp.exportLiteral(outfile, level)
- showIndent(outfile, level)
- outfile.write('),\n')
def build(self, node):
+ self.__sourcenode__ = node
self.buildAttributes(node, node.attrib, [])
for child in node:
nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
@@ -4508,7 +3241,7 @@ def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
"""
def usage():
- print USAGE_TEXT
+ print(USAGE_TEXT)
sys.exit(1)
def parse(inFileName):
@@ -4523,13 +3256,13 @@ def parse(inFileName):
# Enable Python to collect the space used by the DOM.
doc = None
sys.stdout.write('\n')
- rootObj.export(sys.stdout, 0, name_=rootTag,
+ rootObj.export(sys.stdout, 0, name_=rootTag,
namespacedef_='')
return rootObj
def parseString(inString):
- from StringIO import StringIO
+ from mixbox.vendor.six import StringIO
doc = parsexml_(StringIO(inString))
rootNode = doc.getroot()
rootTag, rootClass = get_root_tag(rootNode)
diff --git a/maec/bundle/__init__.py b/maec/bundle/__init__.py
index e397f01..64d4a80 100644
--- a/maec/bundle/__init__.py
+++ b/maec/bundle/__init__.py
@@ -1 +1,29 @@
-_namespace = 'http://maec.mitre.org/XMLSchema/maec-bundle-4'
\ No newline at end of file
+_namespace = 'http://maec.mitre.org/XMLSchema/maec-bundle-4'
+
+from .malware_action import (MalwareAction, ActionImplementation, APICall, # noqa
+ ParameterList, Parameter) # noqa
+from .object_reference import ObjectReferenceList, ObjectReference # noqa
+from .av_classification import AVClassification, AVClassifications # noqa
+from .behavior_reference import BehaviorReference # noqa
+from .behavior import (Behavior, AssociatedCode, BehaviorPurpose, Exploit, # noqa
+ CVEVulnerability, PlatformList, BehavioralActions, # noqa
+ BehavioralAction, BehavioralActionReference, # noqa
+ BehavioralActionEquivalenceReference) # noqa
+from .action_reference_list import ActionReferenceList # noqa
+from .candidate_indicator import (CandidateIndicatorList, CandidateIndicator, # noqa
+ CandidateIndicatorComposition, MalwareEntity) # noqa
+from .process_tree import ProcessTree, ProcessTreeNode # noqa
+from .bundle_reference import BundleReference # noqa
+from .capability import (CapabilityList, Capability, CapabilityObjective, # noqa
+ CapabilityProperty, CapabilityRelationship, # noqa
+ CapabilityObjectiveRelationship, CapabilityReference, # noqa
+ CapabilityObjectiveReference) # noqa
+from .object_history import ObjectHistoryEntry, ObjectHistory # noqa
+from .bundle import (Bundle, BehaviorReference, Collections, # noqa
+ CandidateIndicatorCollectionList, ObjectCollectionList, # noqa
+ ActionCollectionList, BehaviorCollectionList, # noqa
+ CandidateIndicatorCollection, ObjectCollection, # noqa
+ BehaviorCollection, ActionCollection, BaseCollection, # noqa
+ ObjectList, ActionList, BehaviorList) # noqa
+
+
diff --git a/maec/bundle/action_reference_list.py b/maec/bundle/action_reference_list.py
index 10b5d83..99f417e 100644
--- a/maec/bundle/action_reference_list.py
+++ b/maec/bundle/action_reference_list.py
@@ -1,19 +1,16 @@
-#MAEC Action Reference List Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-from cybox.core import ActionReference
-
-import maec
-import maec.bindings.maec_bundle as bundle_binding
-
-
-class ActionReferenceList(maec.EntityList):
- _contained_type = ActionReference
- _binding_class = bundle_binding.ActionReferenceListType
- _binding_var = "Action_Reference"
- _namespace = maec.bundle._namespace
+#MAEC Action Reference List Class
+
+#Copyright (c) 2018, The MITRE Corporation
+#All rights reserved
+
+from cybox.core import ActionReference
+
+import maec
+from . import _namespace
+import maec.bindings.maec_bundle as bundle_binding
+from mixbox import fields
+
+class ActionReferenceList(maec.EntityList):
+ _binding_class = bundle_binding.ActionReferenceListType
+ _namespace = _namespace
+ action_reference = fields.TypedField("Action_Reference", ActionReference, multiple=True)
diff --git a/maec/bundle/av_classification.py b/maec/bundle/av_classification.py
index 657c99f..1148303 100644
--- a/maec/bundle/av_classification.py
+++ b/maec/bundle/av_classification.py
@@ -1,52 +1,71 @@
+# MAEC AV Classification classes
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from cybox.common import ToolInformation
+from mixbox import fields
+
import maec
+from . import _namespace
import maec.bindings.maec_bundle as bundle_binding
-from cybox.common import ToolInformation
-class AVClassification(ToolInformation):
- _namespace = maec.bundle._namespace
- def __init__(self, classification = None, tool_name = None, tool_vendor = None):
- super(AVClassification, self).__init__(tool_name, tool_vendor)
+class AVClassification(ToolInformation, maec.Entity):
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.AVClassificationType
+
+ def __init__(self, classification=None, tool_name=None, tool_vendor=None):
+ super(AVClassification, self).__init__(tool_name=tool_name, tool_vendor=tool_vendor)
self.engine_version = None
self.definition_version = None
- self.classification_name = None
+ self.classification_name = classification
- def to_obj(self):
- av_classification_obj = super(AVClassification, self).to_obj(bundle_binding.AVClassificationType())
- if self.engine_version is not None : av_classification_obj.set_Engine_Version(self.engine_version)
- if self.definition_version is not None : av_classification_obj.set_Definition_Version(self.definition_version)
- if self.classification_name is not None : av_classification_obj.set_Classification_Name(self.classification_name)
- return av_classification_obj
+ def to_obj(self, ns_info=None):
+ obj = super(AVClassification, self).to_obj(ns_info=ns_info)
+ if self.engine_version is not None :
+ obj.Engine_Version = self.engine_version
+ if self.definition_version is not None :
+ obj.Definition_Version = self.definition_version
+ if self.classification_name is not None :
+ obj.Classification_Name = self.classification_name
+ return obj
def to_dict(self):
- av_classification_dict = super(AVClassification, self).to_dict()
- if self.engine_version is not None : av_classification_dict['engine_version'] = self.engine_version
- if self.definition_version is not None : av_classification_dict['definition_version'] = self.definition_version
- if self.classification_name is not None : av_classification_dict['classification_name'] = self.classification_name
- return av_classification_dict
-
- @staticmethod
- def from_dict(av_classification_dict):
- if not av_classification_dict:
+ d = super(AVClassification, self).to_dict()
+
+ if self.engine_version is not None:
+ d['engine_version'] = self.engine_version
+ if self.definition_version is not None:
+ d['definition_version'] = self.definition_version
+ if self.classification_name is not None:
+ d['classification_name'] = self.classification_name
+
+ return d
+
+ @classmethod
+ def from_dict(cls, cls_dict):
+ if not cls_dict:
return None
- av_classification_ = ToolInformation.from_dict(av_classification_dict, AVClassification())
- av_classification_.engine_version = av_classification_dict.get('engine_version')
- av_classification_.definition_version = av_classification_dict.get('definition_version')
- av_classification_.classification_name = av_classification_dict.get('classification_name')
+
+ av_classification_ = super(AVClassification, cls).from_dict(cls_dict)
+ av_classification_.engine_version = cls_dict.get('engine_version')
+ av_classification_.definition_version = cls_dict.get('definition_version')
+ av_classification_.classification_name = cls_dict.get('classification_name')
return av_classification_
- @staticmethod
- def from_obj(av_classification_obj):
- if not av_classification_obj:
+ @classmethod
+ def from_obj(cls, cls_obj):
+ if not cls_obj:
return None
- av_classification_ = ToolInformation.from_obj(av_classification_obj, AVClassification())
- av_classification_.engine_version = av_classification_obj.get_Engine_Version()
- av_classification_.definition_version = av_classification_obj.get_Definition_Version()
- av_classification_.classification_name = av_classification_obj.get_Classification_Name()
+ av_classification_ = super(AVClassification, cls).from_obj(cls_obj)
+ av_classification_.engine_version = cls_obj.Engine_Version
+ av_classification_.definition_version = cls_obj.Definition_Version
+ av_classification_.classification_name = cls_obj.Classification_Name
return av_classification_
+
class AVClassifications(maec.EntityList):
- _contained_type = AVClassification
_binding_class = bundle_binding.AVClassificationsType
- _binding_var = "AV_Classification"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ av_classification = fields.TypedField("AV_Classification", AVClassification, multiple=True)
diff --git a/maec/bundle/behavior.py b/maec/bundle/behavior.py
index 90e7e1a..b4dc62e 100644
--- a/maec/bundle/behavior.py
+++ b/maec/bundle/behavior.py
@@ -1,113 +1,114 @@
-#MAEC Behavior Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 04/15/2014
-
-import maec
-import maec.bindings.maec_bundle as bundle_binding
-from cybox.core.action_reference import ActionReference
-from cybox.common.measuresource import MeasureSource
-from cybox.common.platform_specification import PlatformSpecification
-from maec.bundle.malware_action import MalwareAction
-from cybox.objects.code_object import Code
-#from maec.bundle.bundle import ActionCollection
-import datetime
-
-class BehavioralActionEquivalenceReference(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.BehavioralActionEquivalenceReferenceType
- _namespace = maec.bundle._namespace
-
- action_equivalence_idref = maec.TypedField('action_equivalence_idref')
- behavioral_ordering = maec.TypedField('behavioral_ordering')
-
-class BehavioralActionReference(ActionReference):
- _binding = bundle_binding
- _binding_class = bundle_binding.BehavioralActionReferenceType
- _namespace = maec.bundle._namespace
-
- behavioral_ordering = maec.TypedField('behavioral_ordering')
-
-class BehavioralAction(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.BehavioralActionType
- _namespace = maec.bundle._namespace
-
- behavioral_ordering = maec.TypedField('behavioral_ordering')
-
-class BehavioralActions(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.BehavioralActionsType
- _namespace = maec.bundle._namespace
-
- #action_collection = maec.TypedField('Action_Collection', ActionCollection, multiple=True) #TODO: solve recursive import
- action = maec.TypedField('Action', BehavioralAction, multiple=True)
- action_reference = maec.TypedField('Action_Reference', BehavioralActionReference, multiple=True)
- action_equivalence_reference = maec.TypedField('Action_Equivalence_Reference', BehavioralActionEquivalenceReference, multiple=True)
-
-class PlatformList(maec.EntityList):
- _binding = bundle_binding
- _binding_class = bundle_binding.PlatformListType
- _binding_var = "Platform"
- _contained_type = PlatformSpecification
- _namespace = maec.bundle._namespace
-
-class CVEVulnerability(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.CVEVulnerabilityType
- _namespace = maec.bundle._namespace
-
- cve_id = maec.TypedField('cve_id')
- description = maec.TypedField('Description')
-
-class Exploit(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.ExploitType
- _namespace = maec.bundle._namespace
-
- known_vulnerability = maec.TypedField('known_vulnerability')
- cve = maec.TypedField('CVE', CVEVulnerability)
- cwe_id = maec.TypedField('CWE_ID', multiple=True)
- targeted_platforms = maec.TypedField('Targeted_Platforms', PlatformList)
-
-class BehaviorPurpose(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.BehaviorPurposeType
- _namespace = maec.bundle._namespace
-
- description = maec.TypedField('Description')
- vulnerability_exploit = maec.TypedField('Vulnerability_Exploit', Exploit)
-
-class AssociatedCode(maec.EntityList):
- _binding = bundle_binding
- _binding_class = bundle_binding.AssociatedCodeType
- _binding_var = "Code_Snippet"
- _contained_type = Code
- _namespace = maec.bundle._namespace
-
-class Behavior(maec.Entity):
- _binding = bundle_binding
- _binding_class = bundle_binding.BehaviorType
- _namespace = maec.bundle._namespace
-
- id_ = maec.TypedField('id')
- ordinal_position = maec.TypedField('ordinal_position')
- status = maec.TypedField('status')
- duration = maec.TypedField('duration')
- purpose = maec.TypedField('Purpose', BehaviorPurpose)
- description = maec.TypedField('Description')
- discovery_method = maec.TypedField('Discovery_Method', MeasureSource)
- action_composition = maec.TypedField('Action_Composition', BehavioralActions)
- associated_code = maec.TypedField('Associated_Code', AssociatedCode)
- #relationships = maec.TypedField('Relationships', BehaviorRelationshipList) # TODO: implement
-
- def __init__(self, id = None, description = None):
- super(Behavior, self).__init__()
- if id:
- self.id_ = id
- else:
- self.id_ = maec.utils.idgen.create_id(prefix="behavior")
- self.description = description
+# MAEC Behavior Class
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from mixbox import fields
+from mixbox import idgen
+
+import maec
+from . import _namespace
+import maec.bindings.maec_bundle as bundle_binding
+from cybox.core.action_reference import ActionReference
+from cybox.common.measuresource import MeasureSource
+from cybox.common.platform_specification import PlatformSpecification
+from cybox.objects.code_object import Code
+
+class BehavioralActionEquivalenceReference(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehavioralActionEquivalenceReferenceType
+ _namespace = _namespace
+
+ action_equivalence_idref = fields.TypedField('action_equivalence_idref')
+ behavioral_ordering = fields.TypedField('behavioral_ordering')
+
+class BehavioralActionReference(ActionReference):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehavioralActionReferenceType
+ _namespace = _namespace
+
+ behavioral_ordering = fields.TypedField('behavioral_ordering')
+
+class BehavioralAction(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehavioralActionType
+ _namespace = _namespace
+
+ behavioral_ordering = fields.TypedField('behavioral_ordering')
+
+class BehavioralActions(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehavioralActionsType
+ _namespace = _namespace
+
+ #TODO: action_collection.type_ is set below to avoid circular import.
+ action_collection = fields.TypedField('Action_Collection', None, multiple=True)
+ action = fields.TypedField('Action', BehavioralAction, multiple=True)
+ action_reference = fields.TypedField('Action_Reference', BehavioralActionReference, multiple=True)
+ action_equivalence_reference = fields.TypedField('Action_Equivalence_Reference', BehavioralActionEquivalenceReference, multiple=True)
+
+class PlatformList(maec.EntityList):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.PlatformListType
+ _namespace = _namespace
+ platform = fields.TypedField("Platform", PlatformSpecification, multiple=True)
+
+class CVEVulnerability(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CVEVulnerabilityType
+ _namespace = _namespace
+
+ cve_id = fields.TypedField('cve_id')
+ description = fields.TypedField('Description')
+
+class Exploit(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ExploitType
+ _namespace = _namespace
+
+ known_vulnerability = fields.TypedField('known_vulnerability')
+ cve = fields.TypedField('CVE', CVEVulnerability)
+ cwe_id = fields.TypedField('CWE_ID', multiple=True)
+ targeted_platforms = fields.TypedField('Targeted_Platforms', PlatformList)
+
+class BehaviorPurpose(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehaviorPurposeType
+ _namespace = _namespace
+
+ description = fields.TypedField('Description')
+ vulnerability_exploit = fields.TypedField('Vulnerability_Exploit', Exploit)
+
+class AssociatedCode(maec.EntityList):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.AssociatedCodeType
+ _namespace = _namespace
+ code_snippet = fields.TypedField("Code_Snippet", Code, multiple=True)
+
+class Behavior(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehaviorType
+ _namespace = _namespace
+
+ id_ = fields.TypedField('id')
+ ordinal_position = fields.TypedField('ordinal_position')
+ status = fields.TypedField('status')
+ duration = fields.TypedField('duration')
+ purpose = fields.TypedField('Purpose', BehaviorPurpose)
+ description = fields.TypedField('Description')
+ discovery_method = fields.TypedField('Discovery_Method', MeasureSource)
+ action_composition = fields.TypedField('Action_Composition', BehavioralActions)
+ associated_code = fields.TypedField('Associated_Code', AssociatedCode)
+ #relationships = fields.TypedField('Relationships', BehaviorRelationshipList) # TODO: implement
+
+ def __init__(self, id = None, description = None):
+ super(Behavior, self).__init__()
+ if id:
+ self.id_ = id
+ else:
+ self.id_ = idgen.create_id(prefix="behavior")
+ self.description = description
+
+
+from maec.bundle.bundle import ActionCollection
+BehavioralActions.action_collection.type_ = ActionCollection
diff --git a/maec/bundle/behavior_reference.py b/maec/bundle/behavior_reference.py
index e4d4afa..c9eca18 100644
--- a/maec/bundle/behavior_reference.py
+++ b/maec/bundle/behavior_reference.py
@@ -1,44 +1,21 @@
-#MAEC Behavior Reference Class
+# MAEC Behavior Reference Class
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
import maec
+from . import _namespace
import maec.bindings.maec_bundle as bundle_binding
-
+
class BehaviorReference(maec.Entity):
- _namespace = maec.bundle._namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehaviorReferenceType
+ _namespace = _namespace
+
+ behavior_idref = fields.TypedField("behavior_idref")
- def init(self, behavior_idref = None):
+ def __init__(self, behavior_idref = None):
super(BehaviorReference, self).__init__()
self.behavior_idref = behavior_idref
-
- def to_obj(self):
- behavior_reference_obj = bundle_binding.BehaviorReferenceType()
- if self.behavior_idref is not None : behavior_reference_obj.set_behavior_idref(self.behavior_idref)
- return behavior_reference_obj
-
- def to_dict(self):
- behavior_reference_dict = {}
- if self.behavior_idref is not None : behavior_reference_dict['behavior_idref'] = self.behavior_idref
- return behavior_reference_dict
-
- @staticmethod
- def from_dict(behavior_reference_dict):
- if not behavior_reference_dict:
- return None
- behavior_reference_ = BehaviorReference()
- behavior_reference_.behavior_idref = behavior_reference_dict.get('behavior_idref')
- return behavior_reference_
-
- @staticmethod
- def from_obj(behavior_reference_obj):
- if not behavior_reference_obj:
- return None
- behavior_reference_ = BehaviorReference()
- behavior_reference_.behavior_idref = behavior_reference_obj.get_behavior_idref()
- return behavior_reference_
-
\ No newline at end of file
diff --git a/maec/bundle/bundle.py b/maec/bundle/bundle.py
index e75678c..f4aad2a 100644
--- a/maec/bundle/bundle.py
+++ b/maec/bundle/bundle.py
@@ -1,821 +1,630 @@
-#MAEC Bundle Class
+# MAEC Bundle Class
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 06/19/2014
-
-
-import datetime
+from mixbox import fields
+from mixbox import idgen
from cybox.core import Object
+from cybox.utils.normalize import normalize_object_properties
import maec
import maec.bindings.maec_bundle as bundle_binding
-from maec.bundle.malware_action import MalwareAction
-from maec.bundle.av_classification import AVClassifications
-from maec.bundle.behavior import Behavior
-from maec.bundle.candidate_indicator import CandidateIndicator, CandidateIndicatorList
-from maec.bundle.action_reference_list import ActionReferenceList
-from maec.bundle.process_tree import ProcessTree
-from maec.bundle.capability import CapabilityList
-from maec.utils.comparator import BundleComparator
-from maec.utils.deduplicator import BundleDeduplicator
-
-
-class Bundle(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self, id = None, defined_subject = "False", schema_version = "4.1", content_type = None, malware_instance_object = None):
- super(Bundle, self).__init__()
- if id:
- self.id = id
- else:
- self.id = maec.utils.idgen.create_id(prefix="bundle")
- self.schema_version = schema_version
- self.defined_subject = defined_subject
- self.content_type = content_type
- self.timestamp = None
- self.malware_instance_object_attributes = malware_instance_object
- #Add all of the top-level containers
- self.av_classifications = AVClassifications()
- self.actions = ActionList()
- self.process_tree = None
- self.behaviors = BehaviorList()
- self.capabilities = CapabilityList()
- self.objects = ObjectList()
- self.candidate_indicators = CandidateIndicatorList()
- self.collections = Collections()
-
- #Set the Malware Instance Object Attributes
- def set_malware_instance_object_atttributes(self, malware_instance_object):
- self.malware_instance_object_attributes = malware_instance_object
-
- #Add an AV classification
- def add_av_classification(self, av_classification):
- self.av_classifications.append(av_classification)
-
- #Add a Capability
- def add_capability(self, capability):
- capabilities = None
- if self.capabilities:
- capabilities = self.capabilities
- else:
- capabilities = CapabilityList()
- capabilities.capability.append(capability)
-
- #Set the Process Tree, in the top-level element
- def set_process_tree(self, process_tree):
- self.process_tree = process_tree
+from maec.utils import BundleComparator, BundleDeduplicator
- #Add a new Named Action Collection
- def add_named_action_collection(self, collection_name, collection_id = None):
- if not self.collections:
- self.collections = Collections()
- if collection_name is not None:
- self.collections.action_collections.append(ActionCollection(collection_name, collection_id))
-
- #Add an Action to an existing named collection; if it does not exist, add it to the top-level element
- def add_action(self, action, action_collection_name = None):
- if action_collection_name is not None:
- #The collection has already been defined
- if self.collections.action_collections.has_collection(action_collection_name):
- action_collection = self.collections.action_collections.get_named_collection(action_collection_name)
- action_collection.add_action(action)
- elif action_collection_name == None:
- self.actions.append(action)
+from . import _namespace
+from .malware_action import MalwareAction
+from .av_classification import AVClassifications
+from .behavior import Behavior
+from .candidate_indicator import CandidateIndicatorList
+from .process_tree import ProcessTree
+from .capability import CapabilityList
+from .object_history import ObjectHistory
- #Add a new Named Object Collection
- def add_named_object_collection(self, collection_name, collection_id = None):
- if not self.collections:
- self.collections = Collections()
- if collection_name is not None:
- self.collections.object_collections.append(ObjectCollection(collection_name, collection_id))
-
- # return a list of all abjects from self.actions and all action collections
- def get_all_actions(self, bin = False):
- all_actions = []
-
- for action in self.actions:
- all_actions.append(action)
-
- if self.collections and self.collections.action_collections:
- for collection in self.collections.action_collections:
- for action in collection.action_list:
- all_actions.append(action)
-
- if bin:
- binned_actions = {}
- for action in all_actions:
- if action.name and action.name.value not in binned_actions:
- binned_actions[action.name.value] = [action]
- elif action.name and action.name.value in binned_actions:
- binned_actions[action.name.value].append(action)
- return binned_actions
- else:
- return all_actions
-
- def get_all_actions_on_object(self, object):
- """Return a list of all of the Actions that operate on a particular Object"""
- object_actions = []
- if object.id_:
- for action in self.get_all_actions():
- associated_objects = action.associated_objects
- if associated_objects:
- for associated_object in associated_objects:
- if associated_object.idref and associated_object.idref == object.id_:
- object_actions.append(action)
- elif associated_object.id_ and associated_object.id_ == object.id_:
- object_actions.append(action)
- return object_actions
-
- #Add an Object to an existing named collection; if it does not exist, add it to the top-level element
- def add_object(self, object, object_collection_name = None):
- if object_collection_name is not None:
- #The collection has already been defined
- if self.collections.object_collections.has_collection(object_collection_name):
- object_collection = self.collections.object_collections.get_named_collection(object_collection_name)
- object_collection.add_object(object)
- elif object_collection_name == None:
- self.objects.append(object)
-
- # return a list of all objects from self.objects and all object collections
- def get_all_objects(self, include_actions = False):
- all_objects = []
- for obj in self.objects:
- all_objects.append(obj)
- for related_obj in obj.related_objects:
- all_objects.append(related_obj)
-
- if self.collections:
- for collection in self.collections.object_collections:
- for obj in collection.object_list:
- all_objects.append(obj)
- for related_obj in obj.related_objects:
- all_objects.append(related_obj)
-
- # Include Objects in Actions, if include_actions flag is specified
- if include_actions:
- for action in self.get_all_actions():
- associated_objects = action.associated_objects
- if associated_objects:
- for associated_object in associated_objects:
- all_objects.append(associated_object)
- for related_obj in associated_object.related_objects:
- all_objects.append(related_obj)
-
- return all_objects
-
- def get_all_multiple_referenced_objects(self):
- """Return a list of all Objects in the Bundle that are referenced more than once."""
- idref_list = [x.idref for x in self.get_all_objects() if x.idref]
- return [self.get_object_by_id(x) for x in idref_list if self.get_object_by_id(x)]
-
- def get_all_non_reference_objects(self):
- """Return a list of all Objects in the Bundle that are not references (i.e. all of the actual Objects in the Bundle)."""
- return [x for x in self.get_all_objects(True) if x.id_ and not x.idref]
-
- # finds actions and objects by id
- def get_object_by_id(self, id):
- for action in self.actions:
- if action.id_ == id:
- return action
-
- for associated_obj in action.associated_objects:
- if associated_obj.id_ == id:
- return associated_obj
-
- for collection in self.collections.action_collections:
- for action in collection.action_list:
- if action.id_ == id:
- return action
-
- for associated_obj in action.associated_objects:
- if associated_obj.id_ == id:
- return associated_obj
-
- for obj in self.objects:
- if obj.id_ == id:
- return obj
-
- for collection in self.collections.object_collections:
- for obj in collection.object_list:
- if obj.id_ == id:
- return obj
-
- #Add a new Named Behavior Collection
- def add_named_behavior_collection(self, collection_name):
- if collection_name is not None:
- self.collections.behavior_collections.append(BehaviorCollection(collection_name, collection_id))
-
- #Add a Behavior to an existing named collection; if it does not exist, add it to the top-level element
- def add_behavior(self, behavior, behavior_collection_name = None):
- if behavior_collection_name is not None:
- #The collection has already been defined
- if self.collections.behavior_collections.has_collection(behavior_collection_name):
- behavior_collection = self.collections.behavior_collections.get_named_collection(behavior_collection_name)
- behavior_collection.add_Behavior(behavior)
- elif behavior_collection_name == None:
- self.behaviors.append(behavior)
-
- #Add a new Named Behavior Collection
- def add_named_candidate_indicator_collection(self, collection_name, collection_id):
- if collection_name is not None and collection_id is not None:
- self.collections.candidate_indicator_collections.append(CandidateIndicatorCollection(collection_name, collection_id))
-
- #Add a Candidate Indicator to an existing named collection; if it does not exist, add it to the top-level element
- def add_candidate_indicator(self, candidate_indicator, candidate_indicator_collection_name = None):
- if candidate_indicator_collection_name is not None:
- #The collection has already been defined
- if self.collections.candidate_indicator_collections.has_collection(candidate_indicator_collection_name):
- candidate_indicator_collection = self.collections.candidate_indicator_collections.get_named_collection(candidate_indicator_collection_name)
- candidate_indicator_collection.add_candidate_indicator(candidate_indicator)
- elif candidate_indicator_collection_name == None:
- self.candidate_indicators.append(candidate_indicator)
-
- def to_obj(self):
- bundle_obj = bundle_binding.BundleType(id=self.id)
- #Set the bundle schema version
- bundle_obj.set_schema_version(self.schema_version)
- #Set whether this Bundle has a defined_subject
- bundle_obj.set_defined_subject(self.defined_subject)
- #Set the bundle timestamp
- if self.timestamp is not None : bundle_obj.set_timestamp(self.timestamp.isoformat())
- #Set the content_type if it is not none
- if self.content_type is not None: bundle_obj.set_content_type(self.content_type)
- #Set the Malware Instance Object Attributes (a CybOX object) if they are not none
- if self.malware_instance_object_attributes is not None: bundle_obj.set_Malware_Instance_Object_Attributes(self.malware_instance_object_attributes.to_obj())
- #Add the AV Classifications
- if self.av_classifications: bundle_obj.set_AV_Classifications(self.av_classifications.to_obj())
- #Add the Behaviors
- if self.behaviors: bundle_obj.set_Behaviors(self.behaviors.to_obj())
- #Add the Capabilities
- if self.capabilities and (self.capabilities.capability or self.capabilities.capability_reference): bundle_obj.set_Capabilities(self.capabilities.to_obj())
- #Add the Actions
- if self.actions: bundle_obj.set_Actions(self.actions.to_obj())
- #Add the Objects
- if self.objects: bundle_obj.set_Objects(self.objects.to_obj())
- #Add the Process Tree
- if self.process_tree is not None: bundle_obj.set_Process_Tree(self.process_tree.to_obj())
- #Add the Candidate Indicators
- if self.candidate_indicators: bundle_obj.set_Candidate_Indicators(self.candidate_indicators.to_obj())
- #Add the collections
- if self.collections is not None and self.collections.has_content(): bundle_obj.set_Collections(self.collections.to_obj())
- return bundle_obj
-
- def to_dict(self):
- bundle_dict = {}
- if self.id is not None : bundle_dict['id'] = self.id
- if self.schema_version is not None : bundle_dict['schema_version'] = self.schema_version
- if self.defined_subject is not None : bundle_dict['defined_subject'] = self.defined_subject
- if self.content_type is not None : bundle_dict['content_type'] = self.content_type
- if self.timestamp is not None : bundle_dict['timestamp'] = self.timestamp.isoformat()
- if self.malware_instance_object_attributes is not None : bundle_dict['malware_instance_object_attributes'] = self.malware_instance_object_attributes.to_dict()
- if self.av_classifications : bundle_dict['av_classifications'] = self.av_classifications.to_list()
- if self.process_tree is not None : bundle_dict['process_tree'] = self.process_tree.to_dict()
- if self.behaviors : bundle_dict['behaviors'] = self.behaviors.to_list()
- if self.capabilities : bundle_dict['capabilities'] = self.capabilities.to_dict()
- if self.actions : bundle_dict['actions'] = self.actions.to_list()
- if self.objects : bundle_dict['objects'] = self.objects.to_list()
- if self.candidate_indicators : bundle_dict['candidate_indicators'] = self.candidate_indicators.to_list()
- if self.collections is not None and self.collections.has_content(): bundle_dict['collections'] = self.collections.to_dict()
- return bundle_dict
-
- @staticmethod
- def from_obj(bundle_obj):
- if not bundle_obj:
- return None
- bundle_ = Bundle(None, None)
- bundle_.id = bundle_obj.get_id()
- bundle_.schema_version = bundle_obj.get_schema_version()
- bundle_.defined_subject = bundle_obj.get_defined_subject()
- bundle_.content_type = bundle_obj.get_content_type()
- bundle_.timestamp = bundle_obj.get_timestamp()
- bundle_.malware_instance_object_attributes = Object.from_obj(bundle_obj.get_Malware_Instance_Object_Attributes())
- if bundle_obj.get_AV_Classifications() is not None: bundle_.av_classifications = AVClassifications.from_obj(bundle_obj.get_AV_Classifications())
- bundle_.process_tree = ProcessTree.from_obj(bundle_obj.get_Process_Tree())
- if bundle_obj.get_Behaviors() is not None : bundle_.behaviors = BehaviorList.from_obj(bundle_obj.get_Behaviors())
- if bundle_obj.get_Capabilities() is not None : bundle_.capabilities = CapabilityList.from_obj(bundle_obj.get_Capabilities())
- if bundle_obj.get_Actions() is not None : bundle_.actions = ActionList.from_obj(bundle_obj.get_Actions())
- if bundle_obj.get_Objects() is not None : bundle_.objects = ObjectList.from_obj(bundle_obj.get_Objects())
- if bundle_obj.get_Candidate_Indicators() is not None : bundle_.candidate_indicators = CandidateIndicatorList.from_obj(bundle_obj.get_Candidate_Indicators())
- bundle_.collections = Collections.from_obj(bundle_obj.get_Collections())
- return bundle_
-
- @staticmethod
- def from_dict(bundle_dict):
- if not bundle_dict:
- return None
- bundle_ = Bundle(None, None)
- bundle_.id = bundle_dict.get('id')
- bundle_.schema_version = bundle_dict.get('schema_version')
- bundle_.defined_subject = bundle_dict.get('defined_subject')
- bundle_.content_type = bundle_dict.get('content_type')
- if bundle_dict.get('timestamp'):
- bundle_.timestamp = datetime.datetime.strptime(bundle_dict.get('timestamp'), "%Y-%m-%dT%H:%M:%S.%f")
- bundle_.malware_instance_object_attributes = Object.from_dict(bundle_dict.get('malware_instance_object_attributes'))
- bundle_.av_classifications = AVClassifications.from_list(bundle_dict.get('av_classifications'))
- bundle_.process_tree = ProcessTree.from_dict(bundle_dict.get('process_tree'))
- bundle_.behaviors = BehaviorList.from_list(bundle_dict.get('behaviors', []))
- bundle_.capabilities = CapabilityList.from_dict(bundle_dict.get('capabilities'))
- bundle_.actions = ActionList.from_list(bundle_dict.get('actions', []))
- bundle_.objects = ObjectList.from_list(bundle_dict.get('objects', []))
- bundle_.candidate_indicators = CandidateIndicatorList.from_list(bundle_dict.get('candidate_indicators', []))
- bundle_.collections = Collections.from_dict(bundle_dict.get('collections'))
- return bundle_
-
- @classmethod
- def compare(cls, bundle_list, match_on = None, case_sensitive = True):
- return BundleComparator.compare(bundle_list, match_on, case_sensitive);
-
- def deduplicate(self):
- BundleDeduplicator.deduplicate(self)
-
- def get_action_objects(self, action_name_list):
- """Get all Objects corresponding to one or more types of Actions, specified via a list of Action names"""
- action_objects = {}
- all_actions = self.get_all_actions(bin=True)
- for action_name in action_name_list:
- if action_name in all_actions:
- associated_objects = []
- associated_object_lists = [[y for y in x.associated_objects if x.associated_objects] for x in all_actions[action_name]]
- for associated_object_list in associated_object_lists:
- associated_objects += associated_object_list
- action_objects[action_name] = associated_objects
- return action_objects
-
- def get_object_history(self):
- """Build and return the Object history for the Bundle"""
- return ObjectHistory.build(self)
-
-class ObjectHistory(object):
- @classmethod
- def build(cls, bundle):
- """Build the Object History for a Bundle"""
- cls.entries = [] # A list of the Objects in the Object History
- # Get the Objects that are not references
- objects = bundle.get_all_non_reference_objects()
- for object in objects:
- object_history_entry = ObjectHistoryEntry(object)
- # Find and set all Actions that operate on the Object
- if bundle.get_all_actions_on_object(object):
- object_history_entry.actions = bundle.get_all_actions_on_object(object)
- # Add the history entry to the list
- cls.entries.append(object_history_entry)
-
-class ObjectHistoryEntry(object):
- def __init__(self, object = None):
- self.object = object
- self.actions = [] # A list of the Actions that operate on the Object
- self.behaviors = [] # A list of Behaviors that make use of the Object (through Actions?)
-
- def get_action_names(self):
- """Return a list of the Actions that operated on the Object, via their names"""
- return [x.name.value for x in self.actions if x.name]
class BehaviorList(maec.EntityList):
- _contained_type = Behavior
_binding_class = bundle_binding.BehaviorListType
- _binding_var = "Behavior"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ behavior = fields.TypedField("Behavior", Behavior, multiple=True)
class ActionList(maec.EntityList):
- _contained_type = MalwareAction
_binding_class = bundle_binding.ActionListType
- _binding_var = "Action"
- _namespace = maec.bundle._namespace
-
+ _namespace = _namespace
+ action = fields.TypedField("Action", MalwareAction, multiple=True)
+
+
class ObjectList(maec.EntityList):
- _contained_type = Object
_binding_class = bundle_binding.ObjectListType
- _binding_var = "Object"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ object = fields.TypedField("Object", Object, multiple=True)
+
class BaseCollection(maec.Entity):
- _namespace = maec.bundle._namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BaseCollectionType
+ _namespace = _namespace
+
+ name = fields.TypedField("name")
+ affinity_type = fields.TypedField("Affinity_Type")
+ affinity_degree = fields.TypedField("Affinity_Degree")
+ description = fields.TypedField("Description")
def __init__(self, name = None):
super(BaseCollection, self).__init__()
self.name = name
- self.affinity_type = None
- self.affinity_degree = None
- self.description = None
- def to_obj(self, derived_collection_obj = None):
- if derived_collection_obj == None:
- collection_obj = bundle_binding.BaseCollectionType()
- else:
- collection_obj = derived_collection_obj
- if self.name is not None: collection_obj.set_name(self.name)
- if self.affinity_type is not None: collection_obj.set_Affinity_Type(self.affinity_type)
- if self.affinity_degree is not None: collection_obj.set_Affinity_Degree(self.affinity_degree)
- if self.description is not None: collection_obj.set_Description(self.description)
- return collection_obj
-
- def to_dict(self):
- base_collection_dict = {}
- if self.name is not None : base_collection_dict['name'] = self.name
- if self.affinity_type is not None : base_collection_dict['affinity_type'] = self.affinity_type
- if self.affinity_degree is not None : base_collection_dict['affinity_degree'] = self.affinity_degree
- if self.description is not None : base_collection_dict['description'] = self.description
- return base_collection_dict
-
- @staticmethod
- def from_obj(collection_obj, derived_collection_cls = None):
- if not collection_obj:
- return None
- if derived_collection_cls == None:
- collection_obj_ = BaseCollection()
- else:
- collection_obj_ = derived_collection_cls
- collection_obj_.name = collection_obj.get_name()
- collection_obj_.affinity_type = collection_obj.get_Affinity_Type()
- collection_obj_.affinity_degree = collection_obj.get_Affinity_Degree()
- collection_obj_.description = collection_obj.get_Description()
- return collection_obj_
-
- @staticmethod
- def from_dict(collection_dict, derived_collection_cls = None):
- if not collection_dict:
- return None
- if derived_collection_cls == None:
- collection_obj_ = BaseCollection()
- else:
- collection_obj_ = derived_collection_cls
- collection_obj_.name = collection_dict.get('name')
- collection_obj_.affinity_type = collection_dict.get('affinity_type')
- collection_obj_.affinity_degree = collection_dict.get('affinity_degree')
- collection_obj_.description = collection_dict.get('description')
- return collection_obj_
class ActionCollection(BaseCollection):
- superclass = BaseCollection
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ActionCollectionType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ action_list = fields.TypedField("Action_List", ActionList)
def __init__(self, name = None, id = None):
super(ActionCollection, self).__init__(name)
if id:
- self.id = id
+ self.id_ = id
else:
- self.id = maec.utils.idgen.create_id(prefix="action_collection")
+ self.id_ = idgen.create_id(prefix="action_collection")
self.action_list = ActionList()
def add_action(self, action):
+ """Add an input Action to the Collection."""
self.action_list.append(action)
- def to_obj(self):
- action_collection_obj = super(ActionCollection, self).to_obj(bundle_binding.ActionCollectionType())
- if self.id is not None : action_collection_obj.set_id(self.id)
- if len(self.action_list) > 0: action_collection_obj.set_Action_List(self.action_list.to_obj())
- return action_collection_obj
-
- def to_dict(self):
- action_collection_dict = super(ActionCollection, self).to_dict()
- if self.id is not None : action_collection_dict['id'] = self.id
- if len(self.action_list) > 0: action_collection_dict['action_list'] = self.action_list.to_list()
- return action_collection_dict
-
- @staticmethod
- def from_obj(action_collection_obj):
- if not action_collection_obj:
- return None
- action_collection_ = BaseCollection.from_obj(action_collection_obj, ActionCollection())
- action_collection_.id = action_collection_obj.get_id()
- action_collection_.action_list = ActionList.from_obj(action_collection_obj.get_Action_List())
- return action_collection_
-
- @staticmethod
- def from_dict(action_collection_dict):
- if not action_collection_dict:
- return action_collection_dict
- action_collection_ = BaseCollection.from_dict(action_collection_dict, ActionCollection())
- action_collection_.id = action_collection_dict.get('id')
- action_collection_.action_list = ActionList.from_list(action_collection_dict.get('action_list'))
- return action_collection_
class BehaviorCollection(BaseCollection):
- superclass = BaseCollection
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BehaviorCollectionType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ behavior_list = fields.TypedField("Behavior_List", BehaviorList)
def __init__(self, name = None, id = None):
super(BehaviorCollection, self).__init__(name)
if id:
- self.id = id
+ self.id_ = id
else:
- self.id = maec.utils.idgen.create_id(prefix="behavior_collection")
+ self.id_ = idgen.create_id(prefix="behavior_collection")
self.behavior_list = BehaviorList()
def add_behavior(self, behavior):
+ """Add an input Behavior to the Collection."""
self.behavior_list.append(behavior)
- def to_obj(self):
- behavior_collection_obj = super(BehaviorCollection, self).to_obj(bundle_binding.BehaviorCollectionType())
- if self.id is not None : behavior_collection_obj.set_id(self.id)
- if len(self.behavior_list) > 0: behavior_collection_obj.set_Behavior_List(self.behavior_list.to_obj())
- return behavior_collection_obj
-
- def to_dict(self):
- behavior_collection_dict = super(BehaviorCollection, self).to_dict()
- if self.id is not None : behavior_collection_dict['id'] = self.id
- if len(self.behavior_list) > 0: behavior_collection_dict['behavior_list'] = self.behavior_list.to_list()
- return behavior_collection_dict
-
- @staticmethod
- def from_obj(behavior_collection_obj):
- if not behavior_collection_obj:
- return None
- behavior_collection_ = BaseCollection.from_obj(behavior_collection_obj, BehaviorCollection())
- behavior_collection_.id = behavior_collection_obj.get_id()
- behavior_collection_.behavior_list = BehaviorList.from_obj(behavior_collection_obj.get_Behavior_List())
- return behavior_collection_
-
- @staticmethod
- def from_dict(behavior_collection_dict):
- if not behavior_collection_dict:
- return None
- behavior_collection_ = BaseCollection.from_dict(behavior_collection_dict, BehaviorCollection())
- behavior_collection_.id = behavior_collection_dict.get('id')
- behavior_collection_.behavior_list = BehaviorList.from_list(behavior_collection_dict.get('behavior_list'))
- return behavior_collection_
class ObjectCollection(BaseCollection):
- superclass = BaseCollection
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ObjectCollectionType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ object_list = fields.TypedField("Object_List", ObjectList)
def __init__(self, name = None, id = None):
super(ObjectCollection, self).__init__(name)
if id:
- self.id = id
+ self.id_ = id
else:
- self.id = maec.utils.idgen.create_id(prefix="object_collection")
+ self.id_ = idgen.create_id(prefix="object_collection")
self.object_list = ObjectList()
def add_object(self, object):
+ """Add an input Object to the Collection."""
self.object_list.append(object)
- def to_obj(self):
- object_collection_obj = super(ObjectCollection, self).to_obj(bundle_binding.ObjectCollectionType())
- if self.id is not None : object_collection_obj.set_id(self.id)
- if len(self.object_list) > 0 : object_collection_obj.set_Object_List(self.object_list.to_obj())
- return object_collection_obj
-
- def to_dict(self):
- object_collection_dict = {}
- if self.id is not None : object_collection_dict['id'] = self.id
- if len(self.object_list) > 0 : object_collection_dict['object_list'] = self.object_list.to_list()
- return object_collection_dict
-
- @staticmethod
- def from_obj(object_collection_obj):
- if not object_collection_obj:
- return None
- object_collection_ = BaseCollection.from_obj(object_collection_obj, ObjectCollection())
- object_collection_.id = object_collection_obj.get_id()
- object_collection_.object_list = ObjectList.from_obj(object_collection_obj.get_Object_List())
- return object_collection_
-
- @staticmethod
- def from_dict(object_collection_dict):
- if not object_collection_dict:
- return None
- object_collection_ = BaseCollection.from_dict(object_collection_dict, ObjectCollection())
- object_collection_.id = object_collection_dict.get('id')
- object_collection_.object_list = ObjectList.from_list(object_collection_dict.get('object_list'))
- return object_collection_
class CandidateIndicatorCollection(BaseCollection):
- superclass = BaseCollection
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CandidateIndicatorCollectionType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ candidate_indicator_list = fields.TypedField("Candidate_Indicator_List", CandidateIndicatorList)
def __init__(self, name = None, id = None):
super(CandidateIndicatorCollection, self).__init__(name)
if id:
- self.id = id
+ self.id_ = id
else:
- self.id = maec.utils.idgen.create_id(prefix="candidate_indicator_collection")
+ self.id_ = idgen.create_id(prefix="candidate_indicator_collection")
self.candidate_indicator_list = CandidateIndicatorList()
def add_candidate_indicator(self, candidate_indicator):
+ """Add an input Candidate Indicator to the Collection."""
self.candidate_indicator_list.append(candidate_indicator)
- def to_obj(self):
- candidate_indicator_collection_obj = super(CandidateIndicatorCollection, self).to_obj(bundle_binding.CandidateIndicatorCollectionType())
- if self.id is not None : candidate_indicator_collection_obj.set_id(self.id)
- if len(self.candidate_indicator_list) > 0 is not None: candidate_indicator_collection_obj.set_Candidate_Indicator_List(self.candidate_indicator_list.to_obj())
- return candidate_indicator_collection_obj
-
- def to_dict(self):
- candidate_indicator_collection_dict = {}
- if self.id is not None : candidate_indicator_collection_dict['id'] = self.id
- if len(self.candidate_indicator_list) > 0 is not None: candidate_indicator_collection_dict['candidate_indicator_list'] = self.candidate_indicator_list.to_list()
- return candidate_indicator_collection_dict
-
- @staticmethod
- def from_obj(candidate_indicator_collection_obj):
- if not candidate_indicator_collection_obj:
- return None
- candidate_indicator_collection_ = BaseCollection.from_obj(candidate_indicator_collection_obj, CandidateIndicatorCollection())
- candidate_indicator_collection_.id = candidate_indicator_collection_obj.get_id()
- candidate_indicator_collection_.candidate_indicator_list = CandidateIndicatorList.from_obj(candidate_indicator_collection_obj.get_Candidate_Indicator_List())
- return candidate_indicator_collection_
-
- @staticmethod
- def from_dict(candidate_indicator_collection_dict):
- if not candidate_indicator_collection_dict:
- return None
- candidate_indicator_collection_ = BaseCollection.from_dict(candidate_indicator_collection_dict, CandidateIndicatorCollection())
- candidate_indicator_collection_.id = candidate_indicator_collection_dict.get('id')
- candidate_indicator_collection_.candidate_indicator_list = CandidateIndicatorList.from_list(candidate_indicator_collection_dict.get('candidate_indicator_list'))
- return candidate_indicator_collection_
class BehaviorCollectionList(maec.EntityList):
- _contained_type = BehaviorCollection
_binding_class = bundle_binding.BehaviorCollectionListType
- _binding_var = "Behavior_Collection"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ behavior_collection = fields.TypedField("Behavior_Collection", BehaviorCollection, multiple=True)
def __init__(self):
super(BehaviorCollectionList, self).__init__()
- def to_obj(self):
- behavior_collection_list_obj = bundle_binding.BehaviorCollectionListType()
+ def to_obj(self, ns_info=None):
+ behavior_collection_list_obj = super(BehaviorCollectionList, self).to_obj()
+
for behavior_collection in self:
if len(behavior_collection.behavior_list) > 0:
- behavior_collection_list_obj.add_Behavior_Collection(behavior_collection.to_obj())
+ behavior_collection_list_obj.add_Behavior_Collection(behavior_collection.to_obj(ns_info=ns_info))
if behavior_collection_list_obj.hasContent_():
return behavior_collection_list_obj
- #Checks for the existence of a named collection in the list
def has_collection(self, collection_name):
+ """Checks for the existence of a specific named Collection in the list, based on the its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return True
return False
- #Get a specific named collection in the list
def get_named_collection(self, collection_name):
+ """Return a specific named Collection from the list, based on its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return collection
return None
+
class ActionCollectionList(maec.EntityList):
- _contained_type = ActionCollection
_binding_class = bundle_binding.ActionCollectionListType
- _binding_var = "Action_Collection"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ action_collection = fields.TypedField("Action_Collection", ActionCollection, multiple=True)
def __init__(self):
super(ActionCollectionList, self).__init__()
- def to_obj(self):
- action_collection_list_obj = bundle_binding.ActionCollectionListType()
+ def to_obj(self, ns_info=None):
+ action_collection_list_obj = super(ActionCollectionList, self).to_obj()
+ action_collection_list_obj.set_Action_Collection([])
+
for action_collection in self:
if len(action_collection.action_list) > 0:
- action_collection_list_obj.add_Action_Collection(action_collection.to_obj())
+ action_collection_list_obj.add_Action_Collection(action_collection.to_obj(ns_info=ns_info))
if action_collection_list_obj.hasContent_():
return action_collection_list_obj
- #Checks for the existence of a named collection in the list
def has_collection(self, collection_name):
+ """Checks for the existence of a specific named Collection in the list, based on the its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return True
return False
- #Get a specific named collection in the list
def get_named_collection(self, collection_name):
+ """Return a specific named Collection from the list, based on its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return collection
return None
+
class ObjectCollectionList(maec.EntityList):
- _contained_type = ObjectCollection
_binding_class = bundle_binding.ObjectCollectionListType
- _binding_var = "Object_Collection"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ object_collection = fields.TypedField("Object_Collection", ObjectCollection, multiple=True)
def __init__(self):
super(ObjectCollectionList, self).__init__()
- def to_obj(self):
- object_collection_list_obj = bundle_binding.ObjectCollectionListType()
+ def to_obj(self, ns_info=None):
+ object_collection_list_obj = super(ObjectCollectionList, self).to_obj()
+
for object_collection in self:
if len(object_collection.object_list) > 0:
- object_collection_list_obj.add_Object_Collection(object_collection.to_obj())
+ object_collection_list_obj.add_Object_Collection(object_collection.to_obj(ns_info=ns_info))
if object_collection_list_obj.hasContent_():
return object_collection_list_obj
- #Checks for the existence of a named collection in the list
def has_collection(self, collection_name):
+ """Checks for the existence of a specific named Collection in the list, based on the its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return True
return False
- #Get a specific named collection in the list
def get_named_collection(self, collection_name):
+ """Return a specific named Collection from the list, based on its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return collection
return None
+
class CandidateIndicatorCollectionList(maec.EntityList):
- _contained_type = CandidateIndicatorCollection
_binding_class = bundle_binding.CandidateIndicatorCollectionListType
- _binding_var = "Candidate_Indicator_Collection"
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ candidate_indicator_collection = fields.TypedField("Candidate_Indicator_Collection", CandidateIndicatorCollection, multiple=True)
def __init__(self):
super(CandidateIndicatorCollectionList, self).__init__()
- def to_obj(self):
- candidate_indicator_collection_list_obj = bundle_binding.CandidateIndicatorCollectionListType()
+ def to_obj(self, ns_info=None):
+ candidate_indicator_collection_list_obj = super(CandidateIndicatorCollectionList, self).to_obj()
+
for candidate_indicator_collection in self:
if len(candidate_indicator_collection.candidate_indicator_list) > 0:
- candidate_indicator_collection_list_obj.add_Candidate_Indicator_Collection(candidate_indicator_collection.to_obj())
+ candidate_indicator_collection_list_obj.add_Candidate_Indicator_Collection(candidate_indicator_collection.to_obj(ns_info=ns_info))
if candidate_indicator_collection_list_obj.hasContent_():
return candidate_indicator_collection_list_obj
- #Checks for the existence of a named collection in the list
def has_collection(self, collection_name):
+ """Checks for the existence of a specific named Collection in the list, based on the its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return True
return False
- #Get a specific named collection in the list
def get_named_collection(self, collection_name):
+ """Return a specific named Collection from the list, based on its name."""
for collection in self:
if collection.name is not None and collection.name == collection_name:
return collection
return None
+
class Collections(maec.Entity):
- _namespace = maec.bundle._namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CollectionsType
+ _namespace = _namespace
+
+ behavior_collections = fields.TypedField("Behavior_Collections", BehaviorCollectionList)
+ action_collections = fields.TypedField("Action_Collections", ActionCollectionList)
+ object_collections = fields.TypedField("Object_Collections", ObjectCollectionList)
+ candidate_indicator_collections = fields.TypedField("Candidate_Indicator_Collections", CandidateIndicatorCollectionList)
def __init__(self):
super(Collections, self).__init__()
- self.behavior_collections = BehaviorCollectionList()
- self.action_collections = ActionCollectionList()
- self.object_collections = ObjectCollectionList()
- self.candidate_indicator_collections = CandidateIndicatorCollectionList()
- #Checks if the collections instance has any of its lists populated
+ def add_named_action_collection(self, action_collection_name, collection_id = None):
+ """Add a new named Action Collection to the Collections instance."""
+ if not self.action_collections:
+ self.action_collections = ActionCollectionList()
+ self.action_collections.append(ActionCollection(action_collection_name, collection_id))
+
+ def add_named_object_collection(self, object_collection_name, collection_id = None):
+ """Add a new named Object Collection to the Collections instance."""
+ if not self.object_collections:
+ self.object_collections = ObjectCollectionList()
+ self.object_collections.append(ObjectCollection(object_collection_name, collection_id))
+
+ def add_named_behavior_collection(self, behavior_collection_name, collection_id = None):
+ """Add a new named Behavior Collection to the Collections instance."""
+ if not self.behavior_collections:
+ self.behavior_collections = BehaviorCollectionList()
+ self.behavior_collections.append(BehaviorCollection(behavior_collection_name, collection_id))
+
+ def add_named_candidate_indicator_collection(self, candidate_indicator_collection_name, collection_id = None):
+ """Add a new named Candidate Indicator Collection to the Collections instance."""
+ if not self.candidate_indicator_collections:
+ self.candidate_indicator_collections = CandidateIndicatorCollectionList()
+ self.candidate_indicator_collections.append(CandidateIndicatorCollection(candidate_indicator_collection_name, collection_id))
+
def has_content(self):
- if len(self.behavior_collections) > 0:
+ """Returns true if any Collections instance inside of the Collection has len > 0."""
+ if self.behavior_collections and len(self.behavior_collections) > 0:
return True
- elif len(self.action_collections) > 0:
+ elif self.action_collections and len(self.action_collections) > 0:
return True
- elif len(self.object_collections) > 0:
+ elif self.object_collections and len(self.object_collections) > 0:
return True
- elif len(self.candidate_indicator_collections) > 0:
+ elif self.candidate_indicator_collections and len(self.candidate_indicator_collections) > 0:
return True
return False
- def to_obj(self):
- collections_obj = bundle_binding.CollectionsType()
- if self.behavior_collections: collections_obj.set_Behavior_Collections(self.behavior_collections.to_obj())
- if self.action_collections: collections_obj.set_Action_Collections(self.action_collections.to_obj())
- if self.object_collections: collections_obj.set_Object_Collections(self.object_collections.to_obj())
- if self.candidate_indicator_collections: collections_obj.set_Candidate_Indicator_Collections(self.candidate_indicator_collections.to_obj())
- return collections_obj
-
- def to_dict(self):
- collections_dict = {}
- if self.behavior_collections: collections_dict['behavior_collections'] = self.behavior_collections.to_list()
- if self.action_collections: collections_dict['action_collections'] = self.action_collections.to_list()
- if self.object_collections: collections_dict['object_collections'] = self.object_collections.to_list()
- if self.candidate_indicator_collections: collections_dict['candidate_indicator_collections'] = self.candidate_indicator_collections.to_list()
- return collections_dict
-
- @staticmethod
- def from_dict(collections_dict):
- if not collections_dict:
- return None
- collections_ = Collections()
- collections_.behavior_collections = BehaviorCollectionList.from_list(collections_dict.get('behavior_collections', []))
- collections_.action_collections = ActionCollectionList.from_list(collections_dict.get('action_collections', []))
- collections_.object_collections = ObjectCollectionList.from_list(collections_dict.get('object_collections', []))
- collections_.candidate_indicator_collections = CandidateIndicatorCollectionList.from_list(collections_dict.get('candidate_indicator_collections', []))
- return collections_
-
- @staticmethod
- def from_obj(collections_obj):
- if not collections_obj:
- return None
- collections_ = Collections()
- if collections_obj.get_Behavior_Collections() is not None:
- collections_.behavior_collections = BehaviorCollectionList.from_obj(collections_obj.get_Behavior_Collections())
- if collections_obj.get_Action_Collections() is not None:
- collections_.action_collections = ActionCollectionList.from_obj(collections_obj.get_Action_Collections())
- if collections_obj.get_Object_Collections() is not None:
- collections_.object_collections = ObjectCollectionList.from_obj(collections_obj.get_Object_Collections())
- if collections_obj.get_Candidate_Indicator_Collections() is not None:
- collections_.candidate_indicator_collections = CandidateIndicatorCollectionList.from_obj(collections_obj.get_Candidate_Indicator_Collections())
- return collections_
class BehaviorReference(maec.Entity):
_binding = bundle_binding
_binding_class = bundle_binding.BehaviorReferenceType
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+
+ behavior_idref = fields.TypedField('behavior_idref')
+
+
+class Bundle(maec.Entity):
+ _binding = bundle_binding
+ _namespace = _namespace
+ _binding_class = bundle_binding.BundleType
+
+ id_ = fields.TypedField("id")
+ schema_version = fields.TypedField("schema_version")
+ defined_subject = fields.TypedField("defined_subject")
+ content_type = fields.TypedField("content_type")
+ timestamp = fields.TypedField("timestamp")
+ malware_instance_object_attributes = fields.TypedField("Malware_Instance_Object_Attributes", Object)
+ av_classifications = fields.TypedField("AV_Classifications", AVClassifications)
+ actions = fields.TypedField("Actions", ActionList)
+ process_tree = fields.TypedField("Process_Tree", ProcessTree)
+ behaviors = fields.TypedField("Behaviors", BehaviorList)
+ capabilities = fields.TypedField("Capabilities", CapabilityList)
+ objects = fields.TypedField("Objects", ObjectList)
+ candidate_indicators = fields.TypedField("Candidate_Indicators", CandidateIndicatorList)
+ collections = fields.TypedField("Collections", Collections)
+
+ def __init__(self, id = None, defined_subject = False, schema_version = "4.1", content_type = None, malware_instance_object = None):
+ super(Bundle, self).__init__()
+ if id:
+ self.id_ = id
+ else:
+ self.id_ = idgen.create_id(prefix="bundle")
+ self.schema_version = schema_version
+ self.defined_subject = defined_subject
+ self.content_type = content_type
+ self.timestamp = None
+ self.malware_instance_object_attributes = malware_instance_object
+ self.__input_namespaces__ = {}
+ self.__input_schemalocations__ = {}
+
+ def set_malware_instance_object_attributes(self, malware_instance_object):
+ """Set the top-level Malware Instance Object Attributes entity in the Bundle."""
+ self.malware_instance_object_attributes = malware_instance_object
+
+ def add_av_classification(self, av_classification):
+ """Add an AV Classification to the top-level AV_Classifications entity in the Bundle."""
+ if not self.av_classifications:
+ self.av_classifications = AVClassifications()
+ self.av_classifications.append(av_classification)
+
+ def add_capability(self, capability):
+ """Add a Capability to the top-level Capabilities entity in the Bundle."""
+ if not self.capabilities:
+ self.capabilities = CapabilityList()
+ self.capabilities.capability.append(capability)
+
+ def set_process_tree(self, process_tree):
+ """Set the Process Tree, in the top-level element."""
+ self.process_tree = process_tree
+
+ def add_named_action_collection(self, collection_name, collection_id = None):
+ """Add a new named Action Collection to the top-level Collections entity in the Bundle."""
+ if not self.collections:
+ self.collections = Collections()
+ if collection_name is not None:
+ self.collections.add_named_action_collection(collection_name, collection_id)
+
+ def add_action(self, action, action_collection_name = None):
+ """Add an Action to an existing named Action Collection in the Collections entity.
+ If it does not exist, add it to the top-level Actions entity."""
+ if action_collection_name is not None and self.collections:
+ #The collection has already been defined
+ if self.collections.action_collections.has_collection(action_collection_name):
+ action_collection = self.collections.action_collections.get_named_collection(action_collection_name)
+ action_collection.add_action(action)
+ elif action_collection_name == None:
+ if not self.actions:
+ self.actions = ActionList()
+ self.actions.append(action)
+
+ def add_named_object_collection(self, collection_name, collection_id = None):
+ """Add a new named Object Collection to the Collections entity in the Bundle."""
+ if not self.collections:
+ self.collections = Collections()
+ if collection_name is not None:
+ self.collections.add_named_object_collection(collection_name, collection_id)
+
+ def get_all_actions(self, bin = False):
+ """Return a list of all Actions in the Bundle."""
+ all_actions = []
+
+ if self.actions:
+ for action in self.actions:
+ all_actions.append(action)
+
+ if self.collections and self.collections.action_collections:
+ for collection in self.collections.action_collections:
+ for action in collection.action_list:
+ all_actions.append(action)
+
+ if bin:
+ binned_actions = {}
+ for action in all_actions:
+ if action.name and action.name.value not in binned_actions:
+ binned_actions[action.name.value] = [action]
+ elif action.name and action.name.value in binned_actions:
+ binned_actions[action.name.value].append(action)
+ return binned_actions
+ else:
+ return all_actions
+
+ def get_all_actions_on_object(self, object):
+ """Return a list of all of the Actions in the Bundle that operate on a particular input Object."""
+ object_actions = []
+ if object.id_:
+ for action in self.get_all_actions():
+ associated_objects = action.associated_objects
+ if associated_objects:
+ for associated_object in associated_objects:
+ if associated_object.idref and associated_object.idref == object.id_:
+ object_actions.append(action)
+ elif associated_object.id_ and associated_object.id_ == object.id_:
+ object_actions.append(action)
+ return object_actions
+
+ def add_object(self, object, object_collection_name = None):
+ """Add an Object to an existing named Object Collection in the Collections entity.
+ If it does not exist, add it to the top-level Object entity."""
+ if object_collection_name is not None and self.collections:
+ #The collection has already been defined
+ if self.collections.object_collections.has_collection(object_collection_name):
+ object_collection = self.collections.object_collections.get_named_collection(object_collection_name)
+ object_collection.add_object(object)
+ elif object_collection_name == None:
+ if not self.objects:
+ self.objects = ObjectList()
+ self.objects.append(object)
+
+ def get_all_objects(self, include_actions = False):
+ """Return a list of all Objects in the Bundle."""
+ all_objects = []
+
+ if self.objects:
+ for obj in self.objects:
+ all_objects.append(obj)
+ if obj.related_objects:
+ for related_obj in obj.related_objects:
+ all_objects.append(related_obj)
+
+ if self.collections and self.collections.object_collections:
+ for collection in self.collections.object_collections:
+ for obj in collection.object_list:
+ all_objects.append(obj)
+ if obj.related_objects:
+ for related_obj in obj.related_objects:
+ all_objects.append(related_obj)
+
+ # Include Objects in Actions, if include_actions flag is specified
+ if include_actions:
+ for action in self.get_all_actions():
+ associated_objects = action.associated_objects
+ if associated_objects:
+ for associated_object in associated_objects:
+ all_objects.append(associated_object)
+ if associated_object.related_objects:
+ for related_obj in associated_object.related_objects:
+ all_objects.append(related_obj)
+
+ # Add the Object corresponding to the Malware Instance Object Attributes, if specified
+ if self.malware_instance_object_attributes:
+ all_objects.append(self.malware_instance_object_attributes)
+
+ return all_objects
+
+ def get_all_multiple_referenced_objects(self):
+ """Return a list of all Objects in the Bundle that are referenced more than once."""
+ idref_list = [x.idref for x in self.get_all_objects() if x.idref]
+ return [self.get_object_by_id(x) for x in idref_list if self.get_object_by_id(x)]
+
+ def get_all_non_reference_objects(self):
+ """Return a list of all Objects in the Bundle that are not references (i.e. all of the actual Objects in the Bundle)."""
+ return [x for x in self.get_all_objects(True) if x.id_ and not x.idref]
+
+ def get_object_by_id(self, id, extra_objects = [], ignore_actions = False):
+ """Find and return the Entity (Action, Object, etc.) with the specified ID."""
+ if not ignore_actions:
+ if self.actions:
+ for action in self.actions:
+ if action.id_ == id:
+ return action
+
+ if action.associated_objects:
+ for associated_obj in action.associated_objects:
+ if associated_obj.id_ == id:
+ return associated_obj
+ if self.collections and self.collections.action_collections:
+ for collection in self.collections.action_collections:
+ for action in collection.action_list:
+ if action.id_ == id:
+ return action
+
+ if action.associated_objects:
+ for associated_obj in action.associated_objects:
+ if associated_obj.id_ == id:
+ return associated_obj
+ if self.objects:
+ for obj in self.objects:
+ if obj.id_ == id:
+ return obj
+
+ if self.collections and self.collections.object_collections:
+ for collection in self.collections.object_collections:
+ for obj in collection.object_list:
+ if obj.id_ == id:
+ return obj
+
+ # Test the extra_objects Array
+ for obj in extra_objects:
+ if obj.id_ == id:
+ return obj
+
+ def add_named_behavior_collection(self, collection_name, collection_id = None):
+ """Add a new named Behavior Collection to the Collections entity in the Bundle."""
+ if not self.collections:
+ self.collections = Collections()
+ if collection_name is not None:
+ self.collections.add_named_behavior_collection(collection_name, collection_id)
+
+ def add_behavior(self, behavior, behavior_collection_name = None):
+ """Add a Behavior to an existing named Behavior Collection in the Collections entity.
+ If it does not exist, add it to the top-level Behaviors entity."""
+ if behavior_collection_name is not None and self.collections:
+ #The collection has already been defined
+ if self.collections.behavior_collections.has_collection(behavior_collection_name):
+ behavior_collection = self.collections.behavior_collections.get_named_collection(behavior_collection_name)
+ behavior_collection.add_behavior(behavior)
+ elif behavior_collection_name == None:
+ if not self.behaviors:
+ self.behaviors = BehaviorList()
+ self.behaviors.append(behavior)
+
+ def add_named_candidate_indicator_collection(self, collection_name, collection_id = None):
+ """Add a new named Candidate Indicator Collection to the Collections entity in the Bundle."""
+ if not self.collections:
+ self.collections = Collections()
+ if collection_name is not None:
+ self.collections.add_named_candidate_indicator_collection(collection_name, collection_id)
+
+ def add_candidate_indicator(self, candidate_indicator, candidate_indicator_collection_name = None):
+ """Add a Candidate Indicator to an existing named Candidate Indicator Collection in the Collections entity.
+ If it does not exist, add it to the top-level Candidate Indicators entity."""
+ if candidate_indicator_collection_name is not None and self.collections:
+ #The collection has already been defined
+ if self.collections.candidate_indicator_collections.has_collection(candidate_indicator_collection_name):
+ candidate_indicator_collection = self.collections.candidate_indicator_collections.get_named_collection(candidate_indicator_collection_name)
+ candidate_indicator_collection.add_candidate_indicator(candidate_indicator)
+ elif candidate_indicator_collection_name == None:
+ if not self.candidate_indicators:
+ self.candidate_indicators = CandidateIndicatorList()
+ self.candidate_indicators.append(candidate_indicator)
- behavior_idref = maec.TypedField('behavior_idref')
\ No newline at end of file
+ def deduplicate(self):
+ """Deduplicate all Objects in the Bundle.
+ Add duplicate Objects to new "Deduplicated Objects" Object Collection,
+ and replace duplicate entries with references to corresponding Object."""
+ BundleDeduplicator.deduplicate(self)
+
+ def get_action_objects(self, action_name_list):
+ """Get all Objects corresponding to one or more types of Actions, specified via a list of Action names."""
+ action_objects = {}
+ all_actions = self.get_all_actions(bin=True)
+ for action_name in action_name_list:
+ if action_name in all_actions:
+ associated_objects = []
+ associated_object_lists = [[y for y in x.associated_objects if x.associated_objects] for x in all_actions[action_name]]
+ for associated_object_list in associated_object_lists:
+ associated_objects += associated_object_list
+ action_objects[action_name] = associated_objects
+ return action_objects
+
+ def get_object_history(self):
+ """Build and return the Object history for the Bundle."""
+ return ObjectHistory.build(self)
+
+ def normalize_objects(self):
+ """Normalize all Objects in the Bundle, using the CybOX normalize module."""
+ all_objects = self.get_all_objects(include_actions = True)
+ for object in all_objects:
+ if object.properties:
+ normalize_object_properties(object.properties)
+
+ def dereference_objects(self, extra_objects = []):
+ """Dereference any Objects in the Bundle by replacing them with the entities they reference."""
+ all_objects = self.get_all_objects(include_actions=True)
+ # Add any extra objects that were passed, e.g. from a Malware Subject
+ all_objects = all_objects + extra_objects
+ for object in all_objects:
+ if object.idref and not object.id_:
+ real_object = self.get_object_by_id(object.idref, extra_objects, ignore_actions = True)
+ if real_object:
+ object.idref = None
+ object.id_ = real_object.id_
+ object.properties = real_object.properties
+
+ @classmethod
+ def compare(cls, bundle_list, match_on = None, case_sensitive = True):
+ """Compare the Bundle to a list of other Bundles, returning a BundleComparator object."""
+ return BundleComparator.compare(bundle_list, match_on, case_sensitive)
diff --git a/maec/bundle/bundle_reference.py b/maec/bundle/bundle_reference.py
index 39ea59f..fc1806e 100644
--- a/maec/bundle/bundle_reference.py
+++ b/maec/bundle/bundle_reference.py
@@ -1,44 +1,21 @@
#MAEC Bundle Reference Class
-#Copyright (c) 2014, The MITRE Corporation
+#Copyright (c) 2018, The MITRE Corporation
#All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
import maec
+from . import _namespace
import maec.bindings.maec_bundle as bundle_binding
-
+
class BundleReference(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.BundleReferenceType
+
+ bundle_idref = fields.TypedField("bundle_idref")
- def init(self, bundle_idref = None):
+ def __init__(self, bundle_idref = None):
super(BundleReference, self).__init__()
self.bundle_idref = bundle_idref
-
- def to_obj(self):
- bundle_reference_obj = bundle_binding.BundleReferenceType()
- if self.bundle_idref is not None : bundle_reference_obj.set_bundle_idref(self.bundle_idref)
- return bundle_reference_obj
-
- def to_dict(self):
- bundle_reference_dict = {}
- if self.bundle_idref is not None : bundle_reference_dict['bundle_idref'] = self.bundle_idref
- return bundle_reference_dict
-
- @staticmethod
- def from_dict(bundle_reference_dict):
- if not bundle_reference_dict:
- return None
- bundle_reference_ = BundleReference()
- bundle_reference_.bundle_idref = bundle_reference_dict.get('bundle_idref')
- return bundle_reference_
-
- @staticmethod
- def from_obj(bundle_reference_obj):
- if not bundle_reference_obj:
- return None
- bundle_reference_ = BundleReference()
- bundle_reference_.bundle_idref = bundle_reference_obj.get_bundle_idref()
- return bundle_reference_
-
\ No newline at end of file
diff --git a/maec/bundle/candidate_indicator.py b/maec/bundle/candidate_indicator.py
index 2cd9d52..5c23574 100644
--- a/maec/bundle/candidate_indicator.py
+++ b/maec/bundle/candidate_indicator.py
@@ -1,225 +1,71 @@
-#MAEC Candidate Indicator Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-import maec
-import maec.bindings.maec_bundle as bundle_binding
-from maec.bundle.object_reference import ObjectReference
-from maec.bundle.behavior_reference import BehaviorReference
-from cybox.common import VocabString
-from cybox.core import ActionReference
-
-class CandidateIndicator(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self, id = None):
- super(CandidateIndicator, self).__init__()
- if id:
- self.id = id
- else:
- self.id = maec.utils.idgen.create_id(prefix="candidate_indicator")
- self.creation_datetime = None
- self.lastupdate_datetime = None
- self.version = None
- self.importance = None
- self.numeric_importance = None
- self.author = None
- self.description = None
- self.malware_entity = None
- self.composition = None
-
- def to_obj(self):
- candidate_indicator_obj = bundle_binding.CandidateIndicatorType()
- if self.id is not None : candidate_indicator_obj.set_id(self.id)
- if self.creation_datetime is not None : candidate_indicator_obj.set_creation_datetime(self.creation_datetime)
- if self.version is not None : candidate_indicator_obj.set_version(self.version)
- if self.importance is not None : candidate_indicator_obj.set_Importance(self.importance.to_obj())
- if self.numeric_importance is not None : candidate_indicator_obj.set_Numeric_Importance(self.numeric_importance)
- if self.author is not None : candidate_indicator_obj.set_Numeric_Importance(self.author)
- if self.description is not None : candidate_indicator_obj.set_Description(self.description)
- if self.malware_entity is not None : candidate_indicator_obj.set_Malware_Entity(self.malware_entity.to_obj())
- if self.composition is not None : candidate_indicator_obj.set_Composition(self.composition.to_obj())
- return candidate_indicator_obj
-
- def to_dict(self):
- candidate_indicator_dict = {}
- if self.id is not None : candidate_indicator_dict['id'] = self.id
- if self.creation_datetime is not None : candidate_indicator_dict['creation_datetime'] = self.creation_datetime
- if self.version is not None : candidate_indicator_dict['version'] = self.version
- if self.importance is not None : candidate_indicator_dict['importance'] = self.importance.to_dict()
- if self.numeric_importance is not None : candidate_indicator_dict['numeric_importance'] = self.numeric_importance
- if self.author is not None : candidate_indicator_dict['author'] = self.author
- if self.description is not None : candidate_indicator_dict['description'] = self.description
- if self.malware_entity is not None : candidate_indicator_dict['malware_entity'] = self.malware_entity.to_dict()
- if self.composition is not None : candidate_indicator_dict['composition'] = self.composition.to_dict()
- return candidate_indicator_dict
-
- @staticmethod
- def from_dict(candidate_indicator_dict):
- if not candidate_indicator_dict:
- return None
- candidate_indicator_ = CandidateIndicator()
- candidate_indicator_.id = candidate_indicator_dict.get('id')
- candidate_indicator_.creation_datetime = candidate_indicator_dict.get('creation_datetime')
- candidate_indicator_.version = candidate_indicator_dict.get('version')
- candidate_indicator_.importance = VocabString.from_dict(candidate_indicator_dict.get('importance'))
- candidate_indicator_.numeric_importance = candidate_indicator_dict.get('numeric_importance')
- candidate_indicator_.author = candidate_indicator_dict.get('author')
- candidate_indicator_.description = candidate_indicator_dict.get('description')
- candidate_indicator_.malware_entity = MalwareEntity.from_dict(candidate_indicator_dict.get('malware_entity'))
- candidate_indicator_.composition = CandidateIndicatorComposition.from_dict(candidate_indicator_dict.get('composition'))
- return candidate_indicator_
-
- @staticmethod
- def from_obj(candidate_indicator_obj):
- if not candidate_indicator_obj:
- return None
- candidate_indicator_ = CandidateIndicator()
- candidate_indicator_.id = candidate_indicator_obj.get_id()
- candidate_indicator_.creation_datetime = candidate_indicator_obj.get_creation_datetime()
- candidate_indicator_.version = candidate_indicator_obj.get_version()
- candidate_indicator_.importance = VocabString.from_obj(candidate_indicator_obj.get_Importance())
- candidate_indicator_.numeric_importance = candidate_indicator_obj.get_Numeric_Importance()
- candidate_indicator_.author = candidate_indicator_obj.get_Author()
- candidate_indicator_.description = candidate_indicator_obj.get_Description()
- candidate_indicator_.malware_entity = MalwareEntity.from_obj(candidate_indicator_obj.get_Malware_Entity())
- candidate_indicator_.composition = CandidateIndicatorComposition.from_obj(candidate_indicator_obj.get_Composition())
- return candidate_indicator_
-
-class MalwareEntity(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self):
- super(MalwareEntity, self).__init__()
- self.type = None
- self.name = None
- self.description = None
-
- def to_obj(self):
- malware_entity_obj = bundle_binding.MalwareEntityType()
- if self.type is not None : malware_entity_obj.set_Type(self.type.to_obj())
- if self.name is not None : malware_entity_obj.set_Name(self.name)
- if self.description is not None : malware_entity_obj.set_Description(self.description)
- return malware_entity_obj
-
- def to_dict(self):
- malware_entity_dict = {}
- if self.type is not None : malware_entity_dict['type'] = self.type.to_dict()
- if self.name is not None : malware_entity_dict['name'] = self.name
- if self.description is not None : malware_entity_dict['description'] = self.description
- return malware_entity_dict
-
- @staticmethod
- def from_dict(malware_entity_dict):
- if not malware_entity_dict:
- return None
- malware_entity_ = MalwareEntity()
- malware_entity_.type = VocabString.from_dict(malware_entity_dict.get('type'))
- malware_entity_.name = malware_entity_dict.get('name')
- malware_entity_.description = malware_entity_dict.get('description')
- return malware_entity_
-
- @staticmethod
- def from_obj(malware_entity_obj):
- if not malware_entity_obj:
- return None
- malware_entity_ = MalwareEntity()
- malware_entity_.type = VocabString.from_obj(malware_entity_obj.get_Type())
- malware_entity_.name = malware_entity_obj.get_Name()
- malware_entity_.description = malware_entity_obj.get_Description()
- return malware_entity_
-
-class CandidateIndicatorComposition(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self):
- super(CandidateIndicatorComposition, self).__init__()
- self.operator = None
- self.behavior_references = []
- self.action_references = []
- self.object_references = []
- self.sub_compositions = []
-
- def to_obj(self):
- candidate_indc_comp_obj = bundle_binding.CandidateIndicatorCompositionType()
- if self.operator is not None : candidate_indc_comp_obj.set_operator(self.operator)
- if len(self.behavior_references) > 0:
- for behavior_reference in self.behavior_references: candidate_indc_comp_obj.add_Behavior_Reference(behavior_reference.to_obj())
- if len(self.action_references) > 0:
- for action_reference in self.action_references: candidate_indc_comp_obj.add_Action_Reference(action_reference.to_obj())
- if len(self.object_references) > 0:
- for object_reference in self.object_references: candidate_indc_comp_obj.add_Object_Reference(object_reference.to_obj())
- if len(self.sub_compositions) > 0:
- for sub_composition in self.sub_compositions: candidate_indc_comp_obj.add_Sub_Composition(sub_composition.to_obj())
- return candidate_indc_comp_obj
-
- def to_dict(self):
- candidate_indc_comp_dict = {}
- if self.operator is not None : candidate_indc_comp_dict['operator'] = self.operator
- if len(self.behavior_references) > 0:
- behavior_reference_list = []
- for behavior_reference in self.behavior_references: behavior_reference_list.append(behavior_reference.to_dict())
- candidate_indc_comp_dict['behavior_references'] = behavior_reference_list
- if len(self.action_references) > 0:
- action_reference_list = []
- for action_reference in self.action_references: action_reference_list.append(action_reference.to_dict())
- candidate_indc_comp_dict['action_references'] = action_reference_list
- if len(self.object_references) > 0:
- object_reference_list = []
- for object_reference in self.object_references: object_reference_list.append(object_reference.to_dict())
- candidate_indc_comp_dict['object_references'] = object_reference_list
- if len(self.sub_compositions) > 0:
- sub_composition_list = []
- for sub_composition in self.sub_compositions: sub_composition_list.append(sub_composition.to_dict())
- candidate_indc_comp_dict['sub_compositions'] = sub_composition_list
- return candidate_indc_comp_dict
-
- @staticmethod
- def from_dict(candidate_indc_comp_dict):
- if not candidate_indc_comp_dict:
- return None
- candidate_indicator_composition_ = CandidateIndicatorComposition()
- candidate_indicator_composition_.operator = candidate_indc_comp_dict.get('operator')
- if candidate_indc_comp_dict.get('behavior_references') is not None:
- for behavior_reference_dict in candidate_indc_comp_dict.get('behavior_references'):
- candidate_indicator_composition_.behavior_references.append(BehaviorReference.from_dict(behavior_reference_dict))
- if candidate_indc_comp_dict.get('action_references') is not None:
- for action_reference_dict in candidate_indc_comp_dict.get('action_references'):
- candidate_indicator_composition_.action_references.append(ActionReference.from_dict(action_reference_dict))
- if candidate_indc_comp_dict.get('object_references') is not None:
- for object_reference_dict in candidate_indc_comp_dict.get('object_references'):
- candidate_indicator_composition_.object_references.append(ObjectReference.from_dict(object_reference_dict))
- if candidate_indc_comp_dict.get('sub_compositions') is not None:
- for sub_composition_dict in candidate_indc_comp_dict.get('sub_compositions'):
- candidate_indicator_composition_.sub_compositions.append(CandidateIndicatorComposition.from_dict(sub_composition_dict))
- return candidate_indicator_composition_
-
- @staticmethod
- def from_obj(candidate_indc_comp_obj):
- if not candidate_indc_comp_obj:
- return None
- candidate_indicator_composition_ = CandidateIndicatorComposition()
- candidate_indicator_composition_.operator = candidate_indc_comp_obj.get_operator()
- if len(candidate_indc_comp_obj.get_Behavior_Reference()) > 0:
- for behavior_reference_obj in candidate_indc_comp_obj.get_Behavior_Reference():
- candidate_indicator_composition_.behavior_references.append(BehaviorReference.from_obj(behavior_reference_obj))
- if len(candidate_indc_comp_obj.get_Action_Reference()) > 0:
- for action_reference_obj in candidate_indc_comp_obj.get_Action_Reference():
- candidate_indicator_composition_.action_references.append(ActionReference.from_obj(action_reference_obj))
- if len(candidate_indc_comp_obj.get_Object_Reference()) > 0:
- for object_reference_obj in candidate_indc_comp_obj.get_Object_Reference():
- candidate_indicator_composition_.object_references.append(ObjectReference.from_obj(object_reference_obj))
- if len(candidate_indc_comp_obj.get_Sub_Composition()) > 0:
- for sub_composition_obj in candidate_indc_comp_obj.get_Sub_Composition():
- candidate_indicator_composition_.sub_compositions.append(CandidateIndicatorComposition.from_obj(sub_composition_obj))
- return candidate_indicator_composition_
-
-class CandidateIndicatorList(maec.EntityList):
- _contained_type = CandidateIndicator
- _binding_class = bundle_binding.CandidateIndicatorListType
- _binding_var = "Candidate_Indicator"
- _namespace = maec.bundle._namespace
\ No newline at end of file
+# MAEC Candidate Indicator Class
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from mixbox import fields
+from mixbox import idgen
+
+import maec
+from . import _namespace
+import maec.bindings.maec_bundle as bundle_binding
+from maec.bundle import ObjectReference, BehaviorReference
+from cybox.common import VocabString
+from cybox.core import ActionReference
+
+class MalwareEntity(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.MalwareEntityType
+ _namespace = _namespace
+
+ type_ = fields.TypedField("Type", VocabString)
+ name = fields.TypedField("Name")
+ description = fields.TypedField("Description")
+
+ def __init__(self):
+ super(MalwareEntity, self).__init__()
+
+class CandidateIndicatorComposition(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CandidateIndicatorCompositionType
+ _namespace = _namespace
+
+ operator = fields.TypedField("operator")
+ behavior_reference = fields.TypedField("Behavior_Reference", BehaviorReference, multiple = True)
+ action_reference = fields.TypedField("Action_Reference", ActionReference, multiple = True)
+ object_reference = fields.TypedField("Object_Reference", ObjectReference, multiple = True)
+ sub_composition = fields.TypedField("Sub_Composition", multiple = True)
+
+ def __init__(self):
+ super(CandidateIndicatorComposition, self).__init__()
+
+# Allow recursive definition of CandidateIndicatorCompositions
+CandidateIndicatorComposition.sub_composition.type_ = CandidateIndicatorComposition
+
+class CandidateIndicator(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CandidateIndicatorType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ creation_datetime = fields.TypedField("creation_datetime")
+ lastupdate_datetime = fields.TypedField("lastupdate_datetime")
+ version = fields.TypedField("version")
+ importance = fields.TypedField("Importance", VocabString)
+ numeric_importance = fields.TypedField("Numeric_Importance")
+ author = fields.TypedField("Author")
+ description = fields.TypedField("Description")
+ malware_entity = fields.TypedField("Malware_Entity", MalwareEntity)
+ composition = fields.TypedField("Composition", CandidateIndicatorComposition)
+
+ def __init__(self, id = None):
+ super(CandidateIndicator, self).__init__()
+ if id:
+ id_ = id
+ else:
+ id_ = idgen.create_id(prefix="candidate_indicator")
+
+class CandidateIndicatorList(maec.EntityList):
+ _binding_class = bundle_binding.CandidateIndicatorListType
+ _namespace = _namespace
+ candidate_indicator = fields.TypedField("Candidate_Indicator", CandidateIndicator, multiple=True)
diff --git a/maec/bundle/capability.py b/maec/bundle/capability.py
index 481691f..86a9ac9 100644
--- a/maec/bundle/capability.py
+++ b/maec/bundle/capability.py
@@ -1,429 +1,142 @@
-#MAEC Capability Class
+# MAEC Capability Classes
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
+from mixbox import idgen
import maec
+from . import _namespace
import maec.bindings.maec_bundle as bundle_binding
-from maec.bundle.behavior_reference import BehaviorReference
+from maec.bundle import BehaviorReference
from cybox.common import VocabString, String
+
class CapabilityObjectiveReference(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityObjectiveReferenceType
+
+ objective_idref = fields.TypedField("objective_idref")
def __init__(self):
super(CapabilityObjectiveReference, self).__init__()
- self.objective_idref = None
-
- def to_obj(self):
- capability_objective_reference_obj = bundle_binding.CapabilityObjectiveReferenceType()
- if self.objective_idref is not None: capability_objective_reference_obj.set_objective_idref(self.objective_idref)
- return capability_objective_reference_obj
-
- def to_dict(self):
- capability_objective_reference_dict = {}
- if self.objective_idref is not None: capability_objective_reference_dict['objective_idref'] = self.objective_idref
- return capability_objective_reference_dict
-
- @staticmethod
- def from_obj(capability_objective_reference_obj):
- if not capability_objective_reference_obj:
- return None
- capability_objective_reference_ = CapabilityObjectiveReference()
- capability_objective_reference_.objective_idref = capability_objective_reference_obj.get_objective_idref()
- return capability_objective_reference_
-
- @staticmethod
- def from_dict(capability_objective_reference_dict):
- if not capability_objective_reference_dict:
- return None
- capability_objective_reference_ = CapabilityObjectiveReference()
- capability_objective_reference_.objective_idref = capability_objective_reference_dict['objective_idref']
- return capability_objective_reference_
+
class CapabilityReference(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityReferenceType
+
+ capability_idref = fields.TypedField("capability_idref")
def __init__(self):
super(CapabilityReference, self).__init__()
- self.capability_idref = None
-
- def to_obj(self):
- capability_reference_obj = bundle_binding.CapabilityReferenceType()
- if self.capability_idref is not None: capability_reference_obj.set_capability_idref(self.capability_idref)
- return capability_reference_obj
-
- def to_dict(self):
- capability_reference_dict = {}
- if self.capability_idref is not None: capability_reference_dict['capability_idref'] = self.capability_idref
- return capability_reference_dict
-
- @staticmethod
- def from_obj(capability_reference_obj):
- if not capability_reference_obj:
- return None
- capability_reference_ = CapabilityReference()
- capability_reference_.capability_idref = capability_reference_obj.get_capability_idref()
- return capability_reference_
-
- @staticmethod
- def from_dict(capability_reference_dict):
- if not capability_reference_dict:
- return None
- capability_reference_ = CapabilityReference()
- capability_reference_.capability_idref = capability_reference_dict['capability_idref']
- return capability_reference_
+
class CapabilityObjectiveRelationship(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityObjectiveRelationshipType
+
+ relationship_type = fields.TypedField("Relationship_Type", VocabString)
+ objective_reference = fields.TypedField("Objective_Reference", CapabilityObjectiveReference, multiple=True)
def __init__(self):
super(CapabilityObjectiveRelationship, self).__init__()
- self.relationship_type = None
self.objective_reference = []
- def to_obj(self):
- capability_obj_rel_obj = bundle_binding.CapabilityObjectiveRelationshipType()
- if self.relationship_type is not None: capability_obj_rel_obj.set_Relationship_Type(self.relationship_type.to_obj())
- if self.objective_reference is not None:
- for objective_ref in self.objective_reference:
- capability_obj_rel_obj.add_Objective_Reference(objective_ref.to_obj())
- return capability_obj_rel_obj
-
- def to_dict(self):
- capability_obj_rel_dict = {}
- if self.relationship_type is not None: capability_obj_rel_dict['relationship_type'] = self.relationship_type.to_dict()
- if self.objective_reference is not None:
- capability_obj_rel_dict['objective_reference'] = [x.to_dict() for x in self.objective_reference]
- return capability_obj_rel_dict
-
- @staticmethod
- def from_obj(capability_obj_rel_obj):
- if not capability_obj_rel_obj:
- return None
- capability_obj_rel_ = CapabilityObjectiveRelationship()
- capability_obj_rel_.relationship_type = VocabString.from_obj(capability_obj_rel_obj.get_Relationship_Type())
- if capability_obj_rel_obj.get_Objective_Reference():
- capability_obj_rel_.objective_reference = [CapabilityObjectiveReference.from_obj(x) for x in capability_obj_rel_obj.get_Objective_Reference()]
- return capability_obj_rel_
-
- @staticmethod
- def from_dict(capability_obj_rel_dict):
- if not capability_obj_rel_dict:
- return None
- capability_obj_rel_ = CapabilityRelationship()
- capability_obj_rel_.relationship_type = VocabString.from_dict(capability_obj_rel_dict['relationship_type'])
- if capability_obj_rel_dict['objective_reference']:
- capability_obj_rel_.objective_reference = [CapabilityObjectiveReference.from_dict(x) for x in capability_obj_rel_dict['objective_reference']]
- return capability_obj_rel_
class CapabilityRelationship(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityRelationshipType
+
+ relationship_type = fields.TypedField("Relationship_Type", VocabString)
+ capability_reference = fields.TypedField("Capability_Reference", CapabilityReference, multiple=True)
def __init__(self):
super(CapabilityRelationship, self).__init__()
- self.relationship_type = None
self.capability_reference = []
- def to_obj(self):
- capability_rel_obj = bundle_binding.CapabilityRelationshipType()
- if self.relationship_type is not None: capability_rel_obj.set_Relationship_Type(self.relationship_type.to_obj())
- if self.capability_reference is not None:
- for capability_ref in self.capability_reference:
- capability_rel_obj.add_Capability_Reference(capability_ref.to_obj())
- return capability_rel_obj
-
- def to_dict(self):
- capability_rel_dict = {}
- if self.relationship_type is not None: capability_rel_dict['relationship_type'] = self.relationship_type.to_dict()
- if self.capability_reference is not None:
- capability_rel_dict['capability_reference'] = [x.to_dict() for x in self.capability_reference]
- return capability_rel_dict
-
- @staticmethod
- def from_obj(capability_rel_obj):
- if not capability_rel_obj:
- return None
- capability_rel_ = CapabilityRelationship()
- capability_rel_.relationship_type = VocabString.from_obj(capability_rel_obj.get_Relationship_Type())
- if capability_rel_obj.get_Capability_Reference():
- capability_rel_.capability_reference = [CapabilityReference.from_obj(x) for x in capability_rel_obj.get_Capability_Reference()]
- return capability_rel_
-
- @staticmethod
- def from_dict(capability_rel_dict):
- if not capability_rel_dict:
- return None
- capability_rel_ = CapabilityRelationship()
- capability_rel_.relationship_type = VocabString.from_dict(capability_rel_dict['relationship_type'])
- if capability_rel_dict['capability_reference']:
- capability_rel_.capability_reference = [CapabilityReference.from_dict(x) for x in capability_rel_dict['capability_reference']]
- return capability_rel_
-
-class CapabilityObjective(maec.Entity):
- _namespace = maec.bundle._namespace
- def __init__(self):
- super(CapabilityObjective, self).__init__()
- self.id_ = maec.utils.idgen.create_id(prefix="capability_objective")
- self.name = None
- self.description = None
- self.property = []
- self.behavior_reference = []
- self.relationship = []
-
- def to_obj(self):
- capability_objective_obj = bundle_binding.CapabilityObjectiveType()
- if self.id_ is not None: capability_objective_obj.set_id(self.id_)
- if self.name is not None: capability_objective_obj.set_Name(self.name.to_obj())
- if self.description is not None: capability_objective_obj.set_Description(self.description.to_obj())
- if self.property:
- for prop in self.property:
- capability_objective_obj.add_Property(prop.to_obj())
- if self.behavior_reference:
- for behavior_ref in self.behavior_reference:
- capability_objective_obj.add_Behavior_Reference(behavior_ref.to_obj())
- if self.relationship:
- for rel in self.relationship:
- capability_objective_obj.add_Relationship(rel.to_obj())
- return capability_objective_obj
-
- def to_dict(self):
- capability_objective_dict = {}
- if self.id_ is not None: capability_objective_dict['id'] = self.id_
- if self.name is not None: capability_objective_dict['name'] = self.name.to_dict()
- if self.description is not None: capability_objective_dict['description'] = self.description
- if self.property:
- capability_objective_dict['property'] = [x.to_dict() for x in self.property]
- if self.behavior_reference:
- capability_objective_dict['behavior_reference'] = [x.to_dict() for x in self.behavior_reference]
- if self.relationship:
- capability_objective_dict['relationship'] = [x.to_dict() for x in self.relationship]
-
- return capability_objective_dict
-
- @staticmethod
- def from_obj(capability_objective_obj):
- if not capability_objective_obj:
- return None
- capability_objective_ = CapabilityObjective()
- if capability_objective_obj.get_id(): capability_objective_.id_ = capability_objective_obj.get_id()
- capability_objective_.name = VocabString.from_obj(capability_objective_obj.get_Name())
- capability_objective_.description = capability_objective_obj.get_Description()
- if capability_objective_obj.get_Property():
- capability_objective_.property = [CapabilityProperty.from_obj(x) for x in capability_objective_obj.get_Property()]
- if capability_objective_obj.get_Behavior_Reference():
- capability_objective_.behavior_reference = [BehaviorReference.from_obj(x) for x in capability_objective_obj.get_Behavior_Reference()]
- if capability_objective_obj.get_Relationship():
- capability_objective_.relationship = [CapabilityObjectiveRelationship.from_obj(x) for x in capability_objective_obj.get_Relationship()]
- return capability_objective_
-
- @staticmethod
- def from_dict(capability_objective_dict):
- if not capability_objective_dict:
- return None
- capability_objective_ = CapabilityObjective()
- if capability_objective_dict.get('id'): capability_objective_.id_ = capability_objective_dict.get('id')
- capability_objective_.name = VocabString.from_dict(capability_objective_dict.get('name'))
- capability_objective_.description = capability_objective_dict.get('description')
- if capability_objective_dict.get('property'):
- capability_objective_.property = [CapabilityProperty.from_dict(x) for x in capability_objective_dict.get('property')]
- if capability_objective_dict.get('behavior_reference'):
- capability_objective_.behavior_reference = [BehaviorReference.from_dict(x) for x in capability_objective_dict.get('behavior_reference')]
- if capability_objective_dict.get('relationship'):
- capability_objective_.relationship = [CapabilityObjectiveRelationship.from_dict(x) for x in capability_objective_dict.get('relationship')]
- return capability_objective_
-
class CapabilityProperty(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityPropertyType
+
+ name = fields.TypedField("Name", VocabString)
+ value = fields.TypedField("Value", String)
def __init__(self):
super(CapabilityProperty, self).__init__()
- self.name = None
- self.value = None
-
- def to_obj(self):
- capability_property_obj = bundle_binding.CapabilityPropertyType()
- if self.name is not None: capability_property_obj.set_Name(self.name.to_obj())
- if self.value is not None: capability_property_obj.set_Value(self.value.to_obj())
- return capability_property_obj
-
- def to_dict(self):
- capability_property_dict = {}
- if self.name is not None: capability_property_dict['name'] = self.name.to_dict()
- if self.value is not None: capability_property_dict['value'] = self.value.to_dict()
- return capability_property_dict
-
- @staticmethod
- def from_obj(capability_property_obj):
- if not capability_property_obj:
- return None
- capability_property_ = CapabilityProperty()
- capability_property_.name = VocabString.from_obj(capability_property_obj.get_Name())
- capability_property_.value = String.from_obj(capability_property_obj.get_Value())
- return capability_property_
-
- @staticmethod
- def from_dict(capability_property_dict):
- if not capability_property_dict:
- return None
- capability_property_ = CapabilityProperty()
- capability_property_.name = VocabString.from_dict(capability_property_dict['name'])
- capability_property_.value = String.from_dict(capability_property_dict['value'])
- return capability_property_
-class Capability(maec.Entity):
- _namespace = maec.bundle._namespace
- def __init__(self, id = None, name = None):
+class CapabilityObjective(maec.Entity):
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityObjectiveType
+
+ id_ = fields.TypedField("id")
+ name = fields.TypedField("Name", VocabString)
+ description = fields.TypedField("Description")
+ property = fields.TypedField("Property", CapabilityProperty, multiple=True)
+ behavior_reference = fields.TypedField("Behavior_Reference", BehaviorReference, multiple=True)
+ relationship = fields.TypedField("Relationship", CapabilityObjectiveRelationship, multiple=True)
+
+ def __init__(self, id=None):
+ super(CapabilityObjective, self).__init__()
+ if id:
+ self.id_ = id
+ else:
+ self.id_ = idgen.create_id(prefix="capability_objective")
+
+
+class Capability(maec.Entity):
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityType
+
+ id_ = fields.TypedField("id")
+ name = fields.TypedField("name")
+ description = fields.TypedField("Description")
+ property = fields.TypedField("Property", CapabilityProperty, multiple=True)
+ strategic_objective = fields.TypedField("Strategic_Objective", CapabilityObjective, multiple=True)
+ tactical_objective = fields.TypedField("Tactical_Objective", CapabilityObjective, multiple=True)
+ behavior_reference = fields.TypedField("Behavior_Reference", BehaviorReference, multiple=True)
+ relationship = fields.TypedField("Relationship", CapabilityRelationship, multiple=True)
+
+ def __init__(self, id=None, name=None):
super(Capability, self).__init__()
if id:
self.id_ = id
else:
- self.id_ = maec.utils.idgen.create_id(prefix="capability")
+ self.id_ = idgen.create_id(prefix="capability")
self.name = name
- self.description = None
- self.property = []
- self.strategic_objective = []
- self.tactical_objective = []
- self.behavior_reference = []
- self.relationship = []
def add_tactical_objective(self, tactical_objective):
+ """Add a Tactical Objective to the Capability."""
+ if not self.tactical_objective:
+ self.tactical_objective = []
self.tactical_objective.append(tactical_objective)
def add_strategic_objective(self, strategic_objective):
+ """Add a Strategic Objective to the Capability."""
+ if not self.strategic_objective:
+ self.strategic_objective = []
self.strategic_objective.append(strategic_objective)
- def to_obj(self):
- capability_obj = bundle_binding.CapabilityType()
- if self.id_ is not None: capability_obj.set_id(self.id_)
- if self.name is not None: capability_obj.set_name(self.name)
- if self.description is not None: capability_obj.set_Description(self.description)
- if self.property:
- for prop in self.property:
- capability_obj.add_Property(prop.to_obj())
- if self.strategic_objective:
- for strategic_obj in self.strategic_objective:
- capability_obj.add_Strategic_Objective(strategic_obj.to_obj())
- if self.tactical_objective:
- for tactical_obj in self.tactical_objective:
- capability_obj.add_Tactical_Objective(tactical_obj.to_obj())
- if self.behavior_reference:
- for behavior_ref in self.behavior_reference:
- capability_obj.add_Behavior_Reference(behavior_ref.to_obj())
- if self.relationship:
- for rel in self.relationship:
- capability_obj.add_Relationship(rel.to_obj())
-
- return capability_obj
-
- def to_dict(self):
- capability_dict = {}
- if self.id_ is not None: capability_dict['id'] = self.id_
- if self.name is not None: capability_dict['name'] = self.name
- if self.description is not None: capability_dict['description'] = self.description
- if self.property:
- capability_dict['property'] = [x.to_dict() for x in self.property]
- if self.strategic_objective:
- capability_dict['strategic_objective'] = [x.to_dict() for x in self.strategic_objective]
- if self.tactical_objective:
- capability_dict['tactical_objective'] = [x.to_dict() for x in self.tactical_objective]
- if self.behavior_reference:
- capability_dict['behavior_reference'] = [x.to_dict() for x in self.behavior_reference]
- if self.relationship:
- capability_dict['relationship'] = [x.to_dict() for x in self.relationship]
-
- return capability_dict
-
- @staticmethod
- def from_dict(capability_dict):
- if not capability_dict:
- return None
- capability_ = Capability()
- if capability_dict.get('id'): capability_.id_ = capability_dict.get('id')
- capability_.name = capability_dict.get('name')
- capability_.description = capability_dict.get('description')
- if capability_dict.get('property'):
- capability_.property = [CapabilityProperty.from_dict(x) for x in capability_dict.get('property')]
- if capability_dict.get('strategic_objective'):
- capability_.strategic_objective = [CapabilityObjective.from_dict(x) for x in capability_dict.get('strategic_objective')]
- if capability_dict.get('tactical_objective'):
- capability_.tactical_objective = [CapabilityObjective.from_dict(x) for x in capability_dict.get('tactical_objective')]
- if capability_dict.get('behavior_reference'):
- capability_.behavior_reference = [BehaviorReference.from_dict(x) for x in capability_dict.get('behavior_reference')]
- if capability_dict.get('relationship'):
- capability_.relationship = [CapabilityRelationship.from_dict(x) for x in capability_dict.get('relationship')]
- return capability_
-
- @staticmethod
- def from_obj(capability_obj):
- if not capability_obj:
- return None
- capability_ = Capability()
- if capability_obj.get_id(): capability_.id_ = capability_obj.get_id()
- capability_.name = capability_obj.get_name()
- capability_.description = capability_obj.get_Description()
- if capability_obj.get_Property():
- capability_.property = [CapabilityProperty.from_obj(x) for x in capability_obj.get_Property()]
- if capability_obj.get_Strategic_Objective():
- capability_.strategic_objective = [CapabilityObjective.from_obj(x) for x in capability_obj.get_Strategic_Objective()]
- if capability_obj.get_Tactical_Objective():
- capability_.tactical_objective = [CapabilityObjective.from_obj(x) for x in capability_obj.get_Tactical_Objective()]
- if capability_obj.get_Behavior_Reference():
- capability_.behavior_reference = [BehaviorReference.from_obj(x) for x in capability_obj.get_Behavior_Reference()]
- if capability_obj.get_Relationship():
- capability_.relationship = [CapabilityRelationship.from_obj(x) for x in capability_obj.get_Relationship()]
- return capability_
-
+
class CapabilityList(maec.Entity):
- _namespace = maec.bundle._namespace
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.CapabilityListType
+
+ capability = fields.TypedField("Capability", Capability, multiple=True)
+ capability_reference = fields.TypedField("Capability_Reference", CapabilityReference, multiple=True)
def __init__(self):
super(CapabilityList, self).__init__()
self.capability = []
self.capability_reference = []
-
- def to_obj(self):
- capability_list_obj = bundle_binding.CapabilityListType()
- if self.capability:
- for cap in self.capability:
- capability_list_obj.add_Capability(cap.to_obj())
- if self.capability_reference:
- for cap_ref in self.capability_reference:
- capability_list_obj.add_Capability_Reference(cap_ref.to_obj())
- return capability_list_obj
-
- def to_dict(self):
- capability_list_dict = {}
- if self.capability:
- capability_list_dict['capability'] = [x.to_dict() for x in self.capability]
- if self.capability_reference:
- capability_list_dict['capability_reference'] = [x.to_dict() for x in self.capability_reference]
- return capability_list_dict
-
- @staticmethod
- def from_obj(capability_list_obj):
- if not capability_list_obj:
- return None
- capability_list_ = CapabilityList()
- if capability_list_obj.get_Capability():
- capability_list_.capability = [Capability.from_obj(x) for x in capability_list_obj.get_Capability()]
- if capability_list_obj.get_Capability_Reference():
- capability_list_.capability_reference = [CapabilityReference.from_obj(x) for x in capability_list_obj.get_Capability_Reference()]
- return capability_list_
-
- @staticmethod
- def from_dict(capability_list_dict):
- if not capability_list_dict:
- return None
- capability_list_ = CapabilityList()
- if capability_list_dict.get('capability'):
- capability_list_.capability = [Capability.from_dict(x) for x in capability_list_dict['capability']]
- if capability_list_dict.get('capability_reference'):
- capability_list_.capability_reference = [CapabilityReference.from_dict(x) for x in capability_list_dict['capability_reference']]
- return capability_list_
\ No newline at end of file
diff --git a/maec/bundle/malware_action.py b/maec/bundle/malware_action.py
index 4fdeea8..5500841 100644
--- a/maec/bundle/malware_action.py
+++ b/maec/bundle/malware_action.py
@@ -1,209 +1,66 @@
-#MAEC Malware Action Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-import cybox
-from cybox.core import Action
-from cybox.objects.code_object import Code
-
-import maec
-import maec.bindings.maec_bundle as bundle_binding
-
-class APICall(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self):
- super(APICall, self).__init__()
- self.function_name = None
- self.normalized_function_name = None
- self.address = None
- self.return_value = None
- self.parameters = []
-
- def to_obj(self):
- api_call_obj = bundle_binding.APICallType()
- if self.function_name is not None: api_call_obj.set_function_name(self.function_name)
- if self.normalized_function_name is not None: api_call_obj.set_normalized_function_name(self.normalized_function_name)
- if self.address is not None: api_call_obj.set_Address(self.address)
- if self.return_value is not None: api_call_obj.set_Return_Value(self.return_value)
- if len(self.parameters) > 0:
- parameter_list_obj = bundle_binding.ParameterListType()
- for parameter in self.parameters:
- parameter_list_obj.add_Parameter(parameter.to_obj())
- api_call_obj.set_Parameters(parameter_list_obj)
- return api_call_obj
-
- def to_dict(self):
- api_call_dict = {}
- if self.function_name is not None: api_call_dict['function_name'] = self.function_name
- if self.normalized_function_name is not None: api_call_dict['normalized_function_name'] = self.normalized_function_name
- if self.address is not None: api_call_dict['address'] = self.address
- if self.return_value is not None: api_call_dict['return_value'] = self.return_value
- if len(self.parameters) > 0:
- parameter_list = []
- for parameter in self.parameters:
- parameter_list.append(parameter.to_dict())
- api_call_dict['parameters'] = parameter_list
- return api_call_dict
-
- @staticmethod
- def from_dict(api_call_dict):
- if not api_call_dict:
- return None
- api_call_ = APICall()
- api_call_.function_name = api_call_dict.get('function_name')
- api_call_.normalized_function_name = api_call_dict.get('normalized_function_name')
- api_call_.address = api_call_dict.get('address')
- api_call_.return_value = api_call_dict.get('return_value')
- api_call_.parameters = ParameterList.from_list(api_call_dict.get('parameters', []))
- return api_call_
-
- @staticmethod
- def from_obj(api_call_obj):
- if not api_call_obj:
- return None
- api_call_ = APICall()
- api_call_.function_name = api_call_obj.get_function_name()
- api_call_.normalized_function_name = api_call_obj.get_normalized_function_name()
- api_call_.address = api_call_obj.get_Address()
- api_call_.return_value = api_call_obj.get_Return_Value()
- if api_call_obj.get_Parameters() is not None : api_call_.parameters = ParameterList.from_obj(api_call_obj.get_Parameters())
- return api_call_
-
-class Parameter(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self):
- super(Parameter, self).__init__()
- self.ordinal_position = None
- self.name = None
- self.value = None
-
- def to_obj(self):
- parameter_obj = bundle_binding.ParameterType()
- if self.ordinal_position is not None: parameter_obj.set_ordinal_position(self.ordinal_position)
- if self.name is not None: parameter_obj.set_name(self.name)
- if self.value is not None: parameter_obj.set_value(self.value)
- return parameter_obj
-
- def to_dict(self):
- parameter_dict = {}
- if self.ordinal_position is not None: parameter_dict['ordinal_position'] = self.ordinal_position
- if self.name is not None: parameter_dict['name'] = self.name
- if self.value is not None: parameter_dict['value'] = self.value
- return parameter_dict
-
- @staticmethod
- def from_dict(parameter_dict):
- if not parameter_dict:
- return None
- parameter_ = Parameter()
- parameter_.ordinal_position = parameter_dict.get('ordinal_position')
- parameter_.name = parameter_dict.get('name')
- parameter_.value = parameter_dict.get('value')
- return parameter_
-
- @staticmethod
- def from_obj(parameter_obj):
- if not parameter_obj:
- return None
- parameter_ = Parameter()
- parameter_.ordinal_position = parameter_obj.get_ordinal_position()
- parameter_.name = parameter_obj.get_name()
- parameter_.value = parameter_obj.get_value()
- return parameter_
-
-class ParameterList(maec.EntityList):
- _contained_type = Parameter
- _binding_class = bundle_binding.ParameterListType
- _binding_var = "Parameter"
- _namespace = maec.bundle._namespace
-
-class ActionImplementation(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self):
- super(ActionImplementation, self).__init__()
- self.id = None
- self.type = None
- self.compatible_platforms = []
- self.api_call = None
- self.code = []
-
- def to_obj(self):
- implementation_obj = bundle_binding.ActionImplementationType()
- if self.id is not None: implementation_obj.set_id(self.id)
- if self.type is not None: implementation_obj.set_type(self.type)
- if self.compatible_platforms is not None: pass
- #platform_list_obj = bundle_binding.PlatformListType() #TODO: implement
- #for platform in self.compatible_platforms:
- # platform_list_obj.add_Platform(platform.to_obj())
- #implementation_obj.set_Compatible_Platforms(platform_list_obj)
- if self.api_call is not None: implementation_obj.set_API_Call(self.api_call.to_obj())
- if self.code is not None:
- for code_obj in self.code:
- implementation_obj.add_Code(code_obj.to_obj())
- return implementation_obj
-
- def to_dict(self):
- implementation_dict = {}
- if self.id is not None: implementation_dict['id'] = self.id
- if self.type is not None: implementation_dict['type'] = self.type
- if self.compatible_platforms is not None: pass
- #platform_list_obj = bundle_binding.PlatformListType() #TODO: implement
- #for platform in self.compatible_platforms:
- # platform_list_obj.add_Platform(platform.to_obj())
- #implementation_obj.set_Compatible_Platforms(platform_list_obj)
- if self.api_call is not None: implementation_dict['api_call'] = self.api_call.to_dict()
- if self.code is not None:
- implementation_dict['code'] = [x.to_dict() for x in self.code]
- return implementation_dict
-
- @staticmethod
- def from_dict(implementation_dict):
- if not implementation_dict:
- return None
- implementation_ = ActionImplementation()
- implementation_.id = implementation_dict.get('id')
- implementation_.type = implementation_dict.get('type')
- #implementation_.compatible_platforms = implementation_dict.get('compatible_platforms') #TODO: add support
- implementation_.api_call = APICall.from_dict(implementation_dict.get('api_call'))
- if implementation_dict.get('code'):
- implementation_.code = [Code.from_dict(x) for x in implementation_dict.get('code')]
- return implementation_
-
- @staticmethod
- def from_obj(implementation_obj):
- if not implementation_obj:
- return None
- implementation_ = ActionImplementation()
- implementation_.id = implementation_obj.get_id()
- implementation_.type = implementation_obj.get_type()
- #implementation_.compatible_platforms = implementation_dict.get('compatible_platforms') #TODO: add support
- implementation_.api_call = APICall.from_obj(implementation_obj.get_API_Call())
- if implementation_obj.get_Code():
- implementation_.code = [Code.from_obj(x) for x in implementation_obj.get_Code()]
- return implementation_
-
-class MalwareAction(Action):
- _binding = bundle_binding
- _binding_class = bundle_binding.MalwareActionType
- _namespace = 'http://maec.mitre.org/XMLSchema/maec-bundle-4'
-
- implementation = cybox.TypedField("Implementation", ActionImplementation)
-
- def __init__(self):
- super(MalwareAction, self).__init__()
- self.id_ = maec.utils.idgen.create_id(prefix="action")
-
- #def to_dict(self):
- # action_dict = super(MalwareAction, self).to_dict()
- # action_dict['implementation'] = self.implementation.to_dict()
- # return action_dict
-
-
-
+# MAEC Malware Action Classes
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from mixbox import fields
+from mixbox import idgen
+
+from cybox.core import Action
+from cybox.objects.code_object import Code
+
+import maec
+from . import _namespace
+import maec.bindings.maec_bundle as bundle_binding
+
+
+class Parameter(maec.Entity):
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ParameterType
+
+ ordinal_position = fields.TypedField("ordinal_position")
+ name = fields.TypedField("name")
+ value = fields.TypedField("value")
+
+
+class ParameterList(maec.EntityList):
+ _binding_class = bundle_binding.ParameterListType
+ _namespace = _namespace
+ parameter = fields.TypedField("Parameter", Parameter, multiple=True)
+
+
+class APICall(maec.Entity):
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.APICallType
+
+ function_name = fields.TypedField("function_name")
+ normalized_function_name = fields.TypedField("normalized_function_name")
+ address = fields.TypedField("Address")
+ return_value = fields.TypedField("Return_Value")
+ parameters = fields.TypedField("Parameters", ParameterList)
+
+
+class ActionImplementation(maec.Entity):
+ _namespace = _namespace
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ActionImplementationType
+
+ id_ = fields.TypedField("id")
+ type_ = fields.TypedField("type_", key_name = "type")
+ #compatible_platforms TODO: Add support
+ api_call = fields.TypedField("API_Call", APICall)
+ code = fields.TypedField("Code", Code, multiple = True)
+
+
+class MalwareAction(Action):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.MalwareActionType
+ _namespace = _namespace
+
+ implementation = fields.TypedField("Implementation", ActionImplementation)
+
+ def __init__(self):
+ super(MalwareAction, self).__init__()
+ self.id_ = idgen.create_id(prefix="action")
diff --git a/maec/bundle/object_history.py b/maec/bundle/object_history.py
new file mode 100644
index 0000000..c6a7706
--- /dev/null
+++ b/maec/bundle/object_history.py
@@ -0,0 +1,48 @@
+# MAEC Object History Classes
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+class ObjectHistory(object):
+ @classmethod
+ def build(cls, bundle):
+ """Build the Object History for a Bundle"""
+ cls.entries = [] # A list of the Objects in the Object History
+ # Get the Objects that are not references
+ objects = bundle.get_all_non_reference_objects()
+ for object in objects:
+ object_history_entry = ObjectHistoryEntry(object)
+ # Find and set all Actions that operate on the Object
+ if bundle.get_all_actions_on_object(object):
+ object_history_entry.actions = bundle.get_all_actions_on_object(object)
+ # Add the history entry to the list
+ cls.entries.append(object_history_entry)
+
+class ObjectHistoryEntry(object):
+ def __init__(self, object = None):
+ self.object = object
+ self.actions = [] # A list of the Actions that operate on the Object
+ self.behaviors = [] # A list of Behaviors that make use of the Object (through Actions?)
+
+ def get_action_names(self):
+ """Return a list of the Actions that operated on the Object, via their names"""
+ return [x.name.value for x in self.actions if x.name]
+
+ def get_action_context(self):
+ """Return a list of the Actions that operated on the Object, via their names,
+ along with the Association_Type used in the Action.
+ """
+ context_list = []
+ for action in self.actions:
+ if action.name:
+ action_name = action.name.value
+ else:
+ action_name = None
+ for associated_object in action.associated_objects:
+ if associated_object.association_type:
+ association_type = associated_object.association_type.value
+ else:
+ association_type = None
+ if associated_object.id_ == self.object.id_ or associated_object.idref == self.object.id_:
+ context_list.append((action_name, association_type))
+ return context_list
\ No newline at end of file
diff --git a/maec/bundle/object_reference.py b/maec/bundle/object_reference.py
index d1918d0..b085977 100644
--- a/maec/bundle/object_reference.py
+++ b/maec/bundle/object_reference.py
@@ -1,49 +1,24 @@
-#MAEC Object Reference Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-import maec
-import maec.bindings.maec_bundle as bundle_binding
-
-class ObjectReference(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def init(self, object_idref = None):
- super(ObjectReference, self).__init__()
- self.object_idref = object_idref
-
- def to_obj(self):
- object_reference_obj = bundle_binding.ObjectReferenceType()
- if self.object_idref is not None : object_reference_obj.set_object_idref(self.object_idref)
- return object_reference_obj
-
- def to_dict(self):
- object_reference_dict = {}
- if self.object_idref is not None : object_reference_dict['object_idref'] = self.object_idref
- return object_reference_dict
-
- @staticmethod
- def from_dict(object_reference_dict):
- if not object_reference_dict:
- return None
- object_reference_ = ObjectReference()
- object_reference_.object_idref = object_reference_dict.get('object_idref')
- return object_reference_
-
- @staticmethod
- def from_obj(object_reference_obj):
- if not object_reference_obj:
- return None
- object_reference_ = ObjectReference()
- object_reference_.object_idref = object_reference_obj.get_object_idref()
- return object_reference_
-
-class ObjectReferenceList(maec.EntityList):
- _contained_type = ObjectReference
- _binding_class = bundle_binding.ObjectReferenceListType
- _binding_var = "Object_Reference"
- _namespace = maec.bundle._namespace
\ No newline at end of file
+# MAEC Object Reference Class
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from mixbox import fields
+
+import maec
+from . import _namespace
+import maec.bindings.maec_bundle as bundle_binding
+
+class ObjectReference(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ObjectReferenceType
+ _namespace = _namespace
+
+ def __init__(self, object_idref = None):
+ super(ObjectReference, self).__init__()
+ self.object_idref = object_idref
+
+class ObjectReferenceList(maec.EntityList):
+ _binding_class = bundle_binding.ObjectReferenceListType
+ _namespace = _namespace
+ object_reference = fields.TypedField("Object_Reference", ObjectReference, multiple=True)
diff --git a/maec/bundle/process_tree.py b/maec/bundle/process_tree.py
index b7f8457..c854e63 100644
--- a/maec/bundle/process_tree.py
+++ b/maec/bundle/process_tree.py
@@ -1,174 +1,128 @@
-#MAEC Bundle Class
+# MAEC Process Tree classes
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
+from mixbox import idgen
from cybox.objects.process_object import Process
import maec
import maec.bindings.maec_bundle as bundle_binding
-from maec.bundle.action_reference_list import ActionReferenceList
-
-class ProcessTree(maec.Entity):
- _namespace = maec.bundle._namespace
-
- def __init__(self, root_process = None):
- super(ProcessTree, self).__init__()
- self.root_process = root_process
-
- def set_root_process(self, root_process):
- self.root_process = root_process
-
- def to_obj(self):
- process_tree_obj = bundle_binding.ProcessTreeType()
- if self.root_process is not None:
- process_tree_obj.set_Root_Process(self.root_process.to_obj())
- return process_tree_obj
-
- def to_dict(self):
- process_tree_dict = {}
- if self.root_process is not None:
- process_tree_dict['root_process'] = self.root_process.to_dict()
- return process_tree_dict
-
- @staticmethod
- def from_dict(process_tree_dict):
- if not process_tree_dict:
- return None
- process_tree_ = ProcessTree()
- process_tree_.root_process = ProcessTreeNode.from_dict(process_tree_dict.get('root_process'))
- return process_tree_
-
- @staticmethod
- def from_obj(process_tree_obj):
- if not process_tree_obj:
- return None
- process_tree_ = ProcessTree()
- process_tree_.root_process = ProcessTreeNode.from_obj(process_tree_obj.get_Root_Process())
- return process_tree_
+from . import _namespace
+from .action_reference_list import ActionReferenceList
class ProcessTreeNode(Process):
_binding = bundle_binding
_binding_class = bundle_binding.ProcessTreeNodeType
+ _namespace = _namespace
_XSI_NS = "maecBundle"
_XSI_TYPE = "ProcessTreeNodeType"
-
superclass = Process
+ id_ = fields.TypedField("id")
+ parent_action_idref = fields.TypedField("parent_action_idref")
+ ordinal_position = fields.TypedField("ordinal_position")
+ initiated_actions = fields.TypedField("Initiated_Actions", ActionReferenceList)
+ spawned_process = fields.TypedField("Spawned_Process", multiple = True)
+ injected_process = fields.TypedField("Injected_Process", multiple = True)
+
def __init__(self, id = None, parent_action_idref = None):
super(ProcessTreeNode, self).__init__()
- self.id = maec.utils.idgen.create_id(prefix="process_tree")
+ if id:
+ self.id_ = id
+ else:
+ self.id_ = idgen.create_id(prefix="process_tree")
self.parent_action_idref = parent_action_idref
- self.ordinal_position = None
- self.initiated_actions = ActionReferenceList()
- self.spawned_processes = []
- self.injected_processes = []
def add_spawned_process(self, process_node, process_id = None):
+ """Add a spawned process to the Process Tree node, either directly or to a
+ particular process embedded in the node based on its ID."""
if not process_id:
- self.spawned_processes.append(process_node)
+ if not self.spawned_process:
+ self.spawned_process = []
+ self.spawned_process.append(process_node)
elif process_id:
if str(self.pid) == process_id:
- self.spawned_processes.append(process_node)
+ if not self.spawned_process:
+ self.spawned_process = []
+ self.spawned_process.append(process_node)
else:
embedded_process = self.find_embedded_process(process_id)
if embedded_process:
- embedded_process.spawned_processes.append(process_node)
+ if not embedded_process.spawned_process:
+ embedded_process.spawned_process = []
+ embedded_process.spawned_process.append(process_node)
def add_injected_process(self, process_node, process_id = None):
+ """Add an injected process to the Process Tree node, either directly or to a
+ particular process embedded in the node based on its ID."""
if not process_id:
- self.injected_processes.append(process_node)
+ if not self.injected_process:
+ self.injected_process = []
+ self.injected_process.append(process_node)
elif process_id:
if str(self.pid) == process_id:
- self.injected_processes.append(process_node)
+ if not self.injected_process:
+ self.injected_process = []
+ self.injected_process.append(process_node)
else:
embedded_process = self.find_embedded_process(process_id)
if embedded_process:
- embedded_process.injected_processes.append(process_node)
+ if not embedded_process.injected_process:
+ embedded_process.injected_process = []
+ embedded_process.injected_process.append(process_node)
def add_initiated_action(self, action_id):
+ """Add an initiated Action to the Process Tree node, based on its ID."""
+ if not self.initiated_actions:
+ self.initiated_actions = ActionReferenceList()
self.initiated_actions.append(action_id)
def find_embedded_process(self, process_id):
+ """Find a Process embedded somewhere in the Process Tree node tree, based on its ID."""
embedded_process = None
- for spawned_process in self.spawned_processes:
- if str(spawned_process.pid) == str(process_id):
- embedded_process = spawned_process
- else:
- embedded_process = spawned_process.find_embedded_process(process_id)
- for injected_process in self.injected_processes:
- if str(injected_process.pid) == str(process_id):
- embedded_process = injected_process
- else:
- embedded_process = injected_process.find_embedded_process(process_id)
+ if self.spawned_process:
+ for spawned_process in self.spawned_process:
+ if str(spawned_process.pid) == str(process_id):
+ embedded_process = spawned_process
+ else:
+ embedded_process = spawned_process.find_embedded_process(process_id)
+ if self.injected_process:
+ for injected_process in self.injected_process:
+ if str(injected_process.pid) == str(process_id):
+ embedded_process = injected_process
+ else:
+ embedded_process = injected_process.find_embedded_process(process_id)
return embedded_process
def set_id(self, id):
- self.id = id
+ """Set the ID of the Process Tree node."""
+ self.id_ = id
def set_parent_action(self, parent_action_id):
+ """Set the ID of the parent action of the Process Tree node."""
self.parent_action_idref = parent_action_id
- def to_obj(self):
- process_tree_node_obj = super(ProcessTreeNode, self).to_obj()
- if self.id is not None : process_tree_node_obj.set_id(self.id)
- if self.parent_action_idref is not None : process_tree_node_obj.set_parent_action_idref(self.parent_action_idref)
- if self.ordinal_position is not None : process_tree_node_obj.set_ordinal_position(self.ordinal_position)
- if self.initiated_actions: process_tree_node_obj.set_Initiated_Actions(self.initiated_actions.to_obj())
- if self.spawned_processes:
- for spawned_process in self.spawned_processes:
- process_tree_node_obj.add_Spawned_Process(spawned_process.to_obj())
- if self.injected_processes:
- for injected_process in self.injected_processes:
- process_tree_node_obj.add_Injected_Process(injected_process.to_obj())
- return process_tree_node_obj
-
- def to_dict(self):
- process_tree_node_dict = super(ProcessTreeNode, self).to_dict()
- if self.id is not None : process_tree_node_dict['id'] = self.id
- if self.parent_action_idref is not None : process_tree_node_dict['parent_action_idref'] = self.parent_action_idref
- if self.ordinal_position is not None : process_tree_node_dict['ordinal_position'] = self.ordinal_position
- if self.initiated_actions: process_tree_node_dict['initiated_actions'] = self.initiated_actions.to_list()
- if self.spawned_processes:
- spawned_process_list = []
- for spawned_process in self.spawned_processes:
- spawned_process_list.append(spawned_process.to_dict())
- process_tree_node_dict['spawned_processes'] = spawned_process_list
- if self.injected_processes > 0:
- injected_process_list = []
- for injected_process in self.injected_processes:
- injected_process_list.append(injected_process.to_dict())
- process_tree_node_dict['injected_processes'] = injected_process_list
- return process_tree_node_dict
-
- @classmethod
- def from_dict(cls, process_tree_node_dict):
- if not process_tree_node_dict:
- return None
- process_tree_node_ = super(ProcessTreeNode, cls).from_dict(process_tree_node_dict)
- process_tree_node_.id = process_tree_node_dict.get('id')
- process_tree_node_.parent_action_idref = process_tree_node_dict.get('parent_action_idref')
- process_tree_node_.ordinal_position = process_tree_node_dict.get('ordinal_position')
- process_tree_node_.initiated_actions = ActionReferenceList.from_list(process_tree_node_dict.get('initiated_actions', []))
- process_tree_node_.spawned_processes = [ProcessTreeNode.from_dict(x) for x in process_tree_node_dict.get('spawned_processes', [])]
- process_tree_node_.injected_processes = [ProcessTreeNode.from_dict(x) for x in process_tree_node_dict.get('injected_processes', [])]
- return process_tree_node_
-
- @classmethod
- def from_obj(cls, process_tree_node_obj):
- if not process_tree_node_obj:
- return None
- process_tree_node_ = super(ProcessTreeNode, cls).from_obj(process_tree_node_obj)
- process_tree_node_.id = process_tree_node_obj.get_id()
- process_tree_node_.parent_action_idref = process_tree_node_obj.get_parent_action_idref()
- process_tree_node_.ordinal_position = process_tree_node_obj.get_ordinal_position()
- if process_tree_node_obj.get_Initiated_Actions() is not None:
- process_tree_node_.initiated_actions = ActionReferenceList.from_obj(process_tree_node_obj.get_Initiated_Actions())
- process_tree_node_.spawned_processes = [ProcessTreeNode.from_obj(x) for x in process_tree_node_obj.get_Spawned_Process()]
- process_tree_node_.injected_processes = [ProcessTreeNode.from_obj(x) for x in process_tree_node_obj.get_Injected_Process()]
- return process_tree_node_
+
+class ProcessTree(maec.Entity):
+ _binding = bundle_binding
+ _binding_class = bundle_binding.ProcessTreeType
+ _namespace = _namespace
+
+ root_process = fields.TypedField("Root_Process", ProcessTreeNode)
+
+ def __init__(self, root_process = None):
+ super(ProcessTree, self).__init__()
+ self.root_process = root_process
+
+ def set_root_process(self, root_process):
+ """Set the Root Process node of the Process Tree entity."""
+ self.root_process = root_process
+
+# Allow recursive definition of ProcessTreeNodes
+ProcessTreeNode.spawned_process.type_ = ProcessTreeNode
+ProcessTreeNode.injected_process.type_ = ProcessTreeNode
diff --git a/maec/misc/__init__.py b/maec/misc/__init__.py
new file mode 100644
index 0000000..5404cce
--- /dev/null
+++ b/maec/misc/__init__.py
@@ -0,0 +1,3 @@
+from .exceptions import (LookupNotFoundException, NetworkFailureException, # noqa
+ APIKeyException) # noqa
+from .options import ScriptOptions # noqa
\ No newline at end of file
diff --git a/maec/misc/exceptions.py b/maec/misc/exceptions.py
new file mode 100644
index 0000000..400c3fe
--- /dev/null
+++ b/maec/misc/exceptions.py
@@ -0,0 +1,14 @@
+"""Common exception classes used by MAEC conversion tools."""
+
+"""Indicates a failure caused by a rejected API key."""
+class APIKeyException(Exception):
+ pass
+
+"""Indicates a failure caused by a rejected API key."""
+class NetworkFailureException(Exception):
+ pass
+
+"""Indicates a failure caused by a request for a resource unknown to some service.
+(e.g., asking for a report from ThreatExpert by MD5, but the MD5 is unknown to ThreatExpert)"""
+class LookupNotFoundException(Exception):
+ pass
diff --git a/maec/misc/options.py b/maec/misc/options.py
new file mode 100644
index 0000000..62f5bb1
--- /dev/null
+++ b/maec/misc/options.py
@@ -0,0 +1,29 @@
+class ScriptOptions(object):
+ """Defines configurable options for MAEC scripts and utilities.
+
+ Attributes:
+ deduplicate_bundles: If ``True``, the script will deduplicate all
+ Objects in all Bundles (either as standalone entities or embedded
+ in Malware Subjects) before returning or writing out the MAEC document.
+ Default value is ``False``.
+ dereference_bundles: If ``True``, the script will deference all
+ Objects in all Bundles (either as standalone entities or embedded
+ in Malware Subjects) before returning or writing out the MAEC document.
+ Default value is ``False``.
+ normalize_bundles: If ``True``, the script will normalize all
+ Objects in all Bundles (either as standalone entities or embedded
+ in Malware Subjects) before returning or writing out the MAEC document.
+ Default value is ``False``.
+
+ """
+ def __init__(self):
+ self.deduplicate_bundles = False
+ self.dereference_bundles = False
+ self.normalize_bundles = False
+
+ def to_dict(self):
+ return {
+ "deduplicate_bundles": self.deduplicate_bundles,
+ "dereference_bundles": self.dereference_bundles,
+ "normalize_bundles": self.normalize_bundles
+ }
diff --git a/maec/package/__init__.py b/maec/package/__init__.py
index 76c00c6..0943921 100644
--- a/maec/package/__init__.py
+++ b/maec/package/__init__.py
@@ -1 +1,28 @@
-_namespace = 'http://maec.mitre.org/XMLSchema/maec-package-2'
\ No newline at end of file
+_namespace = 'http://maec.mitre.org/XMLSchema/maec-package-2'
+
+from .action_equivalence import ActionEquivalenceList, ActionEquivalence # noqa
+from .malware_subject_reference import MalwareSubjectReference # noqa
+from .object_equivalence import ObjectEquivalence, ObjectEquivalenceList # noqa
+from .analysis import (Analysis, AnalysisEnvironment, NetworkInfrastructure, # noqa
+ CapturedProtocolList, CapturedProtocol, # noqa
+ AnalysisSystemList, AnalysisSystem, InstalledPrograms, # noqa
+ HypervisorHostSystem, DynamicAnalysisMetadata, # noqa
+ ToolList, CommentList, Comment, Source) # noqa
+from .grouping_relationship import (GroupingRelationshipList, # noqa
+ GroupingRelationship, ClusteringMetadata, # noqa
+ ClusteringAlgorithmParameters, # noqa
+ ClusterComposition, ClusterEdgeNodePair) # noqa
+from .malware_subject import (MalwareSubjectList, MalwareSubject, # noqa
+ MalwareConfigurationDetails, # noqa
+ MalwareConfigurationObfuscationDetails, # noqa
+ MalwareConfigurationObfuscationAlgorithm, # noqa
+ MalwareConfigurationStorageDetails, # noqa
+ MalwareBinaryConfigurationStorageDetails, # noqa
+ MalwareConfigurationParameter, # noqa
+ MalwareDevelopmentEnvironment, # noqa
+ FindingsBundleList, MetaAnalysis, # noqa
+ MalwareSubjectRelationshipList, # noqa
+ MalwareSubjectRelationship, Analyses, # noqa
+ MinorVariants) # noqa
+
+from .package import Package # noqa
diff --git a/maec/package/action_equivalence.py b/maec/package/action_equivalence.py
index 4604584..e467fe0 100644
--- a/maec/package/action_equivalence.py
+++ b/maec/package/action_equivalence.py
@@ -1,31 +1,29 @@
-#MAEC Action Equivalence Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-import maec
-import maec.bindings.maec_package as package_binding
-from cybox.core import ActionReference
-
-
-class ActionEquivalence(maec.Entity):
- _binding = package_binding
- _binding_class = package_binding.ActionEquivalenceType
- _namespace = maec.package._namespace
-
- id = maec.TypedField('id')
- action_reference = maec.TypedField('Action_Reference', ActionReference, multiple = True)
-
- def __init__(self):
- super(ActionEquivalence, self).__init__()
- self.id = maec.utils.idgen.create_id(prefix="action_equivalence")
-
-
-class ActionEquivalenceList(maec.EntityList):
- _contained_type = ActionEquivalence
- _binding_class = package_binding.ActionEquivalenceListType
- _binding_var = "Action_Equivalence"
- _namespace = maec.package._namespace
\ No newline at end of file
+#MAEC Action Equivalence Class
+
+#Copyright (c) 2018, The MITRE Corporation
+#All rights reserved
+
+from mixbox import fields
+from mixbox import idgen
+
+import maec
+from . import _namespace
+import maec.bindings.maec_package as package_binding
+from cybox.core import ActionReference
+
+class ActionEquivalence(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.ActionEquivalenceType
+ _namespace = _namespace
+
+ id_ = fields.TypedField('id')
+ action_reference = fields.TypedField('Action_Reference', ActionReference, multiple = True)
+
+ def __init__(self):
+ super(ActionEquivalence, self).__init__()
+ self.id_ = idgen.create_id(prefix="action_equivalence")
+
+class ActionEquivalenceList(maec.EntityList):
+ _binding_class = package_binding.ActionEquivalenceListType
+ _namespace = _namespace
+ action_equivalence = fields.TypedField("Action_Equivalence", ActionEquivalence, multiple=True)
diff --git a/maec/package/analysis.py b/maec/package/analysis.py
index 8f8573e..d8e6a17 100644
--- a/maec/package/analysis.py
+++ b/maec/package/analysis.py
@@ -1,515 +1,243 @@
-#MAEC Analysis Class
+# MAEC Analysis Class
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
+from mixbox import idgen
from cybox.common import (PlatformSpecification, Personnel, StructuredText,
ToolInformation)
from cybox.objects.system_object import System
import maec
+from . import _namespace
import maec.bindings.maec_package as package_binding
-from maec.bundle.bundle_reference import BundleReference
+from maec.bundle import BundleReference
+class Source(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.SourceType
+ _namespace = _namespace
-class Analysis(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self, id = None, method = None, type = None, findings_bundle_reference = []):
- super(Analysis, self).__init__()
- if id:
- self.id = id
- else:
- self.id = maec.utils.idgen.create_id(prefix="analysis")
- self.method = method
- self.type = type
- self.ordinal_position = None
- self.start_datetime = None
- self.complete_datetime = None
- self.lastupdate_datetime = None
- self.source = None
- self.analysts = None
- self.summary = None
- self.comments = None
- self.findings_bundle_reference = findings_bundle_reference
- self.tools = ToolList()
- self.dynamic_analysis_metadata = None
- self.analysis_environment = None
- self.report = None
-
- #"Public" methods
- def set_findings_bundle(self, bundle_id):
- self.findings_bundle_reference = [BundleReference.from_dict({'bundle_idref' : bundle_id})]
-
- def add_tool(self, tool):
- self.tools.append(tool)
+ name = fields.TypedField("Name")
+ method = fields.TypedField("Method")
+ reference = fields.TypedField("Reference")
+ organization = fields.TypedField("Organization")
+ url = fields.TypedField("URL")
- #Return a bindings object
- def to_obj(self):
- analysis_obj = package_binding.AnalysisType()
- if self.id is not None : analysis_obj.set_id(self.id)
- if self.method is not None: analysis_obj.set_method(self.method)
- if self.type is not None: analysis_obj.set_type(self.type)
- if self.ordinal_position is not None : analysis_obj.set_ordinal_position(self.ordinal_position)
- if self.complete_datetime is not None: analysis_obj.set_complete_datetime(self.complete_datetime)
- if self.start_datetime is not None : analysis_obj.set_start_datetime(self.start_datetime)
- if self.lastupdate_datetime is not None : analysis_obj.set_lastupdate_datetime(self.lastupdate_datetime)
- if self.source is not None : analysis_obj.set_Source(self.source.to_obj())
- if self.analysts is not None : analysis_obj.set_Analysts(self.analysts.to_obj())
- if self.summary is not None : analysis_obj.set_Summary(self.summary.to_obj())
- if self.comments is not None : analysis_obj.set_Comments(self.comments.to_obj())
- if self.findings_bundle_reference is not None :
- for findings_bundle_ref in self.findings_bundle_reference:
- analysis_obj.add_Findings_Bundle_Reference(findings_bundle_ref.to_obj())
- if self.tools: analysis_obj.set_Tools(self.tools.to_obj())
- if self.dynamic_analysis_metadata is not None : analysis_obj.set_Dynamic_Analysis_Metadata(self.dynamic_analysis_metadata.to_obj())
- if self.analysis_environment is not None : analysis_obj.set_Analysis_Environment(self.analysis_environment.to_obj())
- if self.report is not None : analysis_obj.set_Report(self.report.to_obj())
- return analysis_obj
-
- def to_dict(self):
- analysis_dict = {}
- if self.id is not None: analysis_dict['id'] = self.id
- if self.method is not None: analysis_dict['method'] = self.method
- if self.type is not None: analysis_dict['type'] = self.type
- if self.ordinal_position is not None : analysis_dict['ordinal_position'] = self.ordinal_position
- if self.complete_datetime is not None: analysis_dict['complete_datetime'] = self.complete_datetime
- if self.start_datetime is not None : analysis_dict['start_datetime'] = self.start_datetime
- if self.lastupdate_datetime is not None : analysis_dict['lastupdate_datetime'] = self.lastupdate_datetime
- if self.source is not None : analysis_dict['source'] = self.source.to_dict()
- if self.analysts is not None : analysis_dict['analysts'] = self.analysts.to_list()
- if self.summary is not None : analysis_dict['summary'] = self.summary.to_dict()
- if self.comments is not None : analysis_dict['comments'] = self.comments.to_list()
- if self.findings_bundle_reference is not None :
- analysis_dict['findings_bundle_reference'] = [x.to_dict() for x in self.findings_bundle_reference]
- if self.tools: analysis_dict['tools'] = self.tools.to_list()
- if self.dynamic_analysis_metadata is not None : analysis_dict['dynamic_analysis_metadata'] = self.dynamic_analysis_metadata.to_dict()
- if self.analysis_environment is not None : analysis_dict['analysis_environment'] = self.analysis_environment.to_dict()
- if self.report is not None : analysis_dict['report'] = self.report.to_dict()
- return analysis_dict
-
- #Create and return the Analysis from the input dictionary
- @staticmethod
- def from_obj(analysis_obj):
- if not analysis_obj:
- return None
- analysis_ = Analysis(None)
- analysis_.id = analysis_obj.get_id()
- analysis_.method = analysis_obj.get_method()
- analysis_.type = analysis_obj.get_type()
- analysis_.ordinal_position = analysis_obj.get_ordinal_position()
- analysis_.complete_datetime = analysis_obj.get_complete_datetime()
- analysis_.start_datetime = analysis_obj.get_start_datetime()
- analysis_.lastupdate_datetime = analysis_obj.get_lastupdate_datetime()
- analysis_.source = Source.from_obj(analysis_obj.get_Source())
- analysis_.analysts = Personnel.from_obj(analysis_obj.get_Analysts())
- analysis_.summary = StructuredText.from_obj(analysis_obj.get_Summary())
- analysis_.comments = CommentList.from_obj(analysis_obj.get_Comments())
- if analysis_obj.get_Findings_Bundle_Reference():
- analysis_.findings_bundle_reference = [BundleReference.from_obj(x) for x in analysis_obj.get_Findings_Bundle_Reference()]
- analysis_.tools = ToolList.from_obj(analysis_obj.get_Tools())
- analysis_.dynamic_analysis_metadata = DynamicAnalysisMetadata.from_obj(analysis_obj.get_Dynamic_Analysis_Metadata())
- analysis_.analysis_environment = AnalysisEnvironment.from_obj(analysis_obj.get_Analysis_Environment())
- analysis_.report = StructuredText.from_obj(analysis_obj.get_Report())
- return analysis_
-
- #Create and return the Analysis from the input dictionary
- @staticmethod
- def from_dict(analysis_dict):
- if not analysis_dict:
- return None
- analysis_ = Analysis(None)
- analysis_.id = analysis_dict.get('id')
- analysis_.method = analysis_dict.get('method')
- analysis_.type = analysis_dict.get('type')
- analysis_.ordinal_position = analysis_dict.get('ordinal_position')
- analysis_.complete_datetime = analysis_dict.get('complete_datetime')
- analysis_.start_datetime = analysis_dict.get('start_datetime')
- analysis_.lastupdate_datetime = analysis_dict.get('lastupdate_datetime')
- analysis_.source = Source.from_dict(analysis_dict.get('source'))
- analysis_.analysts = Personnel.from_list(analysis_dict.get('analysts'))
- analysis_.summary = StructuredText.from_dict(analysis_dict.get('summary'))
- analysis_.comments = CommentList.from_list(analysis_dict.get('comments'))
- if analysis_dict.get('findings_bundle_reference'):
- analysis_.findings_bundle_reference = [BundleReference.from_dict(x) for x in analysis_dict.get('findings_bundle_reference')]
- analysis_.tools = ToolList.from_list(analysis_dict.get('tools', []))
- analysis_.dynamic_analysis_metadata = DynamicAnalysisMetadata.from_dict(analysis_dict.get('dynamic_analysis_metadata'))
- analysis_.analysis_environment = AnalysisEnvironment.from_dict(analysis_dict.get('analysis_environment'))
- analysis_.report = StructuredText.from_dict(analysis_dict.get('report'))
- return analysis_
+ def __init__(self):
+ super(Source, self).__init__()
class Comment(StructuredText):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.CommentType
+ _namespace = _namespace
- def __init__(self):
- super(Comment, self).__init__()
- self.author = None
- self.timestamp = None
- self.observation_name = None
+ author = fields.TypedField("author")
+ timestamp = fields.TypedField("timestamp")
+ observation_name = fields.TypedField("observation_name")
+
+ def __init__(self, value=None):
+ super(Comment, self).__init__(value)
def is_plain(self):
"""Whether this can be represented as a string rather than a dictionary
"""
- return (super(Comment, self).is_plain() and
+ return (super(Comment, self).is_plain() and
self.author is None and
- self.timestamp is None and
+ self.timestamp is None and
self.observation_name is None)
- def to_obj(self):
- comment_obj = super(Comment, self).to_obj(package_binding.CommentType())
- if self.author is not None : comment_obj.set_author(self.author)
- if self.timestamp is not None : comment_obj.set_timestamp(self.timestamp)
- if self.observation_name is not None : comment_obj.set_observation_name(self.observation_name)
+ def to_obj(self, ns_info=None):
+ comment_obj = super(Comment, self).to_obj()
+
+ if self.author:
+ comment_obj.author = self.author
+ if self.timestamp:
+ comment_obj.timestamp = self.timestamp
+ if self.observation_name:
+ comment_obj.observation_name = self.observation_name
+
return comment_obj
def to_dict(self):
comment_dict = super(Comment, self).to_dict()
- if self.author is not None : comment_dict['author'] = self.author
- if self.timestamp is not None : comment_dict['timestamp'] = self.timestamp
- if self.observation_name is not None : comment_dict['observation_name'] = self.observation_name
+ if self.author:
+ comment_dict['author'] = self.author
+ if self.timestamp:
+ comment_dict['timestamp'] = self.timestamp
+ if self.observation_name:
+ comment_dict['observation_name'] = self.observation_name
+
return comment_dict
- @staticmethod
- def from_dict(comment_dict):
- if not comment_dict:
- return None
- comment_ = StructuredText.from_dict(comment_dict, Comment())
- comment_.author = comment_dict.get('author')
- comment_.timestamp = comment_dict.get('timestamp')
- comment_.observation_name = comment_dict.get('observation_name')
- return comment_
-
- @staticmethod
- def from_obj(comment_obj):
- if not comment_obj:
+ @classmethod
+ def from_obj(cls, cls_obj):
+ if not cls_obj:
return None
- comment_ = StructuredText.from_obj(comment_obj, Comment())
- comment_.author = comment_obj.get_author()
- comment_.timestamp = comment_obj.get_timestamp()
- comment_.observation_name = comment_obj.get_observation_name()
- return comment_
-
-class CommentList(maec.EntityList):
- _contained_type = Comment
- _binding_class = package_binding.CommentListType
- _binding_var = "Comment"
- _namespace = maec.package._namespace
-class DynamicAnalysisMetadata(maec.Entity):
- _namespace = maec.package._namespace
+ comment = super(Comment, cls).from_obj(cls_obj)
+ comment.value = cls_obj.valueOf_
- def __init__(self):
- super(DynamicAnalysisMetadata, self).__init__()
- self.command_line = None
- self.analysis_duration = None
- self.exit_code = None
+ if cls_obj.author:
+ comment.author = cls_obj.author
+ if cls_obj.timestamp:
+ comment.timestamp = cls_obj.timestamp
+ if cls_obj.observation_name:
+ comment.observation_name = cls_obj.observation_name
- def to_obj(self):
- dynamic_analysis_metadata_obj = package_binding.DynamicAnalysisMetadataType()
- if self.command_line is not None : dynamic_analysis_metadata_obj.set_Command_Line(self.command_line)
- if self.analysis_duration is not None : dynamic_analysis_metadata_obj.set_Analysis_Duration(self.analysis_duration)
- if self.exit_code is not None : dynamic_analysis_metadata_obj.set_Exit_Code(self.exit_code)
- return dynamic_analysis_metadata_obj
+ return comment
- def to_dict(self):
- dynamic_analysis_metadata_dict = {}
- if self.command_line is not None : dynamic_analysis_metadata_dict['command_line'] = self.command_line
- if self.analysis_duration is not None : dynamic_analysis_metadata_dict['analysis_duration'] = self.analysis_duration
- if self.exit_code is not None : dynamic_analysis_metadata_dict['exit_code'] = self.exit_code
- return dynamic_analysis_metadata_dict
-
- @staticmethod
- def from_dict(dynamic_analysis_metadata_dict):
- if not dynamic_analysis_metadata_dict:
+ @classmethod
+ def from_dict(cls, cls_dict):
+ if not cls_dict:
return None
- dynamic_analysis_metadata_ = DynamicAnalysisMetadata()
- dynamic_analysis_metadata_.command_line = dynamic_analysis_metadata_dict.get('command_line')
- dynamic_analysis_metadata_.analysis_duration = dynamic_analysis_metadata_dict.get('analysis_duration')
- dynamic_analysis_metadata_.exit_code = dynamic_analysis_metadata_dict.get('exit_code')
- return dynamic_analysis_metadata_
-
- @staticmethod
- def from_obj(dynamic_analysis_metadata_obj):
- if not dynamic_analysis_metadata_obj:
- return None
- dynamic_analysis_metadata_ = DynamicAnalysisMetadata()
- dynamic_analysis_metadata_.command_line = dynamic_analysis_metadata_obj.get_Command_Line()
- dynamic_analysis_metadata_.analysis_duration = dynamic_analysis_metadata_obj.get_Analysis_Duration()
- dynamic_analysis_metadata_.exit_code = dynamic_analysis_metadata_obj.get_Exit_Code()
- return dynamic_analysis_metadata_
-class AnalysisEnvironment(maec.Entity):
- _namespace = maec.package._namespace
+ if not isinstance(cls_dict, dict):
+ comment = cls(cls_dict)
+ else:
+ super(Comment, cls).from_dict(cls_dict)
+ comment.author = cls_dict.get('author')
+ comment.timestamp = cls_dict.get('timestamp')
+ comment.observation_name = cls_dict.get('observation_name')
- def __init__(self):
- super(AnalysisEnvironment, self).__init__()
- self.hypervisor_host_system = None
- self.analysis_systems = None
- self.network_infrastructure = None
+ return comment
- def to_obj(self):
- analysis_environment_obj = package_binding.AnalysisEnvironmentType()
- if self.hypervisor_host_system is not None : analysis_environment_obj.set_Hypervisor_Host_System(self.hypervisor_host_system.to_obj())
- if self.analysis_systems is not None : analysis_environment_obj.set_Analysis_Systems(self.analysis_systems.to_obj())
- if self.network_infrastructure is not None : analysis_environment_obj.set_Network_Infrastructure(self.network_infrastructure.to_obj())
- return analysis_environment_obj
+class CommentList(maec.EntityList):
+ _binding_class = package_binding.CommentListType
+ _namespace = _namespace
+ comment = fields.TypedField("Comment", Comment, multiple=True)
- def to_dict(self):
- analysis_environment_dict = {}
- if self.hypervisor_host_system is not None : analysis_environment_dict['hypervisor_host_system'] = self.hypervisor_host_system.to_dict()
- if self.analysis_systems is not None : analysis_environment_dict['analysis_systems'] = self.analysis_systems.to_list()
- if self.network_infrastructure is not None : analysis_environment_dict['network_infrastructure'] = self.network_infrastructure.to_dict()
- return analysis_environment_obj
-
- @staticmethod
- def from_dict(analysis_environment_dict):
- if not analysis_environment_dict:
- return None
- analysis_environment_ = AnalysisEnvironment()
- analysis_environment_.hypervisor_host_system = HypervisorHostSystem.from_dict(analysis_environment_dict.get('hypervisor_host_system'))
- analysis_environment_.analysis_systems = AnalysisSystemList.from_list(analysis_environment_dict.get('analysis_systems'))
- analysis_environment_.network_infrastructure = NetworkInfrastructure.from_dict(analysis_environment_dict.get('network_infrastructure'))
- return analysis_environment_
-
- @staticmethod
- def from_obj(analysis_environment_obj):
- if not analysis_environment_obj:
- return None
- analysis_environment_ = AnalysisEnvironment()
- analysis_environment_.hypervisor_host_system = HypervisorHostSystem.from_obj(analysis_environment_obj.get_Hypervisor_Host_System())
- analysis_environment_.analysis_systems = AnalysisSystemList.from_obj(analysis_environment_obj.get_Analysis_Systems())
- analysis_environment_.network_infrastructure = NetworkInfrastructure.from_obj(analysis_environment_obj.get_Network_Infrastructure())
- return analysis_environment_
+class ToolList(maec.EntityList):
+ _binding_class = package_binding.ToolListType
+ _namespace = _namespace
+ tool = fields.TypedField("Tool", ToolInformation, multiple=True)
-class HypervisorHostSystem(System):
- _namespace = maec.package._namespace
+class DynamicAnalysisMetadata(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.DynamicAnalysisMetadataType
+ _namespace = _namespace
+
+ command_line = fields.TypedField("Command_Line")
+ analysis_duration = fields.TypedField("Analysis_Duration")
+ exit_code = fields.TypedField("Exit_Code")
+ #raised_exception = fields.TypedField("Raised_Exception", MalwareException)
def __init__(self):
- super(HypervisorHostSystem, self).__init__()
- self.vm_hypervisor = None
+ super(DynamicAnalysisMetadata, self).__init__()
- def to_obj(self):
- hypervisor_host_system_obj = super(HypervisorHostSystem, self).to_obj(package_binding.HypervisorHostSystemType())
- if self.vm_hypervisor is not None : hypervisor_host_system_obj.set_VM_Hypervisor(self.vm_hypervisor.to_obj())
- return hypervisor_host_system_obj
+class HypervisorHostSystem(System):
+ _binding = package_binding
+ _binding_class = package_binding.HypervisorHostSystemType
+ _namespace = _namespace
- def to_dict(self):
- hypervisor_host_system_dict = super(HypervisorHostSystem, self).to_dict()
- if self.vm_hypervisor is not None : hypervisor_host_system_dict['vm_hypervisor'] = self.vm_hypervisor.to_dict()
- return hypervisor_host_system_dict
+ vm_hypervisor = fields.TypedField("VM_Hypervisor", PlatformSpecification)
- @staticmethod
- def from_dict(hypervisor_host_system_dict):
- if not hypervisor_host_system_dict:
- return None
- hypervisor_host_system_ = System.from_dict(hypervisor_host_system_dict, HypervisorHostSystem())
- hypervisor_host_system_.vm_hypervisor = PlatformSpecification.from_dict(hypervisor_host_system_dict.get('vm_hypervisor'))
- return hypervisor_host_system_
+ def __init__(self):
+ super(HypervisorHostSystem, self).__init__()
- @staticmethod
- def from_obj(hypervisor_host_system_obj):
- if not hypervisor_host_system_obj:
- return None
- hypervisor_host_system_ = System.from_obj(hypervisor_host_system_obj, HypervisorHostSystem())
- hypervisor_host_system_.vm_hypervisor = PlatformSpecification.from_obj(hypervisor_host_system_obj.get_VM_Hypervisor())
- return hypervisor_host_system_
+class InstalledPrograms(maec.EntityList):
+ _binding_class = package_binding.InstalledProgramsType
+ _namespace = _namespace
+ program = fields.TypedField("Program", PlatformSpecification, multiple=True)
class AnalysisSystem(System):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.AnalysisSystemType
+ _namespace = _namespace
+
+ installed_programs = fields.TypedField("Installed_Programs", InstalledPrograms)
def __init__(self):
super(AnalysisSystem, self).__init__()
self.installed_programs = InstalledPrograms()
- def to_obj(self):
- analysis_system_obj = super(AnalysisSystem, self).to_obj(package_binding.AnalysisSystemType())
- if len(self.installed_programs) > 0 : analysis_system_obj.set_Installed_Programs(self.installed_programs.to_obj())
- return analysis_system_obj
-
- def to_dict(self):
- analysis_system_dict = super(AnalysisSystem, self).to_dict()
- if len(self.installed_programs) > 0 : analysis_system_dict['installed_programs'] = self.installed_programs.to_list()
- return analysis_system_dict
-
- @staticmethod
- def from_dict(analysis_system_dict):
- if not analysis_system_dict:
- return None
- analysis_system_ = System.from_dict(AnalysisSystem, AnalysisSystem())
- analysis_system_.installed_programs = InstalledPrograms.from_list(analysis_system_dict.get('installed_programs'))
- return analysis_system_
-
- @staticmethod
- def from_obj(analysis_system_obj):
- if not analysis_system_obj:
- return None
- analysis_system_ = System.from_obj(AnalysisSystem, AnalysisSystem())
- if analysis_system_obj.get_Installed_Programs() is not None :
- analysis_system_.installed_programs = InstalledPrograms.from_obj(analysis_system_obj.get_Installed_Programs())
- return analysis_system_
-
-
-class InstalledPrograms(maec.EntityList):
- _contained_type = PlatformSpecification
- _binding_class = package_binding.InstalledProgramsType
- _binding_var = "Program"
- _namespace = maec.package._namespace
-
class AnalysisSystemList(maec.EntityList):
- _contained_type = AnalysisSystem
_binding_class = package_binding.AnalysisSystemListType
- _binding_var = "Analysis_System"
- _namespace = maec.package._namespace
+ _namespace = _namespace
+ analysis_system = fields.TypedField("Analysis_System", AnalysisSystem, multiple=True)
-class NetworkInfrastructure(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self):
- super(NetworkInfrastructure, self).__init__()
- self.captured_protocols = CapturedProtocolList()
+class CapturedProtocol(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.CapturedProtocolType
+ _namespace = _namespace
- def to_obj(self):
- network_infrastructure_obj = package_binding.NetworkInfrastructureType()
- if len(self.captured_protocols) > 0: network_infrastructure_obj.set_Captured_Protocols(self.captured_protocols.to_obj())
- return network_infrastructure_obj
+ layer7_protocol = fields.TypedField("layer7_protocol")
+ layer4_protocol = fields.TypedField("layer4_protocol")
+ port_number = fields.TypedField("port_number")
+ interaction_level = fields.TypedField("interaction_level")
- def to_dict(self):
- network_infrastructure_dict = {}
- if len(self.captured_protocols) > 0: network_infrastructure_dict['captured_protocols'] = self.captured_protocols.to_list()
- return network_infrastructure_dict
+ def __init__(self):
+ super(CapturedProtocol, self).__init__()
- @staticmethod
- def from_dict(network_infrastructure_dict):
- if not network_infrastructure_dict:
- return None
- network_infrastructure_ = NetworkInfrastructure()
- network_infrastructure_.captured_protocols = CapturedProtocolList.from_list(network_infrastructure_dict.get('captured_protocols'))
- return network_infrastructure_
+class CapturedProtocolList(maec.EntityList):
+ _binding_class = package_binding.CapturedProtocolListType
+ _namespace = _namespace
+ protocol = fields.TypedField("Protocol", CapturedProtocol, multiple=True)
- @staticmethod
- def from_obj(network_infrastructure_obj):
- if not network_infrastructure_obj:
- return None
- network_infrastructure_ = NetworkInfrastructure()
- if network_infrastructure_obj.get_Captured_Protocols() is not None :
- network_infrastructure_.captured_protocols = CapturedProtocolList.from_obj(network_infrastructure_obj.get_Captured_Protocols())
- return network_infrastructure_
+class NetworkInfrastructure(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.NetworkInfrastructureType
+ _namespace = _namespace
-class CapturedProtocol(maec.Entity):
- _namespace = maec.package._namespace
+ captured_protocols = fields.TypedField("Captured_Protocols", CapturedProtocolList)
def __init__(self):
- super(CapturedProtocol, self).__init__()
- self.layer7_protocol = None
- self.layer4_protocol = None
- self.port_number = None
- self.interaction_level = None
-
- def to_obj(self):
- captured_protocol_obj = package_binding.CapturedProtocolType()
- if self.layer7_protocol is not None : captured_protocol_obj.set_layer7_protocol(self.layer7_protocol)
- if self.layer4_protocol is not None : captured_protocol_obj.set_layer4_protocol(self.layer4_protocol)
- if self.port_number is not None : captured_protocol_obj.set_port_number(self.port_number)
- if self.interaction_level is not None : captured_protocol_obj.set_interaction_level(self.interaction_level)
- return captured_protocol_obj
-
- def to_dict(self):
- captured_protocol_dict = {}
- if self.layer7_protocol is not None : captured_protocol_dict['layer7_protocol'] = self.layer7_protocol
- if self.layer4_protocol is not None : captured_protocol_dict['layer4_protocol'] = self.layer4_protocol
- if self.port_number is not None : captured_protocol_dict['port_number'] = self.port_number
- if self.interaction_level is not None : captured_protocol_dict['interaction_level'] = self.interaction_level
- return captured_protocol_dict
-
- @staticmethod
- def from_dict(captured_protocol_dict):
- if not captured_protocol_dict:
- return None
- captured_protocol_ = CapturedProtocol()
- captured_protocol_.layer7_protocol = captured_protocol_dict.get('layer7_protocol')
- captured_protocol_.layer4_protocol = captured_protocol_dict.get('layer4_protocol')
- captured_protocol_.port_number = captured_protocol_dict.get('port_number')
- captured_protocol_.interaction_level = captured_protocol_dict.get('interaction_level')
- return captured_protocol_
-
- @staticmethod
- def from_obj(captured_protocol_obj):
- if not captured_protocol_obj:
- return None
- captured_protocol_ = CapturedProtocol()
- captured_protocol_.layer7_protocol = captured_protocol_obj.get_layer7_protocol()
- captured_protocol_.layer4_protocol = captured_protocol_dict.get_layer4_protocol()
- captured_protocol_.port_number = captured_protocol_dict.get_port_number()
- captured_protocol_.interaction_level = captured_protocol_dict.get_interaction_level()
- return captured_protocol_
+ super(NetworkInfrastructure, self).__init__()
+ self.captured_protocols = CapturedProtocolList()
-class CapturedProtocolList(maec.EntityList):
- _contained_type = CapturedProtocol
- _binding_class = package_binding.CapturedProtocolListType
- _binding_var = "Protocol"
- _namespace = maec.package._namespace
+class AnalysisEnvironment(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.AnalysisEnvironmentType
+ _namespace = _namespace
-class ToolList(maec.EntityList):
- _contained_type = ToolInformation
- _binding_class = package_binding.ToolListType
- _binding_var = "Tool"
- _namespace = maec.package._namespace
-
-class Source(maec.Entity):
- _namespace = maec.package._namespace
+ hypervisor_host_system = fields.TypedField("Hypervisor_Host_System", HypervisorHostSystem)
+ analysis_systems = fields.TypedField("Analysis_Systems", AnalysisSystemList)
+ network_infrastructure = fields.TypedField("Network_Infrastructure", NetworkInfrastructure)
def __init__(self):
- super(Source, self).__init__()
- self.name = None
- self.method = None
- self.reference = None
- self.organization = None
- self.url = None
-
- def to_obj(self):
- source_obj = package_binding.SourceType()
- if self.name is not None : source_obj.set_Name(self.name)
- if self.method is not None : source_obj.set_Method(self.method)
- if self.reference is not None : source_obj.set_Reference(self.reference)
- if self.organization is not None : source_obj.set_Organization(self.organization)
- if self.url is not None : source_obj.set_URL(self.url)
- return source_obj
+ super(AnalysisEnvironment, self).__init__()
- def to_dict(self):
- source_dict = {}
- if self.name is not None : source_dict['name'] = self.name
- if self.method is not None : source_dict['method'] = self.method
- if self.reference is not None : source_dict['reference'] = self.reference
- if self.organization is not None : source_dict['organization'] = self.organization
- if self.url is not None : source_dict['url'] = self.url
- return source_dict
-
- @staticmethod
- def from_dict(source_dict):
- if not source_dict:
- return None
- source_ = Source()
- source_.name = source_dict.get('name')
- source_.method = source_dict.get('method')
- source_.reference = source_dict.get('reference')
- source_.organization = source_dict.get('organization')
- source_.url = source_dict.get('url')
- return source_
-
- @staticmethod
- def from_obj(source_obj):
- if not source_obj:
- return None
- source_ = Source()
- source_.name = source_obj.get_Name()
- source_.method = source_obj.get_Method()
- source_.reference = source_obj.get_Reference()
- source_.organization = source_obj.get_Organization()
- source_.url = source_obj.get_URL()
- return source_
+class Analysis(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.AnalysisType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ method = fields.TypedField("method")
+ type_ = fields.TypedField("type")
+ ordinal_position = fields.TypedField("ordinal_position")
+ start_datetime = fields.TypedField("start_datetime")
+ complete_datetime = fields.TypedField("complete_datetime")
+ lastupdate_datetime = fields.TypedField("lastupdate_datetime")
+ source = fields.TypedField("Source", Source)
+ analysts = fields.TypedField("Analysts", Personnel)
+ summary = fields.TypedField("Summary", StructuredText)
+ comments = fields.TypedField("Comments", CommentList)
+ findings_bundle_reference = fields.TypedField("Findings_Bundle_Reference", BundleReference, multiple = True)
+ tools = fields.TypedField("Tools", ToolList)
+ dynamic_analysis_metadata = fields.TypedField("Dynamic_Analysis_Metadata", DynamicAnalysisMetadata)
+ analysis_environment = fields.TypedField("Analysis_Environment", AnalysisEnvironment)
+ report = fields.TypedField("Report", StructuredText)
+ def __init__(self, id = None, method = None, type = None, findings_bundle_reference = []):
+ super(Analysis, self).__init__()
+ if id:
+ self.id_ = id
+ else:
+ self.id_ = idgen.create_id(prefix="analysis")
+ self.method = method
+ self.type_ = type
+ self.findings_bundle_reference = findings_bundle_reference
+ #"Public" methods
+ # set the findings_bundle_reference values; accepts a list of bundle ID values
+ def set_findings_bundle(self, bundle_id):
+ self.findings_bundle_reference = [BundleReference.from_dict({'bundle_idref' : bundle_id})]
+ # add a tool to this Anaysis's ToolList
+ def add_tool(self, tool):
+ if not self.tools:
+ self.tools = ToolList()
+ self.tools.append(tool)
diff --git a/maec/package/grouping_relationship.py b/maec/package/grouping_relationship.py
index cc2fda8..2e29813 100644
--- a/maec/package/grouping_relationship.py
+++ b/maec/package/grouping_relationship.py
@@ -1,251 +1,81 @@
-#MAEC Grouping Relationship Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-import maec
-import maec.bindings.maec_package as package_binding
-from maec.package.malware_subject_reference import MalwareSubjectReference
-from cybox.common import VocabString
-
-class GroupingRelationship(maec.Entity):
- _namespace = maec.package._namespace
-
- def init(self):
- super(GroupingRelationship, self).__init__()
- self.type = None
- self.malware_family_name = None
- self.malware_toolkit_name = None
- self.clustering_metadata = None
-
- def to_obj(self):
- grouping_relationship_obj = package_binding.GroupingRelationshipType()
- if self.type is not None : grouping_relationship_obj.set_Type(self.type.to_obj())
- if self.malware_family_name is not None : grouping_relationship_obj.set_Malware_Family_Name(self.malware_family_name)
- if self.malware_toolkit_name is not None : grouping_relationship_obj.set_Malware_Toolkit_Name(self.malware_toolkit_name)
- if self.clustering_metadata is not None : grouping_relationship_obj.set_Clustering_Metadata(self.clustering_metadata.to_obj())
- return grouping_relationship_obj
-
- def to_dict(self):
- grouping_relationship_dict = {}
- if self.type is not None : grouping_relationship_dict['type'] = self.type.to_dict()
- if self.malware_family_name is not None : grouping_relationship_dict['malware_family_name'] = self.malware_family_name
- if self.malware_toolkit_name is not None : grouping_relationship_dict['malware_toolkit_name'] = self.malware_family_name
- if self.clustering_metadata is not None : grouping_relationship_dict['clustering_metadata'] = self.clustering_metadata.to_dict()
- return grouping_relationship_dict
-
- @staticmethod
- def from_dict(grouping_relationship_dict):
- if not grouping_relationship_dict:
- return None
- grouping_relationship_ = GroupingRelationship()
- grouping_relationship_.type = VocabString.from_dict(grouping_relationship_dict.get('type'))
- grouping_relationship_.malware_family_name = grouping_relationship_dict.get('malware_family_name')
- grouping_relationship_.malware_toolkit_name = grouping_relationship_dict.get('malware_toolkit_name')
- grouping_relationship_.clustering_metadata = ClusteringMetadata.from_dict(grouping_relationship_dict.get('clustering_metadata'))
- return grouping_relationship_
-
- @staticmethod
- def from_obj(grouping_relationship_obj):
- if not grouping_relationship_obj:
- return None
- grouping_relationship_ = GroupingRelationship()
- grouping_relationship_.type = VocabString.from_obj(grouping_relationship_obj.get_Type())
- grouping_relationship_.malware_family_name = grouping_relationship_obj.get_Malware_Family_Name()
- grouping_relationship_.malware_toolkit_name = grouping_relationship_obj.get_Malware_Toolkit_Name()
- grouping_relationship_.clustering_metadata = ClusteringMetadata.from_obj(grouping_relationship_obj.get_Clustering_Metadata())
- return grouping_relationship_
-
-class GroupingRelationshipList(maec.EntityList):
- _contained_type = GroupingRelationship
- _binding_class = package_binding.GroupingRelationshipListType
- _binding_var = "Grouping_Relationship"
- _namespace = maec.package._namespace
-
-class ClusteringMetadata(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self):
- super(ClusteringMetadata, self).__init__()
- self.algorithm_name = None
- self.algorithm_version = None
- self.algorithm_parameters = None
- self.cluster_size = None
- self.cluster_description = None
- self.cluster_composition = None
-
- def to_obj(self):
- clustering_metadata_obj = package_binding.ClusteringMetadataType()
- if self.algorithm_name is not None : clustering_metadata_obj.set_Algorithm_Name(self.algorithm_name)
- if self.algorithm_version is not None : clustering_metadata_obj.set_Algorithm_Version(self.algorithm_version)
- if self.algorithm_parameters is not None : clustering_metadata_obj.set_Algorithm_Parameters(self.algorithm_parameters.to_obj())
- if self.cluster_size is not None : clustering_metadata_obj.set_Cluster_Size(self.cluster_size)
- if self.cluster_description is not None : clustering_metadata_obj.set_Cluster_Description(self.cluster_description)
- if self.cluster_composition is not None : clustering_metadata_obj.set_Cluster_Composition(self.cluster_composition.to_obj())
- return clustering_metadata_obj
-
- def to_dict(self):
- clustering_metadata_dict = {}
- if self.algorithm_name is not None : clustering_metadata_dict['algorithm_name'] = self.algorithm_name
- if self.algorithm_version is not None : clustering_metadata_dict['algorithm_version'] = self.algorithm_version
- if self.algorithm_parameters is not None : clustering_metadata_dict['algorithm_parameters'] = self.algorithm_parameters.to_dict()
- if self.cluster_size is not None : clustering_metadata_dict['cluster_size'] = self.cluster_size
- if self.cluster_description is not None : clustering_metadata_dict['cluster_description'] = self.cluster_description
- if self.cluster_composition is not None : clustering_metadata_dict['cluster_composition'] = self.cluster_composition.to_dict()
- return clustering_metadata_dict
-
- @staticmethod
- def from_dict(clustering_metadata_dict):
- if not clustering_metadata_dict:
- return None
- clustering_metadata_ = ClusteringMetadata()
- clustering_metadata_.algorithm_name = clustering_metadata_dict.get('algorithm_name')
- clustering_metadata_.algorithm_version = clustering_metadata_dict.get('algorithm_version')
- clustering_metadata_.algorithm_parameters = ClusteringAlgorithmParameters.from_dict(clustering_metadata_dict.get('algorithm_parameters'))
- clustering_metadata_.cluster_size = clustering_metadata_dict.get('cluster_size')
- clustering_metadata_.cluster_description = clustering_metadata_dict.get('cluster_description')
- clustering_metadata_.cluster_composition = ClusterComposition.from_dict(clustering_metadata_dict.get('cluster_composition'))
- return clustering_metadata_
-
- @staticmethod
- def from_obj(clustering_metadata_obj):
- if not clustering_metadata_obj:
- return None
- clustering_metadata_ = ClusteringMetadata()
- clustering_metadata_.algorithm_name = clustering_metadata_obj.get_Algorithm_Name()
- clustering_metadata_.algorithm_version = clustering_metadata_obj.get_Algorithm_Version()
- clustering_metadata_.algorithm_parameters = ClusteringAlgorithmParameters.from_obj(clustering_metadata_obj.get_Algorithm_Parameters())
- clustering_metadata_.cluster_size = clustering_metadata_obj.get_Cluster_Size()
- clustering_metadata_.cluster_description = clustering_metadata_obj.get_Cluster_Description()
- clustering_metadata_.cluster_composition = ClusterComposition.from_obj(clustering_metadata_obj.get_Cluster_Composition())
- return clustering_metadata_
-
-
-class ClusteringAlgorithmParameters(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self):
- super(ClusteringAlgorithmParameters, self).__init__()
- self.distance_threshold = None
- self.number_of_iterations = None
-
- def to_obj(self):
- clustering_algorithm_parameters_obj = package_binding.ClusteringAlgorithmParametersType()
- if self.distance_threshold is not None : clustering_algorithm_parameters_obj.set_Distance_Threshold(self.distance_threshold)
- if self.number_of_iterations is not None : clustering_algorithm_parameters_obj.set_Number_of_Iterations(self.number_of_iterations)
- return clustering_algorithm_parameters_obj
-
- def to_dict(self):
- clustering_algorithm_parameters_dict = {}
- if self.distance_threshold is not None : clustering_algorithm_parameters_dict['distance_threshold'] = self.distance_threshold
- if self.number_of_iterations is not None : clustering_algorithm_parameters_dict['number_of_iterations'] = self.number_of_iterations
- return clustering_algorithm_parameters_dict
-
- @staticmethod
- def from_dict(clustering_algorithm_parameters_dict):
- if not clustering_algorithm_parameters_dict:
- return None
- clustering_algorithm_parameters_ = ClusteringAlgorithmParameters()
- clustering_algorithm_parameters_.distance_threshold = clustering_algorithm_parameters_dict.get('distance_threshold')
- clustering_algorithm_parameters_.number_of_iterations = clustering_algorithm_parameters_dict.get('number_of_iterations')
- return clustering_algorithm_parameters_
-
- @staticmethod
- def from_obj(clustering_algorithm_parameters_obj):
- if not clustering_algorithm_parameters_obj:
- return None
- clustering_algorithm_parameters_ = ClusteringAlgorithmParameters()
- clustering_algorithm_parameters_.distance_threshold = clustering_algorithm_parameters_obj.get_Distance_Threshold()
- clustering_algorithm_parameters_.number_of_iterations = clustering_algorithm_parameters_obj.get_Number_of_Iterations()
- return clustering_algorithm_parameters_
-
-class ClusterComposition(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self):
- super(ClusterComposition, self).__init__()
- self.score_type = None
- self.edge_node_pairs = []
-
- def to_obj(self):
- cluster_composition_obj = package_binding.ClusterCompositionType()
- if self.score_type is not None : cluster_composition_obj.set_score_type(self.score_type)
- if len(self.edge_node_pairs) > 0:
- for edge_node_pair in self.edge_node_pairs: cluster_composition_obj.add_Edge_Node_Pair(edge_node_pair.to_obj())
- return cluster_composition_obj
-
- def to_dict(self):
- cluster_composition_dict = {}
- if self.score_type is not None : cluster_composition_dict['score_type'] = self.score_type
- if len(self.edge_node_pairs) > 0:
- cluster_composition_dict['edge_node_pairs'] = [x.to_dict() for x in self.edge_node_pairs]
- return cluster_composition_dict
-
- @staticmethod
- def from_dict(cluster_composition_dict):
- if not cluster_composition_dict:
- return None
- cluster_composition_ = ClusterComposition()
- cluster_composition_.score_type = cluster_composition_dict.get('score_type')
- cluster_composition_.edge_node_pairs = [ClusterEdgeNodePair.from_dict(x) for x in cluster_composition_dict.get('edge_node_pairs',[])]
- return cluster_composition_
-
- @staticmethod
- def from_obj(cluster_composition_obj):
- if not cluster_composition_obj:
- return None
- cluster_composition_ = ClusterComposition()
- cluster_composition_.score_type = cluster_composition_obj.get_score_type()
- cluster_composition_.edge_node_pairs = [ClusterEdgeNodePair.from_obj(x) for x in cluster_composition_obj.get_Edge_Node_Pair()]
- return cluster_composition_
-
-class ClusterEdgeNodePair(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self):
- super(ClusterEdgeNodePair, self).__init__()
- self.similarity_index = None
- self.similarity_distance = None
- self.malware_subject_node_a = None
- self.malware_subject_node_b = None
-
- def to_obj(self):
- cluster_edge_node_pair_obj = package_binding.ClusterEdgeNodePairType()
- if self.similarity_index is not None : cluster_edge_node_pair_obj.set_similarity_index(self.similarity_index)
- if self.similarity_distance is not None : cluster_edge_node_pair_obj.set_similarity_distance(self.similarity_distance)
- if self.malware_subject_node_a is not None : cluster_edge_node_pair_obj.set_Malware_Subject_Node_A(self.malware_subject_node_a.to_obj())
- if self.malware_subject_node_b is not None : cluster_edge_node_pair_obj.set_Malware_Subject_Node_B(self.malware_subject_node_b.to_obj())
- return cluster_edge_node_pair_obj
-
- def to_dict(self):
- cluster_edge_node_pair_dict = {}
- if self.similarity_index is not None : cluster_edge_node_pair_dict['similarity_index'] = self.similarity_index
- if self.similarity_distance is not None : cluster_edge_node_pair_dict['similarity_distance'] = self.similarity_distance
- if self.malware_subject_node_a is not None : cluster_edge_node_pair_dict['malware_subject_node_a'] = self.malware_subject_node_a.to_dict()
- if self.malware_subject_node_b is not None : cluster_edge_node_pair_dict['malware_subject_node_b'] = self.malware_subject_node_b.to_dict()
- return cluster_edge_node_pair_dict
-
- @staticmethod
- def from_dict(cluster_edge_node_pair_dict):
- if not cluster_edge_node_pair_dict:
- return None
- cluster_edge_node_pair_ = ClusterEdgeNodePair()
- cluster_edge_node_pair_.similarity_index = cluster_edge_node_pair_dict.get('similarity_index')
- cluster_edge_node_pair_.similarity_distance = cluster_edge_node_pair_dict.get('similarity_distance')
- cluster_edge_node_pair_.malware_subject_node_a = MalwareSubjectReference.from_dict(cluster_edge_node_pair_dict.get('malware_subject_node_a'))
- cluster_edge_node_pair_.malware_subject_node_b = MalwareSubjectReference.from_dict(cluster_edge_node_pair_dict.get('malware_subject_node_b'))
- return cluster_edge_node_pair_
-
- @staticmethod
- def from_obj(cluster_edge_node_pair_obj):
- if not cluster_edge_node_pair_obj:
- return None
- cluster_edge_node_pair_ = ClusterEdgeNodePair()
- cluster_edge_node_pair_.similarity_index = cluster_edge_node_pair_obj.get_similarity_index()
- cluster_edge_node_pair_.similarity_distance = cluster_edge_node_pair_obj.get_similarity_distance()
- cluster_edge_node_pair_.malware_subject_node_a = MalwareSubjectReference.from_obj(cluster_edge_node_pair_obj.get_Malware_Subject_Node_A())
- cluster_edge_node_pair_.malware_subject_node_b = MalwareSubjectReference.from_obj(cluster_edge_node_pair_obj.get_Malware_Subject_Node_B())
- return cluster_edge_node_pair_
+# MAEC Grouping Relationship Class
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from mixbox import fields
+
+import maec
+from . import _namespace
+import maec.bindings.maec_package as package_binding
+from maec.package.malware_subject_reference import MalwareSubjectReference
+from cybox.common import vocabs
+from maec.vocabs.vocabs import GroupingRelationship as GroupingRelationshipVocab
+
+class ClusterEdgeNodePair(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.ClusterEdgeNodePairType
+ _namespace = _namespace
+
+ similarity_index = fields.TypedField("similarity_index")
+ similarity_distance = fields.TypedField("similarity_distance")
+ malware_subject_node_a = fields.TypedField("Malware_Subject_Node_A", MalwareSubjectReference)
+ malware_subject_node_b = fields.TypedField("Malware_Subject_Node_B", MalwareSubjectReference)
+
+ def __init__(self):
+ super(ClusterEdgeNodePair, self).__init__()
+
+class ClusterComposition(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.ClusterCompositionType
+ _namespace = _namespace
+
+ score_type = fields.TypedField("score_type")
+ edge_node_pair = fields.TypedField("Edge_Node_Pair", ClusterEdgeNodePair, multiple=True)
+
+ def __init__(self):
+ super(ClusterComposition, self).__init__()
+
+class ClusteringAlgorithmParameters(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.ClusteringAlgorithmParametersType
+ _namespace = _namespace
+
+ distance_threashold = fields.TypedField("Distance_Threashold")
+ number_of_iterations = fields.TypedField("Number_of_Iterations")
+
+ def __init__(self):
+ super(ClusteringAlgorithmParameters, self).__init__()
+
+class ClusteringMetadata(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.ClusteringMetadataType
+ _namespace = _namespace
+
+ algorithm_name = fields.TypedField("Algorithm_Name")
+ algorithm_version = fields.TypedField("Algorithm_Version")
+ algorithm_parameters = fields.TypedField("Algorithm_Parameters", ClusteringAlgorithmParameters)
+ cluster_size = fields.TypedField("Cluster_Size")
+ cluster_description = fields.TypedField("Cluster_Description")
+ cluster_composition = fields.TypedField("Cluster_Composition", ClusterComposition)
+
+ def __init__(self):
+ super(ClusteringMetadata, self).__init__()
+
+class GroupingRelationship(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.GroupingRelationshipType
+ _namespace = _namespace
+
+ type_ = vocabs.VocabField("Type", GroupingRelationshipVocab)
+ malware_family_name = fields.TypedField("Malware_Family_Name")
+ malware_toolkit_name = fields.TypedField("Malware_Toolkit_Name")
+ clustering_metadata = fields.TypedField("Clustering_Metadata", ClusteringMetadata)
+
+ def __init__(self):
+ super(GroupingRelationship, self).__init__()
+
+class GroupingRelationshipList(maec.EntityList):
+ _binding_class = package_binding.GroupingRelationshipListType
+ _namespace = _namespace
+ grouping_relationship = fields.TypedField("Grouping_Relationship", GroupingRelationship, multiple=True)
diff --git a/maec/package/malware_subject.py b/maec/package/malware_subject.py
index 7670d9c..9938285 100644
--- a/maec/package/malware_subject.py
+++ b/maec/package/malware_subject.py
@@ -1,614 +1,244 @@
-#MAEC Malware Subject Class
+# MAEC Malware Subject Class
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 06/24/2014
+from mixbox import fields
+from mixbox import idgen
-from cybox.common import VocabString, PlatformSpecification, ToolInformationList
+from cybox.common import vocabs, VocabString, PlatformSpecification, ToolInformation
from cybox.objects.file_object import File
from cybox.objects.uri_object import URI
from cybox.core import Object
import maec
+from . import _namespace
import maec.bindings.maec_package as package_binding
-from maec.bundle.bundle import Bundle
-from maec.package.action_equivalence import ActionEquivalenceList
-from maec.package.analysis import Analysis
-from maec.package.malware_subject_reference import MalwareSubjectReference
-from maec.package.object_equivalence import ObjectEquivalenceList
-
-
-class MalwareSubject(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self, id = None, malware_instance_object_attributes = None):
- super(MalwareSubject, self).__init__()
- if id:
- self.id = id
- else:
- self.id = maec.utils.idgen.create_id(prefix="malware_subject")
- #Set the Malware Instance Object Attributes (a CybOX object) if they are not none
- self.malware_instance_object_attributes = malware_instance_object_attributes
- self.label = []
- self.configuration_details = None
- self.minor_variants = MinorVariants()
- self.development_environment = None
- self.field_data = None
- #Instantiate the lists
- self.analyses = Analyses()
- self.findings_bundles = FindingsBundleList()
- self.relationships = MalwareSubjectRelationshipList()
- self.compatible_platform = []
-
- #Public methods
- #Set the Malware_Instance_Object_Attributes with a CybOX object
- def set_malware_instance_object_attributes(self, malware_instance_object_attributes):
- self.malware_instance_object_attributes = malware_instance_object_attributes
-
- #Add an Analysis to the Analyses
- def add_analysis(self, analysis):
- self.analyses.append(analysis)
-
- def get_analyses(self):
- return self.analyses
-
- #Get all Bundles in the Subject
- def get_all_bundles(self):
- return self.findings_bundles.bundles
-
- #Add a MAEC Bundle to the Findings Bundles
- def add_findings_bundle(self, bundle):
- self.findings_bundles.add_bundle(bundle)
-
- def to_obj(self):
- malware_subject_obj = package_binding.MalwareSubjectType(id = self.id)
- if self.malware_instance_object_attributes is not None: malware_subject_obj.set_Malware_Instance_Object_Attributes(self.malware_instance_object_attributes.to_obj())
- if self.minor_variants: malware_subject_obj.set_Minor_Variants(self.minor_variants.to_obj())
- if self.configuration_details: malware_subject_obj.set_Configuration_Details(self.configuration_details.to_obj())
- if self.development_environment: malware_subject_obj.set_Development_Environment(self.development_environment.to_obj())
- if self.field_data is not None: malware_subject_obj.set_Field_Data(self.field_data.to_obj())
- if self.analyses: malware_subject_obj.set_Analyses(self.analyses.to_obj())
- if self.findings_bundles : malware_subject_obj.set_Findings_Bundles(self.findings_bundles.to_obj())
- if self.relationships: malware_subject_obj.set_Relationships(self.relationships.to_obj())
- if self.label:
- for labl in self.label:
- malware_subject_obj.add_Label(labl.to_obj())
- if self.compatible_platform:
- for platform in self.compatible_platform:
- malware_subject_obj.add_Compatible_Platform(platform.to_obj())
- return malware_subject_obj
-
- def to_dict(self):
- malware_subject_dict = {}
- if self.id is not None : malware_subject_dict['id'] = self.id
- if self.malware_instance_object_attributes is not None: malware_subject_dict['malware_instance_object_attributes'] = self.malware_instance_object_attributes.to_dict()
- if self.minor_variants : malware_subject_dict['minor_variants'] = self.minor_variants.to_list()
- if self.configuration_details : malware_subject_dict['configuration_details'] = self.configuration_details.to_dict()
- if self.development_environment : malware_subject_dict['development_environment'] = self.development_environment.to_dict()
- if self.field_data is not None: malware_subject_dict['field_data'] = self.field_data.to_dict()
- if self.analyses : malware_subject_dict['analyses'] = self.analyses.to_list()
- if self.findings_bundles : malware_subject_dict['findings_bundles'] = self.findings_bundles.to_dict()
- if self.relationships : malware_subject_dict['relationships'] = self.relationships.to_list()
- if self.label:
- malware_subject_dict['label'] = [x.to_dict() for x in self.label]
- if self.compatible_platform:
- malware_subject_dict['compatible_platform'] = [x.to_dict() for x in self.compatible_platform]
- return malware_subject_dict
-
- #Build the Malware Subject from the input dictionary
- @staticmethod
- def from_dict(malware_subject_dict):
- if not malware_subject_dict:
- return None
- malware_subject_ = MalwareSubject(None)
- malware_subject_.id = malware_subject_dict.get('id')
- malware_subject_.malware_instance_object_attributes = Object.from_dict(malware_subject_dict.get('malware_instance_object_attributes'))
- malware_subject_.minor_variants = MinorVariants.from_list(malware_subject_dict.get('minor_variants'))
- malware_subject_.configuration_details = MalwareConfigurationDetails.from_dict(malware_subject_dict.get('configuration_details'))
- malware_subject_.development_environment = MalwareDevelopmentEnvironment.from_dict(malware_subject_dict.get('development_environment'))
- malware_subject_.field_data = None #TODO: add support
- malware_subject_.analyses = Analyses.from_list(malware_subject_dict.get('analyses'))
- malware_subject_.findings_bundles = FindingsBundleList.from_dict(malware_subject_dict.get('findings_bundles'))
- malware_subject_.relationships = MalwareSubjectRelationshipList.from_list(malware_subject_dict.get('id'))
- if malware_subject_dict.get('label'):
- malware_subject_.label = [VocabString.from_dict(x) for x in malware_subject_dict.get('label')]
- if malware_subject_dict.get('compatible_platform'):
- malware_subject_.compatible_platform = [PlatformSpecification.from_dict(x) for x in malware_subject_dict.get('compatible_platform')]
- return malware_subject_
-
- @staticmethod
- def from_obj(malware_subject_obj):
- if not malware_subject_obj:
- return None
- malware_subject_ = MalwareSubject(None)
- malware_subject_.id = malware_subject_obj.get_id()
- malware_subject_.malware_instance_object_attributes = Object.from_obj(malware_subject_obj.get_Malware_Instance_Object_Attributes())
- malware_subject_.minor_variants = MinorVariants.from_obj(malware_subject_obj.get_Minor_Variants())
- malware_subject_.configuration_details = MalwareConfigurationDetails.from_obj(malware_subject_obj.get_Configuration_Details())
- malware_subject_.development_environment = MalwareDevelopmentEnvironment.from_obj(malware_subject_obj.get_Development_Environment())
- malware_subject_.field_data = None #TODO: add support
- malware_subject_.analyses = Analyses.from_obj(malware_subject_obj.get_Analyses())
- malware_subject_.findings_bundles = FindingsBundleList.from_obj(malware_subject_obj.get_Findings_Bundles())
- malware_subject_.relationships = MalwareSubjectRelationshipList.from_obj(malware_subject_obj.get_Relationships())
- if malware_subject_obj.get_Label():
- malware_subject_.label = [VocabString.from_obj(x) for x in malware_subject_obj.get_Label()]
- if malware_subject_obj.get_Compatible_Platform():
- malware_subject_.compatible_platform = [PlatformSpecification.from_obj(x) for x in malware_subject_obj.get_Compatible_Platform()]
- return malware_subject_
-
- def deduplicate_bundles(self):
- """DeDuplicate all Findings Bundles in the Malware Subject. For now, only handles Objects"""
- for findings_bundle in self.findings_bundles.bundles:
- findings_bundle.deduplicate()
+from maec.bundle import Bundle
+from maec.package import (ActionEquivalenceList, Analysis,
+ MalwareSubjectReference, ObjectEquivalenceList)
+from maec.vocabs.vocabs import MalwareLabel
+from maec.vocabs.vocabs import MalwareConfigurationParameter as MalwareConfigParameterVocab
+from maec.vocabs.vocabs import MalwareSubjectRelationship as MalwareSubjectRelationshipVocab
class MinorVariants(maec.EntityList):
- _contained_type = Object
_binding_class = package_binding.MinorVariantListType
- _binding_var = "Minor_Variant"
- _namespace = maec.package._namespace
-
+ _namespace = _namespace
+ minor_variant = fields.TypedField("Minor_Variant", Object, multiple=True)
+
class Analyses(maec.EntityList):
- _contained_type = Analysis
_binding_class = package_binding.AnalysisListType
- _binding_var = "Analysis"
- _namespace = maec.package._namespace
+ _namespace = _namespace
+ analysis = fields.TypedField("Analysis", Analysis, multiple=True)
class MalwareSubjectRelationship(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareSubjectRelationshipType
+ _namespace = _namespace
+
+ malware_subject_reference = fields.TypedField("Malware_Subject_Reference", MalwareSubjectReference, multiple = True)
+ type_ = vocabs.VocabField("Type", MalwareSubjectRelationshipVocab)
def __init__(self):
super(MalwareSubjectRelationship, self).__init__()
- self.type = None
- self.malware_subject_references = []
-
- def to_obj(self):
- malware_subject_relationship_obj = package_binding.MalwareSubjectRelationshipType()
- if self.type is not None : malware_subject_relationship_obj.set_Type(self.type.to_obj())
- if len(self.malware_subject_references) > 0:
- for malware_subject_reference in self.malware_subject_references:
- malware_subject_relationship_obj.add_Malware_Subject_Reference(malware_subject_reference.to_obj())
- return malware_subject_relationship_obj
-
- def to_dict(self):
- malware_subject_relationship_dict = {}
- if self.type is not None : malware_subject_relationship_dict['type'] = self.type.to_dict()
- if len(self.malware_subject_references) > 0:
- malware_subject_refs = []
- for malware_subject_reference in self.malware_subject_references:
- malware_subject_refs.append(malware_subject_reference.to_dict())
- malware_subject_relationship_dict['malware_subject_references'] = malware_subject_refs
- return malware_subject_relationship_dict
-
- @staticmethod
- def from_dict(malware_subject_relationship_dict):
- if not malware_subject_relationship_dict:
- return None
- malware_subject_relationship_ = MalwareSubjectRelationship()
- malware_subject_relationship_.type = VocabString.from_dict(malware_subject_relationship_dict.get('type'))
- malware_subject_relationship_.malware_subject_references = [MalwareSubjectReference.from_dict(x) for x in malware_subject_relationship_dict.get('malware_subject_references', [])]
- return malware_subject_relationship_
-
- @staticmethod
- def from_obj(malware_subject_relationship_obj):
- if not malware_subject_relationship_obj:
- return None
- malware_subject_relationship_ = MalwareSubjectRelationship()
- malware_subject_relationship_.type = VocabString.from_obj(malware_subject_relationship_obj.get_Type())
- malware_subject_relationship_.malware_subject_references = [MalwareSubjectReference.from_obj(x) for x in malware_subject_relationship_obj.get_Malware_Subject_Reference()]
- return malware_subject_relationship_
+
class MalwareSubjectRelationshipList(maec.EntityList):
- _contained_type = MalwareSubjectRelationship
_binding_class = package_binding.MalwareSubjectRelationshipListType
- _binding_var = "Relationship"
- _namespace = maec.package._namespace
+ _namespace = _namespace
+ relationship = fields.TypedField("Relationship", MalwareSubjectRelationship, multiple=True)
+
+class MetaAnalysis(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.MetaAnalysisType
+ _namespace = _namespace
+
+ action_equivalences = fields.TypedField("Action_Equivalences", ActionEquivalenceList)
+ object_equivalences = fields.TypedField("Object_Equivalences", ObjectEquivalenceList)
+
+ def __init__(self):
+ super(MetaAnalysis, self).__init__()
class FindingsBundleList(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.FindingsBundleListType
+ _namespace = _namespace
+
+ meta_analysis = fields.TypedField("Meta_Analysis", MetaAnalysis)
+ bundle = fields.TypedField("Bundle", Bundle, multiple = True)
+ bundle_external_reference = fields.TypedField("Bundle_External_Reference", multiple = True)
def __init__(self):
super(FindingsBundleList, self).__init__()
- self.meta_analysis = None
- self.bundles = []
- self.bundle_external_references = []
def add_bundle(self, bundle):
- self.bundles.append(bundle)
+ if not self.bundle:
+ self.bundle = []
+ self.bundle.append(bundle)
def add_bundle_external_reference(self, bundle_external_reference):
- self.bundle_external_references.append(bundle_external_reference)
-
- def to_obj(self):
- findings_bundle_list_obj = package_binding.FindingsBundleListType()
- if self.meta_analysis is not None : findings_bundle_list_obj.set_Meta_Analysis(self.meta_analysis.to_obj())
- if len(self.bundles) > 0:
- for bundle in self.bundles: findings_bundle_list_obj.add_Bundle(bundle.to_obj())
- if len(self.bundle_external_references) > 0:
- for bundle_external_reference in self.bundle_external_references: findings_bundle_list_obj.add_Bundle_External_Reference(bundle_external_reference)
- return findings_bundle_list_obj
-
- def to_dict(self):
- findings_bundle_list_dict = {}
- if self.meta_analysis is not None : findings_bundle_list_dict['meta_analysis'] = self.meta_analysis.to_dict()
- if len(self.bundles) > 0:
- bundle_list = []
- for bundle in self.bundles: bundle_list.append(bundle.to_dict())
- findings_bundle_list_dict['bundles'] = bundle_list
- if len(self.bundle_external_references) > 0:
- bundle_external_refs_list = []
- for bundle_external_reference in self.bundle_external_references: bundle_external_refs_list.append(bundle_external_reference)
- findings_bundle_list_dict['bundle_external_references'] = bundle_external_refs_list
- return findings_bundle_list_dict
-
- @staticmethod
- def from_dict(findings_bundle_list_dict):
- if not findings_bundle_list_dict:
- return None
- findings_bundle_list_ = FindingsBundleList()
- findings_bundle_list_.meta_analysis = MetaAnalysis.from_dict(findings_bundle_list_dict.get('meta_analysis'))
- findings_bundle_list_.bundles = [Bundle.from_dict(x) for x in findings_bundle_list_dict.get('bundles', [])]
- findings_bundle_list_.bundle_external_references = [x for x in findings_bundle_list_dict.get('bundle_external_references', [])]
- return findings_bundle_list_
-
- @staticmethod
- def from_obj(findings_bundle_list_obj):
- if not findings_bundle_list_obj:
- return None
- findings_bundle_list_ = FindingsBundleList()
- findings_bundle_list_.meta_analysis = MetaAnalysis.from_obj(findings_bundle_list_obj.get_Meta_Analysis())
- findings_bundle_list_.bundles = [Bundle.from_obj(x) for x in findings_bundle_list_obj.get_Bundle()]
- findings_bundle_list_.bundle_external_references = [x for x in findings_bundle_list_obj.get_Bundle_External_Reference()]
- return findings_bundle_list_
-
-class MetaAnalysis(maec.Entity):
- _namespace = maec.package._namespace
-
- def __init__(self):
- super(MetaAnalysis, self).__init__()
- self.action_equivalences = None
- self.object_equivalences = None
-
- def to_obj(self):
- meta_analysis_obj = package_binding.MetaAnalysisType()
- if self.action_equivalences is not None : meta_analysis_obj.set_Action_Equivalences(self.action_equivalences.to_obj())
- if self.object_equivalences is not None : meta_analysis_obj.set_Object_Equivalences(self.object_equivalences.to_obj())
- return meta_analysis_obj
-
- def to_dict(self):
- meta_analysis_dict = {}
- if self.action_equivalences is not None : meta_analysis_dict['action_equivalences'] = self.action_equivalences.to_list()
- if self.object_equivalences is not None : meta_analysis_dict['object_equivalences'] = self.object_equivalences.to_list()
- return meta_analysis_dict
-
- @staticmethod
- def from_dict(meta_analysis_dict):
- if not meta_analysis_dict:
- return None
- meta_analysis_ = MetaAnalysis()
- meta_analysis_.action_equivalences = ActionEquivalenceList.from_list(meta_analysis_dict.get('action_equivalences'))
- meta_analysis_.object_equivalences = ObjectEquivalenceList.from_list(meta_analysis_dict.get('object_equivalences'))
- return meta_analysis_
-
- @staticmethod
- def from_obj(meta_analysis_obj):
- if not meta_analysis_obj:
- return None
- meta_analysis_ = MetaAnalysis()
- meta_analysis_.action_equivalences = ActionEquivalenceList.from_obj(meta_analysis_obj.get_Action_Equivalences())
- meta_analysis_.object_equivalences = ObjectEquivalenceList.from_obj(meta_analysis_obj.get_Object_Equivalences())
- return meta_analysis_
-
-class MalwareSubjectList(maec.EntityList):
- _contained_type = MalwareSubject
- _binding_class = package_binding.MalwareSubjectListType
- _binding_var = "Malware_Subject"
- _namespace = maec.package._namespace
+ if not self.bundle_external_reference:
+ self.bundle_external_reference = []
+ self.bundle_external_reference.append(bundle_external_reference)
class MalwareDevelopmentEnvironment(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareDevelopmentEnvironmentType
+ _namespace = _namespace
+
+ tools = fields.TypedField("Tools", ToolInformation)
+ debugging_file = fields.TypedField("Debugging_File", File, multiple = True)
def __init__(self):
super(MalwareDevelopmentEnvironment, self).__init__()
- self.tools = None
- self.debugging_file = None
-
- def to_obj(self):
- mal_dev_obj = package_binding.MalwareDevelopmentEnvironmentType()
- if self.tools is not None : mal_dev_obj.set_Tools(self.tools.to_obj())
- if self.debugging_file is not None:
- mal_dev_obj.set_Debugging_File([x.to_obj() for x in self.debugging_file])
- return mal_dev_obj
-
- def to_dict(self):
- mal_dev_dict = {}
- if self.tools is not None : mal_dev_dict['tools'] = self.tools.to_list()
- if self.debugging_file is not None:
- mal_dev_dict['debugging_file'] = [x.to_dict() for x in self.debugging_file]
- return mal_dev_dict
-
- @staticmethod
- def from_dict(mal_dev_dict):
- if not mal_dev_dict:
- return None
- mal_dev_env_ = MalwareDevelopmentEnvironment()
- mal_dev_env_.tools = ToolInformationList.from_list(mal_dev_dict['tools'])
- if mal_dev_dict.get('debugging_file'):
- mal_dev_env_.debugging_file = [File.from_dict(x) for x in mal_dev_dict['debugging_file']]
- return mal_dev_env_
-
- @staticmethod
- def from_obj(mal_dev_obj):
- if not mal_dev_obj:
- return None
- mal_dev_env_ = MalwareDevelopmentEnvironment()
- mal_dev_env_.tools = ToolInformationList.from_obj(mal_dev_obj.get_Tools())
- if mal_dev_obj.get_Debugging_File():
- mal_dev_env_.debugging_file = [File.from_obj(x) for x in mal_dev_obj.get_Debugging_File()]
- return mal_dev_env_
+
class MalwareConfigurationParameter(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareConfigurationParameterType
+ _namespace = _namespace
+
+ name = vocabs.VocabField("Name", MalwareConfigParameterVocab)
+ value = fields.TypedField("Value")
def __init__(self):
super(MalwareConfigurationParameter, self).__init__()
- self.name = None
- self.value = None
-
- def to_obj(self):
- mal_conf_param_obj = package_binding.MalwareConfigurationParameterType()
- if self.name is not None : mal_conf_param_obj.set_Name(self.name.to_obj())
- if self.value is not None : mal_conf_param_obj.set_Value(self.value)
- return mal_conf_param_obj
-
- def to_dict(self):
- mal_conf_param_dict = {}
- if self.name is not None : mal_conf_param_dict['name'] = self.name.to_dict()
- if self.value is not None : mal_conf_param_dict['value'] = self.value
- return mal_conf_param_dict
-
- @staticmethod
- def from_dict(mal_conf_param_dict):
- if not mal_conf_param_dict:
- return None
- mal_conf_param_ = MalwareConfigurationParameter()
- mal_conf_param_.name = VocabString.from_dict(mal_conf_param_dict['name'])
- if mal_conf_param_dict.get('value'): mal_conf_param_.value = mal_conf_param_dict['value']
- return mal_conf_param_
-
- @staticmethod
- def from_obj(mal_conf_param_obj):
- if not mal_conf_param_obj:
- return None
- mal_conf_param_ = MalwareConfigurationParameter()
- mal_conf_param_.name = VocabString.from_obj(mal_conf_param_obj.get_Name())
- if mal_conf_param_obj.get_Value(): mal_conf_param_.value = mal_conf_param_obj.get_Value()
- return mal_conf_param_
+
class MalwareBinaryConfigurationStorageDetails(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareBinaryConfigurationStorageDetailsType
+ _namespace = _namespace
+
+ file_offset = fields.TypedField("File_Offset")
+ section_name = fields.TypedField("Section_Name")
+ section_offset = fields.TypedField("Section_Offset")
def __init__(self):
super(MalwareBinaryConfigurationStorageDetails, self).__init__()
- self.file_offset = None
- self.section_name = None
- self.section_offset = None
-
- def to_obj(self):
- mal_binary_conf_storage_obj = package_binding.MalwareBinaryConfigurationStorageDetailsType()
- if self.file_offset is not None : mal_binary_conf_storage_obj.set_File_Offset(self.file_offset)
- if self.section_name is not None : mal_binary_conf_storage_obj.set_Section_Name(self.section_name)
- if self.section_offset is not None : mal_binary_conf_storage_obj.set_Section_Offset(self.section_offset)
- return mal_binary_conf_storage_obj
-
- def to_dict(self):
- mal_binary_conf_storage_dict = {}
- if self.file_offset is not None : mal_binary_conf_storage_dict['file_offset'] = self.file_offset
- if self.section_name is not None : mal_binary_conf_storage_dict['section_name'] = self.section_name
- if self.section_offset is not None : mal_binary_conf_storage_dict['section_offset'] = self.section_offset
- return mal_binary_conf_storage_dict
-
- @staticmethod
- def from_dict(mal_binary_conf_storage_dict):
- if not mal_binary_conf_storage_dict:
- return None
- mal_binary_conf_storage_ = MalwareBinaryConfigurationStorageDetails()
- if mal_conf_storage_dict['file_offset']: mal_binary_conf_storage_.file_offset = mal_conf_storage_dict['file_offset']
- if mal_conf_storage_dict['section_name']: mal_binary_conf_storage_.section_name = mal_conf_storage_dict['section_name']
- if mal_conf_storage_dict['section_offset']: mal_binary_conf_storage_.section_offset = mal_conf_storage_dict['section_offset']
- return mal_binary_conf_storage_
-
- @staticmethod
- def from_obj(mal_binary_conf_storage_obj):
- if not mal_binary_conf_storage_obj:
- return None
- mal_binary_conf_storage_ = MalwareBinaryConfigurationStorageDetails()
- mal_binary_conf_storage_.file_offset = mal_binary_conf_storage_obj.get_File_Offset()
- mal_binary_conf_storage_.section_name = mal_binary_conf_storage_obj.get_Section_Name()
- mal_binary_conf_storage_.section_offset = mal_binary_conf_storage_obj.get_Section_Offset()
- return mal_binary_conf_storage_
class MalwareConfigurationStorageDetails(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareConfigurationStorageDetailsType
+ _namespace = _namespace
+
+ malware_binary = fields.TypedField("Malware_Binary", MalwareBinaryConfigurationStorageDetails)
+ file = fields.TypedField("File", File)
+ url = fields.TypedField("URL", URI, multiple = True)
def __init__(self):
super(MalwareConfigurationStorageDetails, self).__init__()
- self.malware_binary = None
- self.file = None
- self.url = []
-
- def to_obj(self):
- mal_conf_storage_obj = package_binding.MalwareConfigurationStorageDetailsType()
- if self.malware_binary is not None : mal_conf_storage_obj.set_Malware_Binary(self.malware_binary.to_obj())
- if self.file is not None : mal_conf_storage_obj.set_File(self.file.to_obj())
- if self.url is not None:
- mal_conf_storage_obj.set_URL([x.to_obj() for x in self.url])
- return mal_conf_storage_obj
-
- def to_dict(self):
- mal_conf_storage_dict = {}
- if self.malware_binary is not None : mal_conf_storage_dict['malware_binary'] = self.malware_binary.to_dict()
- if self.file is not None : mal_conf_storage_dict['file'] = self.file.to_dict()
- if self.url is not None:
- mal_conf_storage_dict['url'] = [x.to_dict() for x in self.url]
- return mal_conf_storage_dict
-
- @staticmethod
- def from_dict(mal_conf_storage_dict):
- if not mal_conf_storage_dict:
- return None
- mal_conf_storage_ = MalwareConfigurationStorageDetails()
- mal_conf_storage_.malware_binary = MalwareBinaryConfigurationStorageDetails.from_dict(mal_conf_storage_dict['malware_binary'])
- mal_conf_storage_.file = File.from_dict(mal_conf_storage_dict['file'])
- if mal_conf_storage_dict['url']:
- mal_conf_storage_.url = [URI.from_dict(x) for x in mal_conf_storage_dict['configuration_parameter']]
- return mal_conf_storage_
-
- @staticmethod
- def from_obj(mal_conf_storage_obj):
- if not mal_conf_storage_obj:
- return None
- mal_conf_storage_ = MalwareConfigurationStorageDetails()
- mal_conf_storage_.malware_binary = MalwareBinaryConfigurationStorageDetails.from_obj(mal_conf_storage_obj.get_Malware_Binary())
- mal_conf_storage_.file = File.from_obj(mal_conf_storage_obj.get_File())
- if mal_conf_storage_obj.get_URL():
- mal_conf_storage_.url = [URI.from_obj(x) for x in mal_conf_obj.get_URL()]
- return mal_conf_storage_
class MalwareConfigurationObfuscationAlgorithm(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareConfigurationObfuscationAlgorithmType
+ _namespace = _namespace
+
+ ordinal_position = fields.TypedField("ordinal_position")
+ key = fields.TypedField("Key")
+ algorithm_name = fields.TypedField("Algorithm_Name", VocabString)
def __init__(self):
super(MalwareConfigurationObfuscationAlgorithm, self).__init__()
- self.ordinal_position = None
- self.key = None
- self.algorithm_name = None
-
- def to_obj(self):
- mal_binary_obfusc_alg_obj = package_binding.MalwareConfigurationObfuscationAlgorithmType()
- if self.ordinal_position is not None : mal_binary_obfusc_alg_obj.set_ordinal_position(self.ordinal_position)
- if self.key is not None : mal_binary_obfusc_alg_obj.set_Key(self.key)
- if self.algorithm_name is not None : mal_binary_obfusc_alg_obj.set_Algorithm_Name(self.algorithm_name.to_obj())
- return mal_binary_obfusc_alg_obj
-
- def to_dict(self):
- mal_binary_obfusc_alg_dict = {}
- if self.ordinal_position is not None : mal_binary_obfusc_alg_dict['ordinal_position'] = self.ordinal_position
- if self.key is not None : mal_binary_obfusc_alg_dict['key'] = self.key
- if self.algorithm_name is not None : mal_binary_obfusc_alg_dict['algorithm_name'] = self.algorithm_name.to_dict()
- return mal_binary_obfusc_alg_dict
-
- @staticmethod
- def from_dict(mal_binary_obfusc_alg_dict):
- if not mal_binary_obfusc_alg_dict:
- return None
- mal_binary_obfusc_alg_ = MalwareConfigurationObfuscationAlgorithm()
- if mal_binary_obfusc_alg_dict['ordinal_position']: mal_binary_obfusc_alg_.ordinal_position = mal_binary_obfusc_alg_dict['ordinal_position']
- if mal_binary_obfusc_alg_dict['key']: mal_binary_obfusc_alg_.key = mal_binary_obfusc_alg_dict['key']
- mal_binary_obfusc_alg_.algorithm_name = VocabString.from_dict(mal_binary_obfusc_alg_dict['algorithm_name'])
- return mal_binary_obfusc_alg_
-
- @staticmethod
- def from_obj(mal_binary_obfusc_alg_obj):
- if not mal_binary_obfusc_alg_obj:
- return None
- mal_binary_obfusc_alg_ = MalwareConfigurationObfuscationAlgorithm()
- mal_binary_obfusc_alg_.ordinal_position = mal_binary_obfusc_alg_obj.get_ordinal_position()
- mal_binary_obfusc_alg_.key = mal_binary_obfusc_alg_obj.get_Key()
- mal_binary_obfusc_alg_.algorithm_name = VocabString.from_obj(mal_binary_obfusc_alg_obj.get_Algorithm_name())
- return mal_binary_obfusc_alg_
+
class MalwareConfigurationObfuscationDetails(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareConfigurationObfuscationDetailsType
+ _namespace = _namespace
+
+ is_encoded = fields.TypedField("is_encoded")
+ is_encrypted = fields.TypedField("is_encrypted")
+ algorithm_details = fields.TypedField("Algorithm_Details", MalwareConfigurationObfuscationAlgorithm, multiple = True)
def __init__(self):
super(MalwareConfigurationObfuscationDetails, self).__init__()
- self.is_encoded = None
- self.is_encrypted = None
self.algorithm_details = []
- def to_obj(self):
- mal_conf_obfusc_obj = package_binding.MalwareConfigurationObfuscationDetailsType()
- if self.is_encoded is not None : mal_conf_obfusc_obj.set_is_encoded(self.is_encoded)
- if self.is_encrypted is not None : mal_conf_obfusc_obj.set_is_encrypted(self.is_encrypted)
- if self.algorithm_details is not None:
- mal_conf_obfusc_obj.set_Algorithm_Details([x.to_obj() for x in self.algorithm_details])
- return mal_conf_obfusc_obj
-
- def to_dict(self):
- mal_conf_obfusc_dict = {}
- if self.is_encoded is not None : mal_conf_obfusc_dict['is_encoded'] = self.is_encoded
- if self.is_encrypted is not None : mal_conf_obfusc_dict['is_encrypted'] = self.is_encrypted
- if self.algorithm_details is not None:
- mal_conf_obfusc_dict['algorithm_details'] = [x.to_dict() for x in self.algorithm_details]
- return mal_conf_obfusc_dict
-
- @staticmethod
- def from_dict(mal_conf_obfusc_dict):
- if not mal_conf_obfusc_dict:
- return None
- mal_conf_obfusc_ = MalwareConfigurationObfuscationDetails()
- if mal_conf_obfusc_dict['is_encoded']: mal_conf_obfusc_.is_encoded = mal_conf_obfusc_dict['is_encoded']
- if mal_conf_obfusc_dict['is_encrypted']: mal_conf_obfusc_.is_encrypted = mal_conf_obfusc_dict['is_encrypted']
- if mal_conf_obfusc_dict['algorithm_details']:
- mal_conf_obfusc_.algorithm_details = [MalwareConfigurationObfuscationAlgorithm.from_dict(x) for x in mal_conf_obfusc_dict['algorithm_details']]
- return mal_conf_obfusc_
-
- @staticmethod
- def from_obj(mal_conf_obfusc_obj):
- if not mal_conf_obfusc_obj:
- return None
- mal_conf_obfusc_ = MalwareConfigurationObfuscationDetails()
- mal_conf_obfusc_.is_encoded = mal_conf_obfusc_obj.get_is_encoded()
- mal_conf_obfusc_.is_encrypted = mal_conf_obfusc_obj.get_is_encrypted()
- if mal_conf_obfusc_obj.get_Algorithm_Details():
- mal_conf_obfusc_.algorithm_details = [MalwareConfigurationObfuscationAlgorithm.from_obj(x) for x in mal_conf_obfusc_obj.get_Algorithm_Details()]
- return mal_conf_obfusc_
class MalwareConfigurationDetails(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareConfigurationDetailsType
+ _namespace = _namespace
+
+ storage = fields.TypedField("Storage", MalwareConfigurationStorageDetails)
+ obfuscation = fields.TypedField("Obfuscation", MalwareConfigurationObfuscationDetails)
+ configuration_parameter = fields.TypedField("Configuration_Parameter", MalwareConfigurationParameter, multiple = True)
def __init__(self):
super(MalwareConfigurationDetails, self).__init__()
- self.storage = None
- self.obfuscation = None
- self.configuration_parameter = []
-
- def to_obj(self):
- mal_conf_obj = package_binding.MalwareConfigurationDetailsType()
- if self.storage is not None : mal_conf_obj.set_Storage(self.storage.to_obj())
- if self.obfuscation is not None : mal_conf_obj.set_Obfuscation(self.obfuscation.to_obj())
- if self.configuration_parameter is not None:
- mal_conf_obj.set_Configuration_Parameter([x.to_obj() for x in self.configuration_parameter])
- return mal_conf_obj
-
- def to_dict(self):
- mal_conf_dict = {}
- if self.storage is not None : mal_conf_dict['storage'] = self.storage.to_dict()
- if self.obfuscation is not None : mal_conf_dict['obfuscation'] = self.obfuscation.to_dict()
- if self.configuration_parameter is not None:
- mal_conf_dict['configuration_parameter'] = [x.to_dict() for x in self.configuration_parameter]
- return mal_conf_dict
-
- @staticmethod
- def from_dict(mal_conf_dict):
- if not mal_conf_dict:
- return None
- mal_conf_ = MalwareConfigurationDetails()
- mal_conf_.storage = MalwareConfigurationStorageDetails.from_dict(mal_conf_dict.get('storage'))
- mal_conf_.obfuscation = MalwareConfigurationStorageDetails.from_dict(mal_conf_dict.get('obfuscation'))
- if mal_dev_dict['configuration_parameter']:
- mal_conf_.configuration_parameter = [MalwareConfigurationParameter.from_dict(x) for x in mal_conf_dict.get('configuration_parameter')]
- return mal_conf_
-
- @staticmethod
- def from_obj(mal_conf_obj):
- if not mal_conf_obj:
- return None
- mal_conf_ = MalwareConfigurationDetails()
- mal_conf_.storage = MalwareConfigurationStorageDetails.from_obj(mal_conf_obj.get_Storage())
- mal_conf_.obfuscation = MalwareConfigurationStorageDetails.from_obj(mal_conf_obj.get_Obfuscation())
- if mal_conf_obj.get_Configuration_Parameter():
- mal_conf_.configuration_parameter = [MalwareConfigurationParameter.from_obj(x) for x in mal_conf_obj.get_Configuration_Parameter()]
- return mal_conf_
+
+class MalwareSubject(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.MalwareSubjectType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ malware_instance_object_attributes = fields.TypedField("Malware_Instance_Object_Attributes", Object)
+ label = vocabs.VocabField("Label", MalwareLabel, multiple=True)
+ configuration_details = fields.TypedField("Configuration_Details", MalwareConfigurationDetails)
+ minor_variants = fields.TypedField("Minor_Variants", MinorVariants)
+ development_environment = fields.TypedField("Development_Environment", MalwareDevelopmentEnvironment)
+ #field_data = fields.TypedField("field_data") # TODO: support metadata:fieldDataEntry
+ analyses = fields.TypedField("Analyses", Analyses)
+ findings_bundles = fields.TypedField("Findings_Bundles", FindingsBundleList)
+ relationships = fields.TypedField("Relationships", MalwareSubjectRelationshipList)
+ compatible_platform = fields.TypedField("Compatible_Platform", PlatformSpecification, multiple=True)
+
+ def __init__(self, id = None, malware_instance_object_attributes = None):
+ super(MalwareSubject, self).__init__()
+ if id:
+ self.id_ = id
+ else:
+ self.id_ = idgen.create_id(prefix="malware_subject")
+ #Set the Malware Instance Object Attributes (a CybOX object) if they are not none
+ self.malware_instance_object_attributes = malware_instance_object_attributes
+
+ #Public methods
+ #Set the Malware_Instance_Object_Attributes with a CybOX object
+ def set_malware_instance_object_attributes(self, malware_instance_object_attributes):
+ self.malware_instance_object_attributes = malware_instance_object_attributes
+
+ #Add an Analysis to the Analyses
+ def add_analysis(self, analysis):
+ if not self.analyses:
+ self.analyses = Analyses()
+ self.analyses.append(analysis)
+
+ def get_analyses(self):
+ return self.analyses
+
+ #Get all Bundles in the Subject
+ def get_all_bundles(self):
+ return self.findings_bundles.bundle
+
+ #Add a MAEC Bundle to the Findings Bundles
+ def add_findings_bundle(self, bundle):
+ if not self.findings_bundles:
+ self.findings_bundles = FindingsBundleList()
+ self.findings_bundles.add_bundle(bundle)
+
+ def deduplicate_bundles(self):
+ """DeDuplicate all Findings Bundles in the Malware Subject. For now, only handles Objects"""
+ all_bundles = self.get_all_bundles()
+ for bundle in all_bundles:
+ bundle.deduplicate()
+
+ def dereference_bundles(self):
+ """Dereference all Findings Bundles in the Malware Subject. For now, only handles Objects"""
+ all_bundles = self.get_all_bundles()
+ for bundle in all_bundles:
+ bundle.dereference_objects([self.malware_instance_object_attributes])
+
+ def normalize_bundles(self):
+ """Normalize all Findings Bundles in the Malware Subject. For now, only handles Objects"""
+ all_bundles = self.get_all_bundles()
+ for bundle in all_bundles:
+ bundle.normalize_objects()
+
+class MalwareSubjectList(maec.EntityList):
+ _binding_class = package_binding.MalwareSubjectListType
+ #_binding_var = "Malware_Subject"
+ _namespace = _namespace
+
+ malware_subject = fields.TypedField("Malware_Subject", MalwareSubject, multiple=True)
diff --git a/maec/package/malware_subject_reference.py b/maec/package/malware_subject_reference.py
index 6788bac..aadaf1d 100644
--- a/maec/package/malware_subject_reference.py
+++ b/maec/package/malware_subject_reference.py
@@ -1,44 +1,21 @@
-#MAEC Malware Subject Reference Class
+# MAEC Malware Subject Reference Class
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
import maec
+from . import _namespace
import maec.bindings.maec_package as package_binding
-
+
class MalwareSubjectReference(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.MalwareSubjectReferenceType
+ _namespace = _namespace
+
+ malware_subject_idref = fields.TypedField("malware_subject_idref")
- def init(self, malware_subject_idref = None):
+ def __init__(self, malware_subject_idref = None):
super(MalwareSubjectReference, self).__init__()
self.malware_subject_idref = malware_subject_idref
-
- def to_obj(self):
- malware_subject_reference_obj = package_binding.MalwareSubjectReferenceType()
- if self.malware_subject_idref is not None : malware_subject_reference_obj.set_malware_subject_idref(self.malware_subject_idref)
- return malware_subject_reference_obj
-
- def to_dict(self):
- malware_subject_reference_dict = {}
- if self.malware_subject_idref is not None : malware_subject_reference_dict['malware_subject_idref'] = self.malware_subject_idref
- return malware_subject_reference_dict
-
- @staticmethod
- def from_dict(malware_subject_reference_dict):
- if not malware_subject_reference_dict:
- return None
- malware_subject_reference_ = MalwareSubjectReference()
- malware_subject_reference_.malware_subject_idref = malware_subject_reference_dict.get('malware_subject_idref')
- return malware_subject_reference_
-
- @staticmethod
- def from_obj(malware_subject_reference_obj):
- if not malware_subject_reference_obj:
- return None
- malware_subject_reference_ = MalwareSubjectReference()
- malware_subject_reference_.malware_subject_idref = malware_subject_reference_obj.get_malware_subject_idref()
- return malware_subject_reference_
-
\ No newline at end of file
diff --git a/maec/package/object_equivalence.py b/maec/package/object_equivalence.py
index 2ee461f..12a44d4 100644
--- a/maec/package/object_equivalence.py
+++ b/maec/package/object_equivalence.py
@@ -1,59 +1,28 @@
-#MAEC Action Equivalence Class
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
-
-import maec
-import maec.bindings.maec_package as package_binding
-from maec.bundle.object_reference import ObjectReference
-
-class ObjectEquivalence(maec.Entity):
- _namespace = maec.package._namespace
-
- def init(self, id = None):
- super(ObjectEquivalence, self).__init__()
- self.id = id
- self.object_references = []
-
- def to_obj(self):
- object_equivalence_obj = package_binding.ObjectEquivalenceType()
- if self.id is not None : object_equivalence_obj.set_id(self.id)
- if len(self.object_references) > 0:
- for object_reference in self.object_references: object_equivalence_obj.add_object_Reference(object_reference.to_obj())
- return object_equivalence_obj
-
- def to_dict(self):
- object_equivalence_dict = {}
- if self.id is not None : object_equivalence_dict['id'] = self.id
- if len(self.object_references) > 0:
- object_reference_list = []
- for object_reference in self.object_references: object_reference_list.append(object_reference.to_dict())
- object_equivalence_dict['object_references'] = object_reference_list
- return object_equivalence_dict
-
- @staticmethod
- def from_dict(object_equivalence_dict):
- if not object_equivalence_dict:
- return None
- object_equivalence_ = ObjectEquivalence()
- object_equivalence_.id = object_equivalence_dict.get('id')
- object_equivalence_.object_references = [ObjectReference.from_dict(x) for x in object_equivalence_dict.get('object_references', [])]
- return object_equivalence_
-
- @staticmethod
- def from_obj(object_equivalence_obj):
- if not object_equivalence_obj:
- return None
- object_equivalence_ = ObjectEquivalence()
- object_equivalence_.id = object_equivalence_obj.get_id()
- object_equivalence_.object_references = [ObjectReference.from_obj(x) for x in object_equivalence_obj.get_object_Reference()]
- return object_equivalence_
-
-class ObjectEquivalenceList(maec.EntityList):
- _contained_type = ObjectEquivalence
- _binding_class = package_binding.ObjectEquivalenceListType
- _binding_var = "Object_Equivalence"
- _namespace = maec.package._namespace
\ No newline at end of file
+# MAEC Action Equivalence Class
+
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+from mixbox import fields
+
+import maec
+from . import _namespace
+import maec.bindings.maec_package as package_binding
+from maec.bundle import ObjectReference
+
+class ObjectEquivalence(maec.Entity):
+ _binding = package_binding
+ _binding_class = package_binding.ObjectEquivalenceType
+ _namespace = _namespace
+
+ id_ = fields.TypedField("id")
+ object_reference = fields.TypedField("Object_Reference", ObjectReference, multiple = True)
+
+ def init(self, id = None):
+ super(ObjectEquivalence, self).__init__()
+ self.id_ = id
+
+class ObjectEquivalenceList(maec.EntityList):
+ _binding_class = package_binding.ObjectEquivalenceListType
+ _namespace = _namespace
+ object_equivalence = fields.TypedField("Object_Equivalence", ObjectEquivalence, multiple=True)
diff --git a/maec/package/package.py b/maec/package/package.py
index b56a94b..9fa8119 100644
--- a/maec/package/package.py
+++ b/maec/package/package.py
@@ -1,83 +1,52 @@
-#MAEC Package Class
+# MAEC Package Class
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox import fields
+from mixbox import idgen
import maec
-import datetime
import maec.bindings.maec_package as package_binding
-from maec.package.malware_subject import MalwareSubjectList
-from maec.package.grouping_relationship import GroupingRelationshipList
+from maec.package import MalwareSubjectList, GroupingRelationshipList
+from . import _namespace
class Package(maec.Entity):
- _namespace = maec.package._namespace
+ _binding = package_binding
+ _binding_class = package_binding.PackageType
+ _namespace = _namespace
+
+ id_ = fields.TypedField('id')
+ timestamp = fields.TypedField('timestamp')
+ schema_version = fields.TypedField('schema_version')
+ malware_subjects = fields.TypedField('Malware_Subjects', MalwareSubjectList)
+ grouping_relationships = fields.TypedField('Grouping_Relationships', GroupingRelationshipList)
def __init__(self, id = None, schema_version = "2.1", timestamp = None):
super(Package, self).__init__()
if id:
- self.id = id
+ self.id_ = id
else:
- self.id = maec.utils.idgen.create_id(prefix="package")
+ self.id_ = idgen.create_id(prefix="package")
self.schema_version = schema_version
self.timestamp = timestamp
self.malware_subjects = MalwareSubjectList()
- self.grouping_relationships = GroupingRelationshipList()
+ self.__input_namespaces__ = {}
+ self.__input_schemalocations__ = {}
#Public methods
- #Add a malware subject
+ #Add a malware subject to this Package
def add_malware_subject(self, malware_subject):
self.malware_subjects.append(malware_subject)
-
+
#Add a grouping relationship
def add_grouping_relationship(self, grouping_relationship):
+ if not self.grouping_relationships:
+ self.grouping_relationships = GroupingRelationshipList()
self.grouping_relationships.append(grouping_relationship)
- def to_obj(self):
- package_obj = package_binding.PackageType(id=self.id)
- if self.schema_version is not None: package_obj.set_schema_version(self.schema_version)
- if self.timestamp is not None: package_obj.set_timestamp(self.timestamp.isoformat())
- if len(self.malware_subjects) > 0: package_obj.set_Malware_Subjects(self.malware_subjects.to_obj())
- if len(self.grouping_relationships) > 0: package_obj.set_Grouping_Relationships(self.grouping_relationships.to_obj())
- return package_obj
-
- def to_dict(self):
- package_dict = {}
- if self.id is not None : package_dict['id'] = self.id
- if self.schema_version is not None: package_dict['schema_version'] = self.schema_version
- if self.timestamp is not None: package_dict['timestamp'] = self.timestamp.isoformat()
- if len(self.malware_subjects) > 0: package_dict['malware_subjects'] = self.malware_subjects.to_list()
- if len(self.grouping_relationships) > 0: package_dict['grouping_relationships'] = self.grouping_relationships.to_list()
- return package_dict
- #Build the Package from the input dictionary
- @staticmethod
- def from_dict(package_dict):
- if not package_dict:
- return None
- package_ = Package(None)
- package_.id = package_dict.get('id')
- package_.schema_version = package_dict.get('schema_version')
- if package_dict.get('timestamp'):
- package_.timestamp = datetime.datetime.strptime(package_dict.get('timestamp'), "%Y-%m-%dT%H:%M:%S.%f")
- package_.malware_subjects = MalwareSubjectList.from_list(package_dict.get('malware_subjects', []))
- package_.grouping_relationships = GroupingRelationshipList.from_list(package_dict.get('grouping_relationships', []))
- return package_
-
- @staticmethod
- def from_obj(package_obj):
- if not package_obj:
- return None
- package_ = Package(None)
- package_.id = package_obj.get_id()
- package_.schema_version = package_obj.get_schema_version()
- package_.timestamp = package_obj.get_timestamp()
- if package_obj.get_Malware_Subjects() is not None : package_.malware_subjects = MalwareSubjectList.from_obj(package_obj.get_Malware_Subjects())
- if package_obj.get_Grouping_Relationships() is not None : package_.grouping_relationships = GroupingRelationshipList.from_obj(package_obj.get_Grouping_Relationships())
- return package_
-
+ # Create new Package from the XML document at the specified path
@staticmethod
def from_xml(xml_file):
'''
@@ -85,24 +54,16 @@ def from_xml(xml_file):
Parameters:
xml_file - either a filename or a stream object
'''
-
- if isinstance(xml_file, basestring):
- f = open(xml_file, "rb")
- else:
- f = xml_file
-
- doc = package_binding.parsexml_(f)
- maec_package_obj = package_binding.PackageType().factory()
- maec_package_obj.build(doc.getroot())
- maec_package = Package.from_obj(maec_package_obj)
-
- return (maec_package, maec_package_obj)
+ from maec.utils.parser import EntityParser
+
+ parser = EntityParser()
+ maec_package = parser.parse_xml(xml_file)
+ maec_package_obj = maec_package.to_obj()
+ return (maec_package, maec_package_obj)
+ # Transform duplicate objects within this Package into references pointing to a single canonical object
def deduplicate_malware_subjects(self):
"""DeDuplicate all Malware_Subjects in the Package. For now, only handles Objects in Findings Bundles"""
for malware_subject in self.malware_subjects:
malware_subject.deduplicate_bundles()
-
-
-
diff --git a/maec/test/__init__.py b/maec/test/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/maec/test/bundle/__init__.py b/maec/test/bundle/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/maec/test/bundle/av_classification_test.py b/maec/test/bundle/av_classification_test.py
new file mode 100644
index 0000000..3c34a03
--- /dev/null
+++ b/maec/test/bundle/av_classification_test.py
@@ -0,0 +1,25 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.bundle.av_classification import AVClassification
+
+class TestAVClassification(EntityTestCase, unittest.TestCase):
+ klass = AVClassification
+
+ _full_dict = {
+ 'classification_name':'Some!Trojan',
+ 'vendor':'McAfee'
+ }
+
+ def test_round_trip(self):
+ o = AVClassification('Some!Trojan')
+ o.vendor = 'McAfee'
+ o2 = round_trip(o, True)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/test/bundle/behavior_test.py b/maec/test/bundle/behavior_test.py
new file mode 100644
index 0000000..ebbf3e7
--- /dev/null
+++ b/maec/test/bundle/behavior_test.py
@@ -0,0 +1,46 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.bundle.bundle import Behavior
+
+class TestBehavior(EntityTestCase, unittest.TestCase):
+ klass = Behavior
+
+ _full_dict = {
+ 'ordinal_position': 1,
+ 'status': 'Success',
+ 'duration': 'PT3S',
+ 'description': 'Malware engages in some behavior wherein...',
+ 'purpose': {
+ 'description': 'Here is why the malware does this...',
+ 'vulnerability_exploit': {
+ 'known_vulnerability': True,
+ 'cve': {
+ 'cve_id': 'CVE-2013-1337',
+ 'description': '.NET vulnerability'
+ },
+ 'targeted_platforms': [{ 'description': 'Windows ME' }]
+ }
+ },
+ 'action_composition': {
+ 'action':[{ 'behavioral_ordering': 1 }],
+ 'action_reference':[{ 'action_id': 'some_id' }],
+ 'action_equivalence_reference':[{ 'behavioral_ordering': 1 }]
+ }
+ }
+
+ def test_id_autoset(self):
+ o = Behavior()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = Behavior()
+ o2 = round_trip(o, True)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
\ No newline at end of file
diff --git a/maec/test/bundle/bundle_test.py b/maec/test/bundle/bundle_test.py
new file mode 100644
index 0000000..04e01fd
--- /dev/null
+++ b/maec/test/bundle/bundle_test.py
@@ -0,0 +1,54 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.bundle.bundle import Bundle
+from maec.bundle.malware_action import MalwareAction
+from cybox.core import Object
+from maec.bundle.behavior import Behavior
+from maec.bundle.candidate_indicator import CandidateIndicator
+
+class TestBundle(EntityTestCase, unittest.TestCase):
+ klass = Bundle
+
+ _full_dict = {
+ 'defined_subject':False
+ }
+
+ def test_id_autoset(self):
+ o = Bundle()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = Bundle()
+ o2 = round_trip(o, True)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+ def test_add_collections(self):
+ o = Bundle()
+
+ o.add_named_action_collection("Actions")
+ ma = MalwareAction()
+ o.add_action(ma, "Actions")
+ self.assertTrue(o.collections.action_collections.has_collection("Actions"))
+
+ o.add_named_object_collection("Objects")
+ obj = Object()
+ o.add_object(obj, "Objects")
+ self.assertTrue(o.collections.object_collections.has_collection("Objects"))
+
+ o.add_named_behavior_collection("Behaviors")
+ b = Behavior()
+ o.add_behavior(b, "Behaviors")
+ self.assertTrue(o.collections.behavior_collections.has_collection("Behaviors"))
+
+ o.add_named_candidate_indicator_collection("Indicators")
+ ci = CandidateIndicator()
+ o.add_candidate_indicator(ci, "Indicators")
+ self.assertTrue(o.collections.candidate_indicator_collections.has_collection("Indicators"))
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/test/bundle/capability_test.py b/maec/test/bundle/capability_test.py
new file mode 100644
index 0000000..1efe5ca
--- /dev/null
+++ b/maec/test/bundle/capability_test.py
@@ -0,0 +1,53 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.bundle.capability import Capability
+
+class TestCapability(EntityTestCase, unittest.TestCase):
+ klass = Capability
+
+ _full_dict = {
+ 'description':'Perform some action',
+ 'strategic_objective':[{
+ 'name': {
+ 'vocab_reference':'http://maec.mitre.org/XMLSchema/default_vocabularies/2.1/maec_default_vocabularies.xsd#DataTheftStrategicObjectivesVocab-1.0',
+ 'value':'steal stored information'
+ },
+ 'property':[{
+ 'name': {
+ 'vocab_reference': 'http://maec.mitre.org/XMLSchema/default_vocabularies/2.1/maec_default_vocabularies.xsd#CommonCapabilityPropertiesVocab-1.0',
+ 'value':'encryption algorithm'
+ },
+ 'value': 'AES-256'
+ },
+ {
+ 'name': {
+ 'vocab_reference': 'http://maec.mitre.org/XMLSchema/default_vocabularies/2.1/maec_default_vocabularies.xsd#CommonCapabilityPropertiesVocab-1.0',
+ 'value':'protocol used'
+ },
+ 'value': 'TCP'
+ }]
+ }],
+ 'tactical_objective':[{
+ 'name': {
+ 'vocab_reference':'http://maec.mitre.org/XMLSchema/default_vocabularies/2.1/maec_default_vocabularies.xsd#FraudTacticalObjectivesVocab-1.0',
+ 'value':'access premium service'
+ }
+ }]
+ }
+
+ def test_id_autoset(self):
+ o = Capability()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = Capability()
+ o2 = round_trip(o, True)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
\ No newline at end of file
diff --git a/maec/test/bundle/process_tree_test.py b/maec/test/bundle/process_tree_test.py
new file mode 100644
index 0000000..a52f625
--- /dev/null
+++ b/maec/test/bundle/process_tree_test.py
@@ -0,0 +1,58 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.bundle.process_tree import ProcessTree, ProcessTreeNode
+
+class TestCapability(EntityTestCase, unittest.TestCase):
+ klass = ProcessTree
+
+ _full_dict = {
+ "root_process": {
+ "xsi:type": "ProcessTreeNodeType",
+ "id": "example:process_tree-7f44d6ed-1a0b-4bff-ae57-1491b751444f",
+ "injected_process": [{
+ "xsi:type": "ProcessTreeNodeType",
+ "id": "example:process_tree-2897a24c-5f0b-4850-a995-578c98f47ed7"
+ }],
+ "spawned_process": [{
+ "xsi:type": "ProcessTreeNodeType",
+ "id": "example:process_tree-3aacff1f-2c78-46c7-8e71-95d1a61dc05a",
+ "spawned_process": [{
+ "xsi:type": "ProcessTreeNodeType",
+ "id": "example:process_tree-a355d96b-8545-4ce5-b7e5-86670076ecf8"
+ }]
+ }, {
+ "xsi:type": "ProcessTreeNodeType",
+ "id": "example:process_tree-d5589470-c6a5-4d54-a576-62e79c9ba8a0"
+ }]
+ }
+ }
+
+
+ def test_id_autoset(self):
+ o = ProcessTreeNode()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = ProcessTree()
+ root = ProcessTreeNode()
+ spawned_child1 = ProcessTreeNode()
+ spawned_child2 = ProcessTreeNode()
+ injected_child = ProcessTreeNode()
+ spawned_grandchild = ProcessTreeNode()
+
+ o.set_root_process(root)
+ root.add_spawned_process(spawned_child1)
+ root.add_spawned_process(spawned_child2)
+ root.add_injected_process(injected_child)
+ spawned_child1.add_spawned_process(spawned_grandchild)
+
+ o2 = round_trip(o, True)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
\ No newline at end of file
diff --git a/maec/test/encoding_test.py b/maec/test/encoding_test.py
new file mode 100644
index 0000000..0a41506
--- /dev/null
+++ b/maec/test/encoding_test.py
@@ -0,0 +1,99 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+"""Tests for various encoding issues throughout the library"""
+
+import unittest
+
+from mixbox import binding_utils
+from mixbox.vendor.six import text_type
+
+from maec.package.malware_subject import MalwareConfigurationParameter
+from maec.package.analysis import DynamicAnalysisMetadata
+from maec.package.grouping_relationship import GroupingRelationship
+from maec.bundle.bundle import Bundle
+from maec.bundle.av_classification import AVClassification
+from maec.bundle.behavior import Behavior
+from maec.bundle.capability import Capability
+import maec.utils
+
+from cybox.test import round_trip
+
+UNICODE_STR = u"❤ ♎ ☀ ★ ☂ ♞ ☯ ☭ ☢ €☎⚑ ❄♫✂"
+
+class EncodingTests(unittest.TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.orig_encoding = binding_utils.ExternalEncoding
+ binding_utils.ExternalEncoding = 'utf-16'
+
+ @classmethod
+ def tearDownClass(cls):
+ binding_utils.ExternalEncoding = cls.orig_encoding
+
+ def test_malware_configuration_parameter(self):
+ config = MalwareConfigurationParameter()
+ config.value = UNICODE_STR
+ config2 = round_trip(config)
+ self.assertEqual(config.value, config2.value)
+
+ def test_dynamic_analysis_metadata(self):
+ metadata = DynamicAnalysisMetadata()
+ metadata.command_line = UNICODE_STR
+ metadata2 = round_trip(metadata)
+ self.assertEqual(metadata.command_line, metadata2.command_line)
+
+ def test_grouping_relationship(self):
+ relationship = GroupingRelationship()
+ relationship.malware_family_name = UNICODE_STR
+ relationship.malware_toolkit_name = UNICODE_STR
+ relationship2 = round_trip(relationship)
+ self.assertEqual(relationship.malware_family_name, relationship2.malware_family_name)
+ self.assertEqual(relationship.malware_toolkit_name, relationship2.malware_toolkit_name)
+
+ def test_behavior(self):
+ behavior = Behavior()
+ behavior.description = UNICODE_STR
+ behavior2 = round_trip(behavior)
+ self.assertEqual(behavior.description, behavior2.description)
+
+ def test_capability(self):
+ capability = Capability()
+ capability.description = UNICODE_STR
+ capability2 = round_trip(capability)
+ self.assertEqual(capability.description, capability2.description)
+
+ def test_av_classification(self):
+ av_class = AVClassification()
+ av_class.engine_version = UNICODE_STR
+ av_class.definition_version = UNICODE_STR
+ av_class.classification_name = UNICODE_STR
+ av_class2 = round_trip(av_class)
+ self.assertEqual(av_class.engine_version, av_class2.engine_version)
+ self.assertEqual(av_class.definition_version, av_class2.definition_version)
+ self.assertEqual(av_class.classification_name, av_class2.classification_name)
+
+ def test_to_xml_utf16_encoded(self):
+ encoding = 'utf-16'
+ b = Behavior()
+ b.description = UNICODE_STR
+ xml = b.to_xml(encoding=encoding)
+ self.assertTrue(UNICODE_STR in xml.decode(encoding))
+
+ def test_to_xml_default_encoded(self):
+ b = Behavior()
+ b.description = UNICODE_STR
+ xml = b.to_xml()
+ self.assertTrue(UNICODE_STR in xml.decode('utf-8'))
+
+ def test_to_xml_no_encoding(self):
+ b = Behavior()
+ b.description = UNICODE_STR
+ xml = b.to_xml(encoding=None)
+ self.assertTrue(isinstance(xml, text_type))
+ self.assertTrue(UNICODE_STR in xml)
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/test/package/__init__.py b/maec/test/package/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/maec/test/package/analysis_test.py b/maec/test/package/analysis_test.py
new file mode 100644
index 0000000..5583bfc
--- /dev/null
+++ b/maec/test/package/analysis_test.py
@@ -0,0 +1,44 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.package.analysis import Analysis, Source
+
+
+class TestPackage(EntityTestCase, unittest.TestCase):
+ klass = Analysis
+
+ _full_dict = {
+ "source": {
+ "url": "http://www.threatexpert.com",
+ "organization": "ThreatExpert",
+ "name": "ThreatExpert",
+ "method": "triage"
+ },
+ "start_datetime": "2014-08-06T18:30:00",
+ "id": "example:analysis-5e1a1095-65a7-459e-9272-2c7883d9c20f"
+ }
+
+
+ def test_id_autoset(self):
+ o = Analysis()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = Analysis()
+ o.source = Source()
+ o.source.name = "ThreatExpert"
+ o.source.organization = "ThreatExpert"
+ o.source.method = "triage"
+ o.source.url = "http://www.threatexpert.com"
+
+ o.start_datetime = "2014-08-06T18:30:00"
+
+ o2 = round_trip(o, True)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
\ No newline at end of file
diff --git a/maec/test/package/malware_subject_test.py b/maec/test/package/malware_subject_test.py
new file mode 100644
index 0000000..4b21890
--- /dev/null
+++ b/maec/test/package/malware_subject_test.py
@@ -0,0 +1,71 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.package.malware_subject import MalwareSubject
+from maec.bundle.bundle import Bundle
+
+class TestMalwareSubject(EntityTestCase, unittest.TestCase):
+ klass = MalwareSubject
+
+ _full_dict = {
+ 'label':['worm','virus'],
+ 'findings_bundles': {
+ 'bundle': [{
+ 'actions': [{
+ 'associated_objects': [{
+ 'association_type': u'output',
+ 'id': 'example:Object-fdba414a-e46a-4abf-ad50-4dcda819129c',
+ 'properties': {
+ 'file_name': u'abcd.dll',
+ 'size_in_bytes': 123456,
+ 'xsi:type': 'FileObjectType'
+ }
+ }],
+ 'id': 'example:action-912c7a09-91f5-4737-9b5a-129eb42488bf',
+ 'name': {
+ 'value': u'create file',
+ 'xsi:type': 'maecVocabs:FileActionNameVocab-1.0'
+ },
+ }],
+ 'capabilities': {
+ 'capability': [{
+ 'id': 'example:capability-5b1f99c6-203b-422d-831e-b440a1a32052',
+ 'name': 'persistence'
+
+ }],
+ },
+ 'defined_subject': False,
+ 'id': 'example:bundle-09642c48-9136-4f46-98b2-e8f9fb6f69ad',
+ 'schema_version': '4.1'
+ }]
+ },
+ 'id': 'example:malware_subject-89f6a399-badf-43cc-bf66-fd97c66ce4b2',
+ 'malware_instance_object_attributes': {
+ 'id': 'example:Object-aeb67018-a0e9-4199-bafa-1f0c581fb315',
+ 'properties': {
+ 'hashes': [{
+ 'simple_hash_value': u'8743b52063cd84097a65d1633f5c74f5',
+ 'type': u'MD5'
+ }],
+ 'size_in_bytes': 35532,
+ 'xsi:type': 'FileObjectType'
+ }
+ }
+ }
+
+ def test_id_autoset(self):
+ o = MalwareSubject()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = MalwareSubject()
+ o.add_findings_bundle(Bundle())
+ o2 = round_trip(o)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/test/package/package_test.py b/maec/test/package/package_test.py
new file mode 100644
index 0000000..e2f0034
--- /dev/null
+++ b/maec/test/package/package_test.py
@@ -0,0 +1,71 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from cybox.test import EntityTestCase, round_trip
+from maec.package import Package
+
+class TestPackage(EntityTestCase, unittest.TestCase):
+ klass = Package
+
+ _full_dict = {
+ 'malware_subjects':[{
+ 'findings_bundles': {
+ 'bundle': [{
+ 'actions': [{
+ 'associated_objects': [{
+ 'association_type': u'output',
+ 'id': 'example:Object-fdba414a-e46a-4abf-ad50-4dcda819129c',
+ 'properties': {
+ 'file_name': u'abcd.dll',
+ 'size_in_bytes': 123456,
+ 'xsi:type': 'FileObjectType'
+ }
+ }],
+ 'id': 'example:action-912c7a09-91f5-4737-9b5a-129eb42488bf',
+ 'name': {
+ 'value': u'create file',
+ 'xsi:type': 'maecVocabs:FileActionNameVocab-1.0'
+ },
+ }],
+ 'capabilities': {
+ 'capability': [{
+ 'id': 'example:capability-5b1f99c6-203b-422d-831e-b440a1a32052',
+ 'name': 'persistence'
+
+ }],
+ },
+ 'defined_subject': False,
+ 'id': 'example:bundle-09642c48-9136-4f46-98b2-e8f9fb6f69ad',
+ 'schema_version': '4.1'
+ }]
+ },
+ 'id': 'example:malware_subject-89f6a399-badf-43cc-bf66-fd97c66ce4b2',
+ 'malware_instance_object_attributes': {
+ 'id': 'example:Object-aeb67018-a0e9-4199-bafa-1f0c581fb315',
+ 'properties': {
+ 'hashes': [{
+ 'simple_hash_value': u'8743b52063cd84097a65d1633f5c74f5',
+ 'type': u'MD5'
+ }],
+ 'size_in_bytes': 35532,
+ 'xsi:type': 'FileObjectType'
+ }
+ }}],
+ 'grouping_relationships':[{'type':{'value':'same malware family',
+ 'xsi:type':'maecVocabs:GroupingRelationshipTypeVocab-1.0'}}]
+ }
+
+ def test_id_autoset(self):
+ o = Package()
+ self.assertNotEqual(o.id_, None)
+
+ def test_round_trip(self):
+ o = Package()
+ o2 = round_trip(o)
+
+ self.assertEqual(o.to_dict(), o2.to_dict())
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/test/utils/__init__.py b/maec/test/utils/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/maec/test/utils/nsparser_test.py b/maec/test/utils/nsparser_test.py
new file mode 100644
index 0000000..6215e12
--- /dev/null
+++ b/maec/test/utils/nsparser_test.py
@@ -0,0 +1,18 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import unittest
+
+from maec.utils.nsparser import MAEC_NAMESPACES
+
+
+class NSParserTests(unittest.TestCase):
+
+ def test_import(self):
+ """Verify that the namespace list was imported successfully."""
+ self.assertTrue(MAEC_NAMESPACES)
+ self.assertEqual(3, len(MAEC_NAMESPACES))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/test/utils/parser_test.py b/maec/test/utils/parser_test.py
new file mode 100644
index 0000000..c69cb0c
--- /dev/null
+++ b/maec/test/utils/parser_test.py
@@ -0,0 +1,99 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+from mixbox.vendor.six import StringIO
+import unittest
+
+from mixbox.parser import (UnknownVersionError, UnsupportedRootElementError,
+ UnsupportedVersionError)
+
+from maec.bundle import Bundle
+from maec.package import Package
+from maec.utils import EntityParser
+
+
+class ParserTests(unittest.TestCase):
+
+ def test_valid_package(self):
+ valid_package = """
+
+
+ """
+
+ parser = EntityParser()
+ package = parser.parse_xml(StringIO(valid_package))
+
+ self.assertEqual(Package, type(package))
+ self.assertEqual("example:package-1", package.id_)
+
+ def test_valid_bundle(self):
+ valid_bundle = """
+
+
+ """
+
+ parser = EntityParser()
+ package = parser.parse_xml(StringIO(valid_bundle))
+
+ self.assertEqual("example:bundle-1", package.id_)
+
+ def test_wrong_root_element(self):
+ wrong_root = """
+
+
+ """
+
+ parser = EntityParser()
+ self.assertRaises(UnsupportedRootElementError,
+ parser.parse_xml, StringIO(wrong_root))
+
+ # If there's not a valid root element, there's no way to check the
+ # version number.
+ self.assertRaises(UnsupportedVersionError,
+ parser.parse_xml, StringIO(wrong_root),
+ check_root=False)
+
+ def test_wrong_version(self):
+ wrong_version = """
+
+
+ """
+
+ parser = EntityParser()
+ self.assertRaises(UnsupportedVersionError,
+ parser.parse_xml, StringIO(wrong_version))
+
+ package = parser.parse_xml(StringIO(wrong_version),
+ check_version=False)
+
+ self.assertEqual("example:package-1", package.id_)
+ self.assertEqual("10.1.8", package.schema_version)
+
+ def test_missing_version(self):
+ missing_version = """
+
+
+ """
+
+ parser = EntityParser()
+ self.assertRaises(UnknownVersionError,
+ parser.parse_xml, StringIO(missing_version))
+
+ package = parser.parse_xml(StringIO(missing_version),
+ check_version=False)
+
+ self.assertEqual("example:package-1", package.id_)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/maec/utils/__init__.py b/maec/utils/__init__.py
index b868860..ef331dc 100644
--- a/maec/utils/__init__.py
+++ b/maec/utils/__init__.py
@@ -1,19 +1,27 @@
-#MAEC Utility Methods
-
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
-
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+"""MAEC utility methods"""
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox.vendor.six import iteritems
-"""MAEC utility methods"""
+def flip_dict(d):
+ """Returns a copy of the input dictionary `d` where the values of `d`
+ become the keys and the keys become the values.
-from .nsparser import maecMETA
-from .idgen import *
-from .parser import EntityParser
+ Note:
+ This does not even attempt to address key collisions.
+ Args:
+ d: A dictionary
+ """
+ return dict((v,k) for k, v in iteritems(d))
-
+# Namespace flattening
+from .parser import EntityParser # noqa
+from .comparator import (ObjectHash, BundleComparator, SimilarObjectCluster, # noqa
+ ComparisonResult) # noqa
+from .deduplicator import BundleDeduplicator # noqa
+#Ensure MAEC namespaces get registered
+from .nsparser import * # noqa
diff --git a/maec/utils/comparator.py b/maec/utils/comparator.py
index 330e8f7..8aea9aa 100644
--- a/maec/utils/comparator.py
+++ b/maec/utils/comparator.py
@@ -1,11 +1,11 @@
# MAEC Comparator Classes
-import collections
+from mixbox import compat
class ComparisonResult(object):
def __init__(self, bundle_list, lookup_table):
self.lookup_table = lookup_table
self.bundle_list = bundle_list
-
+
def get_unique(self, bundle_list=None):
unique_objs = {}
@@ -13,7 +13,7 @@ def get_unique(self, bundle_list=None):
bundle_list = self.bundle_list
for b in self.bundle_list:
- unique_objs[b.id] = []
+ unique_objs[b.id_] = []
for obj_hash in self.lookup_table:
sources = BundleComparator.get_sources(self.lookup_table, obj_hash)
@@ -59,7 +59,8 @@ def add_object(self, obj, owner):
def get_object_by_owner_id(self, owner_id):
return self[owner_id][0]["object"]
-
+
+
class BundleComparator(object):
@classmethod
def compare(cls, bundle_list, match_on = None, case_sensitive = True):
@@ -68,18 +69,13 @@ def compare(cls, bundle_list, match_on = None, case_sensitive = True):
if not match_on:
# Default matching properties
cls.match_on = {
- 'FileObjectType':
- ['file_name', 'file_path'],
- 'WindowsRegistryKeyObjectType':
- ['hive','key'],
- 'WindowsMutexObjectType':
- ['name'],
- 'SocketObjectType':
- ['address_value', 'port_value'],
- 'WindowsPipeObjectType':
- ['name'],
- 'ProcessObjectType':
- ['name']}
+ 'FileObjectType': ['file_name', 'file_path'],
+ 'WindowsRegistryKeyObjectType': ['hive','key'],
+ 'WindowsMutexObjectType': ['name'],
+ 'SocketObjectType': ['address_value', 'port_value'],
+ 'WindowsPipeObjectType': ['name'],
+ 'ProcessObjectType': ['name']
+ }
else:
cls.match_on = match_on
@@ -87,10 +83,10 @@ def compare(cls, bundle_list, match_on = None, case_sensitive = True):
for bundle in bundle_list:
for action in bundle.get_all_actions():
- cls.process_action(action, lookup_table, bundle.id)
+ cls.process_action(action, lookup_table, bundle.id_)
for obj in bundle.get_all_objects():
- cls.process_object(obj, lookup_table, bundle.id)
+ cls.process_object(obj, lookup_table, bundle.id_)
return ComparisonResult(bundle_list, lookup_table)
@@ -121,6 +117,7 @@ def get_sources(cls, lookup_table, obj_hash):
val.append(obj_dict_list[0]['ownerBundle'])
return val
+
class ObjectHash(object):
@classmethod
def get_hash(cls, obj, match_on, case_sensitive):
@@ -128,18 +125,18 @@ def get_hash(cls, obj, match_on, case_sensitive):
cls.case_sensitive = case_sensitive
hash_val = ''
- for typed_field in obj.properties._get_vars():
+ for attrname, typed_field in obj.properties.typed_fields_with_attrnames():
# Make sure the typed field is comparable
if typed_field.comparable:
# Check if we're dealing with a nested element that we want to compare
- nested_element = cls.is_nested_match(str(typed_field), cls.match_on[obj.properties._XSI_TYPE])
+ nested_element = cls.is_nested_match(attrname, cls.match_on[obj.properties._XSI_TYPE])
# Handle the normal, non-nested case
- if not nested_element and str(typed_field) in cls.match_on[obj.properties._XSI_TYPE]:
- hash_val = cls.get_val(obj, typed_field, hash_val)
+ if not nested_element and attrname in cls.match_on[obj.properties._XSI_TYPE]:
+ hash_val = cls.get_val(obj, attrname, hash_val)
# Handle the nested case
elif nested_element:
split_nested_element = nested_element.split('.')
- hash_val = cls.get_val(obj, typed_field, hash_val, split_nested_element[1:])
+ hash_val = cls.get_val(obj, attrname, hash_val, split_nested_element[1:])
if not cls.case_sensitive:
return hash_val.lower()
else:
@@ -157,7 +154,7 @@ def get_val(cls, obj, typed_field, hash_val, nested_elements = None):
val = getattr(obj.properties, str(typed_field))
if val is not None:
hash_val += str(typed_field) + ":"
- if isinstance(val, collections.MutableSequence):
+ if isinstance(val, compat.MutableSequence):
for list_item in val:
if '/' in str(nested_elements[0]):
hash_val += '['
diff --git a/maec/utils/deduplicator.py b/maec/utils/deduplicator.py
index 8695805..7b96fa3 100644
--- a/maec/utils/deduplicator.py
+++ b/maec/utils/deduplicator.py
@@ -1,14 +1,23 @@
# MAEC Bundle Deduplicator Module
-# Last updated: 12/3/2013
-import collections
-import cybox
-import sets
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
+
+# See LICENSE.txt for complete terms
+
import copy
+
+from mixbox import compat
+from mixbox import entities
+
+from cybox.core import RelatedObject, AssociatedObject
from cybox.common.properties import BaseProperty
+from mixbox.vendor.six import iteritems
+
class BundleDeduplicator(object):
@classmethod
def deduplicate(cls, bundle):
+ """Deduplicate the input Bundle."""
# Dictionary of all unique objects
# Key = object type (xsi:type)
# Value = dictionary of unique objects for that type
@@ -17,6 +26,10 @@ def deduplicate(cls, bundle):
cls.objects_dict = {}
# Dictionary of non-unique -> unique Object ID mappings
cls.object_ids_mapping = {}
+ # Dictionary of Objects with IDs
+ cls.id_objects = {}
+ # Dictionary of Objects with IDrefs
+ cls.idref_objects = {}
# Get all Objects in the Bundle
all_objects = bundle.get_all_objects(include_actions=True)
# Perform the Object mapping
@@ -25,148 +38,185 @@ def deduplicate(cls, bundle):
if cls.object_ids_mapping:
# Next, add the unique objects to their own collection
cls.handle_unique_objects(bundle, all_objects)
- # Replace the non-unique Objects with references
+ # Replace the non-unique Objects with references
# to unique Objects across the entire Bundle
cls.handle_duplicate_objects(bundle, all_objects)
# Finally, perform some cleanup to handle strange
# cases where you may have Objects pointing to each other
cls.cleanup(bundle)
- # Cleanup and remove and Objects that may be referencing the re-used Objects
- # Otherwise, this can create Object->Object->Object etc. references which don't make sense
@classmethod
def cleanup(cls, bundle):
+ """Cleanup and remove and Objects that may be referencing the re-used Objects.
+ Otherwise, this can create Object->Object->Object etc. references which don't make sense.
+ """
+ object_ids = cls.object_ids_mapping.values() # copy aside for lookup later
+
# Cleanup the root-level Objects
if bundle.objects:
# List of Objects to remove
- objs = [x for x in bundle.objects if (x.idref and x.idref in cls.object_ids_mapping.values())]
+ objs = (x for x in bundle.objects if (x.idref and x.idref in object_ids))
# Remove the extraneous Objects
for obj in objs:
bundle.objects.remove(obj)
+
# Cleanup the Object Collections
if bundle.collections and bundle.collections.object_collections:
for collection in bundle.collections.object_collections:
# Ignore the re-used objects collection
- if collection.name and collection.name == "Deduplicated Objects":
+ if collection.name == "Deduplicated Objects":
continue
# List of Objects to remove
- objs = [x for x in collection.object_list if (x.idref and x.idref in cls.object_ids_mapping.values())]
+ objs = (x for x in collection.object_list if (x.idref and x.idref in object_ids))
for obj in objs:
collection.object_list.remove(obj)
- # Replace all of the duplicate Objects with references to
- # the unique object placed in the "Re-used Objects" Collection
@classmethod
def handle_duplicate_objects(cls, bundle, all_objects):
- for duplicate_object_id, unique_object_id in cls.object_ids_mapping.items():
- for object in all_objects:
- if object.id_ == duplicate_object_id or object.idref == duplicate_object_id:
- # Modify the existing Object to serve as a reference to
- # the unique Object in the collection
+ """Replace all of the duplicate Objects with references to the unique object placed in the "Re-used Objects" Collection."""
+ for duplicate_object_id, unique_object_id in iteritems(cls.object_ids_mapping):
+ # Modify the existing Object to serve as a reference to
+ # the unique Object in the collection
+ if duplicate_object_id and duplicate_object_id in cls.id_objects:
+ object = cls.id_objects[duplicate_object_id]
+ object.idref = unique_object_id
+ object.id_ = None
+ object.properties = None
+ object.related_objects = None
+ object.domain_specific_object_properties = None
+
+ if duplicate_object_id and duplicate_object_id in cls.idref_objects:
+ for object in cls.idref_objects[duplicate_object_id]:
object.idref = unique_object_id
- object.id_ = None
- object.properties = None
- object.related_objects = None
- object.domain_specific_object_properties = None
- # Add a new Object collection to the Bundle for storing the unique Objects
- # Add the Objects to said collection
@classmethod
def handle_unique_objects(cls, bundle, all_objects):
+ """Add a new Object collection to the Bundle for storing the unique Objects.
+ Add the Objects to the collection. """
# First, find the ID of the last Object Collection (if applicable)
counter = 1
if bundle.collections and bundle.collections.object_collections:
- for object_collection in bundle.collections.object_collections:
- counter += 1
+ counter += len(bundle.collections.object_collections)
+
# Find the namespace used in the Bundle IDs
- bundle_namespace = bundle.id.split('-')[1]
+ bundle_namespace = bundle.id_.split('-')[1]
+
# Build the collection ID
- collection_id = "maec-" + bundle_namespace + "-objc-" + str(counter)
+ collection_id = "maec-%s-objc-%s" % (bundle_namespace, counter)
+
# Add the named Object collection
bundle.add_named_object_collection("Deduplicated Objects", collection_id)
+
# Add the unique Objects to the collection
cls.add_unique_objects(bundle, all_objects)
- # Add the unique Objects to the collection and perform the properties replacement
@classmethod
def add_unique_objects(cls, bundle, all_objects):
+ """Add the unique Objects to the collection and perform the properties replacement."""
added_ids = []
for unique_object_id in cls.object_ids_mapping.values():
if unique_object_id not in added_ids:
for object in all_objects:
if object.id_ and object.id_ == unique_object_id:
object_copy = copy.deepcopy(object)
- if isinstance(object_copy, cybox.core.AssociatedObject):
+ if isinstance(object_copy, AssociatedObject):
object_copy.association_type = None
- elif isinstance(object_copy, cybox.core.RelatedObject):
+ elif isinstance(object_copy, RelatedObject):
object_copy.relationship = None
+
# Modify the existing Object to serve as a reference to the Object in the collection
object.idref = object.id_
object.id_ = None
object.properties = None
object.related_objects = None
object.domain_specific_object_properties = None
+
# Add the unique Object to the collection
bundle.add_object(object_copy, "Deduplicated Objects")
+
# Break out of the all_objects loop
break
+
added_ids.append(unique_object_id)
- # Map the non-unique Objects to their unique (first observed) counterparts
@classmethod
def map_objects(cls, all_objects):
+ """Map the non-unique Objects to their unique (first observed) counterparts."""
# Do the object mapping
for obj in all_objects:
+ # Add the Object to its respective dictionary
+ if obj.id_:
+ cls.id_objects[obj.id_] = obj
+ elif obj.idref and obj.idref not in cls.idref_objects:
+ cls.idref_objects[obj.idref] = [obj]
+ elif obj.idref and obj.idref in cls.idref_objects:
+ cls.idref_objects[obj.idref].append(obj)
+
+ # Find a matching ID for the Object
matching_object_id = cls.find_matching_object(obj)
if matching_object_id:
cls.object_ids_mapping[obj.id_] = matching_object_id
- # Returns the value contained in a TypedField or its nested members, if applicable
@classmethod
- def get_typedfield_values(cls, val, name, values):
+ def get_typedfield_values(cls, val, name, values, ignoreCase=False):
+ """Returns the value contained in a TypedField or its nested members, if applicable."""
# If it's a BaseProperty instance, then we're done. Return it.
if isinstance(val, BaseProperty):
- values.add(name + ":" + str(val))
- # If it's a list, then we need to iterate through each of its members
- elif isinstance(val, collections.MutableSequence):
+ val = str(val) if ignoreCase else str(val).lower() # TODO (bworrell): This seems backwards.
+ values.add("%s:%s" % (name, val))
+ return
+
+ # If it's an Entity, iterate over the typedfields and find the values
+ # for each field.
+ if isinstance(val, entities.Entity):
+ for attrname, item_property in val.typed_fields_with_attrnames:
+ path = "{name}/{attrname}".format(**locals())
+ fieldval = getattr(val, attrname)
+ cls.get_typedfield_values(fieldval, path, values, ignoreCase)
+
+ # If the value is a mutable sequence, attempt to find TypedFields as
+ # in each item. EntityLists are Entity subclasses that can have
+ # TypedFields, so we don't make this an elif.
+ if isinstance(val, compat.MutableSequence):
for list_item in val:
- for list_item_property in list_item._get_vars():
- cls.get_typedfield_values(getattr(list_item, str(list_item_property)), name + "/" + str(list_item_property), values)
- # If it's a cybox.Entity, then we need to iterate through its properties
- elif isinstance(val, cybox.Entity):
- for item_property in val._get_vars():
- cls.get_typedfield_values(getattr(val, str(item_property)), name + "/" + str(item_property), values)
-
- # Get the values specified for an object's properties as a set
+ cls.get_typedfield_values(list_item, name, values, ignoreCase)
+
@classmethod
- def get_object_values(cls, obj):
+ def get_object_values(cls, obj, ignoreCase=False):
+ """Get the values specified for an Object's properties as a set."""
values = set()
- for typed_field in obj.properties._get_vars():
+ for attrname, typed_field in obj.properties.typed_fields_with_attrnames:
# Make sure the typed field is comparable
if typed_field.comparable:
- val = getattr(obj.properties, str(typed_field))
+ val = getattr(obj.properties, attrname)
if val is not None:
- cls.get_typedfield_values(val, str(typed_field), values)
+ cls.get_typedfield_values(val, attrname, values, ignoreCase)
return values
- # Find a matching object, if it exists
@classmethod
def find_matching_object(cls, obj):
+ """Find a matching object, if it exists."""
if obj and obj.properties:
object_values = cls.get_object_values(obj)
- xsi_type = obj.properties._XSI_TYPE
- if xsi_type and xsi_type in cls.objects_dict:
+ xsi_type = obj.properties._XSI_TYPE
+
+ if not xsi_type:
+ return None
+ elif xsi_type in cls.objects_dict:
types_dict = cls.objects_dict[xsi_type]
+
# See if we already have an identical object in the dictionary
- for obj_id, obj_values in types_dict.items():
+ for obj_id, obj_values in types_dict.iteritems():
if obj_values == object_values:
# If so, return its ID for use in the IDREF
return obj_id
+
# If not, add it to the dictionary
types_dict[obj.id_] = object_values
- elif xsi_type and xsi_type not in cls.objects_dict:
+ else:
types_dict = {obj.id_:object_values}
cls.objects_dict[xsi_type] = types_dict
- return None
+
+ return None
diff --git a/maec/utils/idgen.py b/maec/utils/idgen.py
deleted file mode 100644
index 22a29a2..0000000
--- a/maec/utils/idgen.py
+++ /dev/null
@@ -1,105 +0,0 @@
-# Copyright (c) 2014, The MITRE Corporation. All rights reserved.
-# See LICENSE.txt for complete terms.
-
-import uuid
-from cybox.utils import Namespace
-
-EXAMPLE_NAMESPACE = Namespace("http://example.com", "example")
-
-class InvalidMethodError(ValueError):
- def __init__(self, method):
- ValueError.__init__(self, "invalid method: %s" % method)
-
-class IDGenerator(object):
- """Utility class for generating MAEC IDs for objects"""
- METHOD_UUID = 1
- METHOD_INT = 2
-
- METHODS = (METHOD_UUID, METHOD_INT)
-
- def __init__(self, namespace=EXAMPLE_NAMESPACE, method=METHOD_UUID):
- self.namespace = namespace
- self.method = method
- self.reset()
-
- def reset(self):
- self.next_int = 1
-
- @property
- def namespace(self):
- return self._namespace
-
- @namespace.setter
- def namespace(self, value):
- if not isinstance(value, Namespace):
- raise ValueError("Must be a Namespace object")
- self._namespace = value
- self.reset()
-
- @property
- def method(self):
- return self._method
-
- @method.setter
- def method(self, value):
- if value not in IDGenerator.METHODS:
- raise InvalidMethodError("invalid method: %s" % value)
- self._method = value
- self.reset()
-
- def create_id(self, prefix="guid"):
- """Create an ID.
-
- Note that if `prefix` is not provided, it will be `quid`, even if the
- `method` is `METHOD_INT`.
- """
- if self.method == IDGenerator.METHOD_UUID:
- id_ = str(uuid.uuid4())
- elif self.method == IDGenerator.METHOD_INT:
- id_ = self.next_int
- self.next_int += 1
- else:
- raise InvalidMethodError()
-
- return "%s:%s-%s" % (self.namespace.prefix, prefix, id_)
-
-# Singleton instance within this module. It is lazily instantiated, so simply
-# importing the utils module will not create the object.
-__generator = None
-
-def _get_generator():
- """Return the `maec.utils` module's generator object.
-
- Only under rare circumstances should this function be called by external
- code. More likely, external code should initialize its own IDGenerator or
- use the `set_id_namespace`, `set_id_method`, or `create_id` functions of
- the `maec.utils` module.
- """
- global __generator
- if not __generator:
- __generator = IDGenerator()
- return __generator
-
-
-def set_id_namespace(namespace):
- """ Set the namespace for the module-level ID Generator"""
- _get_generator().namespace = namespace
-
-def set_id_method(method):
- """ Set the method for the module-level ID Generator"""
- _get_generator().method = method
-
-def get_id_namespace():
- """Return the namespace associated with generated ids"""
- return _get_generator().namespace.iterkeys().next()
-
-def get_id_namespace_alias():
- """Returns the namespace alias assoicated with generated ids"""
- return _get_generator().namespace.itervalues().next()
-
-def create_id(prefix=None):
- """ Create an ID using the module-level ID Generator"""
- if not prefix:
- return _get_generator().create_id()
- else:
- return _get_generator().create_id(prefix)
\ No newline at end of file
diff --git a/maec/utils/merge.py b/maec/utils/merge.py
new file mode 100644
index 0000000..b7258cc
--- /dev/null
+++ b/maec/utils/merge.py
@@ -0,0 +1,245 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+"""Methods for merging MAEC documents"""
+
+from copy import deepcopy
+import itertools
+
+from mixbox import idgen
+from mixbox.namespaces import Namespace
+from mixbox.vendor.six import iteritems
+
+from cybox.core import Object
+from cybox.common import HashList
+
+import maec
+from maec.package import (Package, MalwareSubject, MalwareConfigurationDetails,
+ FindingsBundleList, MetaAnalysis, Analyses,
+ MinorVariants, MalwareSubjectRelationshipList,
+ MalwareSubjectList)
+
+def dict_merge(target, *args):
+ '''Merge multiple dictionaries into one'''
+ if len(args) > 1:
+ for obj in args:
+ dict_merge(target, obj)
+ return target
+
+ # Recursively merge dicts and set non-dict values
+ obj = args[0]
+ if not isinstance(obj, dict):
+ return obj
+ for k, v in iteritems(obj):
+ if k in target and isinstance(target[k], dict):
+ dict_merge(target[k], v)
+ elif k in target and isinstance(target[k], list):
+ target[k] = (target[k] + v)
+ else:
+ target[k] = deepcopy(v)
+ return target
+
+def merge_documents(input_list, output_file):
+ '''Merge a list of input MAEC documents and write them to an output file'''
+ parsed_documents = []
+ # Parse the documents and get their API representation
+ for input_file in input_list:
+ api_representation = maec.parse_xml_instance(input_file)['api']
+ parsed_documents.append(api_representation)
+ # Do a sanity check on the input list of documents
+ for document in parsed_documents:
+ if isinstance(document, Package):
+ continue
+ else:
+ print('Error: unsupported document type. Currently only MAEC Packages are supported')
+
+ # Merge the MAEC packages
+ merged_package = merge_packages(parsed_documents)
+ # Write the merged package to the output file
+ merged_package.to_xml_file(output_file, {"https://github.com/MAECProject/python-maec":"merged"})
+
+def merge_packages(package_list, namespace = None):
+ '''Merge a list of input MAEC Packages and return a merged Package instance.'''
+ malware_subjects = []
+ # Instantiate the ID generator class (for automatic ID generation)
+ if not namespace:
+ NS = Namespace("https://github.com/MAECProject/python-maec", "merged")
+ else:
+ NS = namespace
+ maec.utils.set_id_namespace(NS)
+ # Build the list of Malware Subjects
+ for package in package_list:
+ for malware_subject in package.malware_subjects:
+ malware_subjects.append(malware_subject)
+ # Merge the Malware Subjects
+ merged_subjects = merge_malware_subjects(malware_subjects)
+ # Merge the input namespace/schemaLocation dictionaries
+ merged_namespaces = {}
+ merged_schemalocations = {}
+ for package in package_list:
+ merged_namespaces.update(package.__input_namespaces__)
+ merged_schemalocations.update(package.__input_schemalocations__)
+ # Create a new Package with the merged Malware Subjects
+ merged_package = Package()
+ merged_package.malware_subjects = MalwareSubjectList(merged_subjects)
+ merged_package.__input_namespaces__ = merged_namespaces
+ merged_package.__input_schemalocations__ = merged_schemalocations
+ return merged_package
+
+def bin_malware_subjects(malware_subject_list, default_hash_type='md5'):
+ '''Bin a list of Malware Subjects by hash
+ Default = MD5
+ '''
+ binned_subjects = {}
+ for malware_subject in malware_subject_list:
+ mal_inst_obj = malware_subject.malware_instance_object_attributes
+ if mal_inst_obj:
+ obj_properties = mal_inst_obj.properties
+ if obj_properties and obj_properties.hashes:
+ for hash in obj_properties.hashes:
+ if hash.type_ and hash.simple_hash_value:
+ hash_type = ''
+ hash_value = ''
+ # Get the hash type
+ hash_type = str(hash.type_).lower()
+ # Get the hash value
+ hash_value = str(hash.simple_hash_value).lower()
+
+ # Check the hash type and bin accordingly
+ if hash_type == default_hash_type:
+ if hash_value in binned_subjects:
+ binned_subjects[hash_value].append(malware_subject)
+ else:
+ binned_subjects[hash_value] = [malware_subject]
+ return binned_subjects
+
+def merge_entities(entity_list):
+ '''Merge a list of MAEC/CybOX entities'''
+ dict_list = [x.to_dict() for x in entity_list]
+ output_dict = dict_merge({}, *dict_list)
+ return output_dict
+
+def deduplicate_vocabulary_list(entity_list, value_name = "value"): # TODO: Move this to the deduplicator module?
+ '''Deduplicate a simple list of MAEC/CybOX vocabulary entries'''
+ temp = []
+ output_list = []
+ for entity in entity_list:
+ entity_value = getattr(entity, value_name)
+ entity_lower = str(entity_value).lower()
+ if entity_value and entity_lower not in temp:
+ temp.append(entity_lower)
+ output_list.append(entity)
+ elif not entity_value:
+ output_list.append(entity)
+ return output_list
+
+def merge_findings_bundles(findings_bundles_list):
+ '''Merge two or more Malware Subject Findings Bundles'''
+ # Merge the meta-analysis
+ merged_meta_analysis = None
+ meta_analysis_list = [x.meta_analysis for x in findings_bundles_list if x.meta_analysis]
+ if meta_analysis_list:
+ merged_meta_analysis = MetaAnalysis.from_dict(merge_entities(meta_analysis_list))
+ # Merge the list of bundles
+ merged_bundles = list(itertools.chain(*[x.bundle for x in findings_bundles_list if x.bundle]))
+ # Merge the list of external bundle references
+ merged_bundle_external_references = list(itertools.chain(*[x.bundle_external_reference for x in findings_bundles_list if x.bundle_external_reference]))
+
+ # Construct the merged Findings Bundle List entity
+ merged_findings_bundle_list = FindingsBundleList()
+ if merged_meta_analysis:
+ merged_findings_bundle_list.meta_analysis = merged_meta_analysis
+ if merged_bundles:
+ merged_findings_bundle_list.bundle = merged_bundles
+ if merged_bundle_external_references:
+ merged_findings_bundle_list.bundle_external_reference = merged_bundle_external_references
+
+ return merged_findings_bundle_list
+
+def create_mappings(mapping_dict, original_malware_subject_list, merged_malware_subject):
+ '''Map the IDs of a list of existing Malware Subjects to the new merged Malware Subject'''
+ for malware_subject in original_malware_subject_list:
+ mapping_dict[malware_subject.id_] = merged_malware_subject.id_
+
+def merge_binned_malware_subjects(merged_malware_subject, binned_list, id_mappings_dict):
+ '''Merge a list of input binned (related) Malware Subjects'''
+ # Merge the Malware_Instance_Object_Attributes
+ mal_inst_obj_list = [x.malware_instance_object_attributes for x in binned_list]
+ merged_inst_obj = Object.from_dict(merge_entities(mal_inst_obj_list))
+ # Give the merged Object a new ID
+ merged_inst_obj.id_ = idgen.create_id('object')
+ # Deduplicate the hash values, if they exist
+ if merged_inst_obj.properties and merged_inst_obj.properties.hashes:
+ hashes = merged_inst_obj.properties.hashes
+ hashes = HashList(deduplicate_vocabulary_list(hashes, value_name = 'simple_hash_value'))
+ hashes = HashList(deduplicate_vocabulary_list(hashes, value_name = 'fuzzy_hash_value'))
+ merged_inst_obj.properties.hashes = hashes
+ # Merge and deduplicate the labels
+ merged_labels = list(itertools.chain(*[x.label for x in binned_list if x.label]))
+ deduplicated_labels = deduplicate_vocabulary_list(merged_labels)
+ # Merge the configuration details
+ config_details_list = [x.configuration_details for x in binned_list if x.configuration_details]
+ merged_config_details = None
+ if config_details_list:
+ merged_config_details = MalwareConfigurationDetails.from_dict(merge_entities(config_details_list))
+ # Merge the minor variants
+ merged_minor_variants = list(itertools.chain(*[x.minor_variants for x in binned_list if x.minor_variants]))
+ # Merge the field data # TODO: Add support. Not implemented in the APIs.
+ # Merge the analyses
+ merged_analyses = list(itertools.chain(*[x.analyses for x in binned_list if x.analyses]))
+ # Merge the findings bundles
+ merged_findings_bundles = merge_findings_bundles([x.findings_bundles for x in binned_list if x.findings_bundles])
+ # Merge the relationships
+ merged_relationships = list(itertools.chain(*[x.relationships for x in binned_list if x.relationships]))
+ # Merge the compatible platforms
+ merged_compatible_platforms = list(itertools.chain(*[x.compatible_platform for x in binned_list if x.compatible_platform]))
+
+
+
+ # Build the merged Malware Subject
+ merged_malware_subject.malware_instance_object_attributes = merged_inst_obj
+ if deduplicated_labels: merged_malware_subject.label = deduplicated_labels
+ if merged_config_details: merged_malware_subject.configuration_details = merged_config_details
+ if merged_minor_variants: merged_malware_subject.minor_variants = MinorVariants(merged_minor_variants)
+ if merged_analyses: merged_malware_subject.analyses = Analyses(merged_analyses)
+ if merged_findings_bundles: merged_malware_subject.findings_bundles = merged_findings_bundles
+ if merged_relationships: merged_malware_subject.relationships = MalwareSubjectRelationshipList(merged_relationships)
+ if merged_compatible_platforms: merged_malware_subject.compatible_platform = merged_compatible_platforms
+
+def update_relationships(malware_subject_list, id_mappings):
+ '''Update any existing Malware Subject relationships to account for merged Malware Subjects'''
+ for malware_subject in malware_subject_list:
+ if malware_subject.relationships:
+ relationships = malware_subject.relationships
+ for relationship in relationships:
+ malware_subject_references = relationship.malware_subject_references
+ for malware_subject_reference in malware_subject_references:
+ if malware_subject_reference.malware_subject_idref in id_mappings.keys():
+ malware_subject_reference.malware_subject_idref = id_mappings[malware_subject_reference.malware_subject_idref]
+
+def merge_malware_subjects(malware_subject_list):
+ '''Merge a list of input Malware Subjects'''
+ id_mappings = {}
+ output_subjects = []
+ # Bin the Malware Subjects by hash
+ binned_subjects = bin_malware_subjects(malware_subject_list)
+ # Merge the Malware Subjects that were binned
+ for binned_list in binned_subjects.values():
+ # Make sure we're dealing with at least two subjects
+ if len(binned_list) > 1:
+ # Instantiate the merged Malware Subject
+ merged_malware_subject = MalwareSubject()
+ # Add the ID mappings from the old (merged) subject to the new one
+ create_mappings(id_mappings, binned_list, merged_malware_subject)
+ # Perform the merging
+ merge_binned_malware_subjects(merged_malware_subject, binned_list, id_mappings)
+ # Add the merged Malware Subject to the output list
+ output_subjects.append(merged_malware_subject)
+ # Add the Malware Subjects that weren't merged
+ for malware_subject in malware_subject_list:
+ if malware_subject.id_ not in id_mappings.keys():
+ output_subjects.append(malware_subject)
+ # Update the relationships for the Malware Subjects to account for the merges
+ update_relationships(output_subjects, id_mappings)
+ # Return the list of original and merged Malware Subjects
+ return output_subjects
diff --git a/maec/utils/nsparser.py b/maec/utils/nsparser.py
index 987a687..a1c0647 100644
--- a/maec/utils/nsparser.py
+++ b/maec/utils/nsparser.py
@@ -1,46 +1,19 @@
-#MAEC Namespace Parser
+# Copyright (c) 2018, The MITRE Corporation
+# All rights reserved
-#Copyright (c) 2014, The MITRE Corporation
-#All rights reserved
+# Compatible with MAEC v4.1
-#Compatible with MAEC v4.1
-#Last updated 02/18/2014
+from mixbox.namespaces import Namespace, NamespaceSet, register_namespace
-import maec.bindings.maec_bundle as bundle_binding
-import maec.bindings.maec_package as package_binding
-from cybox.utils import Namespace, META
+NS_MAEC_BUNDLE = Namespace('http://maec.mitre.org/XMLSchema/maec-bundle-4', 'maecBundle', 'http://maec.mitre.org/language/version4.1/maec_bundle_schema.xsd')
+NS_MAEC_PACKAGE = Namespace('http://maec.mitre.org/XMLSchema/maec-package-2', 'maecPackage', 'http://maec.mitre.org/language/version4.1/maec_package_schema.xsd')
+NS_MAEC_VOCABS = Namespace('http://maec.mitre.org/default_vocabularies-1', 'maecVocabs', 'http://maec.mitre.org/language/version4.1/maec_default_vocabularies.xsd')
-import itertools
-class Metadata(object):
- """Metadata about MAEC namespaces."""
+MAEC_NAMESPACES = NamespaceSet()
- def __init__(self, namespace_list):
- self._ns_dict = {}
- self._prefix_dict = {}
-
- for ns in namespace_list:
- n = Namespace(*ns)
- self.add_namespace(n)
-
- def add_namespace(self, namespace):
- self._ns_dict[namespace.name] = namespace
- self._prefix_dict[namespace.prefix] = namespace
-
- def lookup_namespace(self, namespace):
- return self._ns_dict.get(namespace)
-
- def lookup_prefix(self, prefix):
- return self._prefix_dict.get(prefix)
-
-
-# A list of (namespace, prefix, schemalocation) tuples
-# This is loaded by the Metadata class and should not be accessed directly.
-NS_LIST = [
- ('http://www.w3.org/2001/XMLSchema-instance', 'xsi', ''),
- ('http://maec.mitre.org/XMLSchema/maec-bundle-4', 'maecBundle', 'http://maec.mitre.org/language/version4.1/maec_bundle_schema.xsd'),
- ('http://maec.mitre.org/XMLSchema/maec-package-2', 'maecPackage', 'http://maec.mitre.org/language/version4.1/maec_package_schema.xsd'),
- ('http://maec.mitre.org/default_vocabularies-1', 'maecVocabs', 'http://maec.mitre.org/language/version4.1/maec_default_vocabularies.xsd')
-]
-
-maecMETA = Metadata(NS_LIST)
+# Magic to automatically register all Namespaces defined in this module.
+for k, v in dict(globals()).items():
+ if k.startswith('NS_'):
+ register_namespace(v)
+ MAEC_NAMESPACES.add_namespace(v)
diff --git a/maec/utils/parser.py b/maec/utils/parser.py
index 6505b9a..efedc3d 100644
--- a/maec/utils/parser.py
+++ b/maec/utils/parser.py
@@ -1,117 +1,37 @@
-# Copyright (c) 2014, The MITRE Corporation. All rights reserved.
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
-import maec
-from distutils.version import StrictVersion
-from lxml import etree
+import mixbox.parser
+from mixbox.parser import (UnknownVersionError, UnsupportedVersionError,
+ UnsupportedRootElementError)
-class UnsupportedVersionError(Exception):
- pass
+# Alias for backwards compatibility
+UnsupportedRootElement = UnsupportedRootElementError
-class UnknownVersionError(Exception):
- pass
+TAG_MAEC_BUNDLE = "{http://maec.mitre.org/XMLSchema/maec-bundle-4}MAEC_Bundle"
+TAG_MAEC_PACKAGE = "{http://maec.mitre.org/XMLSchema/maec-package-2}MAEC_Package"
-class UnsupportedRootElement(Exception):
- pass
-class EntityParser(object):
- def __init__(self):
- self.is_bundle = False
- self.is_package = False
+class EntityParser(mixbox.parser.EntityParser):
- def _check_version(self, tree):
- '''Returns true of the instance document @tree is a version supported by python-maec'''
+ def supported_tags(self):
+ return [TAG_MAEC_BUNDLE, TAG_MAEC_PACKAGE]
- try:
- root = tree.getroot() # is tree an lxml.Element or lxml.ElementTree
- except AttributeError:
- root = tree
+ def get_version(self, root):
+ return root.attrib.get('schema_version')
- if not root.attrib.get('schema_version'):
- raise UnknownVersionError("No version attribute set on xml instance. Unable to determine version compatibility")
+ def supported_versions(self, tag):
+ if tag == TAG_MAEC_BUNDLE:
+ return ['4.1']
+ elif tag == TAG_MAEC_PACKAGE:
+ return ['2.1']
+ else:
+ return []
- python_maec_version = maec.__version__ # ex: '4.1.0.0'
- supported_maec_version = ('4.1', '2.1') # ex: '4.1.0'
- document_version = root.attrib['schema_version']
-
- if document_version not in supported_maec_version:
- raise UnsupportedVersionError("Your python-maec library supports MAEC %s, or the MAEC Bundle Schema at %s and MAEC Package Schema at %s. Document version was %s" % (supported_maec_version[0], supported_maec_version[0], supported_maec_version[1], document_version))
-
- return True
-
- def _check_root(self, tree):
- try:
- root = tree.getroot() # is tree an lxml.Element or lxml.ElementTree
- except AttributeError:
- root = tree
- # General compatibility check
- if root.tag not in ("{http://maec.mitre.org/XMLSchema/maec-bundle-4}MAEC_Bundle", "{http://maec.mitre.org/XMLSchema/maec-package-2}MAEC_Package"):
- raise UnsupportedRootElement("Document root element must be an instance of MAEC_Package or MAEC_Bundle")
-
- # Determine if we're dealing with a MAEC Bundle or MAEC Package
- if "MAEC_Bundle" in root.tag:
- self.is_bundle = True
- elif "MAEC_Package" in root.tag:
- self.is_package = True
-
- return True
-
- def _apply_input_namespaces(self, tree, entity):
- try:
- root = tree.getroot() # is tree an lxml.Element or lxml.ElementTree
- except AttributeError:
- root = tree
-
- entity.__input_namespaces__ = {}
- for alias,ns in root.nsmap.iteritems():
- entity.__input_namespaces__[ns] = alias
-
- def parse_xml_to_obj(self, xml_file, check_version=True):
- """Creates a MAEC binding object from the supplied xml file.
-
- Arguments:
- xml_file -- A filename/path or a file-like object reprenting a MAEC instance document
- check_version -- Inspect the version before parsing.
- """
- parser = etree.ETCompatXMLParser(huge_tree=True)
- tree = etree.parse(xml_file, parser=parser)
-
- # Check the root and determine the type of document we're dealing with
- self._check_root(tree)
-
- if check_version:
- self._check_version(tree)
-
- binding_obj = None
- if self.is_package:
- import maec.bindings.maec_package as maec_package_binding
- binding_obj = maec_package_binding.PackageType().factory()
- binding_obj.build(tree.getroot())
- elif self.is_bundle:
- import maec.bindings.maec_bundle as maec_bundle_binding
- binding_obj = maec_bundle_binding.BundleType().factory()
- binding_obj.build(tree.getroot())
-
- return binding_obj
-
- def parse_xml(self, xml_file, check_version=True):
- """Creates a python-maec Bundle or Package object from the supplied xml_file.
-
- Arguments:
- xml_file -- A filename/path or a file-like object reprenting a MAEC instance (i.e. Package or Bundle) document
- check_version -- Inspect the version before parsing.
- """
- parser = etree.ETCompatXMLParser(huge_tree=True)
- tree = etree.parse(xml_file, parser=parser)
-
- api_obj = None
- binding_obj = self.parse_xml_to_obj(xml_file, check_version)
- if self.is_package:
- from maec.package.package import Package # resolve circular dependencies
- api_obj = Package().from_obj(binding_obj)
- elif self.is_bundle:
- from maec.bundle.bundle import Bundle # resolve circular dependencies
- api_obj = Bundle().from_obj(binding_obj)
- self._apply_input_namespaces(tree, api_obj)
-
- return api_obj
\ No newline at end of file
+ def get_entity_class(self, tag):
+ if tag == TAG_MAEC_BUNDLE:
+ from maec.bundle import Bundle
+ return Bundle
+ elif tag == TAG_MAEC_PACKAGE:
+ from maec.package import Package
+ return Package
diff --git a/maec/version.py b/maec/version.py
new file mode 100644
index 0000000..b87b594
--- /dev/null
+++ b/maec/version.py
@@ -0,0 +1,4 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+__version__ = "4.1.0.17"
diff --git a/maec/vocabs/__init__.py b/maec/vocabs/__init__.py
new file mode 100644
index 0000000..d82ed31
--- /dev/null
+++ b/maec/vocabs/__init__.py
@@ -0,0 +1 @@
+from .vocabs import * # noqa
\ No newline at end of file
diff --git a/maec/vocabs/vocabs.py b/maec/vocabs/vocabs.py
new file mode 100644
index 0000000..b06e7dd
--- /dev/null
+++ b/maec/vocabs/vocabs.py
@@ -0,0 +1,1264 @@
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+from cybox.common.vocabs import VocabString, register_vocab
+
+@register_vocab
+class MalwareCapability(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = "maecVocabs:MalwareCapabilityEnum-1.0"
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ANTI_BEHAVIORAL_ANALYSIS = 'anti-behavioral analysis'
+ TERM_ANTI_CODE_ANALYSIS = 'anti-code analysis'
+ TERM_ANTI_DETECTION = 'anti-detection'
+ TERM_ANTI_REMOVAL = 'anti-removal'
+ TERM_AVAILABILITY_VIOLATION = 'availability violation'
+ TERM_COMMAND_AND_CONTROL = 'command and control'
+ TERM_DATA_EXFILTRATION = 'data exfiltration'
+ TERM_DATA_THEFT = 'data theft'
+ TERM_DESTRUCTION = 'destruction'
+ TERM_FRAUD = 'fraud'
+ TERM_INFECTION_PROPAGATION = 'infection/propagation'
+ TERM_INTEGRITY_VIOLATION = 'integrity violation'
+ TERM_MACHINE_ACCESS_CONTROL = 'machine access/control'
+ TERM_PERSISTENCE = 'persistence'
+ TERM_PRIVILEGE_ESCALATION = 'privilege escalation'
+ TERM_PROBING = 'probing'
+ TERM_REMOTE_MACHINE_MANIPULATION = 'remote machine manipulation'
+ TERM_SECONDARY_OPERATION = 'secondary operation'
+ TERM_SECURITY_DEGRADATION = 'security degradation'
+ TERM_SPYING = 'spying'
+
+
+@register_vocab
+class DataTheftTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DataTheftTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_STEAL_BROWSER_CACHE = 'steal browser cache'
+ TERM_STEAL_BROWSER_HISTORY = 'steal browser history'
+ TERM_STEAL_CONTACT_LIST_DATA = 'steal contact list data'
+ TERM_STEAL_COOKIE = 'steal cookie'
+ TERM_STEAL_CRYPTOCURRENCY_DATA = 'steal cryptocurrency data'
+ TERM_STEAL_DATABASE_CONTENT = 'steal database content'
+ TERM_STEAL_DIALED_PHONE_NUMBERS = 'steal dialed phone numbers'
+ TERM_STEAL_DOCUMENTS = 'steal documents'
+ TERM_STEAL_EMAIL_DATA = 'steal email data'
+ TERM_STEAL_IMAGES = 'steal images'
+ TERM_STEAL_MAKE_MODEL = 'steal make/model'
+ TERM_STEAL_NETWORK_ADDRESS = 'steal network address'
+ TERM_STEAL_OPEN_PORT = 'steal open port'
+ TERM_STEAL_PASSWORD_HASH = 'steal password hash'
+ TERM_STEAL_PKI_KEY = 'steal pki key'
+ TERM_STEAL_PKI_SOFTWARE_CERTIFICATE = 'steal pki software certificate'
+ TERM_STEAL_REFERRER_URLS = 'steal referrer urls'
+ TERM_STEAL_SERIAL_NUMBERS = 'steal serial numbers'
+ TERM_STEAL_SMS_DATABASE = 'steal sms database'
+ TERM_STEAL_WEB_NETWORK_CREDENTIAL = 'steal web/network credential'
+
+
+@register_vocab
+class MachineAccessControlTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MachineAccessControlTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CONTROL_MACHINE_VIA_REMOTE_COMMAND = 'control machine via remote command'
+
+
+@register_vocab
+class DataTheftProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DataTheftPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_TARGETED_APPLICATION = 'targeted application'
+ TERM_TARGETED_WEBSITE = 'targeted website'
+
+
+@register_vocab
+class SecondaryOperationProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SecondaryOperationPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_TRIGGER_TYPE = 'trigger type'
+
+
+@register_vocab
+class SystemActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SystemActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ADD_SCHEDULED_TASK = 'add scheduled task'
+ TERM_ENUMERATE_SYSTEM_HANDLES = 'enumerate system handles'
+ TERM_GET_ELAPSED_SYSTEM_UP_TIME = 'get elapsed system up time'
+ TERM_GET_NETBIOS_NAME = 'get netbios name'
+ TERM_GET_SYSTEM_GLOBAL_FLAGS = 'get system global flags'
+ TERM_GET_SYSTEM_HOST_NAME = 'get system host name'
+ TERM_GET_SYSTEM_LOCAL_TIME = 'get system local time'
+ TERM_GET_SYSTEM_TIME = 'get system time'
+ TERM_GET_USERNAME = 'get username'
+ TERM_GET_WINDOWS_DIRECTORY = 'get windows directory'
+ TERM_GET_WINDOWS_SYSTEM_DIRECTORY = 'get windows system directory'
+ TERM_GET_WINDOWS_TEMPORARY_FILES_DIRECTORY = 'get windows temporary files directory'
+ TERM_SET_NETBIOS_NAME = 'set netbios name'
+ TERM_SET_SYSTEM_GLOBAL_FLAGS = 'set system global flags'
+ TERM_SET_SYSTEM_HOST_NAME = 'set system host name'
+ TERM_SET_SYSTEM_LOCAL_TIME = 'set system local time'
+ TERM_SET_SYSTEM_TIME = 'set system time'
+ TERM_SHUTDOWN_SYSTEM = 'shutdown system'
+ TERM_SLEEP_SYSTEM = 'sleep system'
+
+
+@register_vocab
+class AvailabilityViolationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AvailabilityViolationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_COMPROMISE_ACCESS_TO_INFORMATION_ASSETS = 'compromise access to information assets'
+ TERM_COMPROMISE_LOCAL_SYSTEM_AVAILABILITY = 'compromise local system availability'
+ TERM_CRACK_PASSWORDS = 'crack passwords'
+ TERM_DENIAL_OF_SERVICE = 'denial of service'
+ TERM_MINE_FOR_CRYPTOCURRENCY = 'mine for cryptocurrency'
+
+
+@register_vocab
+class ActionObjectAssociationType(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ActionObjectAssociationTypeVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_INPUT = 'input'
+ TERM_OUTPUT = 'output'
+ TERM_SIDE_EFFECT = 'side-effect'
+
+
+@register_vocab
+class CommonCapabilityProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:CommonCapabilityPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ENCRYPTION_ALGORITHM = 'encryption algorithm'
+ TERM_PROTOCOL_USED = 'protocol used'
+
+
+@register_vocab
+class RemoteMachineManipulationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:RemoteMachineManipulationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_COMPROMISE_REMOTE_MACHINE = 'compromise remote machine'
+
+
+@register_vocab
+class PrivilegeEscalationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:PrivilegeEscalationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ESCALATE_USER_PRIVILEGE = 'escalate user privilege'
+ TERM_IMPERSONATE_USER = 'impersonate user'
+
+
+@register_vocab
+class DebuggingActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DebuggingActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CHECK_FOR_KERNEL_DEBUGGER = 'check for kernel debugger'
+ TERM_CHECK_FOR_REMOTE_DEBUGGER = 'check for remote debugger'
+
+
+@register_vocab
+class DataExfiltrationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DataExfiltrationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_OBFUSCATE_DATA_FOR_EXFILTRATION = 'obfuscate data for exfiltration'
+ TERM_PERFORM_DATA_EXFILTRATION = 'perform data exfiltration'
+ TERM_STAGE_DATA_FOR_EXFILTRATION = 'stage data for exfiltration'
+
+
+@register_vocab
+class DeviceDriverActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DeviceDriverActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_EMULATE_DRIVER = 'emulate driver'
+ TERM_LOAD_AND_CALL_DRIVER = 'load and call driver'
+ TERM_LOAD_DRIVER = 'load driver'
+ TERM_UNLOAD_DRIVER = 'unload driver'
+
+
+@register_vocab
+class ImportanceType(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ImportanceTypeVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_HIGH = 'high'
+ TERM_INFORMATIONAL = 'informational'
+ TERM_LOW = 'low'
+ TERM_MEDIUM = 'medium'
+ TERM_NUMERIC = 'numeric'
+ TERM_UNKNOWN = 'unknown'
+
+
+@register_vocab
+class HTTPActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:HTTPActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_RECEIVE_HTTP_RESPONSE = 'receive http response'
+ TERM_SEND_HTTP_CONNECT_REQUEST = 'send http connect request'
+ TERM_SEND_HTTP_DELETE_REQUEST = 'send http delete request'
+ TERM_SEND_HTTP_GET_REQUEST = 'send http get request'
+ TERM_SEND_HTTP_HEAD_REQUEST = 'send http head request'
+ TERM_SEND_HTTP_OPTIONS_REQUEST = 'send http options request'
+ TERM_SEND_HTTP_PATCH_REQUEST = 'send http patch request'
+ TERM_SEND_HTTP_POST_REQUEST = 'send http post request'
+ TERM_SEND_HTTP_PUT_REQUEST = 'send http put request'
+ TERM_SEND_HTTP_TRACE_REQUEST = 'send http trace request'
+
+
+@register_vocab
+class AntiDetectionStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiDetectionStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ANTI_MEMORY_FORENSICS = 'anti-memory forensics'
+ TERM_HIDE_EXECUTING_CODE = 'hide executing code'
+ TERM_HIDE_MALWARE_ARTIFACTS = 'hide malware artifacts'
+ TERM_HIDE_NON_EXECUTING_CODE = 'hide non-executing code'
+ TERM_SECURITY_SOFTWARE_EVASION = 'security software evasion'
+ TERM_SELF_MODIFICATION = 'self-modification'
+
+
+@register_vocab
+class SocketActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SocketActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ACCEPT_SOCKET_CONNECTION = 'accept socket connection'
+ TERM_BIND_ADDRESS_TO_SOCKET = 'bind address to socket'
+ TERM_CLOSE_SOCKET = 'close socket'
+ TERM_CONNECT_TO_SOCKET = 'connect to socket'
+ TERM_CREATE_SOCKET = 'create socket'
+ TERM_DISCONNECT_FROM_SOCKET = 'disconnect from socket'
+ TERM_GET_HOST_BY_ADDRESS = 'get host by address'
+ TERM_GET_HOST_BY_NAME = 'get host by name'
+ TERM_LISTEN_ON_SOCKET = 'listen on socket'
+ TERM_RECEIVE_DATA_ON_SOCKET = 'receive data on socket'
+ TERM_SEND_DATA_ON_SOCKET = 'send data on socket'
+ TERM_SEND_DATA_TO_ADDRESS_ON_SOCKET = 'send data to address on socket'
+
+
+@register_vocab
+class CommandandControlTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:CommandandControlTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CHECK_FOR_PAYLOAD = 'check for payload'
+ TERM_CONTROL_MALWARE_VIA_REMOTE_COMMAND = 'control malware via remote command'
+ TERM_GENERATE_C2_DOMAIN_NAME_S = 'generate c2 domain name(s)'
+ TERM_SEND_HEARTBEAT_DATA = 'send heartbeat data'
+ TERM_SEND_SYSTEM_INFORMATION = 'send system information'
+ TERM_UPDATE_CONFIGURATION = 'update configuration'
+ TERM_VALIDATE_DATA = 'validate data'
+
+
+@register_vocab
+class HookingActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:HookingActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_ADD_SYSTEM_CALL_HOOK = 'add system call hook'
+ TERM_ADD_WINDOWS_HOOK = 'add windows hook'
+ TERM_HIDE_HOOK = 'hide hook'
+
+
+@register_vocab
+class GroupingRelationship(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:GroupingRelationshipVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CLUSTERED_TOGETHER = 'clustered together'
+ TERM_OBSERVED_TOGETHER = 'observed together'
+ TERM_PART_OF_INTRUSION_SET = 'part of intrusion set'
+ TERM_SAME_MALWARE_FAMILY = 'same malware family'
+ TERM_SAME_MALWARE_TOOLKIT = 'same malware toolkit'
+
+
+@register_vocab
+class PersistenceProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:PersistencePropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_SCOPE = 'scope'
+
+
+@register_vocab
+class DestructionProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DestructionPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ERASURE_SCOPE = 'erasure scope'
+
+
+@register_vocab
+class AntiCodeAnalysisStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiCodeAnalysisStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ANTI_DEBUGGING = 'anti-debugging'
+ TERM_ANTI_DISASSEMBLY = 'anti-disassembly'
+ TERM_CODE_OBFUSCATION = 'code obfuscation'
+
+
+@register_vocab
+class AvailabilityViolationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AvailabilityViolationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_COMPROMISE_DATA_AVAILABILITY = 'compromise data availability'
+ TERM_COMPROMISE_SYSTEM_AVAILABILITY = 'compromise system availability'
+ TERM_CONSUME_SYSTEM_RESOURCES = 'consume system resources'
+
+
+@register_vocab
+class IPCActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:IPCActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CONNECT_TO_NAMED_PIPE = 'connect to named pipe'
+ TERM_CREATE_MAILSLOT = 'create mailslot'
+ TERM_CREATE_NAMED_PIPE = 'create named pipe'
+ TERM_DELETE_NAMED_PIPE = 'delete named pipe'
+ TERM_DISCONNECT_FROM_NAMED_PIPE = 'disconnect from named pipe'
+ TERM_READ_FROM_MAILSLOT = 'read from mailslot'
+ TERM_READ_FROM_NAMED_PIPE = 'read from named pipe'
+ TERM_WRITE_TO_MAILSLOT = 'write to mailslot'
+ TERM_WRITE_TO_NAMED_PIPE = 'write to named pipe'
+
+
+@register_vocab
+class DirectoryActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DirectoryActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_CREATE_DIRECTORY = 'create directory'
+ TERM_DELETE_DIRECTORY = 'delete directory'
+ TERM_HIDE_DIRECTORY = 'hide directory'
+ TERM_MONITOR_DIRECTORY = 'monitor directory'
+
+
+@register_vocab
+class NetworkShareActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:NetworkShareActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ADD_CONNECTION_TO_NETWORK_SHARE = 'add connection to network share'
+ TERM_ADD_NETWORK_SHARE = 'add network share'
+ TERM_CONNECT_TO_NETWORK_SHARE = 'connect to network share'
+ TERM_DELETE_NETWORK_SHARE = 'delete network share'
+ TERM_DISCONNECT_FROM_NETWORK_SHARE = 'disconnect from network share'
+ TERM_ENUMERATE_NETWORK_SHARES = 'enumerate network shares'
+
+
+@register_vocab
+class InfectionPropagationProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:InfectionPropagationPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_AUTONOMY = 'autonomy'
+ TERM_FILE_INFECTION_TYPE = 'file infection type'
+ TERM_INFECTION_TARGETING = 'infection targeting'
+ TERM_SCOPE = 'scope'
+ TERM_TARGETED_FILE_ARCHITECTURE_TYPE = 'targeted file architecture type'
+ TERM_TARGETED_FILE_TYPE = 'targeted file type'
+
+
+@register_vocab
+class ProbingStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ProbingStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_PROBE_HOST_CONFIGURATION = 'probe host configuration'
+ TERM_PROBE_NETWORK_ENVIRONMENT = 'probe network environment'
+
+
+@register_vocab
+class InfectionPropagationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:InfectionPropagationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_IDENTIFY_FILE = 'identify file'
+ TERM_IDENTIFY_TARGET_MACHINE_S = 'identify target machine(s)'
+ TERM_INVENTORY_VICTIMS = 'inventory victims'
+ TERM_MODIFY_FILE = 'modify file'
+ TERM_PERFORM_AUTONOMOUS_REMOTE_INFECTION = 'perform autonomous remote infection'
+ TERM_PERFORM_SOCIAL_ENGINEERING_BASED_REMOTE_INFECTION = 'perform social-engineering based remote infection'
+ TERM_WRITE_CODE_INTO_FILE = 'write code into file'
+
+
+@register_vocab
+class DataExfiltrationProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DataExfiltrationPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ARCHIVE_TYPE = 'archive type'
+ TERM_FILE_TYPE = 'file type'
+
+
+@register_vocab
+class LibraryActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:LibraryActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_CALL_LIBRARY_FUNCTION = 'call library function'
+ TERM_ENUMERATE_LIBRARIES = 'enumerate libraries'
+ TERM_FREE_LIBRARY = 'free library'
+ TERM_GET_FUNCTION_ADDRESS = 'get function address'
+ TERM_LOAD_LIBRARY = 'load library'
+
+
+@register_vocab
+class MalwareDevelopmentTool(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MalwareDevelopmentToolVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_BUILDER = 'builder'
+ TERM_COMPILER = 'compiler'
+ TERM_CRYPTER = 'crypter'
+ TERM_LINKER = 'linker'
+ TERM_PACKER = 'packer'
+ TERM_PROTECTOR = 'protector'
+
+
+@register_vocab
+class FileActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:FileActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_CLOSE_FILE = 'close file'
+ TERM_COPY_FILE = 'copy file'
+ TERM_CREATE_FILE = 'create file'
+ TERM_CREATE_FILE_ALTERNATE_DATA_STREAM = 'create file alternate data stream'
+ TERM_CREATE_FILE_MAPPING = 'create file mapping'
+ TERM_CREATE_FILE_SYMBOLIC_LINK = 'create file symbolic link'
+ TERM_DELETE_FILE = 'delete file'
+ TERM_EXECUTE_FILE = 'execute file'
+ TERM_FIND_FILE = 'find file'
+ TERM_GET_FILE_ATTRIBUTES = 'get file attributes'
+ TERM_HIDE_FILE = 'hide file'
+ TERM_LOCK_FILE = 'lock file'
+ TERM_MODIFY_FILE = 'modify file'
+ TERM_MOVE_FILE = 'move file'
+ TERM_OPEN_FILE = 'open file'
+ TERM_OPEN_FILE_MAPPING = 'open file mapping'
+ TERM_READ_FROM_FILE = 'read from file'
+ TERM_RENAME_FILE = 'rename file'
+ TERM_SEND_CONTROL_CODE_TO_FILE = 'send control code to file'
+ TERM_SET_FILE_ATTRIBUTES = 'set file attributes'
+ TERM_UNLOCK_FILE = 'unlock file'
+ TERM_WRITE_TO_FILE = 'write to file'
+
+
+@register_vocab
+class CommandandControlProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:CommandandControlPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_FREQUENCY = 'frequency'
+
+
+@register_vocab
+class IRCActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:IRCActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CONNECT_TO_IRC_SERVER = 'connect to irc server'
+ TERM_DISCONNECT_FROM_IRC_SERVER = 'disconnect from irc server'
+ TERM_JOIN_IRC_CHANNEL = 'join irc channel'
+ TERM_LEAVE_IRC_CHANNEL = 'leave irc channel'
+ TERM_RECEIVE_IRC_PRIVATE_MESSAGE = 'receive irc private message'
+ TERM_SEND_IRC_PRIVATE_MESSAGE = 'send irc private message'
+ TERM_SET_IRC_NICKNAME = 'set irc nickname'
+
+
+@register_vocab
+class InfectionPropagationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:InfectionPropagationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_INFECT_FILE = 'infect file'
+ TERM_INFECT_REMOTE_MACHINE = 'infect remote machine'
+ TERM_PREVENT_DUPLICATE_INFECTION = 'prevent duplicate infection'
+
+
+@register_vocab
+class AntiBehavioralAnalysisProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiBehavioralAnalysisPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_TARGETED_SANDBOX = 'targeted sandbox'
+ TERM_TARGETED_VM = 'targeted vm'
+
+
+@register_vocab
+class DNSActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DNSActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_SEND_DNS_QUERY = 'send dns query'
+ TERM_SEND_REVERSE_DNS_LOOKUP = 'send reverse dns lookup'
+
+
+@register_vocab
+class RemoteMachineManipulationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:RemoteMachineManipulationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ACCESS_REMOTE_MACHINE = 'access remote machine'
+ TERM_SEARCH_FOR_REMOTE_MACHINES = 'search for remote machines'
+
+
+@register_vocab
+class ProcessActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ProcessActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CREATE_PROCESS = 'create process'
+ TERM_CREATE_PROCESS_AS_USER = 'create process as user'
+ TERM_ENUMERATE_PROCESSES = 'enumerate processes'
+ TERM_FLUSH_PROCESS_INSTRUCTION_CACHE = 'flush process instruction cache'
+ TERM_GET_PROCESS_CURRENT_DIRECTORY = 'get process current directory'
+ TERM_GET_PROCESS_ENVIRONMENT_VARIABLE = 'get process environment variable'
+ TERM_GET_PROCESS_STARTUPINFO = 'get process startupinfo'
+ TERM_KILL_PROCESS = 'kill process'
+ TERM_OPEN_PROCESS = 'open process'
+ TERM_SET_PROCESS_CURRENT_DIRECTORY = 'set process current directory'
+ TERM_SET_PROCESS_ENVIRONMENT_VARIABLE = 'set process environment variable'
+ TERM_SLEEP_PROCESS = 'sleep process'
+
+
+@register_vocab
+class PersistenceStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:PersistenceStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ENSURE_COMPATIBILITY = 'ensure compatibility'
+ TERM_GATHER_INFORMATION_FOR_IMPROVEMENT = 'gather information for improvement'
+ TERM_PERSIST_TO_CONTINUOUSLY_EXECUTE_ON_SYSTEM = 'persist to continuously execute on system'
+ TERM_PERSIST_TO_RE_INFECT_SYSTEM = 'persist to re-infect system'
+
+
+@register_vocab
+class NetworkActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:NetworkActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_CLOSE_PORT = 'close port'
+ TERM_CONNECT_TO_IP = 'connect to ip'
+ TERM_CONNECT_TO_SOCKET_ADDRESS = 'connect to socket address'
+ TERM_CONNECT_TO_URL = 'connect to url'
+ TERM_DISCONNECT_FROM_IP = 'disconnect from ip'
+ TERM_DOWNLOAD_FILE = 'download file'
+ TERM_LISTEN_ON_PORT = 'listen on port'
+ TERM_OPEN_PORT = 'open port'
+ TERM_RECEIVE_NETWORK_PACKET = 'receive network packet'
+ TERM_SEND_EMAIL_MESSAGE = 'send email message'
+ TERM_SEND_ICMP_REQUEST = 'send icmp request'
+ TERM_SEND_NETWORK_PACKET = 'send network packet'
+ TERM_UPLOAD_FILE = 'upload file'
+
+
+@register_vocab
+class SecondaryOperationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SecondaryOperationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_INSTALL_OTHER_COMPONENTS = 'install other components'
+ TERM_LAY_DORMANT = 'lay dormant'
+ TERM_LOG_ACTIVITY = 'log activity'
+ TERM_PATCH_OPERATING_SYSTEM_FILE_S = 'patch operating system file(s)'
+ TERM_REMOVE_TRACES_OF_INFECTION = 'remove traces of infection'
+ TERM_SUICIDE_EXIT = 'suicide exit'
+
+
+@register_vocab
+class FraudTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:FraudTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ACCESS_PREMIUM_SERVICE = 'access premium service'
+
+
+@register_vocab
+class ProcessMemoryActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ProcessMemoryActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ALLOCATE_PROCESS_VIRTUAL_MEMORY = 'allocate process virtual memory'
+ TERM_FREE_PROCESS_VIRTUAL_MEMORY = 'free process virtual memory'
+ TERM_MAP_FILE_INTO_PROCESS = 'map file into process'
+ TERM_MAP_LIBRARY_INTO_PROCESS = 'map library into process'
+ TERM_MODIFY_PROCESS_VIRTUAL_MEMORY_PROTECTION = 'modify process virtual memory protection'
+ TERM_READ_FROM_PROCESS_MEMORY = 'read from process memory'
+ TERM_UNMAP_FILE_FROM_PROCESS = 'unmap file from process'
+ TERM_WRITE_TO_PROCESS_MEMORY = 'write to process memory'
+
+
+@register_vocab
+class RegistryActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:RegistryActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CLOSE_REGISTRY_KEY = 'close registry key'
+ TERM_CREATE_REGISTRY_KEY = 'create registry key'
+ TERM_CREATE_REGISTRY_KEY_VALUE = 'create registry key value'
+ TERM_DELETE_REGISTRY_KEY = 'delete registry key'
+ TERM_DELETE_REGISTRY_KEY_VALUE = 'delete registry key value'
+ TERM_ENUMERATE_REGISTRY_KEY_SUBKEYS = 'enumerate registry key subkeys'
+ TERM_ENUMERATE_REGISTRY_KEY_VALUES = 'enumerate registry key values'
+ TERM_GET_REGISTRY_KEY_ATTRIBUTES = 'get registry key attributes'
+ TERM_MODIFY_REGISTRY_KEY = 'modify registry key'
+ TERM_MODIFY_REGISTRY_KEY_VALUE = 'modify registry key value'
+ TERM_MONITOR_REGISTRY_KEY = 'monitor registry key'
+ TERM_OPEN_REGISTRY_KEY = 'open registry key'
+ TERM_READ_REGISTRY_KEY_VALUE = 'read registry key value'
+
+
+@register_vocab
+class AvailabilityViolationProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AvailabilityViolationPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CRYPTOCURRENCY_TYPE = 'cryptocurrency type'
+
+
+@register_vocab
+class CommandandControlStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:CommandandControlStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DETERMINE_C2_SERVER = 'determine c2 server'
+ TERM_RECEIVE_DATA_FROM_C2_SERVER = 'receive data from c2 server'
+ TERM_SEND_DATA_TO_C2_SERVER = 'send data to c2 server'
+
+
+@register_vocab
+class DestructionTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DestructionTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DESTROY_FIRMWARE = 'destroy firmware'
+ TERM_DESTROY_HARDWARE = 'destroy hardware'
+ TERM_ERASE_DATA = 'erase data'
+
+
+@register_vocab
+class SpyingStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SpyingStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CAPTURE_SYSTEM_INPUT_PERIPHERAL_DATA = 'capture system input peripheral data'
+ TERM_CAPTURE_SYSTEM_INTERFACE_DATA = 'capture system interface data'
+ TERM_CAPTURE_SYSTEM_OUTPUT_PERIPHERAL_DATA = 'capture system output peripheral data'
+ TERM_CAPTURE_SYSTEM_STATE_DATA = 'capture system state data'
+
+
+@register_vocab
+class FTPActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:FTPActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CONNECT_TO_FTP_SERVER = 'connect to ftp server'
+ TERM_DISCONNECT_FROM_FTP_SERVER = 'disconnect from ftp server'
+ TERM_SEND_FTP_COMMAND = 'send ftp command'
+
+
+@register_vocab
+class MachineAccessControlStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MachineAccessControlStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CONTROL_LOCAL_MACHINE = 'control local machine'
+ TERM_INSTALL_BACKDOOR = 'install backdoor'
+
+
+@register_vocab
+class IntegrityViolationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:IntegrityViolationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ANNOY_USER = 'annoy user'
+ TERM_COMPROMISE_NETWORK_OPERATIONAL_INTEGRITY = 'compromise network operational integrity'
+ TERM_COMPROMISE_SYSTEM_DATA_INTEGRITY = 'compromise system data integrity'
+ TERM_COMPROMISE_SYSTEM_OPERATIONAL_INTEGRITY = 'compromise system operational integrity'
+ TERM_COMPROMISE_USER_DATA_INTEGRITY = 'compromise user data integrity'
+
+
+@register_vocab
+class ProbingTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ProbingTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CHECK_FOR_FIREWALL = 'check for firewall'
+ TERM_CHECK_FOR_INTERNET_CONNECTIVITY = 'check for internet connectivity'
+ TERM_CHECK_FOR_NETWORK_DRIVES = 'check for network drives'
+ TERM_CHECK_FOR_PROXY = 'check for proxy'
+ TERM_CHECK_LANGUAGE = 'check language'
+ TERM_IDENTIFY_OS = 'identify os'
+ TERM_INVENTORY_SYSTEM_APPLICATIONS = 'inventory system applications'
+ TERM_MAP_LOCAL_NETWORK = 'map local network'
+
+
+@register_vocab
+class MalwareEntityType(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MalwareEntityTypeVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CLASS = 'class'
+ TERM_FAMILY = 'family'
+ TERM_INSTANCE = 'instance'
+
+
+@register_vocab
+class FraudStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:FraudStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_PERFORM_CLICK_FRAUD = 'perform click fraud'
+ TERM_PERFORM_PREMIUM_RATE_FRAUD = 'perform premium rate fraud'
+
+
+@register_vocab
+class SpyingTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SpyingTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CAPTURE_CAMERA_INPUT = 'capture camera input'
+ TERM_CAPTURE_FILE_SYSTEM = 'capture file system'
+ TERM_CAPTURE_GPS_DATA = 'capture gps data'
+ TERM_CAPTURE_KEYBOARD_INPUT = 'capture keyboard input'
+ TERM_CAPTURE_MICROPHONE_INPUT = 'capture microphone input'
+ TERM_CAPTURE_MOUSE_INPUT = 'capture mouse input'
+ TERM_CAPTURE_PRINTER_OUTPUT = 'capture printer output'
+ TERM_CAPTURE_SYSTEM_MEMORY = 'capture system memory'
+ TERM_CAPTURE_SYSTEM_NETWORK_TRAFFIC = 'capture system network traffic'
+ TERM_CAPTURE_SYSTEM_SCREENSHOT = 'capture system screenshot'
+ TERM_CAPTURE_TOUCHSCREEN_INPUT = 'capture touchscreen input'
+
+
+@register_vocab
+class ProcessThreadActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ProcessThreadActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CREATE_REMOTE_THREAD_IN_PROCESS = 'create remote thread in process'
+ TERM_CREATE_THREAD = 'create thread'
+ TERM_ENUMERATE_THREADS = 'enumerate threads'
+ TERM_GET_THREAD_CONTEXT = 'get thread context'
+ TERM_GET_THREAD_USERNAME = 'get thread username'
+ TERM_IMPERSONATE_PROCESS = 'impersonate process'
+ TERM_KILL_THREAD = 'kill thread'
+ TERM_QUEUE_APC_IN_THREAD = 'queue apc in thread'
+ TERM_REVERT_THREAD_TO_SELF = 'revert thread to self'
+ TERM_SET_THREAD_CONTEXT = 'set thread context'
+
+
+@register_vocab
+class DataTheftStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DataTheftStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_STEAL_AUTHENTICATION_CREDENTIALS = 'steal authentication credentials'
+ TERM_STEAL_STORED_INFORMATION = 'steal stored information'
+ TERM_STEAL_SYSTEM_INFORMATION = 'steal system information'
+ TERM_STEAL_USER_DATA = 'steal user data'
+
+
+@register_vocab
+class AntiCodeAnalysisTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiCodeAnalysisTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DEFEAT_CALL_GRAPH_GENERATION = 'defeat call graph generation'
+ TERM_DEFEAT_FLOW_ORIENTED_RECURSIVE_TRAVERSAL_DISASSEMBLER = 'defeat flow-oriented (recursive traversal) disassembler'
+ TERM_DEFEAT_LINEAR_DISASSEMBLER = 'defeat linear disassembler'
+ TERM_DETECT_DEBUGGING = 'detect debugging'
+ TERM_OBFUSCATE_IMPORTS = 'obfuscate imports'
+ TERM_OBFUSCATE_INSTRUCTIONS = 'obfuscate instructions'
+ TERM_OBFUSCATE_RUNTIME_CODE = 'obfuscate runtime code'
+ TERM_PREVENT_DEBUGGING = 'prevent debugging'
+ TERM_RESTRUCTURE_ARRAYS = 'restructure arrays'
+ TERM_TRANSFORM_CONTROL_FLOW = 'transform control flow'
+
+
+@register_vocab
+class PrivilegeEscalationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:PrivilegeEscalationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ELEVATE_CPU_MODE = 'elevate cpu mode'
+
+
+@register_vocab
+class MalwareSubjectRelationship(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MalwareSubjectRelationshipVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_32_BIT_VERSION_OF = '32-bit version of'
+ TERM_64_BIT_VERSION_OF = '64-bit version of'
+ TERM_CONTAINED_IN_DISK_IMAGE = 'contained in disk image'
+ TERM_CONTAINED_IN_MEMORY_IMAGE = 'contained in memory image'
+ TERM_CONTAINED_IN_NETWORK_TRAFFIC_CAPTURE = 'contained in network traffic capture'
+ TERM_DECRYPTED_VERSION_OF = 'decrypted version of'
+ TERM_DIRECT_ANCESTOR_OF = 'direct ancestor of'
+ TERM_DIRECT_DESCENDANT_OF = 'direct descendant of'
+ TERM_DISK_IMAGE_OF = 'disk image of'
+ TERM_DOWNLOADED_BY = 'downloaded by'
+ TERM_DOWNLOADS = 'downloads'
+ TERM_DROPPED_BY = 'dropped by'
+ TERM_DROPS = 'drops'
+ TERM_ENCRYPTED_VERSION_OF = 'encrypted version of'
+ TERM_EXTRACTED_FROM = 'extracted from'
+ TERM_EXTRACTS = 'extracts'
+ TERM_INSTALLED_BY = 'installed by'
+ TERM_INSTALLS = 'installs'
+ TERM_MEMORY_IMAGE_OF = 'memory image of'
+ TERM_NETWORK_TRAFFIC_CAPTURE_OF = 'network traffic capture of'
+ TERM_PACKED_VERSION_OF = 'packed version of'
+ TERM_UNPACKED_VERSION_OF = 'unpacked version of'
+
+
+@register_vocab
+class AntiBehavioralAnalysisTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiBehavioralAnalysisTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DETECT_SANDBOX_ENVIRONMENT = 'detect sandbox environment'
+ TERM_DETECT_VM_ENVIRONMENT = 'detect vm environment'
+ TERM_OVERLOAD_SANDBOX = 'overload sandbox'
+ TERM_PREVENT_EXECUTION_IN_SANDBOX = 'prevent execution in sandbox'
+ TERM_PREVENT_EXECUTION_IN_VM = 'prevent execution in vm'
+
+
+@register_vocab
+class PersistenceTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:PersistenceTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DROP_RETRIEVE_DEBUG_LOG_FILE = 'drop/retrieve debug log file'
+ TERM_LIMIT_APPLICATION_TYPE_VERSION = 'limit application type/version'
+ TERM_PERSIST_AFTER_OS_INSTALL_REINSTALL = 'persist after os install/reinstall'
+ TERM_PERSIST_AFTER_SYSTEM_REBOOT = 'persist after system reboot'
+ TERM_PERSIST_INDEPENDENT_OF_HARD_DISK_OS_CHANGES = 'persist independent of hard disk/os changes'
+ TERM_REINSTANTIATE_SELF_AFTER_INITIAL_DETECTION = 'reinstantiate self after initial detection'
+
+
+@register_vocab
+class SynchronizationActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SynchronizationActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CREATE_CRITICAL_SECTION = 'create critical section'
+ TERM_CREATE_EVENT = 'create event'
+ TERM_CREATE_MUTEX = 'create mutex'
+ TERM_CREATE_SEMAPHORE = 'create semaphore'
+ TERM_DELETE_CRITICAL_SECTION = 'delete critical section'
+ TERM_DELETE_EVENT = 'delete event'
+ TERM_DELETE_MUTEX = 'delete mutex'
+ TERM_DELETE_SEMAPHORE = 'delete semaphore'
+ TERM_OPEN_CRITICAL_SECTION = 'open critical section'
+ TERM_OPEN_EVENT = 'open event'
+ TERM_OPEN_MUTEX = 'open mutex'
+ TERM_OPEN_SEMAPHORE = 'open semaphore'
+ TERM_RELEASE_CRITICAL_SECTION = 'release critical section'
+ TERM_RELEASE_MUTEX = 'release mutex'
+ TERM_RELEASE_SEMAPHORE = 'release semaphore'
+ TERM_RESET_EVENT = 'reset event'
+
+
+@register_vocab
+class AntiRemovalTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiRemovalTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_PREVENT_API_UNHOOKING = 'prevent api unhooking'
+ TERM_PREVENT_FILE_ACCESS = 'prevent file access'
+ TERM_PREVENT_FILE_DELETION = 'prevent file deletion'
+ TERM_PREVENT_MEMORY_ACCESS = 'prevent memory access'
+ TERM_PREVENT_REGISTRY_ACCESS = 'prevent registry access'
+ TERM_PREVENT_REGISTRY_DELETION = 'prevent registry deletion'
+
+
+@register_vocab
+class SecurityDegradationStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SecurityDegradationStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DEGRADE_SECURITY_PROGRAMS = 'degrade security programs'
+ TERM_DISABLE_HOST_BASED_OR_OS_ACCESS_CONTROLS = 'disable [host-based or os] access controls'
+ TERM_DISABLE_OS_SECURITY_FEATURES = 'disable os security features'
+ TERM_DISABLE_SERVICE_PROVIDER_SECURITY_FEATURES = 'disable service provider security features'
+ TERM_DISABLE_SYSTEM_UPDATES = 'disable system updates'
+
+
+@register_vocab
+class PrivilegeEscalationProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:PrivilegeEscalationPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_USER_PRIVILEGE_ESCALATION_TYPE = 'user privilege escalation type'
+
+
+@register_vocab
+class GUIActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:GUIActionNameVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CREATE_DIALOG_BOX = 'create dialog box'
+ TERM_CREATE_WINDOW = 'create window'
+ TERM_ENUMERATE_WINDOWS = 'enumerate windows'
+ TERM_FIND_WINDOW = 'find window'
+ TERM_HIDE_WINDOW = 'hide window'
+ TERM_KILL_WINDOW = 'kill window'
+ TERM_SHOW_WINDOW = 'show window'
+
+
+@register_vocab
+class SecurityDegradationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SecurityDegradationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DISABLE_ACCESS_RIGHT_CHECKING = 'disable access right checking'
+ TERM_DISABLE_FIREWALL = 'disable firewall'
+ TERM_DISABLE_KERNEL_PATCHING_PROTECTION = 'disable kernel patching protection'
+ TERM_DISABLE_OS_SECURITY_ALERTS = 'disable os security alerts'
+ TERM_DISABLE_PRIVILEGE_LIMITING = 'disable privilege limiting'
+ TERM_DISABLE_SYSTEM_FILE_OVERWRITE_PROTECTION = 'disable system file overwrite protection'
+ TERM_DISABLE_SYSTEM_SERVICE_PACK_PATCH_INSTALLATION = 'disable system service pack/patch installation'
+ TERM_DISABLE_SYSTEM_UPDATE_SERVICES_DAEMONS = 'disable system update services/daemons'
+ TERM_DISABLE_USER_ACCOUNT_CONTROL = 'disable user account control'
+ TERM_GATHER_SECURITY_PRODUCT_INFO = 'gather security product info'
+ TERM_MODIFY_SECURITY_PROGRAM_CONFIGURATION = 'modify security program configuration'
+ TERM_PREVENT_ACCESS_TO_SECURITY_WEBSITES = 'prevent access to security websites'
+ TERM_PREVENT_SECURITY_PROGRAM_FROM_RUNNING = 'prevent security program from running'
+ TERM_REMOVE_SMS_WARNING_MESSAGES = 'remove sms warning messages'
+ TERM_STOP_EXECUTION_OF_SECURITY_PROGRAM = 'stop execution of security program'
+
+
+@register_vocab
+class MalwareConfigurationParameter(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MalwareConfigurationParameterVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_FILENAME = 'filename'
+ TERM_GROUP_ID = 'group id'
+ TERM_ID = 'id'
+ TERM_INSTALLATION_PATH = 'installation path'
+ TERM_MAGIC_NUMBER = 'magic number'
+ TERM_MUTEX = 'mutex'
+
+
+@register_vocab
+class MachineAccessControlProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MachineAccessControlPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_BACKDOOR_TYPE = 'backdoor type'
+
+
+@register_vocab
+class ServiceActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:ServiceActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_CREATE_SERVICE = 'create service'
+ TERM_DELETE_SERVICE = 'delete service'
+ TERM_ENUMERATE_SERVICES = 'enumerate services'
+ TERM_MODIFY_SERVICE_CONFIGURATION = 'modify service configuration'
+ TERM_OPEN_SERVICE = 'open service'
+ TERM_SEND_CONTROL_CODE_TO_SERVICE = 'send control code to service'
+ TERM_START_SERVICE = 'start service'
+ TERM_STOP_SERVICE = 'stop service'
+
+
+@register_vocab
+class AntiBehavioralAnalysisStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiBehavioralAnalysisStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ANTI_SANDBOX = 'anti-sandbox'
+ TERM_ANTI_VM = 'anti-vm'
+
+
+@register_vocab
+class CapabilityObjectiveRelationship(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:CapabilityObjectiveRelationshipVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CHILD_OF = 'child of'
+ TERM_INCORPORATED_BY = 'incorporated by'
+ TERM_INCORPORATES = 'incorporates'
+ TERM_PARENT_OF = 'parent of'
+
+
+@register_vocab
+class DataExfiltrationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DataExfiltrationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ENCRYPT_DATA = 'encrypt data'
+ TERM_EXFILTRATE_VIA_COVERT_CHANNEL = 'exfiltrate via covert channel'
+ TERM_EXFILTRATE_VIA_DUMPSTER_DIVE = 'exfiltrate via dumpster dive'
+ TERM_EXFILTRATE_VIA_FAX = 'exfiltrate via fax'
+ TERM_EXFILTRATE_VIA_NETWORK = 'exfiltrate via network'
+ TERM_EXFILTRATE_VIA_PHYSICAL_MEDIA = 'exfiltrate via physical media'
+ TERM_EXFILTRATE_VIA_VOIP_PHONE = 'exfiltrate via voip/phone'
+ TERM_HIDE_DATA = 'hide data'
+ TERM_MOVE_DATA_TO_STAGING_SERVER = 'move data to staging server'
+ TERM_PACKAGE_DATA = 'package data'
+
+
+@register_vocab
+class UserActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:UserActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_ADD_USER = 'add user'
+ TERM_ADD_USER_TO_GROUP = 'add user to group'
+ TERM_CHANGE_PASSWORD = 'change password'
+ TERM_DELETE_USER = 'delete user'
+ TERM_ENUMERATE_USERS = 'enumerate users'
+ TERM_GET_USER_ATTRIBUTES = 'get user attributes'
+ TERM_INVOKE_USER_PRIVILEGE = 'invoke user privilege'
+ TERM_LOGON_AS_USER = 'logon as user'
+ TERM_REMOVE_USER_FROM_GROUP = 'remove user from group'
+
+
+@register_vocab
+class DestructionStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DestructionStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_DESTROY_PHYSICAL_ENTITY = 'destroy physical entity'
+ TERM_DESTROY_VIRTUAL_ENTITY = 'destroy virtual entity'
+
+
+@register_vocab
+class AntiRemovalStrategicObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiRemovalStrategicObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_PREVENT_MALWARE_ARTIFACT_ACCESS = 'prevent malware artifact access'
+ TERM_PREVENT_MALWARE_ARTIFACT_DELETION = 'prevent malware artifact deletion'
+
+
+@register_vocab
+class SecondaryOperationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SecondaryOperationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_INSTALL_LEGITIMATE_SOFTWARE = 'install legitimate software'
+ TERM_INSTALL_SECONDARY_MALWARE = 'install secondary malware'
+ TERM_INSTALL_SECONDARY_MODULE = 'install secondary module'
+ TERM_REMOVE_SELF = 'remove self'
+ TERM_REMOVE_SYSTEM_ARTIFACTS = 'remove system artifacts'
+
+
+@register_vocab
+class MalwareLabel(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:MalwareLabelVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ADWARE = 'adware'
+ TERM_APPENDER = 'appender'
+ TERM_BACKDOOR = 'backdoor'
+ TERM_BOOT_SECTOR_VIRUS = 'boot sector virus'
+ TERM_BOT = 'bot'
+ TERM_CAVITY_FILLER = 'cavity filler'
+ TERM_CLICKER = 'clicker'
+ TERM_COMPANION_VIRUS = 'companion virus'
+ TERM_DATA_DIDDLER = 'data diddler'
+ TERM_DOWNLOADER = 'downloader'
+ TERM_DROPPER_FILE = 'dropper file'
+ TERM_FILE_INFECTOR_VIRUS = 'file infector virus'
+ TERM_FORK_BOMB = 'fork bomb'
+ TERM_GREYWARE = 'greyware'
+ TERM_IMPLANT = 'implant'
+ TERM_INFECTOR = 'infector'
+ TERM_KEYLOGGER = 'keylogger'
+ TERM_KLEPTOGRAPHIC_WORM = 'kleptographic worm'
+ TERM_MACRO_VIRUS = 'macro virus'
+ TERM_MALCODE = 'malcode'
+ TERM_MASS_MAILER = 'mass-mailer'
+ TERM_METAMORPHIC_VIRUS = 'metamorphic virus'
+ TERM_MID_INFECTOR = 'mid-infector'
+ TERM_MOBILE_CODE = 'mobile code'
+ TERM_MULTIPARTITE_VIRUS = 'multipartite virus'
+ TERM_PASSWORD_STEALER = 'password stealer'
+ TERM_POLYMORPHIC_VIRUS = 'polymorphic virus'
+ TERM_PREMIUM_DIALER_SMSER = 'premium dialer/smser'
+ TERM_PREPENDER = 'prepender'
+ TERM_RANSOMWARE = 'ransomware'
+ TERM_RAT = 'rat'
+ TERM_ROGUE_ANTI_MALWARE = 'rogue anti-malware'
+ TERM_ROOTKIT = 'rootkit'
+ TERM_SHELLCODE = 'shellcode'
+ TERM_SPAGHETTI_PACKER = 'spaghetti packer'
+ TERM_SPYWARE = 'spyware'
+ TERM_TROJAN_HORSE = 'trojan horse'
+ TERM_VARIANT = 'variant'
+ TERM_VIRUS = 'virus'
+ TERM_WABBIT = 'wabbit'
+ TERM_WEB_BUG = 'web bug'
+ TERM_WIPER = 'wiper'
+ TERM_WORM = 'worm'
+ TERM_ZIP_BOMB = 'zip bomb'
+
+
+@register_vocab
+class SecurityDegradationProperties(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:SecurityDegradationPropertiesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_TARGETED_PROGRAM = 'targeted program'
+
+
+@register_vocab
+class DiskActionName(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:DiskActionNameVocab-1.1'
+ _VOCAB_VERSION = '1.1'
+
+ TERM_EMULATE_DISK = 'emulate disk'
+ TERM_GET_DISK_ATTRIBUTES = 'get disk attributes'
+ TERM_GET_DISK_TYPE = 'get disk type'
+ TERM_LIST_DISKS = 'list disks'
+ TERM_MONITOR_DISK = 'monitor disk'
+ TERM_MOUNT_DISK = 'mount disk'
+ TERM_UNMOUNT_DISK = 'unmount disk'
+
+
+@register_vocab
+class IntegrityViolationTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:IntegrityViolationTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_ANNOY_LOCAL_SYSTEM_USER = 'annoy local system user'
+ TERM_ANNOY_REMOTE_USER = 'annoy remote user'
+ TERM_CORRUPT_SYSTEM_DATA = 'corrupt system data'
+ TERM_CORRUPT_USER_DATA = 'corrupt user data'
+ TERM_INTERCEPT_MANIPULATE_NETWORK_TRAFFIC = 'intercept/manipulate network traffic'
+ TERM_SUBVERT_SYSTEM = 'subvert system'
+
+
+@register_vocab
+class AntiDetectionTacticalObjectives(VocabString):
+ _namespace = 'http://maec.mitre.org/default_vocabularies-1'
+ _XSI_TYPE = 'maecVocabs:AntiDetectionTacticalObjectivesVocab-1.0'
+ _VOCAB_VERSION = '1.0'
+
+ TERM_CHANGE_ADD_CONTENT = 'change/add content'
+ TERM_ENCRYPT_SELF = 'encrypt self'
+ TERM_EXECUTE_BEFORE_EXTERNAL_TO_KERNEL_HYPERVISOR = 'execute before/external to kernel/hypervisor'
+ TERM_EXECUTE_NON_MAIN_CPU_CODE = 'execute non-main cpu code'
+ TERM_EXECUTE_STEALTHY_CODE = 'execute stealthy code'
+ TERM_FEED_MISINFORMATION_DURING_PHYSICAL_MEMORY_ACQUISITION = 'feed misinformation during physical memory acquisition'
+ TERM_HIDE_ARBITRARY_VIRTUAL_MEMORY = 'hide arbitrary virtual memory'
+ TERM_HIDE_CODE_IN_FILE = 'hide code in file'
+ TERM_HIDE_FILE_SYSTEM_ARTIFACTS = 'hide file system artifacts'
+ TERM_HIDE_KERNEL_MODULES = 'hide kernel modules'
+ TERM_HIDE_NETWORK_TRAFFIC = 'hide network traffic'
+ TERM_HIDE_OPEN_NETWORK_PORTS = 'hide open network ports'
+ TERM_HIDE_PROCESSES = 'hide processes'
+ TERM_HIDE_REGISTRY_ARTIFACTS = 'hide registry artifacts'
+ TERM_HIDE_SERVICES = 'hide services'
+ TERM_HIDE_THREADS = 'hide threads'
+ TERM_HIDE_USERSPACE_LIBRARIES = 'hide userspace libraries'
+ TERM_OBFUSCATE_ARTIFACT_PROPERTIES = 'obfuscate artifact properties'
+ TERM_PREVENT_NATIVE_API_HOOKING = 'prevent native api hooking'
+ TERM_PREVENT_PHYSICAL_MEMORY_ACQUISITION = 'prevent physical memory acquisition'
diff --git a/requirements.txt b/requirements.txt
index 142b6ca..54d4638 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1 +1 @@
--e .[docs]
+-e .[docs,test]
diff --git a/scripts/calculate_distance.py b/scripts/calculate_distance.py
new file mode 100644
index 0000000..0677f56
--- /dev/null
+++ b/scripts/calculate_distance.py
@@ -0,0 +1,57 @@
+# calculate_distance script
+# Calculates and prints the distance between two or more MAEC Malware Subjects
+# NOTE: This code imports and uses the maec.analytics.distance module, which uses the external numpy library.
+# Numpy can be found here: https://pypi.python.org/pypi/numpy
+
+# Copyright (c) 2018, The MITRE Corporation. All rights reserved.
+# See LICENSE.txt for complete terms.
+
+import os
+import maec
+import argparse
+from maec.analytics.distance import Distance
+from maec.package.package import Package
+
+def main():
+ # Setup the argument parser
+ parser = argparse.ArgumentParser(description="MAEC Distance Calculation script")
+ group = parser.add_mutually_exclusive_group()
+ group.add_argument("-l", "-list", nargs="+", help="a space separated list of MAEC Package files to calculate the distances for")
+ group.add_argument("-d", "-directory", help="the path to a directory of MAEC Package files to calculate the distances for")
+ parser.add_argument("--only_static", "--only_static", help="use only static features in the distance calculation", action="store_true")
+ parser.add_argument("--only_dynamic", "--only_dynamic", help="use only dynamic features (Actions) in the distance calculation", action="store_true")
+ parser.add_argument("output", help="the name of the CSV file to which the calculated distances will be written")
+ args = parser.parse_args()
+ package_list = []
+
+ # Parse the input files
+ if args.l:
+ for file in args.l:
+ api_obj = maec.parse_xml_instance(file)['api']
+ if isinstance(api_obj, Package):
+ package_list.append(api_obj)
+ elif args.d:
+ for filename in os.listdir(args.d):
+ if '.xml' not in filename:
+ pass
+ else:
+ api_obj = maec.parse_xml_instance(os.path.join(args.d, filename))['api']
+ if isinstance(api_obj, Package):
+ package_list.append(api_obj)
+
+ # Perform the distance calculation
+ dist = Distance(package_list)
+ # Set the particular features that will be used
+ if args.only_static:
+ dist.options_dict['use_dynamic_features'] = False
+ if args.only_dynamic:
+ dist.options_dict['use_static_features'] = False
+ dist.calculate()
+ # Write the results to the specified CSV file
+ out_file = open(args.output, mode='w')
+ dist.print_distances(out_file)
+ out_file.close()
+
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/scripts/maec_4.0.1_to_4.1.py b/scripts/maec_4.0.1_to_4.1.py
old mode 100644
new mode 100755
index cc5a96b..7f53135
--- a/scripts/maec_4.0.1_to_4.1.py
+++ b/scripts/maec_4.0.1_to_4.1.py
@@ -1,88 +1,88 @@
-# MAEC 4.0.1 to MAEC 4.1 Converter Script
-# Translates a MAEC 4.0.1 Package or Bundle into a valid MAEC 4.1 Package or Bundle
-
-import sys
-import os
-import shutil
-import maec
-from maec.bundle.bundle import Bundle
-from maec.package.package import Package
-
-# Update the MAEC v4.0.1 file to MAEC v4.1
-def update_maec(infilename, outfilename):
- # Parse the input document using the parse_xml_instance() method
- maec_objects = maec.parse_xml_instance(infilename, check_version = False)
-
- # Get the API Object from the parsed input
- api_object = maec_objects['api']
-
- # Determine if we're dealing with a Package or Bundle
- if isinstance(api_object, Package):
- # Update the Package schema_version
- api_object.schema_version = "2.1"
- for malware_subject in api_object.malware_subjects:
- for analysis in malware_subject.analyses:
- # Replace the Analysis type value of "manual" with "in-depth"
- if analysis.type and analysis.type == "manual":
- analysis.type = "in-depth"
- # Update the schema_versions on the Bundles
- for bundle in malware_subject.findings_bundles.bundles:
- bundle.schema_version = "4.1"
- elif isinstance(api_object, Bundle):
- # Update the Bundle schema_version
- api_object.schema_version = "4.1"
-
- # Output the updated MAEC object to XML
- api_object.to_xml_file(outfilename)
-
-# Print the usage text
-def usage():
- print USAGE_TEXT
- sys.exit(1)
-
-USAGE_TEXT = """
-MAEC 4.0.1 --> MAEC 4.1 XML Converter Utility
-
-Usage: python maec_4.0.1_to_4.1.py -i -o