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