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
8from . import win_handle_object
9
10
11class WinEventType(cybox_common.BaseObjectPropertyType):
12    """WinEventType specifies Windows event types, via a union of the
13    WinEventTypeEnum type and the atomic xs:string type. Its base
14    type is the CybOX Core cybox_common.BaseObjectPropertyType, for permitting
15    complex (i.e. regular-expression based) specifications.This
16    attribute is optional and specifies the expected type for the
17    value of the specified property."""
18
19    subclass = None
20    superclass = cybox_common.BaseObjectPropertyType
21    def __init__(self, obfuscation_algorithm_ref=None, refanging_transform_type=None, has_changed=None, delimiter='##comma##', pattern_type=None, datatype='string', refanging_transform=None, is_case_sensitive=True, bit_mask=None, appears_random=None, observed_encoding=None, defanging_algorithm_ref=None, is_obfuscated=None, regex_syntax=None, apply_condition='ANY', trend=None, idref=None, is_defanged=None, id=None, condition=None, valueOf_=None):
22        super(WinEventType, self).__init__(obfuscation_algorithm_ref, refanging_transform_type, has_changed, delimiter, pattern_type, datatype, refanging_transform, is_case_sensitive, bit_mask, appears_random, observed_encoding, defanging_algorithm_ref, is_obfuscated, regex_syntax, apply_condition, trend, idref, is_defanged, id, condition, valueOf_)
23        self.datatype = _cast(None, datatype)
24        self.valueOf_ = valueOf_
25    def factory(*args_, **kwargs_):
26        if WinEventType.subclass:
27            return WinEventType.subclass(*args_, **kwargs_)
28        else:
29            return WinEventType(*args_, **kwargs_)
30    factory = staticmethod(factory)
31    def get_datatype(self): return self.datatype
32    def set_datatype(self, datatype): self.datatype = datatype
33    def get_valueOf_(self): return self.valueOf_
34    def set_valueOf_(self, valueOf_): self.valueOf_ = valueOf_
35    def hasContent_(self):
36        if (
37            self.valueOf_ or
38            super(WinEventType, self).hasContent_()
39            ):
40            return True
41        else:
42            return False
43    def export(self, lwrite, level, namespace_='WinEventObj:', name_='WinEventType', namespacedef_='', pretty_print=True):
44        if pretty_print:
45            eol_ = '\n'
46        else:
47            eol_ = ''
48        showIndent(lwrite, level, pretty_print)
49        lwrite('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
50        already_processed = set()
51        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='WinEventType')
52        if self.hasContent_():
53            lwrite('>')
54            lwrite(quote_xml(self.valueOf_))
55            self.exportChildren(lwrite, level + 1, namespace_, name_, pretty_print=pretty_print)
56            lwrite('</%s%s>%s' % (namespace_, name_, eol_))
57        else:
58            lwrite('/>%s' % (eol_, ))
59    def exportAttributes(self, lwrite, level, already_processed, namespace_='WinEventObj:', name_='WinEventType'):
60        super(WinEventType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='WinEventType')
61        if self.datatype is not None:
62
63            lwrite(' datatype=%s' % (quote_attrib(self.datatype), ))
64    def exportChildren(self, lwrite, level, namespace_='WinEventObj:', name_='WinEventType', fromsubclass_=False, pretty_print=True):
65        super(WinEventType, self).exportChildren(lwrite, level, 'WinEventObj:', name_, True, pretty_print=pretty_print)
66        pass
67    def build(self, node):
68        self.__sourcenode__ = node
69        already_processed = set()
70        self.buildAttributes(node, node.attrib, already_processed)
71        self.valueOf_ = get_all_text_(node)
72        for child in node:
73            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
74            self.buildChildren(child, node, nodeName_)
75    def buildAttributes(self, node, attrs, already_processed):
76        value = find_attr_value_('datatype', node)
77        if value is not None:
78
79            self.datatype = value
80        super(WinEventType, self).buildAttributes(node, attrs, already_processed)
81    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
82        pass
83# end class WinEventType
84
85class WindowsEventObjectType(cybox_common.ObjectPropertiesType):
86    """The WindowsEventObjectType type is intended to characterize Windows
87    event (synchronization) objects."""
88
89    subclass = None
90    superclass = cybox_common.ObjectPropertiesType
91    def __init__(self, object_reference=None, Custom_Properties=None, xsi_type=None, Handle=None, Name=None, Type=None):
92        super(WindowsEventObjectType, self).__init__(object_reference, Custom_Properties, xsi_type )
93        self.Handle = Handle
94        self.Name = Name
95        self.Type = Type
96    def factory(*args_, **kwargs_):
97        if WindowsEventObjectType.subclass:
98            return WindowsEventObjectType.subclass(*args_, **kwargs_)
99        else:
100            return WindowsEventObjectType(*args_, **kwargs_)
101    factory = staticmethod(factory)
102    def get_Handle(self): return self.Handle
103    def set_Handle(self, Handle): self.Handle = Handle
104    def get_Name(self): return self.Name
105    def set_Name(self, Name): self.Name = Name
106    def validate_StringObjectPropertyType(self, value):
107        # Validate type cybox_common.StringObjectPropertyType, a restriction on None.
108        pass
109    def get_Type(self): return self.Type
110    def set_Type(self, Type): self.Type = Type
111    def validate_WinEventType(self, value):
112        # Validate type WinEventType, a restriction on None.
113        pass
114    def hasContent_(self):
115        if (
116            self.Handle is not None or
117            self.Name is not None or
118            self.Type is not None or
119            super(WindowsEventObjectType, self).hasContent_()
120            ):
121            return True
122        else:
123            return False
124    def export(self, lwrite, level, namespace_='WinEventObj:', name_='WindowsEventObjectType', namespacedef_='', pretty_print=True):
125        if pretty_print:
126            eol_ = '\n'
127        else:
128            eol_ = ''
129        showIndent(lwrite, level, pretty_print)
130        lwrite('<%s%s%s' % (namespace_, name_, namespacedef_ and ' ' + namespacedef_ or '', ))
131        already_processed = set()
132        self.exportAttributes(lwrite, level, already_processed, namespace_, name_='WindowsEventObjectType')
133        if self.hasContent_():
134            lwrite('>%s' % (eol_, ))
135            self.exportChildren(lwrite, level + 1, namespace_, name_, pretty_print=pretty_print)
136            showIndent(lwrite, level, pretty_print)
137            lwrite('</%s%s>%s' % (namespace_, name_, eol_))
138        else:
139            lwrite('/>%s' % (eol_, ))
140    def exportAttributes(self, lwrite, level, already_processed, namespace_='WinEventObj:', name_='WindowsEventObjectType'):
141        super(WindowsEventObjectType, self).exportAttributes(lwrite, level, already_processed, namespace_, name_='WindowsEventObjectType')
142    def exportChildren(self, lwrite, level, namespace_='WinEventObj:', name_='WindowsEventObjectType', fromsubclass_=False, pretty_print=True):
143        super(WindowsEventObjectType, self).exportChildren(lwrite, level, 'WinEventObj:', name_, True, pretty_print=pretty_print)
144        if pretty_print:
145            eol_ = '\n'
146        else:
147            eol_ = ''
148        if self.Handle is not None:
149            self.Handle.export(lwrite, level, 'WinEventObj:', name_='Handle', pretty_print=pretty_print)
150        if self.Name is not None:
151            self.Name.export(lwrite, level, 'WinEventObj:', name_='Name', pretty_print=pretty_print)
152        if self.Type is not None:
153            self.Type.export(lwrite, level, 'WinEventObj:', name_='Type', pretty_print=pretty_print)
154    def build(self, node):
155        self.__sourcenode__ = node
156        already_processed = set()
157        self.buildAttributes(node, node.attrib, already_processed)
158        for child in node:
159            nodeName_ = Tag_pattern_.match(child.tag).groups()[-1]
160            self.buildChildren(child, node, nodeName_)
161    def buildAttributes(self, node, attrs, already_processed):
162        super(WindowsEventObjectType, self).buildAttributes(node, attrs, already_processed)
163    def buildChildren(self, child_, node, nodeName_, fromsubclass_=False):
164        if nodeName_ == 'Handle':
165            obj_ = win_handle_object.WindowsHandleObjectType.factory()
166            obj_.build(child_)
167            self.set_Handle(obj_)
168        elif nodeName_ == 'Name':
169            obj_ = cybox_common.StringObjectPropertyType.factory()
170            obj_.build(child_)
171            self.set_Name(obj_)
172        elif nodeName_ == 'Type':
173            obj_ = WinEventType.factory()
174            obj_.build(child_)
175            self.set_Type(obj_)
176        super(WindowsEventObjectType, self).buildChildren(child_, node, nodeName_, True)
177# end class WindowsEventObjectType
178
179GDSClassesMapping = {
180    'Build_Utility': cybox_common.BuildUtilityType,
181    'Errors': cybox_common.ErrorsType,
182    'Time': cybox_common.TimeType,
183    'Certificate_Issuer': cybox_common.StringObjectPropertyType,
184    'Metadata': cybox_common.MetadataType,
185    'Hash': cybox_common.HashType,
186    'Information_Source_Type': cybox_common.ControlledVocabularyStringType,
187    'Block_Hash_Value': cybox_common.HashValueType,
188    'Fuzzy_Hash_Structure': cybox_common.FuzzyHashStructureType,
189    'SubDatum': cybox_common.MetadataType,
190    'Segment_Hash': cybox_common.HashValueType,
191    'Digital_Signature': cybox_common.DigitalSignatureInfoType,
192    'Code_Snippets': cybox_common.CodeSnippetsType,
193    'Value': cybox_common.StringObjectPropertyType,
194    'Length': cybox_common.IntegerObjectPropertyType,
195    'Encoding': cybox_common.ControlledVocabularyStringType,
196    'Internationalization_Settings': cybox_common.InternationalizationSettingsType,
197    'Tool_Configuration': cybox_common.ToolConfigurationType,
198    'Object_Address': cybox_common.UnsignedLongObjectPropertyType,
199    'English_Translation': cybox_common.StringObjectPropertyType,
200    'Functions': cybox_common.FunctionsType,
201    'String_Value': cybox_common.StringObjectPropertyType,
202    'Pointer_Count': cybox_common.UnsignedLongObjectPropertyType,
203    'Build_Utility_Platform_Specification': cybox_common.PlatformSpecificationType,
204    'Compiler_Informal_Description': cybox_common.CompilerInformalDescriptionType,
205    'System': cybox_common.ObjectPropertiesType,
206    'Platform': cybox_common.PlatformSpecificationType,
207    'Usage_Context_Assumptions': cybox_common.UsageContextAssumptionsType,
208    'Type': win_handle_object.HandleType,
209    'Compilers': cybox_common.CompilersType,
210    'Tool_Type': cybox_common.ControlledVocabularyStringType,
211    'String': cybox_common.ExtractedStringType,
212    'Tool': cybox_common.ToolInformationType,
213    'Build_Information': cybox_common.BuildInformationType,
214    'Tool_Hashes': cybox_common.HashListType,
215    'Compiler_Platform_Specification': cybox_common.PlatformSpecificationType,
216    'Error_Instances': cybox_common.ErrorInstancesType,
217    'Data_Segment': cybox_common.StringObjectPropertyType,
218    'Certificate_Subject': cybox_common.StringObjectPropertyType,
219    'Language': cybox_common.StringObjectPropertyType,
220    'Identifier': cybox_common.PlatformIdentifierType,
221    'Strings': cybox_common.ExtractedStringsType,
222    'File_System_Offset': cybox_common.IntegerObjectPropertyType,
223    'Reference_Description': cybox_common.StructuredTextType,
224    'User_Account_Info': cybox_common.ObjectPropertiesType,
225    'Configuration_Settings': cybox_common.ConfigurationSettingsType,
226    'Simple_Hash_Value': cybox_common.SimpleHashValueType,
227    'Byte_String_Value': cybox_common.HexBinaryObjectPropertyType,
228    'Instance': cybox_common.ObjectPropertiesType,
229    'Import': cybox_common.StringObjectPropertyType,
230    'Access_Mask': cybox_common.UnsignedLongObjectPropertyType,
231    'Property': cybox_common.PropertyType,
232    'Tool_Specific_Data': cybox_common.ToolSpecificDataType,
233    'Execution_Environment': cybox_common.ExecutionEnvironmentType,
234    'ID': cybox_common.UnsignedIntegerObjectPropertyType,
235    'Dependencies': cybox_common.DependenciesType,
236    'Offset': cybox_common.IntegerObjectPropertyType,
237    'Date': cybox_common.DateRangeType,
238    'Hashes': cybox_common.HashListType,
239    'Segments': cybox_common.HashSegmentsType,
240    'Segment_Count': cybox_common.IntegerObjectPropertyType,
241    'Usage_Context_Assumption': cybox_common.StructuredTextType,
242    'Block_Hash': cybox_common.FuzzyHashBlockType,
243    'Dependency': cybox_common.DependencyType,
244    'Error': cybox_common.ErrorType,
245    'Trigger_Point': cybox_common.HexBinaryObjectPropertyType,
246    'Environment_Variable': cybox_common.EnvironmentVariableType,
247    'Byte_Run': cybox_common.ByteRunType,
248    'Contributors': cybox_common.PersonnelType,
249    'Image_Offset': cybox_common.IntegerObjectPropertyType,
250    'Imports': cybox_common.ImportsType,
251    'Library': cybox_common.LibraryType,
252    'References': cybox_common.ToolReferencesType,
253    'Windows_Handle': win_handle_object.WindowsHandleObjectType,
254    'Internal_Strings': cybox_common.InternalStringsType,
255    'Custom_Properties': cybox_common.CustomPropertiesType,
256    'Configuration_Setting': cybox_common.ConfigurationSettingType,
257    'Libraries': cybox_common.LibrariesType,
258    'Function': cybox_common.StringObjectPropertyType,
259    'Handle': win_handle_object.WindowsHandleObjectType,
260    'Description': cybox_common.StructuredTextType,
261    'Code_Snippet': cybox_common.ObjectPropertiesType,
262    'Build_Configuration': cybox_common.BuildConfigurationType,
263    'Address': cybox_common.HexBinaryObjectPropertyType,
264    'Search_Within': cybox_common.IntegerObjectPropertyType,
265    'Segment': cybox_common.HashSegmentType,
266    'Compiler': cybox_common.CompilerType,
267    'Name': cybox_common.StringObjectPropertyType,
268    'Signature_Description': cybox_common.StringObjectPropertyType,
269    'Block_Size': cybox_common.IntegerObjectPropertyType,
270    'Search_Distance': cybox_common.IntegerObjectPropertyType,
271    'Fuzzy_Hash_Value': cybox_common.FuzzyHashValueType,
272    'Dependency_Description': cybox_common.StructuredTextType,
273    'Contributor': cybox_common.ContributorType,
274    'Tools': cybox_common.ToolsInformationType,
275    'Data_Size': cybox_common.DataSizeType,
276}
277
278USAGE_TEXT = """
279Usage: python <Parser>.py [ -s ] <in_xml_file>
280"""
281
282def usage():
283    print(USAGE_TEXT)
284    sys.exit(1)
285
286def get_root_tag(node):
287    tag = Tag_pattern_.match(node.tag).groups()[-1]
288    rootClass = GDSClassesMapping.get(tag)
289    if rootClass is None:
290        rootClass = globals().get(tag)
291    return tag, rootClass
292
293def parse(inFileName):
294    doc = parsexml_(inFileName)
295    rootNode = doc.getroot()
296    rootTag, rootClass = get_root_tag(rootNode)
297    if rootClass is None:
298        rootTag = 'Windows_Event'
299        rootClass = WindowsEventObjectType
300    rootObj = rootClass.factory()
301    rootObj.build(rootNode)
302    # Enable Python to collect the space used by the DOM.
303    doc = None
304#    sys.stdout.write('<?xml version="1.0" ?>\n')
305#    rootObj.export(sys.stdout.write, 0, name_=rootTag,
306#        namespacedef_='',
307#        pretty_print=True)
308    return rootObj
309
310def parseEtree(inFileName):
311    doc = parsexml_(inFileName)
312    rootNode = doc.getroot()
313    rootTag, rootClass = get_root_tag(rootNode)
314    if rootClass is None:
315        rootTag = 'Windows_Event'
316        rootClass = WindowsEventObjectType
317    rootObj = rootClass.factory()
318    rootObj.build(rootNode)
319    # Enable Python to collect the space used by the DOM.
320    doc = None
321    rootElement = rootObj.to_etree(None, name_=rootTag)
322    content = etree_.tostring(rootElement, pretty_print=True,
323        xml_declaration=True, encoding="utf-8")
324    sys.stdout.write(content)
325    sys.stdout.write('\n')
326    return rootObj, rootElement
327
328def parseString(inString):
329    from mixbox.vendor.six import StringIO
330    doc = parsexml_(StringIO(inString))
331    rootNode = doc.getroot()
332    rootTag, rootClass = get_root_tag(rootNode)
333    if rootClass is None:
334        rootTag = 'Windows_Event'
335        rootClass = WindowsEventObjectType
336    rootObj = rootClass.factory()
337    rootObj.build(rootNode)
338    # Enable Python to collect the space used by the DOM.
339    doc = None
340#    sys.stdout.write('<?xml version="1.0" ?>\n')
341#    rootObj.export(sys.stdout.write, 0, name_="Windows_Event",
342#        namespacedef_='')
343    return rootObj
344
345def main():
346    args = sys.argv[1:]
347    if len(args) == 1:
348        parse(args[0])
349    else:
350        usage()
351
352if __name__ == '__main__':
353    #import pdb; pdb.set_trace()
354    main()
355
356__all__ = [
357    "WindowsEventObjectType",
358    "WinEventType"
359    ]
360