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