def get_fault(self, reply): """ Extract the fault from the specified soap reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A soap reply message. @type reply: str @return: A fault object. @rtype: tuple ( L{Element}, L{Object} ) """ reply = self.replyfilter(reply) sax = Parser() faultroot = sax.parse(string=reply) soapenv = faultroot.getChild('Envelope') soapbody = soapenv.getChild('Body') fault = soapbody.getChild('Fault') unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, faultroot) try: detail = p.detail except AttributeError: try: detail = p.faultstring except AttributeError: detail = "Unknown Error" return (faultroot, detail)
def get_reply(self, method, reply): """ Process the I{reply} for the specified I{method} by sax parsing the I{reply} and then unmarshalling into python object(s). @param method: The name of the invoked method. @type method: str @param reply: The reply XML received after invoking the specified method. @type reply: str @return: The unmarshalled reply. The returned value is an L{Object} for a I{list} depending on whether the service returns a single object or a collection. @rtype: tuple ( L{Element}, L{Object} ) """ reply = self.replyfilter(reply) sax = Parser() replyroot = sax.parse(string=reply) soapenv = replyroot.getChild('Envelope') soapenv.promotePrefixes() soapbody = soapenv.getChild('Body') soapbody = self.multiref.process(soapbody) nodes = self.replycontent(method, soapbody) rtypes = self.returned_types(method) if len(rtypes) > 1: result = self.replycomposite(rtypes, nodes) return (replyroot, result) if len(rtypes) == 1: if rtypes[0].unbounded(): result = self.replylist(rtypes[0], nodes) return (replyroot, result) if len(nodes): unmarshaller = self.unmarshaller() resolved = rtypes[0].resolve(nobuiltin=True) result = unmarshaller.process(nodes[0], resolved) return (replyroot, result) return (replyroot, None)
def get_fault(self, reply): """ Extract the fault from the specified soap reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A soap reply message. @type reply: str @return: A fault object. @rtype: tuple ( L{Element}, L{Object} ) """ reply = self.replyfilter(reply) sax = Parser() faultroot = sax.parse(string=reply) soapenv = faultroot.getChild('Envelope') if soapenv is None: # If there isn't an <Envelope>, then we probably got a regular 500 error page (HTML) back. Not sure what to do # in this case, let's throw a generic exception (non-WebFault) for now. raise ServerErrorMissingSoapEnvelope(faultroot) soapbody = soapenv.getChild('Body') fault = soapbody.getChild('Fault') unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, faultroot) return (faultroot, p.detail)
def get_fault(self, reply): """ Extract the fault from the specified SOAP reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A SOAP reply message. @type reply: str @return: A fault object. @rtype: tuple ( L{Element}, L{Object} ) """ _reply = self.replyfilter(reply) sax = Parser() faultroot = sax.parse(string=_reply) soapenv = faultroot.getChild('Envelope') soapbody = soapenv.getChild('Body') fault = soapbody.getChild('Fault') unmarshaller = self.unmarshaller(False) if fault: p = unmarshaller.process(fault) if self.options().faults: raise WebFault(p, faultroot) return (True, faultroot, p.detail) else: #p = unmarshaller.process(soapbody) #if self.options().faults: #raise WebFault(p, faultroot) return (False, faultroot, reply)
def cdata(): xml = '<a><![CDATA[<b>This is my &<tag></b>]]></a>' p = Parser() d = p.parse(string=xml) print d a = d.root() print a.getText()
def get_user(self, user_id): """ Returns data of the user with id == `user_id` as a dict of type: { 'firstname': ..., 'lastname': ..., 'internalemailaddress': ..., 'systemuserid': ..., } """ response = self.make_retrieve_soap_request( 'systemuser', user_id, ['firstname', 'lastname', 'internalemailaddress'] ) parser = Parser() doc = parser.parse(string=response.content) attrs_el = doc.childAtPath('Envelope/Body/RetrieveResponse/RetrieveResult/Attributes') data = {} for attr_el in attrs_el: key = attr_el.getChild('key').text value = attr_el.getChild('value').text data[key] = value return data
def get(self, mangled): """Override this to prevent attempted purges.""" fp = self.getf(mangled) if fp is None: return None p = Parser() return p.parse(fp)
def extract_auth_tokens_on_premise(self, resp_content): fix_suds() from suds.sax.parser import Parser p = Parser() doc = p.parse(string=resp_content) created = (self.now - timedelta(minutes=1)).isoformat() expires = (self.now + timedelta(minutes=60)).isoformat() rst_resp = doc.childAtPath('Envelope/Body/RequestSecurityTokenResponseCollection/RequestSecurityTokenResponse') key_ident = rst_resp.childAtPath('RequestedAttachedReference/SecurityTokenReference/KeyIdentifier').text binary_secret = rst_resp.childAtPath('RequestedProofToken/BinarySecret').text signature, signature_digest = self.generate_hmac_signature(binary_secret, created, expires) enc_data = rst_resp.childAtPath('RequestedSecurityToken/EncryptedData') key_ciphertext = enc_data.childAtPath('KeyInfo/EncryptedKey/CipherData/CipherValue').text token_ciphertext = enc_data.childAtPath('CipherData/CipherValue').text x509_info = enc_data.childAtPath('KeyInfo/EncryptedKey/KeyInfo/SecurityTokenReference/X509Data/X509IssuerSerial') issuer_name_x509 = x509_info.childAtPath('X509IssuerName').text serial_number_x509 = x509_info.childAtPath('X509SerialNumber').text context = { 'key_ciphertext': key_ciphertext, 'token_ciphertext': token_ciphertext, 'key_ident': key_ident, 'created': created, 'expires': expires, 'issuer_name_x509': issuer_name_x509, 'serial_number_x509': serial_number_x509, 'signature_digest': signature_digest, 'signature': signature, } return context
def extract_adfs_url(self, resp_content): fix_suds() from suds.sax.parser import Parser p = Parser() doc = p.parse(string=resp_content) all_policies = doc.childAtPath('definitions/Policy/ExactlyOne/All') url = all_policies.childAtPath('AuthenticationPolicy/SecureTokenService/Identifier').text return url.replace('http:', 'https:')
def get(self, id): try: fp = self.getf(id) if fp is None: return None p = Parser() return p.parse(fp) except Exception: self.purge(id)
def get(self, id): try: fp = FileCache.getf(self, id) if fp is None: return None p = Parser() return p.parse(fp) except Exception: FileCache.purge(self, id)
def marshall_response(vim, response): from suds.sax.parser import Parser from suds.bindings.document import Document parser = Parser() document = parser.parse(string=response) obj = document.getChildren()[0] binding = Document(vim.client.wsdl) unmarshaller = binding.unmarshaller() marshalled_obj = unmarshaller.process(obj, None) return vim._parse_object_content(marshalled_obj)
def get_whoami(self, resp_content): fix_suds() from suds.sax.parser import Parser p = Parser() doc = p.parse(string=resp_content) id = '' results = doc.childAtPath('Envelope/Body/ExecuteResponse/ExecuteResult/Results') for result in results.children: if result.childAtPath('key').text == 'UserId': id = result.childAtPath('value').text return id
def download(self, url): """ Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like """ store = DocumentStore() fp = store.open(url) if fp is None: fp = self.options.transport.open(Request(url)) sax = Parser() return sax.parse(file=fp)
def download(reader, url): company = None info = url.split('/') filename = 'mocks/%s.xml' % info[-1].lower() # If the url contains the company name, take it and append it to response if len(info) == 3: company = info[0] with open(os.path.join(os.path.dirname(__file__), filename), 'r') as f: response = f.read() sax = Parser() result = sax.parse(string=response) if company: element = result.children[0].children[-1].children[0].children[0] location = element.get('location') element.set('location', '%s/%s' %(company, location)) return result
def download(self, url): """ Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like """ store = DocumentStore() if url.startswith('http') or url.startswith('suds'): fp = store.open(url) if fp is None: fp = self.options.transport.open(Request(url)) else: fp = open(url, 'r') sax = Parser() return sax.parse(file=fp)
def download(self, url): """ Download the docuemnt. @param url: A document url. @type url: str. @return: A file pointer to the docuemnt. @rtype: file-like """ store = DocumentStore() fp = store.open(url) if fp is None: fp = self.options.transport.open(Request(url)) content = fp.read() fp.close() ctx = self.plugins.document.loaded(url=url, document=content) content = ctx.document sax = Parser() return sax.parse(string=content)
def suds_unmarshall(data): try: from suds.sax.parser import Parser from suds.umx.basic import Basic except ImportError: print "ERROR: Could not import SUDS." print "You must install SUDS for the '-t' option to work" print "https://fedorahosted.org/suds/" return None p = Parser() obj = None try: root = p.parse(string=data).root() umx = Basic() obj = umx.process(root) except Exception, e: print "SAX Excpetion:", e
def open(self, url): """ Open an XML document at the specified I{url}. First, the document attempted to be retrieved from the I{document cache}. If not found, it is downloaded and parsed using the SAX parser. The result is added to the document store for the next open(). @param url: A document url. @type url: str. @return: The specified XML document. @rtype: I{Document} """ d = self.options.cache.get(url) if d is None: fp = self.options.transport.open(Request(url)) sax = Parser() d = sax.parse(file=fp) #self.options.cache.put(url, d) return d
def _extract_auth_tokens(self, resp_content): """ Internal method which extracts the auth data from the content of a SOAP response, generates signatures and other related fields needed for the next SOAP request and returns a dict with all of them. """ parser = Parser() doc = parser.parse(string=resp_content) now = get_request_now() creation_date = now.isoformat() expiration_date_dt = (now + datetime.timedelta(minutes=CDMS_EXPIRATION_TOKEN_DELTA)) expiration_date = expiration_date_dt.isoformat() rst_resp = doc.childAtPath('Envelope/Body/RequestSecurityTokenResponseCollection/RequestSecurityTokenResponse') enc_data = rst_resp.childAtPath('RequestedSecurityToken/EncryptedData') key_identifier = rst_resp.childAtPath('RequestedAttachedReference/SecurityTokenReference/KeyIdentifier').text ciphertext_key = enc_data.childAtPath('KeyInfo/EncryptedKey/CipherData/CipherValue').text ciphertext_token = enc_data.childAtPath('CipherData/CipherValue').text x509_info = enc_data.childAtPath( 'KeyInfo/EncryptedKey/KeyInfo/SecurityTokenReference/X509Data/X509IssuerSerial' ) x509_issuer_name = x509_info.childAtPath('X509IssuerName').text x509_serial_number = x509_info.childAtPath('X509SerialNumber').text binary_secret = rst_resp.childAtPath('RequestedProofToken/BinarySecret').text signature, signature_digest = self._generate_hmac_signature(binary_secret, creation_date, expiration_date) return { 'ciphertext_key': ciphertext_key, 'ciphertext_token': ciphertext_token, 'key_identifier': key_identifier, 'creation_date': creation_date, 'expiration_date': expiration_date, 'expiration_date_dt': expiration_date_dt, 'X509_issuer_name': x509_issuer_name, 'X509_serial_number': x509_serial_number, 'signature_digest': signature_digest, 'signature': signature, }
def basic(): xml = "<a>Me && <b>my</b> shadow's <i>dog</i> love to 'play' and sing "la,la,la";</a>" p = Parser() d = p.parse(string=xml) a = d.root() print 'A(parsed)=\n%s' % a assert str(a) == xml b = Element('a') b.setText('Me && <b>my</b> shadow\'s <i>dog</i> love to \'play\' and sing "la,la,la";') print 'B(encoded)=\n%s' % b assert str(b) == xml print 'A(text-decoded)=\n%s' % a.getText() print 'B(text-decoded)=\n%s' % b.getText() assert a.getText() == b.getText() print 'test pruning' j = Element('A') j.set('n', 1) j.append(Element('B')) print j j.prune() print j
def extract_auth_tokens_online(self, resp_content): fix_suds() from suds.sax.parser import Parser p = Parser() doc = p.parse(string=resp_content) rst_encrypted_data = doc.childAtPath('Envelope/Body/RequestSecurityTokenResponse/RequestedSecurityToken/EncryptedData') token_ciphertext = rst_encrypted_data.childAtPath('CipherData/CipherValue').text encrypted_key = rst_encrypted_data.childAtPath('KeyInfo/EncryptedKey') key_ident = encrypted_key.childAtPath('KeyInfo/SecurityTokenReference/KeyIdentifier').text key_ciphertext = encrypted_key.childAtPath('CipherData/CipherValue').text # raise CrmAuthenticationError("KeyIdentifier or CipherValue not found # in", resp_content) context = { 'key_ciphertext': key_ciphertext, 'token_ciphertext': token_ciphertext, 'key_ident': key_ident, } return context
def download(self, url): """ Download the document. @param url: A document URL. @type url: str. @return: A file pointer to the document. @rtype: file-like """ content = None store = self.options.documentStore if store is not None: content = store.open(url) if content is None: fp = self.options.transport.open(Request(url)) try: content = fp.read() finally: fp.close() ctx = self.plugins.document.loaded(url=url, document=content) content = ctx.document sax = Parser() return sax.parse(string=content)
def get_whoami(self): """ Returns the ids of the logged in user as a dict of type: { 'UserId': ..., 'BusinessUnitId': ..., 'OrganizationId': ... } """ response = self.make_execute_soap_request('WhoAmI') parser = Parser() doc = parser.parse(string=response.content) results_el = doc.childAtPath('Envelope/Body/ExecuteResponse/ExecuteResult/Results') data = {} for result_el in results_el: key = result_el.getChild('key').text value = result_el.getChild('value').text data[key] = value return data
def extract_users(self, resp_content): fix_suds() from suds.sax.parser import Parser p = Parser() doc = p.parse(string=resp_content) users = [] user_elements = doc.childAtPath('Envelope/Body/RetrieveMultipleResponse/RetrieveMultipleResult/Entities') for user in user_elements.children: user_info = {} attributes = user.childrenAtPath('Attributes/KeyValuePairOfstringanyType') for attr in attributes: if attr.childAtPath('key').text == 'systemuserid': user_info['id'] = attr.childAtPath('value').text elif attr.childAtPath('key').text == 'internalemailaddress': user_info['internalemailaddress'] = attr.childAtPath('value').text elif attr.childAtPath('key').text == 'fullname': fullname = attr.childAtPath('value').text user_info['last_name'] = ' '.join(fullname.split()[-1:]) user_info['first_name'] = ' '.join(fullname.split()[:-1]) users.append(user_info) return users
def invoke(self, args, kwargs): """ Send the required soap message to invoke the specified method @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The result of the method invocation. @rtype: I{builtin} or I{subclass of} L{Object} """ simulation = kwargs[self.injkey] msg = simulation.get('msg') reply = simulation.get('reply') fault = simulation.get('fault') if msg is None: if reply is not None: return self.__reply(reply, args, kwargs) if fault is not None: return self.__fault(fault) raise Exception('(reply|fault) expected when msg=None') sax = Parser() msg = sax.parse(string=msg) return self.send(msg)
def open(self, url): """ Open an XML document at the specified I{url}. First, the document attempted to be retrieved from the I{object cache}. If not found, it is downloaded and parsed using the SAX parser. The result is added to the cache for the next open(). @param url: A document url. @type url: str. @return: The specified XML document. @rtype: I{Document} """ cache = self.cache() id = self.mangle(url, 'document') d = cache.get(id) if d is None: d = self.download(url) cache.put(id, d) else: sax = Parser() d = sax.parse(string=d) self.plugins.document.parsed(url=url, document=d.root()) return d
def open(self, url): """ Open an XML document at the specified I{URL}. First, the document attempted to be retrieved from the I{object cache}. If not found, it is downloaded and parsed using the SAX parser. The result is added to the cache for the next open(). @param url: A document URL. @type url: str. @return: The specified XML document. @rtype: I{Document} """ cache = self.cache() id = self.mangle(url, 'document') d = cache.get(id) if d is None: d = self.download(url) cache.put(id, d) else: sax = Parser() d = sax.parse(string=d) self.plugins.document.parsed(url=url, document=d.root()) return d
def basic(): xml = "<a>Me && <b>my</b> shadow's <i>dog</i> love to 'play' and sing "la,la,la";</a>" p = Parser() d = p.parse(string=xml) a = d.root() print('A(parsed)=\n%s' % a) assert str(a) == xml b = Element('a') b.setText( 'Me && <b>my</b> shadow\'s <i>dog</i> love to \'play\' and sing "la,la,la";' ) print('B(encoded)=\n%s' % b) assert str(b) == xml print('A(text-decoded)=\n%s' % a.getText()) print('B(text-decoded)=\n%s' % b.getText()) assert a.getText() == b.getText() print('test pruning') j = Element('A') j.set('n', 1) j.append(Element('B')) print(j) j.prune() print(j)
def __init__(self, url, options): """ @param url: A URL to the WSDL. @type url: str @param options: An options dictionary. @type options: L{options.Options} """ log.debug('reading wsdl at: %s ...', url) p = Parser(options.transport) root = p.parse(url=url).root() WObject.__init__(self, root) self.id = objid(self) self.options = options self.url = url self.tns = self.mktns(root) self.types = [] self.schema = None self.children = [] self.imports = [] self.messages = {} self.port_types = {} self.bindings = {} self.services = [] self.add_children(self.root) self.children.sort() pmd = self.__metadata__.__print__ pmd.excludes.append('children') pmd.excludes.append('wsdl') pmd.wrappers['schema'] = lambda x: repr(x) self.open_imports() self.resolve() self.build_schema() self.set_wrapped() for s in self.services: self.add_methods(s) log.debug("wsdl at '%s' loaded:\n%s", url, self)
def __init__(self, url, options): """ @param url: A URL to the WSDL. @type url: str @param options: An options dictionary. @type options: L{options.Options} """ log.debug('reading wsdl at: %s ...', url) p = Parser(options.transport) root = p.parse(url=url).root() WObject.__init__(self, root) self.id = objid(self) self.options = options self.url = url self.tns = self.mktns(root) self.types = [] self.schema = None self.children = [] self.imports = [] self.messages = {} self.port_types = {} self.bindings = {} self.service = None self.add_children(self.root) self.children.sort() pmd = self.__metadata__.__print__ pmd.excludes.append('children') pmd.excludes.append('wsdl') pmd.wrappers['schema'] = lambda x: repr(x) self.open_imports() self.resolve() self.build_schema() self.set_wrapped() if self.service is not None: self.add_methods() log.debug("wsdl at '%s' loaded:\n%s", url, self)
def _make_soap_request_for_authentication(self, to_address, template, context): """ This is the same as `make_raw_soap_request` but it's internally used to make auth SOAP requests. It expects requests to return 'OK' in most cases. The only 2 cases where the requests could fail are: - auth/authorization error: => raises LoginErrorException - server error: => raises UnexpectedResponseException """ try: return self.make_raw_soap_request(to_address, template, context) except ErrorResponseException as e: if e.status_code == 500: """ As the response is most of the time a 500 error with the 'message' being slightly different and somewhat meanful in each case, we need to parse the xml and try to find out what the real error is. In this case, we are matching the exact text response (I know :-|) to see if it's an authentication/authorization error. """ parser = Parser() doc = parser.parse(string=e.content) reason = doc.childAtPath('Envelope/Body/Fault/Reason/Text').text.lower() if (reason == 'at least one security token in the message could not be validated.'): # not sure 'fixing' the status code is a good idea here but to me it makes sense raise LoginErrorException( 'Invalid credentials', status_code=400, content=e.content ) else: raise UnexpectedResponseException( e, status_code=e.status_code, content=e.content ) raise e
class Binding: """ The soap binding class used to process outgoing and imcoming soap messages per the WSDL port binding. @cvar replyfilter: The reply filter function. @type replyfilter: (lambda s,r: r) @ivar wsdl: The wsdl. @type wsdl: L{suds.wsdl.Definitions} @ivar schema: The collective schema contained within the wsdl. @type schema: L{xsd.schema.Schema} @ivar options: A dictionary options. @type options: L{Options} @ivar parser: A sax parser. @type parser: L{suds.sax.parser.Parser} @ivar xcodecs: The XML (encode|decode) objects. @type xcodecs: (L{Unmarshaller}, L{Marshaller}) """ replyfilter = (lambda s, r: r) def __init__(self, wsdl): """ @param wsdl: A wsdl. @type wsdl: L{wsdl.Definitions} """ self.wsdl = wsdl self.schema = wsdl.schema self.options = Options() self.parser = Parser() self.multiref = MultiRef() self.xcodecs = ( Unmarshaller(self.schema), Marshaller(self.schema), ) def unmarshaller(self, typed=True): """ Get the appropriate XML decoder. @return: Either the (basic|typed) unmarshaller. @rtype: L{Marshaller} """ input = self.xcodecs[0] if typed: return input.typed else: return input.basic def marshaller(self): """ Get the appropriate XML encoder. @return: Either L{literal} marshaller. @rtype: L{Marshaller} """ output = self.xcodecs[1] return output.literal def get_message(self, method, args, kwargs): """ Get the soap message for the specified method, args and soapheaders. This is the entry point for creating the outbound soap message. @param method: The method being invoked. @type method: I{service.Method} @param args: A list of args for the method invoked. @type args: list @param kwargs: Named (keyword) args for the method invoked. @type kwargs: dict @return: The soap message. @rtype: str """ content = self.headercontent(method) header = self.header(content) content = self.bodycontent(method, args, kwargs) body = self.body(content) env = self.envelope(header, body) body.normalizePrefixes() env.promotePrefixes() return env def get_reply(self, method, reply): """ Process the I{reply} for the specified I{method} by sax parsing the I{reply} and then unmarshalling into python object(s). @param method: The name of the invoked method. @type method: str @param reply: The reply XML received after invoking the specified method. @type reply: str @return: The unmarshalled reply. The returned value is an L{Object} for a I{list} depending on whether the service returns a single object or a collection. @rtype: tuple ( L{Element}, L{Object} ) """ reply = self.replyfilter(reply) replyroot = self.parser.parse(string=reply) soapenv = replyroot.getChild('Envelope') soapenv.promotePrefixes() soapbody = soapenv.getChild('Body') soapbody = self.multiref.process(soapbody) nodes = self.replycontent(method, soapbody) rtypes = self.returned_types(method) if len(rtypes) > 1: result = self.replycomposite(rtypes, nodes) return (replyroot, result) if len(rtypes) == 1: if rtypes[0].unbounded(): result = self.replylist(rtypes[0], nodes) return (replyroot, result) if len(nodes): unmarshaller = self.unmarshaller() resolved = rtypes[0].resolve(nobuiltin=True) result = unmarshaller.process(nodes[0], resolved) return (replyroot, result) return (replyroot, None) def replylist(self, rt, nodes): """ Construct a I{list} reply. This mehod is called when it has been detected that the reply is a list. @param rt: The return I{type}. @type rt: L{suds.xsd.sxbase.SchemaObject} @param nodes: A collection of XML nodes. @type nodes: [L{Element},...] @return: A list of I{unmarshalled} objects. @rtype: [L{Object},...] """ result = [] resolved = rt.resolve(nobuiltin=True) unmarshaller = self.unmarshaller() for node in nodes: sobject = unmarshaller.process(node, resolved) result.append(sobject) return result def replycomposite(self, rtypes, nodes): """ Construct a I{composite} reply. This method is called when it has been detected that the reply has multiple root nodes. @param rtypes: A list of known return I{types}. @type rtypes: [L{suds.xsd.sxbase.SchemaObject},...] @param nodes: A collection of XML nodes. @type nodes: [L{Element},...] @return: The I{unmarshalled} composite object. @rtype: L{Object},... """ dictionary = {} for rt in rtypes: dictionary[rt.name] = rt unmarshaller = self.unmarshaller() composite = Factory.object('reply') for node in nodes: tag = node.name rt = dictionary.get(tag, None) if rt is None: if node.get('id') is None: raise Exception('<%s/> not mapped to message part' % tag) else: continue resolved = rt.resolve(nobuiltin=True) sobject = unmarshaller.process(node, resolved) if rt.unbounded(): value = getattr(composite, tag, None) if value is None: value = [] setattr(composite, tag, value) value.append(sobject) else: setattr(composite, tag, sobject) return composite def get_fault(self, reply): """ Extract the fault from the specified soap reply. If I{faults} is True, an exception is raised. Otherwise, the I{unmarshalled} fault L{Object} is returned. This method is called when the server raises a I{web fault}. @param reply: A soap reply message. @type reply: str @return: A fault object. @rtype: tuple ( L{Element}, L{Object} ) """ reply = self.replyfilter(reply) faultroot = self.parser.parse(string=reply) soapenv = faultroot.getChild('Envelope') soapbody = soapenv.getChild('Body') fault = soapbody.getChild('Fault') unmarshaller = self.unmarshaller(False) p = unmarshaller.process(fault) if self.options.faults: raise WebFault(p, faultroot) return (faultroot, p.detail) def mkparam(self, method, pdef, object): """ Builds a parameter for the specified I{method} using the parameter definition (pdef) and the specified value (object). @param method: A method name. @type method: str @param pdef: A parameter definition. @type pdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject}) @param object: The parameter value. @type object: any @return: The parameter fragment. @rtype: L{Element} """ marshaller = self.marshaller() if isinstance(object, (list, tuple)): tags = [] for item in object: tags.append(self.mkparam(method, pdef, item)) return tags content = Content(tag=pdef[0], value=object, type=pdef[1]) return marshaller.process(content) def mkheader(self, method, hdef, object): """ Builds a soapheader for the specified I{method} using the header definition (hdef) and the specified value (object). @param method: A method name. @type method: str @param hdef: A header definition. @type hdef: tuple: (I{name}, L{xsd.sxbase.SchemaObject}) @param object: The header value. @type object: any @return: The parameter fragment. @rtype: L{Element} """ marshaller = self.marshaller() if isinstance(object, (list, tuple)): tags = [] for item in object: tags.append(self.mkheader(method, hdef, item)) return tags content = Content(tag=hdef[0], value=object, type=hdef[1]) return marshaller.process(content) def envelope(self, header, body): """ Build the B{<Envelope/>} for an soap outbound message. @param header: The soap message B{header}. @type header: L{Element} @param body: The soap message B{body}. @type body: L{Element} @return: The soap envelope containing the body and header. @rtype: L{Element} """ env = Element('Envelope', ns=envns) env.addPrefix(Namespace.xsins[0], Namespace.xsins[1]) env.append(header) env.append(body) return env def header(self, content): """ Build the B{<Body/>} for an soap outbound message. @param content: The header content. @type content: L{Element} @return: the soap body fragment. @rtype: L{Element} """ header = Element('Header', ns=envns) header.append(content) return header def headercontent(self, method): """ Get the content for the soap I{Header} node. @param method: A service method. @type method: I{service.Method} @return: The xml content for the <body/> @rtype: [L{Element},..] """ n = 0 content = [] wsse = self.options.wsse if wsse is not None: content.append(wsse.xml()) headers = self.options.soapheaders if len(headers) == 0: return content if not isinstance(headers, (tuple, list, dict)): headers = (headers, ) pts = self.headpart_types(method) if isinstance(headers, (tuple, list)): for header in headers: if isinstance(header, Element): content.append(header) continue if len(pts) == n: break h = self.mkheader(method, pts[n], header) ns = pts[n][1].namespace('ns0') h.setPrefix(ns[0], ns[1]) content.append(h) n += 1 else: for pt in pts: header = headers.get(pt[0]) if header is None: continue h = self.mkheader(method, pt, header) ns = pt[1].namespace('ns0') h.setPrefix(ns[0], ns[1]) content.append(h) return content def body(self, content): """ Build the B{<Body/>} for an soap outbound message. @param content: The body content. @type content: L{Element} @return: the soap body fragment. @rtype: L{Element} """ body = Element('Body', ns=envns) body.append(content) return body def bodypart_types(self, method, input=True): """ Get a list of I{parameter definitions} (pdef) defined for the specified method. Each I{pdef} is a tuple (I{name}, L{xsd.sxbase.SchemaObject}) @param method: A service method. @type method: I{service.Method} @param input: Defines input/output message. @type input: boolean @return: A list of parameter definitions @rtype: [I{pdef},] """ result = [] if input: parts = method.message.input.parts else: parts = method.message.output.parts for p in parts: if p.element is not None: query = ElementQuery(p.element) else: query = TypeQuery(p.type) pt = query.execute(self.schema) if pt is None: raise TypeNotFound(query.ref) if p.type is not None: pt = PartElement(p.name, pt) if input: if pt.name is None: result.append((p.name, pt)) else: result.append((pt.name, pt)) else: result.append(pt) return result def headpart_types(self, method, input=True): """ Get a list of I{parameter definitions} (pdef) defined for the specified method. Each I{pdef} is a tuple (I{name}, L{xsd.sxbase.SchemaObject}) @param method: A service method. @type method: I{service.Method} @param input: Defines input/output message. @type input: boolean @return: A list of parameter definitions @rtype: [I{pdef},] """ result = [] if input: headers = method.soap.input.headers else: headers = method.soap.output.headers for header in headers: for p in header.message.parts: if p.element is not None: query = ElementQuery(p.element) else: query = TypeQuery(p.type) pt = query.execute(self.schema) if pt is None: raise TypeNotFound(query.ref) if p.type is not None: pt = PartElement(p.name, pt) if input: if pt.name is None: result.append((p.name, pt)) else: result.append((pt.name, pt)) else: result.append(pt) return result def returned_types(self, method): """ Get the L{xsd.sxbase.SchemaObject} returned by the I{method}. @param method: A service method. @type method: I{service.Method} @return: The name of the type return by the method. @rtype: [I{rtype},..] """ result = [] for rt in self.bodypart_types(method, input=False): result.append(rt) return result
def readFile(self, fp): sax = Parser() return sax.parse(file=fp)
def decryptMessage(env, keystore, symmetric_keys): enc_data_blocks = [] data_block_id_to_key = dict() def collectEncryptedDataBlock(elt): if elt.match("EncryptedData", ns=wsencns): enc_data_blocks.append(elt) env.walk(collectEncryptedDataBlock) decrypted_elements = [] for key_elt in env.getChild("Header").getChild("Security").getChildren("EncryptedKey", ns=wsencns): key_transport_method = key_elt.getChild("EncryptionMethod").get("Algorithm") key_transport_props = keyTransportProperties[key_transport_method] enc_key = b64decode(key_elt.getChild("CipherData").getChild("CipherValue").getText()) sec_token_reference = key_elt.getChild("KeyInfo").getChild("SecurityTokenReference") if sec_token_reference.getChild("X509Data") is not None: x509_issuer_serial_elt = sec_token_reference.getChild("X509Data").getChild("X509IssuerSerial") reference = X509IssuerSerialKeypairReference(x509_issuer_serial_elt.getChild("X509IssuerName").getText(), int(x509_issuer_serial_elt.getChild("X509SerialNumber").getText())) elif sec_token_reference.getChild("KeyIdentifier") is not None and sec_token_reference.getChild("KeyIdentifier").get("ValueType") == 'http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1': fingerprint = b64decode(sec_token_reference.getChild("KeyIdentifier").getText()) reference = X509FingerprintKeypairReference(fingerprint.encode('hex'), 'sha1') elif sec_token_reference.getChild("KeyIdentifier") is not None and sec_token_reference.getChild("KeyIdentifier").get("ValueType") == 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier': ski = b64decode(sec_token_reference.getChild("KeyIdentifier").getText()) reference = X509SubjectKeyIdentifierKeypairReference(ski.encode('hex')) else: raise Exception, 'Response contained unrecognized SecurityTokenReference' priv_key = keystore.lookup(reference).getRsaPrivateKey() sym_key = priv_key.private_decrypt(enc_key, key_transport_props['padding']) symmetric_keys[key_elt.get("Id")] = sym_key if key_elt.getChild("ReferenceList") is not None: for data_reference in key_elt.getChild("ReferenceList").getChildren("DataReference"): uri = data_reference.get("URI") data_block_id_to_key[uri[1:]] = sym_key for data_block in enc_data_blocks: block_encryption_props = blockEncryptionProperties[data_block.getChild("EncryptionMethod").get("Algorithm")] enc_content = b64decode(data_block.getChild("CipherData").getChild("CipherValue").getText()) iv = enc_content[:block_encryption_props['iv_size']] enc_content = enc_content[block_encryption_props['iv_size']:] if data_block.get("Id") in data_block_id_to_key: sym_key = data_block_id_to_key[data_block.get("Id")] else: sec_token_reference = data_block.getChild("KeyInfo").getChild("SecurityTokenReference") if sec_token_reference.getChild("KeyIdentifier") is not None and sec_token_reference.getChild("KeyIdentifier").get("ValueType") == 'http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1': sha1_id = sec_token_reference.getChild("KeyIdentifier").getText() sym_key = symmetric_keys[b64decode(sha1_id)] elif sec_token_reference.getChild("Reference", ns=wssens) is not None: sym_key = symmetric_keys[sec_token_reference.getChild("Reference", ns=wssens).get("URI")[1:]] else: raise Exception, 'Response contained an encrypted block for which a key could not be found to decrypt' cipher = EVP.Cipher(alg=block_encryption_props['openssl_cipher'], key=sym_key, iv=iv, op=0, padding=0) content = cipher.update(enc_content) content = content + cipher.final() content = content[:-ord(content[-1])] sax = Parser() decrypted_element = sax.parse(string=content) decrypted_elements.extend(decrypted_element.getChildren()) data_block.parent.replaceChild(data_block, decrypted_element.getChildren()) return decrypted_elements
def received(self, context): sax = Parser() self.reply = sax.parse(string=context.reply)