Ejemplo n.º 1
0
def prepare_request(xml,
                    message_id=1,
                    method_name="PRTrans",
                    login="******",
                    password="******",
                    should_compress=True,
                    should_encode=True):
    client = Client(
        "file://./treasury/tests/fixtures/wdsl.xml")  # use the local copy
    factory = client.type_factory("ns0")
    if should_compress:
        xml = compress(xml)
    if should_encode:
        xml = base64.b64encode(xml)
    message = factory.RequestMessage(
        UserLogin=login,
        UserPassword=password,
        MessageId=message_id,
        MethodName=method_name,
        Data=xml,
        DataSign=b"123",
    )
    message_node = client.create_message(client.service, 'SendRequest',
                                         message)
    return etree.tostring(message_node)
Ejemplo n.º 2
0
    def request(self, endpoint_type, operation_name, data):
        if endpoint_type not in EndpointTypeChoices.values.keys():
            raise ValueError(
                'Invalid value for endpoint_type: {}'.format(endpoint_type))

        client = Client(self.endpoints[endpoint_type])
        for prefix, url in self.namespaces.items():
            client.set_ns_prefix(prefix, url)

        if self.dryrun:
            root = client.create_message(client.service, operation_name,
                                         **data)
            print(etree.tostring(root, pretty_print=True).decode('utf-8'))
            return None

        # CommunicationLogEntry.objects.log(data, direction=CommunicationDirectionChoices.outgoing)

        with client.options(raw_response=True):
            response = client.service[operation_name](**data)

        try:
            response_root = etree.fromstring(response.content)
            response_berichtcode = response_root.xpath(
                '//stuf:stuurgegevens/stuf:berichtcode',
                namespaces=self.namespaces)[0].text
        except IndexError as e:
            raise ConsumerException(
                'Server returned unexpected or invalid XML.')
        except Exception as e:
            raise ConsumerException('Server returned invalid XML.')

        # CommunicationLogEntry.objects.log(response, direction=CommunicationDirectionChoices.incomming)

        if response_berichtcode != BerichtcodeChoices.bv03:
            raise UnexpectedAnswerException(
                'Expected "Bv03" but got "{}".'.format(response_berichtcode))

        return response
Ejemplo n.º 3
0
def insertSubscriber():
    client = Client(subscriberWsdl, transport=transport)
    #Insert com os parametros obrigatórios da API
    subscriber = {
        'subscriber': [{
            'username': '******',
            'domain': '189.90.58.141',
            'password': '******',
            'profile': 'FLN_4396_STFC',
            'ratePlanId': 0,
            'resellerId': 0,
            'emailAddress': '*****@*****.**',
            'countryCode': '55',
            'areaCode': '48',
            'callLimit': 1,
            'voicemail': '0',
            'passwordPortal': '$senhadoportal#',
            'activeIncomingCalls': '1',
            'activeOutgoingCalls': '1',
            'blockAnonymousCalls': 'false',
            'blockCollectCalls': 'false',
            'lowCreditLimit': 'false',
            'lowCreditNotification': 'true',
            'resellerBillingType': '0',
            'resellerMarkup': '0.0',
        }],
        #Usuário e Senha da Integracao
        'principal': [{
            'login': '******',
            'password': '******',
        }]
    }

    # insertSubscriber - Serviço do WSDL
    response = client.create_message(client.service, "insertSubscriber",
                                     **subscriber)
Ejemplo n.º 4
0
    'answerTooLateTimer': 19000,
    'delayBeforeRingingCell': 4000,
    'ownerUserId': 'testEndUser',
    'enableUnifiedMobility': True,
    'remoteDestinationProfileName': 'testRemoteDestinationProfile',
    'isMobilePhone': True,
    'enableMobileConnect': True
}

# Due to an issue with the AXL schema vs. implementation (11.5/12.5 - CSCvq98025)
# we have to remove the nil <dualModeDeviceName> element Zeep creates
# via the following lines

# Use the Zeep service to create an XML object of the request - don't send
node = client.create_message(service,
                             'addRemoteDestination',
                             remoteDestination=remote_destination)

# Remove the dualModeDeviceName element
for element in node.xpath("//dualModeDeviceName"):
    element.getparent().remove(element)

# Execute the addRemoteDestination request
# This has to be done a little differently since we want to send a custom payload
try:
    resp = transport.post_xml(
        f'https://{os.getenv( "CUCM_ADDRESS" )}:8443/axl/',
        envelope=node,
        headers=None)
except Fault as err:
    print("Zeep error: addRemoteDestination: {0}".format(err))
                                    key=operator.attrgetter('name'))
            for operation in operations:
                print("method :", operation.name)
                print("  input :", operation.input.signature())
                print("  output:", operation.output.signature())
    except:
        print("OS error: {0}".format(err))


if __name__ == '__main__':
    '''
    #This is my calling my custom code to generate SOAP Requests and Output them to another file called output.xml
    tree = ET.parse(full_path_to_wsdl)
    loaded_template = load_template()
    target_namespace = getNamespace(tree,full_path_to_wsdl)
    methods_and_dt = get_methods_and_data_types(wsdl_url)
    with open("output.xml","w") as f:
        for key,values in methods_and_dt.items():
            output = loaded_template.render(t_namespace=target_namespace, operation=key, dtypes=values)
            f.write(output)
            f.write("\n")
            f.write("\n")
    '''
    #This is getting the soap message delivered to endpoint
    settings = Settings(strict=False, xml_huge_tree=True)
    #wsdl_url = "https://cs.au.dk/~amoeller/WWW/webservices/wsdlexample.html"
    wsdl_url = "http://webservices.oorsprong.org/websamples.countryinfo/CountryInfoService.wso?WSDL"
    client = Client(wsdl_url, settings=settings)
    getEverythingAboutWSDL(wsdl_url)
    node = client.create_message(client.service, "ListOfContinentsByCode")
    print(etree.tostring(node, pretty_print=True).decode())
Ejemplo n.º 6
0
class Adapter:
    xml_template = '<ds:Signature ' \
                   'xmlns:ds="http://www.w3.org/2000/09/xmldsig#">' \
                   '<ds:SignedInfo>' \
                   '<ds:CanonicalizationMethod ' \
                   'Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>' \
                   '<ds:SignatureMethod ' \
                   'Algorithm="http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411"/>' \
                   '<ds:Reference URI="#SIGNED_BY_CALLER"><ds:Transforms>' \
                   '<ds:Transform ' \
                   'Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>' \
                   '<ds:Transform ' \
                   'Algorithm="urn://smev-gov-ru/xmldsig/transform"/>' \
                   '</ds:Transforms>' \
                   '<ds:DigestMethod ' \
                   'Algorithm="http://www.w3.org/2001/04/xmldsig-more#gostr3411"/>' \
                   '<ds:DigestValue></ds:DigestValue></ds:Reference>' \
                   '</ds:SignedInfo><ds:SignatureValue></ds:SignatureValue>' \
                   '<ds:KeyInfo><ds:X509Data><ds:X509Certificate>' \
                   '</ds:X509Certificate></ds:X509Data></ds:KeyInfo>' \
                   '</ds:Signature>'

    def __init__(
            self,
            wsdl="http://smev3-d.test.gosuslugi.ru:7500/smev/v1.2/ws?wsdl",
            ftp_addr="ftp://smev3-d.test.gosuslugi.ru/",
            history=False,
            method='sharp',
            serial=None,
            container=None,
            crt_name=None):
        self.log = logging.getLogger('smev.adapter')
        self.log.setLevel(logging.root.level)
        self.ftp_addr = ftp_addr
        self.crypto = Crypto()
        self.crypto.serial = serial
        self.crypto.crt_name = crt_name
        self.crypto.container = container
        self.method = method

        if history:
            self.history = HistoryPlugin()
            self.proxy = Client(wsdl, plugins=[self.history])
        else:
            self.proxy = Client(wsdl)

    def dump(self):
        res = "Prefixes:\n"
        for prefix, namespace in self.proxy.wsdl.types.prefix_map.items():
            res += ' ' * 4 + '%s: %s\n' % (prefix, namespace)

        res += "\nGlobal elements:\n"
        for elm_obj in sorted(self.proxy.wsdl.types.elements,
                              key=lambda k: k.qname):
            value = elm_obj.signature(schema=self.proxy.wsdl.types)
            res += ' ' * 4 + value + '\n'

        res += "\nGlobal types:\n"
        for type_obj in sorted(self.proxy.wsdl.types.types,
                               key=lambda k: k.qname or ''):
            value = type_obj.signature(schema=self.proxy.wsdl.types)
            res += ' ' * 4 + value + '\n'

        res += "\nBindings:\n"
        for binding_obj in sorted(self.proxy.wsdl.bindings.values(),
                                  key=lambda k: six.text_type(k)):
            res += ' ' * 4 + six.text_type(binding_obj) + '\n'

        res += '\n'
        for service in self.proxy.wsdl.services.values():
            res += six.text_type(service) + '\n'
            for port in service.ports.values():
                res += ' ' * 4 + six.text_type(port) + '\n'
                res += ' ' * 8 + 'Operations:\n'

                operations = sorted(port.binding._operations.values(),
                                    key=operator.attrgetter('name'))

                for operation in operations:
                    res += '%s%s\n' % (' ' * 12, six.text_type(operation))
                res += '\n'
        return res

    # def get_request(self, uri='urn://augo/smev/uslugi/1.0.0',
    #                 local_name='directum'):
    def get_request(self,
                    uri=None,
                    local_name=None,
                    node_id=None,
                    gen_xml_only=False):
        # if (uri and not local_name) or (not uri and local_name):
        #     raise Exception(
        #         'uri и local_name необходимо указывать одновременно')

        operation = 'GetRequest'
        timestamp = datetime.now()
        node = self.proxy.create_message(
            self.proxy.service,
            operation, {
                'NamespaceURI': uri,
                'RootElementLocalName': local_name,
                'Timestamp': timestamp,
                'NodeID': node_id
            },
            CallerInformationSystemSignature=etree.Element('Signature'))
        node[0][0][0].set('Id', 'SIGNED_BY_CALLER')
        node_str = etree.tostring(node)
        self.log.debug(node_str)

        res = self.__call_sign(
            self.__xml_part(node_str, b'ns1:MessageTypeSelector'))
        # COM variant
        # res = self.crypto.sign_com(
        #     self.__xml_part(node_str, b'ns1:MessageTypeSelector').decode())
        # res = self.__xml_part(res, 'Signature')
        # res = res.replace('URI=""', 'URI="#SIGNED_BY_CALLER"')

        # CSP variant
        # self.crypto.container = "049fc71a-1ff0-4e06-8714-03303ae34afd"
        # res = self.crypto.sign_csp(
        #     self.__xml_part(node_str, b'ns1:MessageTypeSelector'))

        # Sharp variant
        # self.crypto.serial = '008E BDC8 291F 0003 81E7 11E1 AF7A 5ED3 27'
        # res = self.crypto.sign_sharp(
        #     self.__xml_part(node_str, b'ns1:MessageTypeSelector'))

        res = node_str.decode().replace('<Signature/>', res)
        if gen_xml_only:
            return res

        res = self.__send(operation, res)
        self.log.debug(type(res))
        self.log.debug(res)

        declar, uuid, reply_to, files = None, None, None, {}

        if 'MessagePrimaryContent' in res:
            xml = etree.fromstring(res)

            declar = Declar.parsexml(
                etree.tostring(
                    xml.find('.//{urn://augo/smev/uslugi/1.0.0}declar')))

            if 'RefAttachmentHeaderList' in res:
                files = {}
                attach_head_list = objectify.fromstring(
                    self.__xml_part(res, b'RefAttachmentHeaderList'))
                for head in attach_head_list.getchildren():
                    files[head.uuid] = {'MimeType': head.MimeType}
                attach_list = objectify.fromstring(
                    self.__xml_part(res, b'FSAttachmentsList'))
                for attach in attach_list.getchildren():
                    files[attach.uuid]['UserName'] = str(attach.UserName)
                    files[attach.uuid]['Password'] = str(attach.Password)
                    files[attach.uuid]['FileName'] = str(attach.FileName)
                for uuid, file in files.items():
                    file_name = file['FileName']
                    fn, ext = path.splitext(file_name)
                    res = self.__load_file(uuid, file['UserName'],
                                           file['Password'], file['FileName'])
                    if isinstance(res, (str, bytes)):
                        new_ext = guess_extension(file_name).lower()
                        ext = ext.lower()
                        if ext != new_ext:
                            file_name = fn + new_ext
                    else:
                        res, e = res
                        file_name = fn + '.txt'
                    declar.files.append({res: file_name})

            uuid = xml.find('.//{*}MessageID').text
            reply_to = xml.find('.//{*}ReplyTo')
            if reply_to:
                reply_to = reply_to.text

        if hasattr(res, 'Request') \
                and hasattr(res.Request, 'SenderProvidedRequestData') \
                and hasattr(res.Request.SenderProvidedRequestData,
                            'MessagePrimaryContent') \
                and res.Request.SenderProvidedRequestData.MessagePrimaryContent:
            # declar = Declar.parsexml(
            #     etree.tostring(
            #         res.Request.SenderProvidedRequestData.MessagePrimaryContent.find(
            #             './/{urn://augo/smev/uslugi/1.0.0}declar')))
            declar = Declar.parsexml(
                etree.tostring(res.Request.SenderProvidedRequestData.
                               MessagePrimaryContent._value_1))
            if hasattr(res.Request, 'FSAttachmentsList') \
                    and res.Request.FSAttachmentsList:
                attach_head_list = res.Request.SenderProvidedRequestData.RefAttachmentHeaderList
                for head in attach_head_list:
                    files[head.uuid] = {'MimeType': head.MimeType}
                attach_list = res.Request.FSAttachmentsList
                for attach in attach_list:
                    files[attach.uuid]['UserName'] = str(attach.UserName)
                    files[attach.uuid]['Password'] = str(attach.Password)
                    files[attach.uuid]['FileName'] = str(attach.FileName)
                for uuid, file in files.items():
                    file_name = file['FileName']
                    fn, ext = path.splitext(file_name)
                    res = self.__load_file(uuid, file['UserName'],
                                           file['Password'], file['FileName'])
                    if isinstance(res, (str, bytes)):
                        new_ext = guess_extension(file_name).lower()
                        ext = ext.lower()
                        if ext != new_ext:
                            file_name = fn + new_ext
                    else:
                        res, e = res
                        file_name = fn + '.txt'
                    # declar.files.append({res: file_name})
                    files[file_name] = res

            uuid = res.Request.SenderProvidedRequestData.MessageID
            reply_to = res.Request.ReplyTo

        if uuid:
            operation = 'Ack'
            tm = etree.Element('AckTargetMessage',
                               Id='SIGNED_BY_CALLER',
                               accepted='true')
            tm.text = uuid
            node = self.proxy.create_message(
                self.proxy.service,
                operation,
                tm,
                CallerInformationSystemSignature=etree.Element('Signature'))
            res = node.find('.//{*}AckTargetMessage')
            res.set('Id', 'SIGNED_BY_CALLER')
            res.set('accepted', 'true')
            res.text = uuid
            node_str = etree.tostring(node)
            self.log.debug(node_str)
            res = self.__xml_part(node_str, b'ns1:AckTargetMessage')
            res = self.__call_sign(res)
            res = node_str.decode().replace('<Signature/>', res)
            res = self.__send(operation, res)
            self.log.debug(res)

        return declar, uuid, reply_to, files

    def get_response(self,
                     uri="",
                     local_name="",
                     node_id=None,
                     gen_xml_only=False):
        operation = 'GetResponse'
        timestamp = datetime.now()
        node = self.proxy.create_message(
            self.proxy.service,
            operation, {
                'NamespaceURI': uri,
                'RootElementLocalName': local_name,
                'Timestamp': timestamp,
                'NodeID': node_id
            },
            CallerInformationSystemSignature=etree.Element('Signature'))
        node[0][0][0].set('Id', 'SIGNED_BY_CALLER')
        node_str = etree.tostring(node)
        self.log.debug(node_str)

        res = self.__call_sign(
            self.__xml_part(node_str, b'ns1:MessageTypeSelector'))

        res = node_str.decode().replace('<Signature/>', res)
        if gen_xml_only:
            return res

        res = self.__send(operation, res)
        self.log.debug(type(res))
        self.log.debug(res)

        request, uuid, reply_to, files = None, None, None, {}

        if hasattr(res, 'Response') \
                and hasattr(res.Response, 'SenderProvidedResponseData'):
            request = res.Response.SenderProvidedResponseData
            if hasattr(res.Response.SenderProvidedResponseData,
                            'MessagePrimaryContent') \
                and res.Response.SenderProvidedResponseData.MessagePrimaryContent:
                # request = RequestResponse.parsexml(
                #     etree.tostring(
                #         res.Response.SenderProvidedResponseData.MessagePrimaryContent._value_1))
                res1 = RequestResponse.parsexml(
                    etree.tostring(res.Response.SenderProvidedResponseData.
                                   MessagePrimaryContent._value_1))
                request.MessagePrimaryContent._value_1 = str(res1)
            if hasattr(res.Response, 'FSAttachmentsList') \
                    and res.Response.FSAttachmentsList:
                attach_head_list = res.Response.SenderProvidedResponseData.RefAttachmentHeaderList
                for head in attach_head_list:
                    files[head.uuid] = {'MimeType': head.MimeType}
                attach_list = res.Response.FSAttachmentsList
                for attach in attach_list:
                    files[attach.uuid]['UserName'] = str(attach.UserName)
                    files[attach.uuid]['Password'] = str(attach.Password)
                    files[attach.uuid]['FileName'] = str(attach.FileName)
                for uuid, file in files.items():
                    file_name = file['FileName']
                    fn, ext = path.splitext(file_name)
                    res = self.__load_file(uuid, file['UserName'],
                                           file['Password'], file['FileName'])
                    if isinstance(res, (str, bytes)):
                        new_ext = guess_extension(file_name).lower()
                        ext = ext.lower()
                        if ext != new_ext:
                            file_name = fn + new_ext
                    else:
                        res, e = res
                        file_name = fn + '.txt'
                    files[file_name] = res

            uuid = res.Response.SenderProvidedResponseData.MessageID
            reply_to = res.Response.SenderProvidedResponseData.To

        if uuid:
            operation = 'Ack'
            tm = etree.Element('AckTargetMessage',
                               Id='SIGNED_BY_CALLER',
                               accepted='true')
            tm.text = uuid
            node = self.proxy.create_message(
                self.proxy.service,
                operation,
                tm,
                CallerInformationSystemSignature=etree.Element('Signature'))
            res = node.find('.//{*}AckTargetMessage')
            res.set('Id', 'SIGNED_BY_CALLER')
            res.set('accepted', 'true')
            res.text = uuid
            node_str = etree.tostring(node)
            self.log.debug(node_str)
            res = self.__xml_part(node_str, b'ns1:AckTargetMessage')
            res = self.__call_sign(res)
            res = node_str.decode().replace('<Signature/>', res)
            res = self.__send(operation, res)
            self.log.debug(res)

        return request, uuid, reply_to, files

    def __add_element(self, parent, ns, elem, data, file_names=list()):
        if not data:
            return
        se = etree.SubElement(parent, '{%s}%s' % (ns, elem))
        if elem == 'AppliedDocument':
            if isinstance(data, list):
                for itm in data:
                    for item in ('title', 'number', 'date', 'valid_until',
                                 'file_name', 'url', 'url_valid_until'):
                        if item in itm and itm[item]:
                            if item == 'file_name':
                                fn = itm[item]
                                file_names.append(fn)
                                self.__add_element(se, ns, item,
                                                   path.basename(fn),
                                                   file_names)
                            else:
                                self.__add_element(se, ns, item, itm[item],
                                                   file_names)
                    if data.index(itm) < len(data) - 1:
                        se = etree.SubElement(parent, '{%s}%s' % (ns, elem))
            else:
                for item in ('title', 'number', 'date', 'valid_until',
                             'file_name', 'url', 'url_valid_until'):
                    if item in data and data[item]:
                        if item == 'file_name':
                            file_names.append(item)
                        self.__add_element(se, ns, item, data[item],
                                           file_names)
        elif elem == 'legal_entity':
            if isinstance(data, list):
                for itm in data:
                    for item in ('name', 'full_name', 'inn', 'kpp', 'address',
                                 'ogrn', 'taxRegDoc', 'govRegDoc',
                                 'govRegDate', 'phone', 'email', 'bossFio',
                                 'buhFio', 'bank', 'bankAccount',
                                 'lastCtrlDate', 'opf', 'govRegOgv', 'person'):
                        if item in itm and itm[item]:
                            self.__add_element(se, ns, item, itm[item],
                                               file_names)
                    if data.index(itm) < len(data) - 1:
                        se = etree.SubElement(parent, '{%s}%s' % (ns, elem))
            else:
                for item in ('name', 'full_name', 'inn', 'kpp', 'address',
                             'ogrn', 'taxRegDoc', 'govRegDoc', 'govRegDate',
                             'phone', 'email', 'bossFio', 'buhFio', 'bank',
                             'bankAccount', 'lastCtrlDate', 'opf', 'govRegOgv',
                             'person'):
                    if item in data and data[item]:
                        self.__add_element(se, ns, item, data[item],
                                           file_names)
        elif 'address' in elem:
            for item in ('Postal_Code', 'Region', 'District', 'City',
                         'Urban_District', 'Soviet_Village', 'Locality',
                         'Street', 'House', 'Reference_point', 'Housing',
                         'Building', 'Apartment'):
                if item in data and data[item]:
                    self.__add_element(se, ns, item, data[item], file_names)
        elif elem in ('person', 'confidant'):
            if isinstance(data, list):
                for itm in data:
                    for item in ('surname', 'first_name', 'patronymic',
                                 'address', 'fact_address', 'email',
                                 'birthdate', 'passport_serial',
                                 'passport_number', 'passport_agency',
                                 'passport_date', 'phone', 'inn', 'sex',
                                 'snils'):
                        if item in itm and itm[item]:
                            self.__add_element(se, ns, item, itm[item],
                                               file_names)
                    if data.index(itm) < len(data) - 1:
                        se = etree.SubElement(parent, '{%s}%s' % (ns, elem))
            else:
                for item in ('surname', 'first_name', 'patronymic', 'address',
                             'fact_address', 'email', 'birthdate',
                             'passport_serial', 'passport_number',
                             'passport_agency', 'passport_date', 'phone',
                             'inn', 'sex', 'snils'):
                    if item in data and data[item]:
                        self.__add_element(se, ns, item, data[item],
                                           file_names)
        else:
            if isinstance(data, (date, datetime)):
                se.text = data.strftime('%Y-%m-%d')
            else:
                se.text = data
        # if isinstance(data, dict):
        #     se = etree.SubElement(parent, '{%s}%s' % (ns, elem))
        #     for k, v in data.items():
        #         if not v:
        #             continue
        #         self.__add_element(se, ns, k, v)
        # elif isinstance(data, (list, tuple)):
        #     for v in data:
        #         if not isinstance(v, (dict, list, tuple)):
        #             etree.SubElement(parent, '{%s}%s' % (ns, elem)).text = v
        #         else:
        #             se = etree.SubElement(parent, '{%s}%s' % (ns, elem))
        #             self.__add_element(se, ns, elem, v)
        # elif isinstance(data, (date, datetime)):
        #     etree.SubElement(parent, '{%s}%s' % (ns, elem)).text = \
        #         data.strftime('%Y-%m-%d')
        # else:
        #     etree.SubElement(parent, '{%s}%s' % (ns, elem)).text = data

    def send_request(self, declar):
        operation = 'SendRequest'
        file_names = []

        element = self.proxy.get_element('ns1:MessagePrimaryContent')
        rr = etree.Element('{urn://augo/smev/uslugi/1.0.0}declar',
                           nsmap={'ns1': 'urn://augo/smev/uslugi/1.0.0'})
        self.log.debug(declar)
        for item in ('declar_number', 'service', 'register_date', 'end_date',
                     'object_address', 'AppliedDocument', 'legal_entity',
                     'person', 'confidant', 'Param'):
            if item in declar and declar[item]:
                self.__add_element(rr, 'urn://augo/smev/uslugi/1.0.0', item,
                                   declar[item], file_names)
        # for k, v in declar.items():
        #     if isinstance(v, list):
        #         for val in v:
        #             se = etree.SubElement(
        #                 rr, '{urn://augo/smev/uslugi/1.0.0}%s' % k)
        #             for n, m in val.items():
        #                 if not m:
        #                     continue
        #                 if n == 'file_name':
        #                     file_names.append(m)
        #                 else:
        #                     self.__add_element(
        #                         se, 'urn://augo/smev/uslugi/1.0.0', n, m)
        #     elif isinstance(v, dict):
        #         se = etree.SubElement(
        #             rr, '{urn://augo/smev/uslugi/1.0.0}%s' % k)
        #         for n, m in v.items():
        #             if not m:
        #                 continue
        #             self.__add_element(
        #                 se, 'urn://augo/smev/uslugi/1.0.0', n, m)
        #     else:
        #         if not v:
        #             continue
        #         self.__add_element(
        #             rr, 'urn://augo/smev/uslugi/1.0.0', k, v)
        mpc = element(rr)

        node = self.proxy.create_message(
            self.proxy.service,
            operation, {
                'MessageID': uuid1(),
                'MessagePrimaryContent': mpc
            },
            CallerInformationSystemSignature=etree.Element('Signature'))
        res = node.find('.//{*}SenderProvidedRequestData')
        res.set('Id', 'SIGNED_BY_CALLER')

        if file_names:
            ns = etree.QName(
                node.find('.//{*}MessagePrimaryContent')).namespace
            rahl = etree.SubElement(res, '{%s}RefAttachmentHeaderList' % ns)
            for file_name in file_names:
                rah = etree.SubElement(rahl, '{%s}RefAttachmentHeader' % ns)
                etree.SubElement(rah,
                                 '{%s}uuid' % ns).text = self.__upload_file(
                                     file_name, translate(basename(file_name)))
                f_hash = self.crypto.get_file_hash(file_name)
                etree.SubElement(rah, '{%s}Hash' % ns).text = f_hash
                etree.SubElement(rah, '{%s}MimeType' %
                                 ns).text = guess_type(file_name)[0]
                # etree.SubElement(
                #     rah,
                #     '{%s}SignaturePKCS7' % ns).text = self.crypto.get_file_sign(
                #     file_name)

        # Mark request as test request
        ns = etree.QName(
            node.find('.//{*}SenderProvidedRequestData')).namespace
        etree.SubElement(res, '{%s}TestMessage' % ns)

        node_str = etree.tostring(node)
        res = etree.QName(res)
        node_str = node_str.replace(
            b'<ns0:SenderProvidedRequestData',
            b'<ns0:SenderProvidedRequestData xmlns:ns0="' +
            res.namespace.encode() + b'"')
        self.log.debug(node_str)
        res = self.__xml_part(node_str, b'ns0:SenderProvidedRequestData')
        res = self.__call_sign(res)
        res = node_str.decode().replace('<Signature/>', res)
        self.log.debug(res)
        res = self.__send(operation, res.encode('utf-8'))
        self.log.debug(res)
        return res

    def send_response(self,
                      reply_to,
                      declar_number,
                      register_date,
                      result='FINAL',
                      text='',
                      applied_documents=list(),
                      ftp_user='',
                      ftp_pass=''):
        files = []
        for doc in applied_documents:
            if isinstance(doc, (bytes, str)):
                file_name = os.path.split(doc)[1]
                uuid = self.__upload_file(doc, file_name, ftp_user, ftp_pass)
                files.append({
                    uuid: {
                        'name': file_name,
                        'type': guess_type(doc)[0],
                        'full_name': doc
                    }
                })
            if doc.file:
                uuid = self.__upload_file(doc.file, doc.file_name, ftp_user,
                                          ftp_pass)
                files.append({
                    uuid: {
                        'name': doc.file_name,
                        'type': guess_type(doc.file)[0],
                        'full_name': doc.file
                    }
                })

        operation = 'SendResponse'
        element = self.proxy.get_element('ns1:MessagePrimaryContent')
        rr = etree.Element('{urn://augo/smev/uslugi/1.0.0}requestResponse',
                           nsmap={'ns1': 'urn://augo/smev/uslugi/1.0.0'})
        etree.SubElement(
            rr,
            '{urn://augo/smev/uslugi/1.0.0}declar_number').text = declar_number
        etree.SubElement(
            rr,
            '{urn://augo/smev/uslugi/1.0.0}register_date').text = \
            register_date.strftime('%Y-%m-%d') if isinstance(
                register_date, (date, datetime)) else register_date
        etree.SubElement(rr,
                         '{urn://augo/smev/uslugi/1.0.0}result').text = result
        if text:
            etree.SubElement(rr,
                             '{urn://augo/smev/uslugi/1.0.0}text').text = text
        if files:
            for doc in applied_documents:
                ad = etree.SubElement(
                    rr, '{urn://augo/smev/uslugi/1.0.0}AppliedDocument')
                etree.SubElement(
                    ad,
                    '{urn://augo/smev/uslugi/1.0.0}title').text = \
                    doc.title
                etree.SubElement(
                    ad,
                    '{urn://augo/smev/uslugi/1.0.0}number').text = \
                    doc.number
                etree.SubElement(
                    ad,
                    '{urn://augo/smev/uslugi/1.0.0}date').text = \
                    doc.date
                etree.SubElement(
                    ad,
                    '{urn://augo/smev/uslugi/1.0.0}valid_until').text = \
                    doc.valid_until
                etree.SubElement(
                    ad,
                    '{urn://augo/smev/uslugi/1.0.0}file_name').text = \
                    doc.file_name
                etree.SubElement(
                    ad, '{urn://augo/smev/uslugi/1.0.0}url').text = doc.url
                etree.SubElement(
                    ad,
                    '{urn://augo/smev/uslugi/1.0.0}url_valid_until').text = \
                    doc.url_valid_until

        mpc = element(rr)
        node = self.proxy.create_message(
            self.proxy.service,
            operation, {
                'MessageID': uuid1(),
                'To': reply_to,
                'MessagePrimaryContent': mpc
            },
            CallerInformationSystemSignature=etree.Element('Signature'))
        res = node.find('.//{*}SenderProvidedResponseData')
        res.set('Id', 'SIGNED_BY_CALLER')

        if files:
            ns = etree.QName(
                node.find('.//{*}MessagePrimaryContent')).namespace
            rahl = etree.SubElement(res, '{%s}RefAttachmentHeaderList' % ns)
            for uuid, file in files:
                rah = etree.SubElement(rahl, '{%s}RefAttachmentHeader' % ns)
                etree.SubElement(rah, '{%s}uuid' % ns).text = uuid
                etree.SubElement(rah, '{%s}Hash' %
                                 ns).text = self.crypto.get_file_hash(
                                     file['full_name'])
                etree.SubElement(rah, '{%s}MimeType' % ns).text = file['type']
                # etree.SubElement(
                #     rah,
                #     '{%s}SignaturePKCS7' % ns).text = self.crypto.get_file_sign(
                #     file['full_name'])

        node_str = etree.tostring(node)
        res = etree.QName(res)
        node_str = node_str.replace(
            b'<ns0:SenderProvidedResponseData',
            b'<ns0:SenderProvidedResponseData xmlns:ns0="' +
            res.namespace.encode() + b'"')
        self.log.debug(node_str)
        res = self.__xml_part(node_str, b'ns0:SenderProvidedResponseData')
        res = self.__call_sign(res)
        res = node_str.decode().replace('<Signature/>', res)
        res = self.__send(operation, res.encode('utf-8'))
        self.log.debug(res)
        return res

    def __call_sign(self, xml):
        method_name = 'sign_' + self.method
        self.log.debug('Calling Crypto.%s' % method_name)
        method = getattr(self.crypto, method_name)
        return method(xml)

    def __upload_file(self,
                      file,
                      file_name,
                      ftp_user='******',
                      ftp_pass='******'):
        self.log.debug(file_name)
        addr = urlparse(self.ftp_addr).netloc
        with ftplib.FTP(addr, ftp_user, ftp_pass) as con:
            uuid = str(uuid1())
            res = con.mkd(uuid)
            self.log.debug(res)
            con.cwd(uuid)
            with open(file, 'rb') as f:
                res = con.storbinary('STOR ' + file_name, f)
            self.log.debug(res)
        return uuid

    def __load_file(self, uuid, user, passwd, file_name):
        addr = urlparse(self.ftp_addr).netloc
        f, file_path = tempfile.mkstemp()
        try:
            with ftplib.FTP(addr, user, passwd) as con:
                con.cwd(uuid)
                if file_name[0] == '/':
                    file_name = file_name[1:]
                close(f)
                with open(file_path, 'wb') as f:
                    con.retrbinary('RETR ' + file_name, f.write)
        except ftplib.all_errors as e:
            self.log.error(str(e))
            write(f, str(e).encode('cp1251'))
            close(f)
            return file_path, e
        return file_path

    def __send(self, operation, msg):
        kw = {'_soapheaders': self.proxy.service._client._default_soapheaders}
        response = self.proxy.transport.post(
            self.proxy.service._binding_options['address'], msg, kw)
        res = self.proxy.service._binding.process_reply(
            self.proxy.service._client,
            self.proxy.service._binding.get(operation), response)
        # if not res and b'--uuid:' in response.content:
        #     res = response.content[
        #               response.content.index(b'Content-Type:'):]
        #     res = res[:res.index(b'--uuid:')]
        #     self.log.debug(res)
        return res

    def __xml_part(self, xml_as_str, tag_name):
        """
        Cuts the XML part from `xml_as_str` bounded by tag `tag_name`

        :param xml_as_str: String with source XML

        :param tag_name: XML tag name bounds target XML part
        """
        b_idx = xml_as_str.index(tag_name) - 1
        try:
            if isinstance(tag_name, str):
                tgn = tag_name + '>'
            else:
                tgn = tag_name + b'>'
            e_idx = xml_as_str.index(tgn,
                                     b_idx + len(tag_name)) + len(tag_name) + 1
        except ValueError:
            if isinstance(tag_name, str):
                tgn = tag_name + ' '
            else:
                tgn = tag_name + b' '
            e_idx = xml_as_str.index(tgn,
                                     b_idx + len(tag_name)) + len(tag_name) + 1
        return xml_as_str[b_idx:e_idx]
Ejemplo n.º 7
0
})
token = result['LoginResult']

client = Client('wsdl/inventory.wsdl', strict=False)

array_of_filter_field = [{
    "FilterField": {
        "Name": "Name",
        "SelectedOperator": "OperationEquals",
        "Value": "LP"
    }
}]
filter = {"Filters": array_of_filter_field}
pager = {
    "StartElement": 0,
    "Descending": False,
    "NumberOfElements": 10,
    "OrderByProperty": None
}

node = client.create_message(client.service,
                             'GetAllProductsFiltered',
                             pager=pager,
                             filter=filter,
                             sessionToken=token)
print("********")
print(etree.tostring(node, pretty_print=True))
"""
>>>
b'<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">\n  <soap-env:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">\n    <wsa:Action>http://tempuri.org/IInventoryService/GetAllProductsFiltered</wsa:Action>\n    <wsa:MessageID>urn:uuid:561120a3-9d97-4556-afc4-55cff9be79d6</wsa:MessageID>\n    <wsa:To>http://ims.surfnet.nl:8095/Inventory/iInventoryHttp</wsa:To>\n  </soap-env:Header>\n  <soap-env:Body>\n    <ns0:GetAllProductsFiltered xmlns:ns0="http://tempuri.org/">\n      <ns0:pager>\n        <ns1:Descending xmlns:ns1="http://schemas.datacontract.org/2004/07/PresentationModel.DatabaseFilter">false</ns1:Descending>\n        <ns2:NumberOfElements xmlns:ns2="http://schemas.datacontract.org/2004/07/PresentationModel.DatabaseFilter">10</ns2:NumberOfElements>\n        <ns3:StartElement xmlns:ns3="http://schemas.datacontract.org/2004/07/PresentationModel.DatabaseFilter">0</ns3:StartElement>\n      </ns0:pager>\n      <ns0:filter>\n        <ns4:Filters xmlns:ns4="http://schemas.datacontract.org/2004/07/PresentationModel.DatabaseFilter">\n          <ns4:FilterField>\n            <ns4:Name>Name</ns4:Name>\n            <ns4:SelectedOperator>OperationEquals</ns4:SelectedOperator>\n            <ns4:Value>LP</ns4:Value>\n          </ns4:FilterField>\n        </ns4:Filters>\n      </ns0:filter>\n      <ns0:sessionToken>a9867af3-c0f5-46a9-99c3-c489fd208cf0</ns0:sessionToken>\n    </ns0:GetAllProductsFiltered>\n  </soap-env:Body>\n</soap-env:Envelope>\n'
"""
Ejemplo n.º 8
0
#random number function
def rn1():
    random.seed(int(datetime.now().strftime("%f")) * 1000)
    rn1 = random.random() * 1000000000
    return int(rn1)


#ID input from user
def getID():
    ID = str(input("\nEnter ID: \n"))
    ID = ID.upper()
    return "ftp://*****:*****@10.10.70.200/UMS/VOD/" + ID + "/" + ID + ".xml"


#WSDL URL
client = Client('http://10.226.187.29:5954/bme/services/AMSService?WSDL')

#RAW SOAP message check
messagexml = client.create_message(client.service,
                                   'notify',
                                   notifyRequest={
                                       'MD5CcheckSum': "",
                                       'NO': rn1(),
                                       'URL': getID()
                                   })
xml1 = tostring(messagexml, encoding="unicode")
print(xml1)

#POST SOAP message
#print(client.service.notify(notifyRequest={'MD5CcheckSum':"", 'NO':rn1(), 'URL':getID()"}))
Ejemplo n.º 9
0
        ipRecordFilesService=
        'http://192.168.1.37:8080/ProsurOfficeWS/IPOfficeWS',
        files=[file1],
        distinctiveSignType='MARCA',
        expiration='2021-06-20-03:00',
        logoDescription='lorem ipsum consequat imperdiet duis',
        niceClasses=[niceClass],
        registrationDate='2005-05-26'
        #'trigger':'afd;',
    )

    user = '******'

    #uncomment nxtlns to see the soap message to send as xml
    node = client.create_message(client.service,
                                 'getRecord',
                                 ipRecord=ds,
                                 user=user)
    print(etree.tostring(node, pretty_print=True))

    #rec = client.service.getRecord(ipRecord,user)
    rec = client.service.createRecord(ds, user)

    #trying to see the methods of the response object
    print(dir(rec.ipRecordId))

    print(rec.ipRecordId)

    print(type(rec))

    for attr in rec:
        print(attr)
Ejemplo n.º 10
0
request_data = {
    'ExecuteDataSourceRequest': {
        'DataSourceKey': "2272",
        'InputParameters': {
            'InputParameter': {
                'Name': 'Workcenter_Key',
                'Value': '61324',
                'Required': 'false',
                'Output': 'false'
            }
        }
    }
}

# node=client.create_message(client.service, 'ExecuteDataSource',**request_data2)
node = client.create_message(client.service, 'ExecuteDataSource',
                             **request_data)
tree = ET.ElementTree(node)
# etree_to_string(tree).de.decode()
tree.write('test2.xml')
#     client.service.ExecuteDataSource(**request_data2)
# except Fault as error:
#     print(ET.tostring(error.detail))
# print(history.last_received)

response = client.service.ExecuteDataSource(**request_data)
# dsn = response.get('DataSourceName')
dsn = response['DataSourceName']
print(dsn)

#Here 'request_data' is the request parameter dictionary.
#Assuming that the operation named 'sendData' is defined in the passed wsdl.
Ejemplo n.º 11
0
def get_feed():

    user_name_token = username_password()
    signature = binary_signature_timestamp()

    client = Client('tweaked_xml/wsdl.xml', wsse=[user_name_token, signature], plugins=[WsAddressingPlugin()])
    # client.set_ns_prefix('', 'http://information.gateway.ofsted.gov.uk/ispp')
    # client.set_ns_prefix('s', 'http://www.w3.org/2003/05/soap-envelope')
    client.set_ns_prefix('a', 'http://www.w3.org/2005/08/addressing')
    client.set_ns_prefix('u', 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd')
    parameters = {
        'LocalAuthorityCode': 825
      }
    
    # Add a "ReplyTo/Address"
    header = xsd.Element(
        '{http://www.w3.org/2005/08/addressing}ReplyTo',
        xsd.ComplexType([
            xsd.Element(
                '{http://www.w3.org/2005/08/addressing}Address',
                xsd.String()),
        ])
    )
    header_value = header(Address='http://www.w3.org/2005/08/addressing/anonymous')
    
    # Request document
    envelope = client.create_message(client.service, 'GetLocalAuthorityChildcareRegister', localAuthorityRequest=parameters, _soapheaders=[header_value])
    
    # # Update a few tricky values

    header_tag = envelope.find('{http://www.w3.org/2003/05/soap-envelope}Header')
    security_tag = header_tag.find('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security')

    # Mark the Timestamp tag for signing:
    timestamp_tag = security_tag.find('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Timestamp')
    timestamp_tag.attrib['{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id']="_0"

    # De-duplicate and tweak the To tag for signing:
    for child_tag in header_tag:
        if child_tag.tag == '{http://www.w3.org/2005/08/addressing}To':
            to_tag = child_tag
            insert_index = header_tag.index(child_tag)
            header_tag.remove(child_tag)
    header_tag.insert(insert_index, to_tag)
    to_tag.attrib['{http://www.w3.org/2003/05/soap-envelope}mustUnderstand']="1"
    to_tag.attrib['{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id']="_1"

    # Remove the standard signature so we can replace it with what's needed for this specific implementation:
    signature_tag = security_tag.find('{http://www.w3.org/2000/09/xmldsig#}Signature')
    signature_index = security_tag.index(signature_tag)
    binary_security_token_tag = security_tag.find('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken')
    security_tag.remove(signature_tag)
    security_tag.remove(binary_security_token_tag)

    # Re-sign in the way that's expected by this service:
    signer = XMLSigner(
        method=methods.detached,
        digest_algorithm='sha1',
        signature_algorithm='rsa-sha1',
        c14n_algorithm='http://www.w3.org/2001/10/xml-exc-c14n#'
        )
    private = get_secret('private_key')
    public = get_secret('certificate')
    signature = signer.sign(envelope, key=private, cert=public, reference_uri=['_0', '_1'])
    security_tag.insert(signature_index, signature)

    # Add the signature to the document:

    xmlstr = str(etree.tostring(envelope, encoding='unicode', pretty_print=True))
    print(f" *** Signed:\n {xmlstr}")

    for tag in security_tag:
        print(tag.tag)
        for subtag in tag:
            print(f' - {subtag.tag}')

    # header = envelope.find('{http://www.w3.org/2003/05/soap-envelope}Header')
    # security = header.find('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security')
    # signature = security.find('{http://www.w3.org/2000/09/xmldsig#}Signature')
    # signature_value = signature.find('{http://www.w3.org/2000/09/xmldsig#}SignatureValue')
    # binary_security_token = security.find('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}BinarySecurityToken')

    # # Reformat base-64 values without line-wrapping 
    # # # (possible the server isn't reading them correctly otherwise)
    # nowrapping(signature_value)
    # nowrapping(binary_security_token)

    # # Sprinkle in some 'mustUnderstand' just in case
    # mustunderstanders = [
    #         '{http://www.w3.org/2005/08/addressing}Action', 
    #         '{http://www.w3.org/2005/08/addressing}To', 
    #         '{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}Security'
    #         ]
    # for child in header:
    #     if child.tag in mustunderstanders:
    #         print(f"Adding mustUnderstand to {child.tag}")
    #         child.attrib['{http://www.w3.org/2003/05/soap-envelope}mustUnderstand']="1"

    # # Temp: c14n test
    # print("...")
    # for child in header:
    #     if child.tag == '{http://www.w3.org/2005/08/addressing}Action':
    #         print(f"C14nning: {child.tag}")
    # print("...")

    
    # # Pop in a couple of missing ids
    # signer = XMLSigner(
    #     method=methods.detached,
    #     digest_algorithm='sha1',
    #     signature_algorithm='rsa-sha1',
    #     c14n_algorithm='http://www.w3.org/2001/10/xml-exc-c14n#'
    #     )
    # ref = 0
    # for child in header:
    #     if child.tag == '{http://www.w3.org/2005/08/addressing}To':
    #         child.attrib['{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id'] = "_1"
    #         private = get_secret('private_key')
    #         public = get_secret('certificate')
    #         signed_root = signer.sign(child, key=private, cert=public, key_info='ouagadougou', reference_uri=f'_{ref}')
    #         ref = ref + 1
    #         #signed_root = XMLSigner().sign(child, key=private, cert=public)
    # xmlstr = str(etree.tostring(signed_root, encoding='unicode', pretty_print=True))
    # print(f" *** Signed:\n {xmlstr}")
    # for child in security:
    #     if child.tag == '{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd}UsernameToken':
    #         child.attrib['{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd}Id'] = "_2"
    
    # # Delete duplicated elements
    # duplicates = ['{http://www.w3.org/2005/08/addressing}Action', '{http://www.w3.org/2005/08/addressing}To', '{http://www.w3.org/2005/08/addressing}MessageID']
    # deduped = {}
    # insert_index = 0
    # for child in header:
    #     if child.tag in duplicates:
    #         deduped[child.tag] = child
    #         header.remove(child)
    #     if child.tag == '{http://www.w3.org/2005/08/addressing}ReplyTo':
    #         insert_index = header.index(child)

    # # Re-insert the de-duped elements
    # for child in deduped.values():
    #     insert_index = insert_index + 1
    #     header.insert(insert_index, child)

    # for child in header:
    #     print(f' - {child.tag[child.tag.rindex("}")+1:]}  {child.tag}  -->  {child.attrib}')
    #     if child.tag=='{http://www.w3.org/2005/08/addressing}ReplyTo':
    #         print(header.index(child))
    
    # xmlstr =  minidom.parseString(ET.tostring(node)).toprettyxml(indent="   ")
    #xmlstr = str(etree.tostring(signed, encoding='unicode', pretty_print=True))
    # print(type(xmlstr))

    # xmlstr=tweak(xmlstr)

    ##print(xmlstr)
    # if os.path.isdir('/output'):
    #     with open('/output/actual1.xml', 'w+') as f:
    #         f.write(xmlstr)
    #         print("Saved generated XML message.")
    if os.path.isdir('../secrets/compare'):
        with open('../secrets/compare/actual1.xml', 'w+') as f:
            f.write(xmlstr)
            print("Saved generated XML message..............................")

    response = call_proxy(envelope)

    if response.status_code != 200:
        print(f"{response.status_code}: {response.text}")

    #return minidom.parseString(response.text)
    #ET.tostring(feed, encoding='unicode').toprettyxml(indent="   ")

    #return Response(f"{response.status_code} -- {response.text}"), 200
    #return "Fin." 
    return Response(response.text, mimetype='text/xml'), response.status_code