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