1# Copyright (c) 2017, The MITRE Corporation. All rights reserved.
2# See LICENSE.txt for complete terms.
3
4import sys
5
6from mixbox.binding_utils import *
7from . import cybox_common
8
9
10class WindowsCriticalSectionObjectType(cybox_common.ObjectPropertiesType):
11    """The WindowsCriticalSectionObjectType type is intended to
12    characterize Windows Critical Section objects."""
13
14    subclass = None
15    superclass = cybox_common.ObjectPropertiesType
16    def __init__(self, object_reference=None, Custom_Properties=None, xsi_type=None, Address=None, Spin_Count=None):
17        super(WindowsCriticalSectionObjectType, self).__init__(object_reference, Custom_Properties, xsi_type )
18        self.Address = Address
19        self.Spin_Count = Spin_Count
20    def factory(*args_, **kwargs_):
21        if WindowsCriticalSectionObjectType.subclass:
22            return WindowsCriticalSectionObjectType.subclass(*args_, **kwargs_)
23        else:
24            return WindowsCriticalSectionObjectType(*args_, **kwargs_)
25    factory = staticmethod(factory)
26    def get_Address(self): return self.Address
27    def set_Address(self, Address): self.Address = Address
28    def validate_HexBinaryObjectPropertyType(self, value):
29        # Validate type cybox_common.HexBinaryObjectPropertyType, a restriction on None.
30        pass
31    def get_Spin_Count(self): return self.Spin_Count
32    def set_Spin_Count(self, Spin_Count): self.Spin_Count = Spin_Count
33    def validate_NonNegativeIntegerObjectPropertyType(self, value):
34        # Validate type cybox_common.NonNegativeIntegerObjectPropertyType, a restriction on None.
35        pass
36    def hasContent_(self):
37        if (
38            self.Address is not None or
39            self.Spin_Count is not None or
40            super(WindowsCriticalSectionObjectType, self).hasContent_()
41            ):
42            return True
43        else:
44            return False
45    def export(self, lwrite, level, namespace_='WinCriticalSectionObj:', name_='WindowsCriticalSectionObjectType', namespacedef_='', pretty_print=True):
46        if pretty_print:
47            eol_ = '\n'
48        else:
49            eol_ = ''
50        showIndent(lwrite, level, pretty_print)
51        lwrite('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
52        already_processed = set()
53        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='WindowsCriticalSectionObjectType')
54        if self.hasContent_():
55            lwrite('>%s' % (eol_, ))
56            self.exportChildren(lwrite, level + 1, namespace_, name_, pretty_print=pretty_print)
57            showIndent(lwrite, level, pretty_print)
58            lwrite('</%s%s>%s' % (namespace_, name_, eol_))
59        else:
60            lwrite('/>%s' % (eol_, ))
61    def exportAttributes(self, lwrite, level, already_processed, namespace_='WinCriticalSectionObj:', name_='WindowsCriticalSectionObjectType'):
62        super(WindowsCriticalSectionObjectType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='WindowsCriticalSectionObjectType')
63    def exportChildren(self, lwrite, level, namespace_='WinCriticalSectionObj:', name_='WindowsCriticalSectionObjectType', fromsubclass_=False, pretty_print=True):
64        super(WindowsCriticalSectionObjectType, self).exportChildren(lwrite, level, 'WinCriticalSectionObj:', name_, True, pretty_print=pretty_print)
65        if pretty_print:
66            eol_ = '\n'
67        else:
68            eol_ = ''
69        if self.Address is not None:
70            self.Address.export(lwrite, level, 'WinCriticalSectionObj:', name_='Address', pretty_print=pretty_print)
71        if self.Spin_Count is not None:
72            self.Spin_Count.export(lwrite, level, 'WinCriticalSectionObj:', name_='Spin_Count', pretty_print=pretty_print)
73    def build(self, node):
74        self.__sourcenode__ = node
75        already_processed = set()
76        self.buildAttributes(node, node.attrib, already_processed)
77        for child in node:
78            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
79            self.buildChildren(child, node, nodeName_)
80    def buildAttributes(self, node, attrs, already_processed):
81        super(WindowsCriticalSectionObjectType, self).buildAttributes(node, attrs, already_processed)
82    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
83        if nodeName_ == 'Address':
84            obj_ = cybox_common.HexBinaryObjectPropertyType.factory()
85            obj_.build(child_)
86            self.set_Address(obj_)
87        elif nodeName_ == 'Spin_Count':
88            obj_ = cybox_common.NonNegativeIntegerObjectPropertyType.factory()
89            obj_.build(child_)
90            self.set_Spin_Count(obj_)
91        super(WindowsCriticalSectionObjectType, self).buildChildren(child_, node, nodeName_, True)
92# end class WindowsCriticalSectionObjectType
93
94GDSClassesMapping = {
95    'Build_Utility': cybox_common.BuildUtilityType,
96    'Errors': cybox_common.ErrorsType,
97    'Time': cybox_common.TimeType,
98    'Certificate_Issuer': cybox_common.StringObjectPropertyType,
99    'Metadata': cybox_common.MetadataType,
100    'Hash': cybox_common.HashType,
101    'Information_Source_Type': cybox_common.ControlledVocabularyStringType,
102    'Block_Hash_Value': cybox_common.HashValueType,
103    'Fuzzy_Hash_Structure': cybox_common.FuzzyHashStructureType,
104    'SubDatum': cybox_common.MetadataType,
105    'Segment_Hash': cybox_common.HashValueType,
106    'Digital_Signature': cybox_common.DigitalSignatureInfoType,
107    'Code_Snippets': cybox_common.CodeSnippetsType,
108    'Value': cybox_common.StringObjectPropertyType,
109    'Length': cybox_common.IntegerObjectPropertyType,
110    'Encoding': cybox_common.ControlledVocabularyStringType,
111    'Internationalization_Settings': cybox_common.InternationalizationSettingsType,
112    'Tool_Configuration': cybox_common.ToolConfigurationType,
113    'English_Translation': cybox_common.StringObjectPropertyType,
114    'Functions': cybox_common.FunctionsType,
115    'String_Value': cybox_common.StringObjectPropertyType,
116    'Build_Utility_Platform_Specification': cybox_common.PlatformSpecificationType,
117    'Compiler_Informal_Description': cybox_common.CompilerInformalDescriptionType,
118    'System': cybox_common.ObjectPropertiesType,
119    'Platform': cybox_common.PlatformSpecificationType,
120    'Usage_Context_Assumptions': cybox_common.UsageContextAssumptionsType,
121    'Type': cybox_common.ControlledVocabularyStringType,
122    'Compilers': cybox_common.CompilersType,
123    'Tool_Type': cybox_common.ControlledVocabularyStringType,
124    'String': cybox_common.ExtractedStringType,
125    'Custom_Properties': cybox_common.CustomPropertiesType,
126    'Build_Information': cybox_common.BuildInformationType,
127    'Tool_Hashes': cybox_common.HashListType,
128    'Compiler_Platform_Specification': cybox_common.PlatformSpecificationType,
129    'Error_Instances': cybox_common.ErrorInstancesType,
130    'Data_Segment': cybox_common.StringObjectPropertyType,
131    'Certificate_Subject': cybox_common.StringObjectPropertyType,
132    'Language': cybox_common.StringObjectPropertyType,
133    'Identifier': cybox_common.PlatformIdentifierType,
134    'Strings': cybox_common.ExtractedStringsType,
135    'Contributors': cybox_common.PersonnelType,
136    'Reference_Description': cybox_common.StructuredTextType,
137    'Code_Snippet': cybox_common.ObjectPropertiesType,
138    'Configuration_Settings': cybox_common.ConfigurationSettingsType,
139    'Simple_Hash_Value': cybox_common.SimpleHashValueType,
140    'Byte_String_Value': cybox_common.HexBinaryObjectPropertyType,
141    'Instance': cybox_common.ObjectPropertiesType,
142    'Import': cybox_common.StringObjectPropertyType,
143    'Property': cybox_common.PropertyType,
144    'Tool_Specific_Data': cybox_common.ToolSpecificDataType,
145    'Execution_Environment': cybox_common.ExecutionEnvironmentType,
146    'Dependencies': cybox_common.DependenciesType,
147    'Offset': cybox_common.IntegerObjectPropertyType,
148    'Date': cybox_common.DateRangeType,
149    'Hashes': cybox_common.HashListType,
150    'Segments': cybox_common.HashSegmentsType,
151    'Segment_Count': cybox_common.IntegerObjectPropertyType,
152    'Usage_Context_Assumption': cybox_common.StructuredTextType,
153    'Block_Hash': cybox_common.FuzzyHashBlockType,
154    'Dependency': cybox_common.DependencyType,
155    'Error': cybox_common.ErrorType,
156    'Trigger_Point': cybox_common.HexBinaryObjectPropertyType,
157    'Environment_Variable': cybox_common.EnvironmentVariableType,
158    'Byte_Run': cybox_common.ByteRunType,
159    'File_System_Offset': cybox_common.IntegerObjectPropertyType,
160    'Spin_Count': cybox_common.NonNegativeIntegerObjectPropertyType,
161    'Image_Offset': cybox_common.IntegerObjectPropertyType,
162    'Imports': cybox_common.ImportsType,
163    'Library': cybox_common.LibraryType,
164    'References': cybox_common.ToolReferencesType,
165    'Internal_Strings': cybox_common.InternalStringsType,
166    'Configuration_Setting': cybox_common.ConfigurationSettingType,
167    'Libraries': cybox_common.LibrariesType,
168    'Function': cybox_common.StringObjectPropertyType,
169    'Description': cybox_common.StructuredTextType,
170    'User_Account_Info': cybox_common.ObjectPropertiesType,
171    'Build_Configuration': cybox_common.BuildConfigurationType,
172    'Address': cybox_common.HexBinaryObjectPropertyType,
173    'Search_Within': cybox_common.IntegerObjectPropertyType,
174    'Segment': cybox_common.HashSegmentType,
175    'Compiler': cybox_common.CompilerType,
176    'Name': cybox_common.StringObjectPropertyType,
177    'Signature_Description': cybox_common.StringObjectPropertyType,
178    'Block_Size': cybox_common.IntegerObjectPropertyType,
179    'Search_Distance': cybox_common.IntegerObjectPropertyType,
180    'Fuzzy_Hash_Value': cybox_common.FuzzyHashValueType,
181    'Data_Size': cybox_common.DataSizeType,
182    'Dependency_Description': cybox_common.StructuredTextType,
183    'Contributor': cybox_common.ContributorType,
184    'Tools': cybox_common.ToolsInformationType,
185    'Tool': cybox_common.ToolInformationType,
186}
187
188USAGE_TEXT = """
189Usage: python <Parser>.py [ -s ] <in_xml_file>
190"""
191
192def usage():
193    print(USAGE_TEXT)
194    sys.exit(1)
195
196def get_root_tag(node):
197    tag = Tag_pattern_.match(node.tag).groups()[-1]
198    rootClass = GDSClassesMapping.get(tag)
199    if rootClass is None:
200        rootClass = globals().get(tag)
201    return tag, rootClass
202
203def parse(inFileName):
204    doc = parsexml_(inFileName)
205    rootNode = doc.getroot()
206    rootTag, rootClass = get_root_tag(rootNode)
207    if rootClass is None:
208        rootTag = 'Windows_Critical_Section'
209        rootClass = WindowsCriticalSectionObjectType
210    rootObj = rootClass.factory()
211    rootObj.build(rootNode)
212    # Enable Python to collect the space used by the DOM.
213    doc = None
214#    sys.stdout.write('<?xml version="1.0" ?>\n')
215#    rootObj.export(sys.stdout.write, 0, name_=rootTag,
216#        namespacedef_='',
217#        pretty_print=True)
218    return rootObj
219
220def parseEtree(inFileName):
221    doc = parsexml_(inFileName)
222    rootNode = doc.getroot()
223    rootTag, rootClass = get_root_tag(rootNode)
224    if rootClass is None:
225        rootTag = 'Windows_Critical_Section'
226        rootClass = WindowsCriticalSectionObjectType
227    rootObj = rootClass.factory()
228    rootObj.build(rootNode)
229    # Enable Python to collect the space used by the DOM.
230    doc = None
231    rootElement = rootObj.to_etree(None, name_=rootTag)
232    content = etree_.tostring(rootElement, pretty_print=True,
233        xml_declaration=True, encoding="utf-8")
234    sys.stdout.write(content)
235    sys.stdout.write('\n')
236    return rootObj, rootElement
237
238def parseString(inString):
239    from mixbox.vendor.six import StringIO
240    doc = parsexml_(StringIO(inString))
241    rootNode = doc.getroot()
242    rootTag, rootClass = get_root_tag(rootNode)
243    if rootClass is None:
244        rootTag = 'Windows_Critical_Section'
245        rootClass = WindowsCriticalSectionObjectType
246    rootObj = rootClass.factory()
247    rootObj.build(rootNode)
248    # Enable Python to collect the space used by the DOM.
249    doc = None
250#    sys.stdout.write('<?xml version="1.0" ?>\n')
251#    rootObj.export(sys.stdout.write, 0, name_="Windows_Critical_Section",
252#        namespacedef_='')
253    return rootObj
254
255def main():
256    args = sys.argv[1:]
257    if len(args) == 1:
258        parse(args[0])
259    else:
260        usage()
261
262if __name__ == '__main__':
263    #import pdb; pdb.set_trace()
264    main()
265
266__all__ = [
267    "WindowsCriticalSectionObjectType"
268    ]
269