def xml(self): usernametoken = Element('UsernameToken', ns=wssens) username = Element('Username', ns=wssens) username.setText(self.username) usernametoken.append(username) password = Element('Password', ns=wssens) s = hashlib.sha1() s.update(self.nonce) s.update(self._print_datetime(self.created).encode('utf-8')) s.update(self.password.encode('utf-8')) password.setText(b64encode(s.digest()).decode('utf-8')) password.set('Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0' '#PasswordDigest') usernametoken.append(password) nonce = Element('Nonce', ns=wssens) nonce.setText(b64encode(self.nonce).decode('utf-8')) nonce.set( 'EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary' ) usernametoken.append(nonce) created = Element('Created', ns=wsuns) created.setText(self._print_datetime(self.created)) usernametoken.append(created) return usernametoken
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) if self.password_digest: p.set('Type', wsdigest) p.setText(self.password_digest) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.nonce_has_encoding: n.set('EncodingType', nonce_encoding_type) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(DateTime(self.created))) root.append(n) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) p.set( 'Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0#' + ('PasswordDigest' if self.digest else 'PasswordText')) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) if self.digest: n.set( 'EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary' ) n.setText(b64encode(self.nonce)) else: n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(str(UTC(self.created))) root.append(n) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.generate_digest()) p.set(wspassd[0], wspassd[1]) root.append(p) n = Element('Nonce', ns=wssens) n.setText(base64.encodestring(self.nonce)[:-1]) n.set(wsenctype[0], wsenctype[1]) root.append(n) n = Element('Created', ns=wsuns) n.setText(self.created) root.append(n) self.reset() return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.generate_digest()) p.set(wspassd[0], wspassd[1]) root.append(p) n = Element('Nonce', ns=wssens) nonce_bytes = self.nonce if not isinstance(self.nonce, bytes): nonce_bytes = self.nonce.encode('utf-8') n.setText(base64.encodebytes(nonce_bytes)[:-1]) n.set(wsenctype[0], wsenctype[1]) root.append(n) n = Element('Created', ns=wsuns) n.setText(self.created) root.append(n) self.reset() return root
def xml(self): if self.digest and self.password is None: raise RuntimeError("Cannot generate password digest without the password.") if self.autosetnonce: self.setnonce() if self.autosetcreated: self.setcreated() root = Element('UsernameToken', ns=WSSENS) u = Element('Username', ns=WSSENS) u.setText(self.username) root.append(u) if self.password is not None: password = self.password if self.digest: password = self.get_digest() p = Element('Password', ns=WSSENS) p.setText(password) p.set('Type', DIGEST_TYPE if self.digest else TEXT_TYPE) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=WSSENS) n.setText(base64.encodestring(self.nonce)[:-1]) n.set('EncodingType', BASE64_ENC_TYPE) root.append(n) if self.created: c = Element('Created', ns=WSUNS) c.setText(str(UTC(self.created))) root.append(c) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('UsernameToken', ns=wssens) root.set('wsu:Id', 'UsernameToken-%i' % hash(self)) u = Element('Username', ns=wssens) u.setText(self.username) root.append(u) p = Element('Password', ns=wssens) p.setText(self.password) # The Type attribute defaults to PasswordText, but some endpoints # seem to want it specified anyway. p.set('Type', PASSWORD_TYPES['plain']) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=wssens) n.setText(self.nonce) root.append(n) if self.created is not None: n = Element('Created', ns=wsuns) n.setText(self.created.isoformat()) root.append(n) return root
def xml(self): if self.digest and self.password is None: raise RuntimeError("Cannot generate password digest without the password.") if self.autosetnonce: self.setnonce() if self.autosetcreated: self.setcreated() root = Element('UsernameToken', ns=WSSENS) u = Element('Username', ns=WSSENS) u.setText(self.username) root.append(u) if self.password is not None: password = self.password if self.digest: password = self.get_digest() p = Element('Password', ns=WSSENS) p.setText(password) p.set('Type', DIGEST_TYPE if self.digest else TEXT_TYPE) root.append(p) if self.nonce is not None: n = Element('Nonce', ns=WSSENS) n.setText(base64.encodestring(self.nonce)[:-1]) n.set('EncodingType', BASE64_ENC_TYPE) root.append(n) if self.created: c = Element('Created', ns=WSUNS) c.setText(iso_utc(self.created)) root.append(c) return root
def encryptMessage(self, env, use_encrypted_header=False, second_pass=False): encrypted_parts = second_pass and self.second_pass_encrypted_parts or self.encrypted_parts elements_to_encrypt = [] encrypted_headers = [] for elements_to_encrypt_func in encrypted_parts: addl_elements = elements_to_encrypt_func(env) if addl_elements[0] is None: continue if not isinstance(addl_elements[0], list): addl_elements = ([addl_elements[0]], addl_elements[1]) for element in addl_elements[0]: if element not in elements_to_encrypt: if element[0].parent.match("Header") and use_encrypted_header: enc_hdr = Element("EncryptedHeader", ns=wsse11ns) element[0].parent.replaceChild(element[0], enc_hdr) enc_hdr.append(element[0]) elements_to_encrypt.append((enc_hdr, "Content")) encrypted_headers.append(enc_hdr) else: elements_to_encrypt.append((element, addl_elements[1])) ref_list = xmlsec.encryptMessage( self.cert, self.symmetricKey, elements_to_encrypt, "#" + self.keyId, self.keyReference, self.keyTransport ) for enc_hdr in encrypted_headers: enc_hdr.set("wsu:Id", enc_hdr[0].get("Id")) enc_hdr[0].unset("Id") if self.includeRefList: self.encryptedKey.append(ref_list) return self.encryptedKey else: return (self.encryptedKey, ref_list)
def xml(self): usernametoken = Element('UsernameToken', ns=wssens) username = Element('Username', ns=wssens) username.setText(self.username) usernametoken.append(username) password = Element('Password', ns=wssens) s = hashlib.sha1() s.update(self.nonce) s.update(self._print_datetime(self.created).encode('utf-8')) s.update(self.password.encode('utf-8')) password.setText(b64encode(s.digest()).decode('utf-8')) password.set( 'Type', 'http://docs.oasis-open.org/wss/2004/01/' 'oasis-200401-wss-username-token-profile-1.0' '#PasswordDigest') usernametoken.append(password) nonce = Element('Nonce', ns=wssens) nonce.setText(b64encode(self.nonce).decode('utf-8')) nonce.set( 'EncodingType', 'http://docs.oasis-open.org/wss/2004' '/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary') usernametoken.append(nonce) created = Element('Created', ns=wsuns) created.setText(self._print_datetime(self.created)) usernametoken.append(created) return usernametoken
def xml(self): usernametoken = Element("UsernameToken", ns=wssens) username = Element("Username", ns=wssens) username.setText(self.username) usernametoken.append(username) password = Element("Password", ns=wssens) s = hashlib.sha1() s.update(self.nonce) s.update(self._print_datetime(self.created).encode("utf-8")) s.update(self.password.encode("utf-8")) password.setText(b64encode(s.digest()).decode("utf-8")) password.set( "Type", "http://docs.oasis-open.org/wss/2004/01/" "oasis-200401-wss-username-token-profile-1.0" "#PasswordDigest", ) usernametoken.append(password) nonce = Element("Nonce", ns=wssens) nonce.setText(b64encode(self.nonce).decode("utf-8")) nonce.set( "EncodingType", "http://docs.oasis-open.org/wss/2004" "/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary", ) usernametoken.append(nonce) created = Element("Created", ns=wsuns) created.setText(self._print_datetime(self.created)) usernametoken.append(created) return usernametoken
def to_xml(self, factory): # Dear Docdata: apparently, reusing Vat was not possible..? #node = factory.create('ns0:totalVatAmount') does not support setting text. element = Element('ns0:totalVatAmount') element.setText(str(int(self.value * 100))) element.set('rate', self.rate) element.set('currency', self.currency) return element
def _build_mouser_header(self): header_partnerid = Element('PartnerID').setText(self._api_key) header_accountinfo = Element('AccountInfo') header_accountinfo.insert(header_partnerid) header = Element('MouserHeader') header.insert(header_accountinfo) header.set('xmlns', 'http://api.mouser.com/service') return header
def to_xml(self, factory): # make sure the namespace is set to the correct one metadata = factory.resolver.find('ns0:totalVatAmount') element = Element("totalVatAmount", ns=metadata.namespace()) element.setText(str(int(self.value * 100))) element.set('rate', self.rate) element.set('currency', self.currency) return element
def to_xml(self, factory): # Needs to be an xsd:int with an attribute # Can't do that with factory.create('ns0:quantity') #metadata = factory.resolver.find('ns0:quantity') #ns = metadata.namespace() element = Element('ns0:quantity') element.setText(str(self.value)) element.set('unitOfMeasure', self.unit) return element
def encryptMessage(cert, symmetric_key, elements_to_encrypt, enc_key_uri, reference_type=KEY_REFERENCE_ISSUER_SERIAL, key_transport=KEY_TRANSPORT_RSA_OAEP): sym_key = symmetric_key.sym_key iv = symmetric_key.iv block_encryption = symmetric_key.block_encryption_algorithm reference_list = Element("ReferenceList", ns=wsencns) for (element_to_encrypt, type) in elements_to_encrypt: reference = Element("DataReference", ns=wsencns) id = "EncDataId-" + str(generate_unique_id()) reference.set("URI", '#' + id) reference_list.append(reference) element_content = element_to_encrypt.canonical() if type == 'Content': element_content = element_content[element_content.index(">") + 1:element_content.rindex("<")] enc_data = Element("EncryptedData", ns=wsencns) enc_data.set("Id", id) enc_data.set("Type", "http://www.w3.org/2001/04/xmlenc#" + type) block_encryption_props = blockEncryptionProperties[block_encryption] enc_method = Element("EncryptionMethod", ns=wsencns) enc_method.set("Algorithm", block_encryption_props['uri']) key_info = Element("KeyInfo", ns=dsns) sec_token_ref = Element("SecurityTokenReference", ns=wssens) wsse_reference = Element("Reference", ns=wssens) wsse_reference.set("URI", enc_key_uri) sec_token_ref.append(wsse_reference) key_info.append(sec_token_ref) cipher_data = Element("CipherData", ns=wsencns) cipher_value = Element("CipherValue", ns=wsencns) cipher = EVP.Cipher(alg=blockEncryptionProperties[block_encryption]['openssl_cipher'], key=sym_key, iv=iv, op=1, padding=0) pad_bytes = block_encryption_props['block_size'] - len(element_content) % block_encryption_props['block_size'] element_content = element_content + ' ' * (pad_bytes - 1) + chr(pad_bytes) enc_content = cipher.update(element_content.encode("utf-8")) enc_content = enc_content + cipher.final() enc_content = iv + enc_content cipher_value.setText(b64encode(enc_content)) cipher_data.append(cipher_value) enc_data.append(enc_method) enc_data.append(key_info) enc_data.append(cipher_data) if type == 'Element': element_to_encrypt.parent.replaceChild(element_to_encrypt, enc_data) elif type == 'Content': element_to_encrypt.setText('') for child in element_to_encrypt.children: element_to_encrypt.remove(child) element_to_encrypt.append(enc_data) return reference_list
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=wssens) root.set('mustUnderstand', str(self.mustUnderstand).lower()) for t in self.tokens: root.append(t.xml()) return root
def add(self, root): """ Add an <xs:import/> to the specified schema root. @param root: A schema root. @type root: L{Element} """ node = Element('import', ns=self.xsdns) node.set('namespace', self.ns) if self.location is not None: node.set('schemaLocation', self.location) log.debug('%s inserted', node) root.insert(node)
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=wssens) root.set('mustUnderstand', 1 if self.mustUnderstand else 0) if self.timestamp: root.append(Timestamp().xml()) for t in self.tokens: root.append(t.xml()) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=WSSE_NS) for p, u in self.nsprefixes.items(): root.addPrefix(p, u) root.set('SOAP-ENV:mustUnderstand', self.mustUnderstand) for t in self.tokens: root.append(t.xml()) return root
def _ensure_service(self): """Trying to add service if no one definied explicitly. EWS workaround.""" if (self.services or not self.bindings or len(self.bindings) > 1 or not self.bindings.keys()[0][0].startswith('Exchange')): return service = Element('service') service.set('name', 'ExchangeServices') port = Element('port', service) port.set('name', 'ExchangeServicePort') port.set('binding', self.bindings.keys()[0][0]) address = Element('address', port) address.set('location', urljoin(self.url, 'exchange.asmx')) port.append(address) service.append(port) service = Factory.create(service, self) service.resolve(self) self.children.append(service) self.services.append(service) log.debug('Auto created service: %s', service)
def to_xml(self, factory): # Needs to be an xsd:int with an attribute. Suds is not # responding nicely with basic types combined with attributes, so # we can't do that with factory.create('ns0:quantity') # # See also: # https://stackoverflow.com/questions/13103023/how-can-i-assign-a-value-to-a-factory-created-simpletype-object-with-python-suds # make sure the namespace is set to the correct one metadata = factory.resolver.find('ns0:quantity') element = Element("quantity", ns=metadata.namespace()) element.setText(str(self.value)) element.set('unitOfMeasure', self.unit) return element
def xml(self, wsse): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element("Security", ns=wssens) root.set("mustUnderstand", "true") if wsse.includeTimestamp and wsse.headerLayout != HEADER_LAYOUT_LAX_TIMESTAMP_LAST: root.append(Timestamp().xml()) for t in wsse.tokens: root.append(UsernameToken(t.username, t.password, t.includenonce).xml()) if wsse.includeTimestamp and wsse.headerLayout == HEADER_LAYOUT_LAX_TIMESTAMP_LAST: root.append(Timestamp().xml()) return root
def xml(self): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Timestamp', ns=wsuns) root.set('wsu:Id', 'Timestamp-%i' % hash(self)) c = Element('Created', ns=wsuns) c.setText(self.created.isoformat()) root.append(c) if self.expires: e = Element('Expires', ns=wsuns) e.setText(self.expires.isoformat()) root.append(e) return root
def xml(self, wsse): """ Get xml representation of the object. @return: The root node. @rtype: L{Element} """ root = Element('Security', ns=wssens) root.set('mustUnderstand', 'true') if wsse.includeTimestamp and wsse.headerLayout != HEADER_LAYOUT_LAX_TIMESTAMP_LAST: root.append(Timestamp().xml()) for t in wsse.tokens: root.append( UsernameToken(t.username, t.password, t.includenonce).xml()) if wsse.includeTimestamp and wsse.headerLayout == HEADER_LAYOUT_LAX_TIMESTAMP_LAST: root.append(Timestamp().xml()) return root
def apply(self, root): """ Apply the import (rule) to the specified schema. If the schema does not already contain an import for the I{namespace} specified here, it is added. @param root: A schema root. @type root: L{Element} """ if not self.filter.match(root, self.ns): return if self.exists(root): return node = Element('import', ns=self.xsdns) node.set('namespace', self.ns) if self.location is not None: node.set('schemaLocation', self.location) log.debug('inserting: %s', node) root.insert(node)
def create_element(self, name, ns=None, prefix=None, attrs=None, text=None): """Создание нового элемента""" new_element = Element(name, ns=ns) if prefix: new_element.setPrefix(prefix) if attrs: for k, v in attrs.items(): new_element.set(k, v) if text: new_element.setText(text) return new_element
def _marshallSObjects(self, sObjects, tag='sObjects'): ''' Marshall generic sObjects into a list of SAX elements This code is going away ASAP tag param is for nested objects (e.g. MergeRequest) where key: object must be in <key/>, not <sObjects/> ''' if not isinstance(sObjects, (tuple, list)): sObjects = (sObjects, ) if sObjects[0].type in [ 'LeadConvert', 'SingleEmailMessage', 'MassEmailMessage' ]: nsPrefix = 'tns:' else: nsPrefix = 'ens:' li = [] for obj in sObjects: el = Element(tag) el.set('xsi:type', nsPrefix + obj.type) for k, v in obj: if k == 'type': continue # This is here to avoid 'duplicate values' error when setting a field in fieldsToNull # Even a tag like <FieldName/> will trigger it if v == None: # not going to win any awards for variable-naming scheme here tmp = Element(k) tmp.set('xsi:nil', 'true') el.append(tmp) elif isinstance(v, (list, tuple)): for value in v: el.append(Element(k).setText(value)) elif isinstance(v, suds.sudsobject.Object): el.append(self._marshallSObjects(v, k)) else: el.append(Element(k).setText(v)) li.append(el) return li
def get_suds_element(suds_obj, element_name): "Build a suds Element based on a suds-encoded response variable" el = Element(element_name) for node in suds_obj: left = node[0] right = node[1] # Attributes start with _ if left[:1] == '_': el.set(left[1:], str(right)) # Otherwise it's a subelement else: if type(right) is list: for item in right: sub = get_suds_element(item, str(left)) el.append(sub) else: sub = get_suds_element(right, str(left)) el.append(sub) return el
def autoblend(self): """ Ensure that all schemas within the collection import each other which has a blending effect. @return: self @rtype: L{SchemaCollection} """ namespaces = self.namespaces.keys() for s in self.children: for ns in namespaces: tns = s.root.get('targetNamespace') if tns == ns: continue for imp in s.root.getChildren('import'): if imp.get('namespace') == ns: continue imp = Element('import', ns=Namespace.xsdns) imp.set('namespace', ns) s.root.append(imp) return self
def call_service(action, address=JMMServer_Address, port=JMMServer_Port): binding.envns = ('s', 'http://www.w3.org/2003/05/soap-envelope') client = Client( format_url(address, port), headers={'Content-Type': 'application/soap+msbin1'}, transport=HttpAuthenticatedBinary(), plugins=[BinaryMessagePlugin()] ) ssnns = ('a', 'http://www.w3.org/2005/08/addressing') element_action = Element('Action', ns=ssnns).setText('http://tempuri.org/IJMMServer/{0}'.format(action)) element_action.set('s:mustUnderstand', "1") element_reply_to = Element('ReplyTo', ns=ssnns) element_address = Element('Address', ns=ssnns).setText('http://www.w3.org/2005/08/addressing/anonymous') element_reply_to.insert(element_address, 0) element_to = Element('To', ns=ssnns).setText('http://{0}:{1}/JMMServerBinary'.format(address, port)) element_to.set('s:mustUnderstand', "1") client.set_options(soapheaders=(element_action, element_reply_to, element_to)) func = getattr(client.service, action) func()
def _marshallSObjects(self, sObjects, tag = 'sObjects'): ''' Marshall generic sObjects into a list of SAX elements This code is going away ASAP tag param is for nested objects (e.g. MergeRequest) where key: object must be in <key/>, not <sObjects/> ''' if not isinstance(sObjects, (tuple, list)): sObjects = (sObjects, ) if sObjects[0].type in ['LeadConvert', 'SingleEmailMessage', 'MassEmailMessage']: nsPrefix = 'tns:' else: nsPrefix = 'ens:' li = [] for obj in sObjects: el = Element(tag) el.set('xsi:type', nsPrefix + obj.type) for k, v in obj: if k == 'type': continue # This is here to avoid 'duplicate values' error when setting a field in fieldsToNull # Even a tag like <FieldName/> will trigger it if v == None: # not going to win any awards for variable-naming scheme here tmp = Element(k) tmp.set('xsi:nil', 'true') el.append(tmp) elif isinstance(v, (list, tuple)): for value in v: el.append(Element(k).setText(value)) elif isinstance(v, suds.sudsobject.Object): el.append(self._marshallSObjects(v, k)) else: el.append(Element(k).setText(v)) li.append(el) return li
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 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 _create_wsse_header(self, username, password): username_element = Element('wsse:Username') username_element.setText(username) password_element = Element('wsse:Password') password_element.set('Type', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText') password_element.setText(sha256(password.encode()).hexdigest()) nonce = Element('wsse:Nonce') nonce.set('EncodingType', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary') nonce.setText(base64.b64encode(os.urandom(64))) bogota_tz = pytz.timezone('America/Bogota') created = Element('wsu:Created') created.setText(pytz.utc.localize(datetime.now()).astimezone(bogota_tz).strftime('%Y-%m-%dT%H:%M:%S.000-05:00')) username_token = Element('wsse:UsernameToken') username_token.set('wsu:Id', 'UsernameToken-1') username_token.append(username_element) username_token.append(password_element) username_token.append(nonce) username_token.append(created) header = Element('wsse:Security').append(username_token) return header
def encryptMessage(self, env, use_encrypted_header=False, second_pass=False): encrypted_parts = second_pass and self.second_pass_encrypted_parts or self.encrypted_parts elements_to_encrypt = [] encrypted_headers = [] for elements_to_encrypt_func in encrypted_parts: addl_elements = elements_to_encrypt_func(env) if addl_elements[0] is None: continue if not isinstance(addl_elements[0], list): addl_elements = ([addl_elements[0]], addl_elements[1]) for element in addl_elements[0]: if element not in elements_to_encrypt: if element[0].parent.match( 'Header') and use_encrypted_header: enc_hdr = Element('EncryptedHeader', ns=wsse11ns) element[0].parent.replaceChild(element[0], enc_hdr) enc_hdr.append(element[0]) elements_to_encrypt.append((enc_hdr, 'Content')) encrypted_headers.append(enc_hdr) else: elements_to_encrypt.append((element, addl_elements[1])) ref_list = xmlsec.encryptMessage(self.cert, self.symmetricKey, elements_to_encrypt, '#' + self.keyId, self.keyReference, self.keyTransport) for enc_hdr in encrypted_headers: enc_hdr.set('wsu:Id', enc_hdr[0].get('Id')) enc_hdr[0].unset('Id') if self.includeRefList: self.encryptedKey.append(ref_list) return self.encryptedKey else: return (self.encryptedKey, ref_list)
def buildEncryptedKey(key_id, cert, sym_key, reference_type=KEY_REFERENCE_ISSUER_SERIAL, block_encryption=BLOCK_ENCRYPTION_AES128_CBC, key_transport=KEY_TRANSPORT_RSA_OAEP): enc_key = Element("EncryptedKey", ns=wsencns) enc_key.set("Id", key_id) enc_method = Element("EncryptionMethod", ns=wsencns) enc_method.set("Algorithm", keyTransportProperties[key_transport]['uri']) key_info = build_key_info(cert, reference_type) cipher_data = Element("CipherData", ns=wsencns) cipher_value = Element("CipherValue", ns=wsencns) block_encryption_props = blockEncryptionProperties[block_encryption] pub_key = cert.getRsaPublicKey() enc_sym_key = pub_key.public_encrypt(sym_key, keyTransportProperties[key_transport]['padding']) cipher_value.setText(b64encode(enc_sym_key)) cipher_data.append(cipher_value) sha1 = EVP.MessageDigest('sha1') sha1.update(enc_sym_key) cipher_value_sha1 = sha1.final() enc_key.append(enc_method) enc_key.append(key_info) enc_key.append(cipher_data) return (enc_key, cipher_value_sha1)
def xml(self): root = Element('UsernameToken', ns=WSSENS) u = Element('Username', ns=WSSENS) u.setText(self.username) root.append(u) if self.password is not None: p = Element('Password', ns=WSSENS) p.setText(self.password) p.set('Type', PASSWORDTEXT_TYPE) root.append(p) if self.autosetnonce: self.setnonce() if self.nonce is not None: n = Element('Nonce', ns=WSSENS) n.setText(self.nonce) n.set('EncodingType', BASE64_ENC_TYPE) root.append(n) if self.autosetcreated: self.setcreated() if self.created: n = Element('Created', ns=WSUNS) n.setText(str(UTC(self.created))) root.append(n) return root
def add_extern_service(self, name, portname, binding, location): """Add a service that was not defined in the wsdl. This is used after the Definitions object has been created. @param name: The name of the new service. @type url: str @param portname: The name of the port of the new service. @type portname: str @param binding: The name of the wsdl binding to use for the new service. The binding must be defined in the wsdl. @type binding: str @param location: The location of the new service. @type location: str """ if binding not in [bind[0] for bind in self.bindings.keys()]: log.debug('Binding "%s" not defined in %s' % (binding, self.url)) raise Exception('Binding "%s" not defined in %s' % (binding, self.url)) service = Element('service') service.set('name', name) port = Element('port', service) port.set('name', portname) port.set('binding', binding) address = Element('address', port) address.set('location', location) port.append(address) service.append(port) service = Factory.create(service, self) service.resolve(self) self.children.append(service) self.services.append(service) self.add_methods(service) log.debug('Created service: %s', service) return service
def main(): # Build transport and client objects using HttpAuth for authentication # and MessagePlugin to allow the capturing of raw XML, necessary for # extracting the IPControl session ID later plugin = MyPlugin() credentials = dict(username=user, password=pw) transport = HttpAuthenticated(**credentials) client = Client('http://ipcontrol.foobar.net/inc-ws/services/Exports?wsdl', headers={ 'username': user, 'password': pw }, transport=transport, plugins=[plugin]) query_parameters = ('ipaddress = 1.2.3.4', False ) # The boolean is for includeFreeBlocks # Exports must be initialized first. The IPControl session ID can then # be extracted from the raw reply data. This is necessary later when # the export service is called. context = client.service.initExportChildBlock(*query_parameters) session_id_re = re.search(r'([0-9-]{19,20})', str(plugin.last_received_raw), re.M) if session_id_re: session_id = session_id_re.group(1) print("SESSION ID: {}".format(session_id)) else: print("NO SESSION ID FOUND") sys.exit() # Build a new SOAP header where the 'sessionID' is set to the value extracted # from the raw initialization reply data above, then apply the new # header to the existing client object. sid = Element( 'sessionID', ns=('ns1', 'http://xml.apache.org/axis/session')).setText(session_id) sid.set("SOAP-ENV:mustUnderstand", "0") sid.set("SOAP-ENV:actor", "http://schemas.xmlsoap.org/soap/actor/next") sid.set("xsi:type", "soapenc:long") client.set_options(soapheaders=sid) result = client.service.exportChildBlock(context) print("RESULT: {}".format(result))
""" default "UsernameToken" in suds produces "Password" element without a "Type" field https://fedorahosted.org/suds/ticket/402 so need to build it manually, specifying namespaces """ wsse = ( 'wsse', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' ) security = Element('Security', ns=wsse) usernametoken = Element('UsernameToken', ns=wsse) uname = Element('Username', ns=wsse).setText('myusername') passwd = Element('Password', ns=wsse).setText('mypassword') passwd.set( 'Type', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText' ) usernametoken.insert(uname) usernametoken.insert(passwd) security.insert(usernametoken) url = 'http://127.0.0.1:5000/soap/someservice?wsdl' client = SudsClient(url=url, cache=None) client.set_options(soapheaders=security) r = client.service.echo(str='hello world', cnt=3) print(r)
def build_key_info(cert, reference_type, ref_id=None): key_info = Element("KeyInfo", ns=dsns) sec_token_ref = Element("SecurityTokenReference", ns=wssens) if reference_type == KEY_REFERENCE_ISSUER_SERIAL: x509_data = Element("X509Data", ns=dsns) issuer_serial = Element("X509IssuerSerial", ns=dsns) issuer_name = Element("X509IssuerName", ns=dsns) issuer_name.setText(cert.getX509IssuerSerial().getIssuer()) serial_number = Element("X509SerialNumber", ns=dsns) serial_number.setText(cert.getX509IssuerSerial().getSerial()) issuer_serial.append(issuer_name) issuer_serial.append(serial_number) x509_data.append(issuer_serial) sec_token_ref.append(x509_data) elif reference_type == KEY_REFERENCE_SUBJECT_KEY_IDENTIFIER: key_ident = Element("KeyIdentifier", ns=wssens) key_ident.set("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary") key_ident.set("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#X509SubjectKeyIdentifier") key_ident.setText(b64encode(cert.getSubjectKeyIdentifier().getSubjectKeyIdentifier().decode('hex'))) sec_token_ref.append(key_ident) elif reference_type == KEY_REFERENCE_FINGERPRINT: key_ident = Element("KeyIdentifier", ns=wssens) key_ident.set("EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary") key_ident.set("ValueType", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1") key_ident.setText(b64encode(cert.getSHA1Fingerprint().getFingerprint().decode('hex'))) sec_token_ref.append(key_ident) elif reference_type == KEY_REFERENCE_BINARY_SECURITY_TOKEN: reference = Element("Reference", ns=wssens) reference.set("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3") reference.set("URI", ref_id) sec_token_ref.append(reference) elif reference_type == KEY_REFERENCE_ENCRYPTED_KEY: reference = Element("Reference", ns=wssens) reference.set("URI", ref_id) reference.set("ValueType", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey") sec_token_ref.append(reference) key_info.append(sec_token_ref) return key_info
exit(10) print 'GetLayers: OK' layers = [layer1, layer2] ##### CREATE MODEL ################################### mod_params = Element('ModelParameters') mod_params.applyns((None, 'http://openmodeller.cria.org.br/xml/1.0')) sampler = Element('Sampler') env = Element('Environment') # Layers for ref_layer in layers: map_element = Element('Map') map_element.set('Id', ref_layer) env.append(map_element) # Mask mask_element = Element('Mask') mask_element.set('Id', layer1) env.append(mask_element) sampler.append(env) # Points presence = Element('Presence') presence.set('Label', 'test_service.py') coord = Element('CoordinateSystem') coord.setText( "GEOGCS['WGS84', DATUM['WGS84', SPHEROID['WGS84', 6378137.0, 298.257223563]], PRIMEM['Greenwich', 0.0], UNIT['degree', 0.017453292519943295], AXIS['Longitude',EAST], AXIS['Latitude',NORTH]]" ) presence.append(coord) p1 = Element('Point')
def signMessage(key, ref, elements_to_digest, reference_type=KEY_REFERENCE_ISSUER_SERIAL, digest_algorithm=DIGEST_SHA1, signature_algorithm=SIGNATURE_RSA_SHA1, ref_id=None): sig = Element("Signature", ns=dsns) signed_info = Element("SignedInfo", ns=dsns) canon_method = Element("CanonicalizationMethod", ns=dsns) canon_method.set("Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#") sig_method = Element("SignatureMethod", ns=dsns) sig_method.set("Algorithm", signature_algorithm) signed_info.append(canon_method) signed_info.append(sig_method) sig_value = Element("SignatureValue", ns=dsns) key_info = build_key_info(ref, reference_type, ref_id) sig.append(signed_info) sig.append(sig_value) sig.append(key_info) for element_to_digest in elements_to_digest: reference = Element("Reference", ns=dsns) transforms = Element("Transforms", ns=dsns) transform = Element("Transform", ns=dsns) transform.set("Algorithm", "http://www.w3.org/2001/10/xml-exc-c14n#") transforms.append(transform) digest_method = Element("DigestMethod", ns=dsns) digest_method.set("Algorithm", digestProperties[digest_algorithm]['uri']) digest_value = Element("DigestValue", ns=dsns) reference.append(transforms) reference.append(digest_method) reference.append(digest_value) signed_info.append(reference) if element_to_digest.namespace()[1] == dsns[1]: id_attribute = 'Id' else: id_attribute = 'wsu:Id' if element_to_digest.get(id_attribute): element_id = element_to_digest.get(id_attribute) else: element_id = "id-" + str(generate_unique_id()) element_to_digest.set(id_attribute, element_id) reference.set("URI", "#" + element_id) element_content = element_to_digest.canonical() digest_props = digestProperties[digest_algorithm] hash = EVP.MessageDigest(digest_props['openssl_alg']) hash.update(element_content.encode('utf-8')) digest_value.setText(b64encode(hash.digest())) element_to_sign = signed_info element_content = element_to_sign.canonical() if signature_algorithm == SIGNATURE_RSA_SHA1: priv_key = key.getEvpPrivateKey() priv_key.sign_init() priv_key.sign_update(element_content.encode("utf-8")) signed_digest = priv_key.sign_final() elif signature_algorithm == SIGNATURE_HMAC_SHA1: enc = EVP.HMAC(key) enc.update(element_content.encode("utf-8")) signed_digest = enc.final() sig_value.setText(b64encode(signed_digest)) return sig
from suds.client import Client as SudsClient from suds.sax.element import Element """ default "UsernameToken" in suds produces "Password" element without a "Type" field https://fedorahosted.org/suds/ticket/402 so need to build it manually, specifying namespaces """ wsse = ('wsse', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd') security = Element('Security', ns=wsse) usernametoken = Element('UsernameToken', ns=wsse) uname = Element('Username', ns=wsse).setText('myusername') passwd = Element('Password', ns=wsse).setText('mypassword') passwd.set('Type', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText') usernametoken.insert(uname) usernametoken.insert(passwd) security.insert(usernametoken) url = 'http://127.0.0.1:5000/soap/someservice?wsdl' client = SudsClient(url=url, cache=None) client.set_options(soapheaders=security) r = client.service.echo(str='hello world', cnt=3) print(r)
class Signature(Object): def buildTokens(self): self.token = None self.bst_id = None if self.keyReference == xmlsec.KEY_REFERENCE_BINARY_SECURITY_TOKEN: self.token = Element("BinarySecurityToken", ns=wssens) self.token.setText(self.x509_issuer_serial.getCertificateText()) self.token.set( "ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" ) self.token.set( "EncodingType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary", ) bst_id = "BSTID-" + str(generate_unique_id()) self.token.set("wsu:Id", bst_id) self.bst_id = "#" + bst_id elif self.keyReference == xmlsec.KEY_REFERENCE_ENCRYPTED_KEY: self.bst_id = self.encKeyUri return self.token def signMessage(self, env, signOnlyEntireHeadersAndBody): elements_to_digest = [] for elements_to_digest_func in self.signed_parts: addl_elements = elements_to_digest_func(env, self) if addl_elements is None: continue if not isinstance(addl_elements, list): addl_elements = [addl_elements] for element in addl_elements: if element not in elements_to_digest: elements_to_digest.append(element) if signOnlyEntireHeadersAndBody: self.verifyOnlyEntireHeadersAndBody(elements_to_digest) if self.signatureAlgorithm == SIGNATURE_RSA_SHA1: key = self.key elif self.signatureAlgorithm == SIGNATURE_HMAC_SHA1: key = self.symmetricKey.sym_key sig = xmlsec.signMessage( key, self.x509_issuer_serial, elements_to_digest, self.keyReference, self.digest, self.signatureAlgorithm, self.bst_id, ) self.element = sig return sig def verifyOnlyEntireHeadersAndBody(self, elements_to_digest): for element in elements_to_digest: if element.match("Body") or element.parent.match("Header") or element.parent.match("Security"): continue raise Exception, "A descendant of a header or the body was signed, but only entire headers and body were permitted to be signed" def __init__(self, options, sym_key=None): Object.__init__(self) self.key = options.key self.x509_issuer_serial = options.cert self.signed_parts = options.signedparts self.digest = options.digest self.keyReference = options.keyreference self.signatureAlgorithm = options.signaturealgorithm self.symmetricKey = sym_key