예제 #1
0
    def test_weak_authentication_methods_soap_passwordtext_auth(
            self, target, port, uri, adm_user, adm_password):
        token = UsernameToken(username=adm_user,
                              password=adm_password,
                              use_digest=False)
        message = etree.fromstring(self.GetUsers)
        token.apply(message, message[0])

        try:
            rsp = requests.post('http://{host}:{port}{uri}'.format(host=target,
                                                                   port=port,
                                                                   uri=uri),
                                etree.tostring(message).decode('utf-8'),
                                headers=self.base_headers,
                                timeout=30)
        except Exception as e:
            if e.args[0].args[0] == 'Connection aborted.':
                logger.info('Exception during request: Connection aborted')
            else:
                logger.error('Exception during request:\n{}'.format(e))
                assert False
        else:
            if rsp.status_code == 400 or rsp.status_code == 401:
                logger.info('SOAP PasswordText authentication rejected')
            elif rsp.status_code == 200:
                logger.critical('SOAP PasswordText authentication accepted')
                assert False
예제 #2
0
    def _send_requests(self, target, port, uri, user, password, n):
        """
        Send a n POST requests to http://target:port/uri with SOAP authentication and calculate the average of
        response time
        :param target: IP address
        :param port: Port number
        :param uri: URI
        :param user: User for the SOAP authentication
        :param password: Password for the SOAP authentication
        :param n: Number of requests to send
        :return: Average of response time
        """
        token = UsernameToken(username=user,
                              password=password,
                              use_digest=True)
        message = etree.fromstring(self.GetUsers)
        token.apply(message, message[0])

        average = datetime.timedelta()

        for i in range(n):
            try:
                rsp = requests.post('http://{host}:{port}{uri}'.format(
                    host=target, port=port, uri=uri),
                                    etree.tostring(message).decode('utf-8'),
                                    headers=self.base_headers,
                                    timeout=30)
            except Exception as e:
                logger.error('Exception during request:\n{}'.format(e))
                assert False
            else:
                average += rsp.elapsed

        return average / n
예제 #3
0
    def test_soap_authentication_with_past_created_value(
            self, target, port, uri, adm_user, adm_password, minutes):
        token = UsernameToken(username=adm_user,
                              password=adm_password,
                              use_digest=True,
                              created=datetime.datetime.utcnow() -
                              datetime.timedelta(minutes=minutes))
        message = etree.fromstring(self.GetUsers)
        token.apply(message, message[0])

        try:
            rsp = requests.post('http://{host}:{port}{uri}'.format(host=target,
                                                                   port=port,
                                                                   uri=uri),
                                etree.tostring(message).decode('utf-8'),
                                headers=self.base_headers,
                                timeout=30)
        except Exception as e:
            if e.args[0].args[0] == 'Connection aborted.':
                logger.info(
                    'Request from the past is rejected (Connection aborted)')
            else:
                logger.error('Exception during request:\n{}'.format(e))
                assert False
        else:
            if rsp.status_code == 400 or rsp.status_code == 401:
                logger.info(
                    'Request from the past is rejected ({} minutes delay)'.
                    format(minutes))
            else:
                logger.critical(
                    'Request from the past is accepted ({} minutes delay)'.
                    format(minutes))
                assert False
예제 #4
0
    def test_authentication_bypass_ldap_injection_soap(self, target, port, uri,
                                                       adm_user):
        for i in self.ldap_injections:
            user = adm_user + i
            token = UsernameToken(username=user, password='', use_digest=True)
            message = etree.fromstring(self.GetUsers)
            token.apply(message, message[0])

            try:
                rsp = requests.post('http://{host}:{port}{uri}'.format(
                    host=target, port=port, uri=uri),
                                    etree.tostring(message).decode('utf-8'),
                                    headers=self.base_headers,
                                    timeout=30)
            except Exception as e:
                logger.error('Exception during request:\n{}'.format(e))
                assert False
            else:
                if rsp.status_code == 200:
                    logger.critical(
                        'Authentication bypass by LDAP injection at SOAP level: {}'
                        .format(user))
                    assert False

        logger.info(
            'No authentication bypass by LDAP injection at SOAP level found')
예제 #5
0
    def test_replay_attack_soap_level(self, target, port, uri, adm_user,
                                      adm_password, delay):
        token = UsernameToken(username=adm_user,
                              password=adm_password,
                              use_digest=True)
        message = etree.fromstring(self.GetUsers)
        token.apply(message, message[0])

        try:
            rsp = requests.post('http://{host}:{port}{uri}'.format(host=target,
                                                                   port=port,
                                                                   uri=uri),
                                etree.tostring(message).decode('utf-8'),
                                headers=self.base_headers,
                                timeout=30)
        except Exception as e:
            logger.error('Exception during request:\n{}'.format(e))
            assert False
        else:
            if rsp.status_code != 200:
                logger.error(
                    'Unexpected return code {} during first request (SOAP auth)'
                    .format(rsp.status_code))
                assert False
            else:
                try:
                    time.sleep(delay)
                    rsp = requests.post(
                        'http://{host}:{port}{uri}'.format(host=target,
                                                           port=port,
                                                           uri=uri),
                        etree.tostring(message).decode('utf-8'),
                        headers=self.base_headers,
                        timeout=30)
                except Exception as e:
                    if e.args[0].args[0] == 'Connection aborted.':
                        logger.info(
                            'Replay attack stopped at SOAP level (Connection aborted)'
                        )
                    else:
                        logger.error('Exception during request:\n{}'.format(e))
                        assert False
                else:
                    if rsp.status_code == 200:
                        logger.critical(
                            'Replay attack successful at SOAP level (delay={}s)'
                            .format(delay))
                        assert False
                    elif rsp.status_code == 400 or rsp.status_code == 401:
                        logger.info(
                            'Replay attack stopped at SOAP level (delay={}s)'.
                            format(delay))
                    else:
                        logger.error(
                            'Unexpected return code {} when replay at SOAP level'
                            .format(rsp.status_code))
                        assert False
예제 #6
0
 def setup_client(self):
     if self.is_use_proxy:
         self.sessions.proxies = self.proxies
         self.wsdl_client = Client(
             self.wsdl_url,
             wsse=UsernameToken(self.user_name, self.password),
             transport=Transport(session=self.sessions))
     else:
         self.wsdl_client = Client(self.wsdl_url,
                                   wsse=UsernameToken(
                                       self.user_name, self.password))
예제 #7
0
def test_password_digest_custom(monkeypatch):
    monkeypatch.setattr(os, 'urandom', lambda x: b'mocked-random')

    envelope = load_xml("""
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        >
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """)

    created = datetime.datetime(2016, 6, 4, 20, 10)
    token = UsernameToken('michael',
                          password_digest='12345',
                          use_digest=True,
                          nonce='iets',
                          created=created)
    envelope, headers = token.sign(envelope, {})
    expected = """
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap-env:Header>
            <ns0:Security xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
              <ns0:UsernameToken>
                <ns0:Username>michael</ns0:Username>
                <ns0:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">12345</ns0:Password>
                <ns0:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">aWV0cw==</ns0:Nonce>
                <ns0:Created xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2016-06-04T20:10:00+00:00</ns0:Created>
              </ns0:UsernameToken>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """  # noqa
    assert_nodes_equal(envelope, expected)
예제 #8
0
def test_password_digest_custom(monkeypatch):
    monkeypatch.setattr(os, 'urandom', lambda x: b'mocked-random')

    envelope = load_xml("""
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        >
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """)

    created = datetime.datetime(2016, 6, 4, 20, 10)
    token = UsernameToken(
        'michael', password_digest='12345', use_digest=True,
        nonce='iets', created=created)
    envelope, headers = token.sign(envelope, {})
    expected = """
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap-env:Header>
            <ns0:Security xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
              <ns0:UsernameToken>
                <ns0:Username>michael</ns0:Username>
                <ns0:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">12345</ns0:Password>
                <ns0:Nonce>aWV0cw==</ns0:Nonce>
                <ns0:Created xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2016-06-04T20:10:00+00:00</ns0:Created>
              </ns0:UsernameToken>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """  # noqa
    assert_nodes_equal(envelope, expected)
예제 #9
0
 def wsse(self, wsse):
     """Sets the wsse property of the class"""
     if isinstance(wsse, UsernameToken):
         self.__wsse = wsse
     elif isinstance(wsse, tuple) and len(wsse) == 2:
         self.__wsse = UsernameToken(wsse[0], wsse[1])
     elif wsse is None and os.access(self.wsse_path, os.R_OK):
         conf = ConfigParser()
         conf.read(self.wsse_path)
         self.__wsse = UsernameToken(conf['wsse']['username'],
                                     conf['wsse']['password'])
     else:
         username, password = self.__get_login()
         self.__wsse = UsernameToken(username, password)
예제 #10
0
def test_password_prepared():
    envelope = load_xml("""
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        >
          <soap-env:Header xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <ns0:Security>
              <ns0:UsernameToken/>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """)  # noqa

    token = UsernameToken('michael', 'geheim')
    envelope, headers = token.sign(envelope, {})
    expected = """
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap-env:Header xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <ns0:Security>
              <ns0:UsernameToken>
                <ns0:Username>michael</ns0:Username>
                <ns0:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">geheim</ns0:Password>
              </ns0:UsernameToken>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """  # noqa
    assert_nodes_equal(envelope, expected)
예제 #11
0
def test_password_prepared():
    envelope = load_xml("""
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        >
          <soap-env:Header xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <ns0:Security>
              <ns0:UsernameToken/>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """)  # noqa

    token = UsernameToken('michael', 'geheim')
    envelope, headers = token.sign(envelope, {})
    expected = """
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap-env:Header xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
            <ns0:Security>
              <ns0:UsernameToken>
                <ns0:Username>michael</ns0:Username>
                <ns0:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">geheim</ns0:Password>
              </ns0:UsernameToken>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """  # noqa
    assert_nodes_equal(envelope, expected)
예제 #12
0
def test_password_digest(monkeypatch):
    monkeypatch.setattr(os, 'urandom', lambda x: b'mocked-random')

    envelope = load_xml("""
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        >
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """)

    token = UsernameToken('michael', 'geheim', use_digest=True)
    envelope, headers = token.sign(envelope, {})
    expected = """
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap-env:Header>
            <ns0:Security xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
              <ns0:UsernameToken>
                <ns0:Username>michael</ns0:Username>
                <ns0:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">hVicspAQSg70JNhe67OHqD9gexc=</ns0:Password>
                <ns0:Nonce>bW9ja2VkLXJhbmRvbQ==</ns0:Nonce>
                <ns0:Created xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2016-05-08T12:00:00+00:00</ns0:Created>
              </ns0:UsernameToken>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """  # noqa
    assert_nodes_equal(envelope, expected)
예제 #13
0
def test_password_digest(monkeypatch):
    monkeypatch.setattr(os, 'urandom', lambda x: b'mocked-random')

    envelope = load_xml("""
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        >
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """)

    token = UsernameToken('michael', 'geheim', use_digest=True)
    envelope, headers = token.sign(envelope, {})
    expected = """
        <soap-env:Envelope
            xmlns:ns0="http://example.com/stockquote.xsd"
            xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
            xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
          <soap-env:Header>
            <ns0:Security xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
              <ns0:UsernameToken>
                <ns0:Username>michael</ns0:Username>
                <ns0:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">hVicspAQSg70JNhe67OHqD9gexc=</ns0:Password>
                <ns0:Nonce>bW9ja2VkLXJhbmRvbQ==</ns0:Nonce>
                <ns0:Created xmlns:ns0="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2016-05-08T12:00:00+00:00</ns0:Created>
              </ns0:UsernameToken>
            </ns0:Security>
          </soap-env:Header>
          <soap-env:Body>
            <ns0:TradePriceRequest>
              <tickerSymbol>foobar</tickerSymbol>
              <ns0:country/>
            </ns0:TradePriceRequest>
          </soap-env:Body>
        </soap-env:Envelope>
    """  # noqa
    assert_nodes_equal(envelope, expected)
예제 #14
0
    def __init__(self, *args, **kwargs):
        """This method intializes the varible that are used in establishing connection to the ACS.
           The method intializes an HTTP SOAP client which will authenticate with the ACS server.

        :param *args: the arguments to be used if any
        :type *args: tuple
        :param **kwargs: extra args to be used if any (mainly contains username, password, ipadress and port)
        :type **kwargs: dict
        """
        self.args = args
        self.kwargs = kwargs
        self.username = self.kwargs['username']
        self.password = self.kwargs['password']
        self.ipaddr = self.kwargs['ipaddr']
        self.port = self.kwargs.get('port', None)

        if self.port is not None:
            target = self.ipaddr + ":" + self.port
        else:
            target = self.ipaddr

        self.wsdl = "http://" + target + "/live/CPEManager/DMInterfaces/soap/getWSDL"

        session = Session()
        session.auth = HTTPBasicAuth(self.username, self.password)

        self.client = Client(wsdl=self.wsdl,
                             transport=Transport(session=session),
                             wsse=UsernameToken(self.username, self.password))
예제 #15
0
    def __init__(self,
                 wsse=None,
                 transport=None,
                 service_name=None,
                 port_name=None,
                 plugins=None,
                 strict=True,
                 xml_huge_tree=False,
                 store_login=True):
        self.wsse_path = os.getenv('FFIEC_USER_CONF',
                                   os.path.join(os.environ['HOME'], '.ffiec'))
        self.wsse = wsse
        zeep.Client.__init__(self, self.wsdl, self.wsse, transport,
                             service_name, port_name, plugins, strict,
                             xml_huge_tree)

        # Ensure that user login (i.e., the wsse variable) was good
        retry = self.__check_login()
        while retry and retry.startswith(('y', 'Y')):
            username, password = self.__get_login()
            self.wsse = UsernameToken(username, password)
            zeep.Client.__init__(self, self.wsdl.location, self.wsse,
                                 transport, service_name, port_name, plugins,
                                 strict, xml_huge_tree)
            retry = self.__check_login()

        if retry is None:
            # User gained access; save login info (as needed) for later use
            wsse_via_file = wsse is None and os.access(self.wsse_path, os.F_OK)
            if store_login and not wsse_via_file:
                self.__store_login()
예제 #16
0
파일: auth.py 프로젝트: zensourcer/workday
    def __init__(
        self,
        username,
        password,
        private_certificate_path,
        public_certificate_path,
        optional_password=None,
    ):
        """
        WS-Security X509 encoded requests with credentials

        :param username: Username to authenticate as, typically user@tenant
        :type  username: ``str``

        :param password: Password for the integration user
        :type  password: ``str``

        :param private_certificate_path: The path to the x509 private cert 
        :type  private_certificate_path: ``str``

        :param public_certificate_path: The path to the x509 public cert 
        :type  public_certificate_path: ``str``

        :param optional_password: (Optional) password for the x509 private cert
        :type  optional_password: ``str``
        """
        self._kwargs = {
            "wsse": [
                UsernameToken(username, password),
                Signature(private_certificate_path, public_certificate_path,
                          optional_password),
            ]
        }
예제 #17
0
def get_jpt(teryt):
    client = Client(
        "https://uslugaterytws1test.stat.gov.pl/wsdl/terytws1.wsdl",
        wsse=UsernameToken(username='******', password='******'))
    client.create_service(
        binding_name='{http://tempuri.org/}custom',
        address='https://uslugaterytws1test.stat.gov.pl/terytws1.svc')
    if client.service.CzyZalogowany() == True:
        factory = client.type_factory('ns2')
        identyfiks = factory.identyfikatory(terc=teryt)
        list_identyfiks = factory.ArrayOfidentyfikatory(identyfiks)
        jpt = client.service.WyszukajJednostkeWRejestrze(
            identyfiks=list_identyfiks,
            kategoria='3',
            DataStanu=datetime.now())
        if jpt != None:
            jpt = jpt[0]
            result = {
                i: jpt[i]
                for i in jpt
                if i == 'GmiNazwa' or i == 'Powiat' or i == 'Wojewodztwo'
            }
            return result
    else:
        return None
예제 #18
0
def get_services(**options):
    """
    This function builds the services dictionary, which is a simple dict of names-to-implementation used by bonobo
    for runtime injection.

    It will be used on top of the defaults provided by bonobo (fs, http, ...). You can override those defaults, or just
    let the framework define them. You can also define your own services and naming is up to you.

    :return: dict
    """

    wsdl_client = Client(
        options['wd_base_url'] +
        'ccx/service/{tenant}/Human_Resources/'.format(
            tenant=options['wd_tenant']) + WORKDAY_API_VERSION + '?wsdl',
        wsse=UsernameToken(
            "%s@%s" % (options['wd_username'], options['wd_tenant']),
            options['wd_password'],
            use_digest=False),
    )

    wsdl_client.set_ns_prefix('bsvc', 'urn:com.workday/bsvc')

    return {
        'workday_url': options['wd_base_url'],
        'workday_tenant': options['wd_tenant'],
        'workday_soap': wsdl_client,
    }
예제 #19
0
def get_workers():

    with open('config.yml', 'r') as cfg_f:
        config = yaml.safe_load(cfg_f)
    username = config['workday_username']
    password = config['workday_password']

    # Soap client
    # https://community.workday.com/sites/default/files/file-hosting/productionapi/Human_Resources/v30.2/Human_Resources.html
    # https://community.workday.com/sites/default/files/file-hosting/productionapi/Human_Resources/v30.2/Get_Workers.html
    wsdl_url = 'https://community.workday.com/sites/default/files/file-hosting/productionapi/Human_Resources/v30.2/Human_Resources.wsdl'
    client = zeep.Client(wsdl_url, wsse=UsernameToken(username, password))

    # Get service location
    # Login to workday, search for Public Web Service, Click on '...' next to Human Resources, Web Service -> View WSDL
    # This will give you an xml file. Open it in a text editor, scroll to the bottom, look for soapbind:address
    # copy the 'location' value
    # also take notice of wsdl:port, see 'binding' is 'wd-wsdl:Human_ResourcesBinding'
    location = 'https://SERVICE-INST.myworkday.com/ccx/service/TENANT/Human_Resources/v30.2'

    # Get binding path
    # http://docs.python-zeep.org/en/master/client.html#creating-new-serviceproxy-objects
    # Open the wsdl_url, search for xmlns:wd-wsdl, you will see 'urn:com.workday/bsvc/Human_Resources'
    # combine with what we saw from 'binding' above
    binding_path = '{urn:com.workday/bsvc/Human_Resources}Human_ResourcesBinding'

    # create service
    service = client.create_service(binding_path, location)
    result = service.Get_Workers()
    print(result)
예제 #20
0
def savedocfromfstore(key, numbso):
    head = {"ip": "127.0.0.1", "login": "******", "mac": "digitmacaddress"}
    client = Client("http://cc-haproxy.rgs.ru:28080/filestore?wsdl",
                    wsse=UsernameToken('yourlogin',
                                       'yourpassword',
                                       use_digest=True))
    keyvalue = {"key": key}
    result = client.service.readFile(head, keyvalue)
    doc = (result["document"])
    cont = doc["content"]
    typedoc = doc["mimeType"]
    type = ""
    i = 0
    for char in typedoc:
        i = i + 1
        if char == "/":
            n = i
    doctype = typedoc[n:i]
    path = os.getcwd() + """/ExportFstore/"""
    res = charinstring(key, '/')
    if res == 1:
        src = key
        key = src.split('/')[5]
    print(key)
    filename = path + key + "_" + numbso + "." + doctype
    out_file = open(filename, "wb")
    out_file.write(cont)
    out_file.close()
    return ("777")
예제 #21
0
    def __call__(self):
        """
        """
        from zeep import Client
        from zeep.wsse.username import UsernameToken
        client = Client(
            'https://webgate.ec.europa.eu/etranslation/si/WSEndpointHandlerService?WSDL',
            wsse=UsernameToken('Marine_EEA_20180706', 'xxxyyyzzz'))
        # todo get the password from ENV

        client.service.translate({
            'priority': '5',
            'external-reference': '1',
            'caller-information': {
                'application': 'Marine_EEA_20180706',
                'username': '******'
            },
            'text-to-translate': 'Hausaufgabe',
            'source-language': 'DE',
            'target-languages': {
                'target-language': 'EN'
            },
            'domain': 'SPD',
            'requester-callback':
            'https://wise-test.eionet.europa.eu/translation_callback',
            'destinations': {
                'http-destination':
                'https://wise-test.eionet.europa.eu/translation_callback'
            }
        })
예제 #22
0
        def try_login_soap(n):
            i = 1
            while i <= n:
                token = UsernameToken(username=adm_user,
                                      password=adm_password + 'bad',
                                      use_digest=True)
                message = etree.fromstring(self.GetUsers)
                token.apply(message, message[0])

                try:
                    rsp = requests.post(
                        'http://{host}:{port}{uri}'.format(host=target,
                                                           port=port,
                                                           uri=uri),
                        etree.tostring(message).decode('utf-8'),
                        headers=self.base_headers,
                        timeout=30)
                except Exception as e:
                    if e.args[0].args[0] != 'Connection aborted.':
                        logger.error('Exception during request:\n{}'.format(e))
                        assert False
                else:
                    if rsp.status_code != 400:
                        logger.error(
                            'Receive unexpected {} status code (SOAP auth)'.
                            format(rsp.status_code))
                        assert False

                i += 1

            token = UsernameToken(username=adm_user,
                                  password=adm_password,
                                  use_digest=True)
            message = etree.fromstring(self.GetUsers)
            token.apply(message, message[0])

            try:
                rsp = requests.post('http://{host}:{port}{uri}'.format(
                    host=target, port=port, uri=uri),
                                    etree.tostring(message).decode('utf-8'),
                                    headers=self.base_headers,
                                    timeout=30)
            except Exception as e:
                if e.args[0].args[0] == 'Connection aborted.':
                    logger.critical(
                        'Account locked out after {} SOAP login attempt (Connection aborted)'
                        .format(i))
                    assert False
                else:
                    logger.error('Exception during request:\n{}'.format(e))
                    assert False
            else:
                if rsp.status_code != 200:
                    logger.critical(
                        'Account locked out after {} SOAP login attempt (code {})'
                        .format(i, rsp.status_code))
    def __init__(self):
        super().__init__()
        self._logger = logging.getLogger(__name__)

        self.client = \
            zeep.Client(
                wsdl=self.wsdl,
                wsse=UsernameToken(username=self.obs_username, password=self._get_dbsync_pw(), ))
예제 #24
0
파일: teryt.py 프로젝트: osm-pl/osm-borders
def _get_teryt_client(session: requests.Session = requests.Session()
                      ) -> zeep.Client:
    __log = logging.getLogger(__name__ + ".get_teryt_client")
    __log.info("Connecting to TERYT web service")
    wsdl = "https://uslugaterytws1.stat.gov.pl/wsdl/terytws1.wsdl"
    wsse = UsernameToken("osmaddrtools", "#06JWOWutt4")
    return zeep.Client(wsdl=wsdl,
                       wsse=wsse,
                       transport=zeep.Transport(session=session))
예제 #25
0
    def _create_wsse_header(self, username, password):

        created = datetime.now()
        token = UsernameToken(username=username,
                              password=sha256(password.encode()).hexdigest(),
                              use_digest=True,
                              created=created)

        return token
예제 #26
0
    def setup(self):
        self.client = zeep.Client(wsdl=self.wsdl_url,
                                  wsse=UsernameToken(self.username,
                                                     self.token))

        if not self.client.service.TestUserAccess():
            raise ValueError(
                'API authentication failed, check your username and token - did you rotate your token?'
            )
예제 #27
0
 def __init__(self, site):
     self.site = site
     self.timestamp = timezone.now()
     self.username = config.chargepoint_api_keys['{}_api_username'.format(
         site)]
     self.password = config.chargepoint_api_keys['{}_api_password'.format(
         site)]
     self.wsdl_url = "https://webservices.chargepoint.com/cp_api_5.1.wsdl"
     self.client = Client(self.wsdl_url,
                          wsse=UsernameToken(self.username, self.password))
예제 #28
0
 def __init__(
     self,
     username,
     password,
     timeout=30,
     endpoint='https://test.paymentgate.ru/testpayment/webservices/merchant-ws?wsdl'
 ):
     self._client = Client(endpoint,
                           wsse=UsernameToken(username, password),
                           transport=Transport(timeout=timeout))
예제 #29
0
 def __init__(self):
     self.username = config.chargepoint_api_keys['google_api_username']
     self.password = config.chargepoint_api_keys['google_api_password']
     # self.username = config.chargepoint_api_keys['slac-gismo_api_username']
     # self.password = config.chargepoint_api_keys['slac-gismo_api_password']
     # self.username = config.chargepoint_api_keys['slac_api_username']
     # self.password = config.chargepoint_api_keys['slac_api_password']
     self.wsdl_url = "https://webservices.chargepoint.com/cp_api_5.1.wsdl"
     self.client = Client(self.wsdl_url,
                          wsse=UsernameToken(self.username, self.password))
예제 #30
0
파일: soap.py 프로젝트: Natali2411/SOAP
 def connectToWebService(self, wsdl):
     session = Session()
     session.verify = False
     transport = Transport(session=session)
     client = Client(wsdl,
                     plugins=[HistoryPlugin()],
                     transport=transport,
                     strict=False,
                     wsse=UsernameToken("testuser", "testuser"))
     return client
예제 #31
0
파일: auth.py 프로젝트: zensourcer/workday
    def __init__(self, username, password):
        """
        WS-Security plaintext username/password request

        :param username: Username to authenticate as, typically user@tenant
        :type  username: ``str``

        :param password: Password for the integration user
        :type  password: ``str``
        """
        self._kwargs = {"wsse": UsernameToken(username, password)}
예제 #32
0
 def __init__(self, *args, **kwargs):
     self.args = args
     self.kwargs = kwargs
     self.username = self.kwargs['username']
     self.password = self.kwargs['password']
     self.ipaddr = self.kwargs['ipaddr']
     self.wsdl = "http://" + self.kwargs[
         'ipaddr'] + "/ftacsws/acsws.asmx?WSDL"
     self.client = Client(wsdl=self.wsdl,
                          wsse=UsernameToken(self.username, self.password))
     self.port = self.kwargs.get('port', '80')
     self.log = ""
def main(env: str,
         dsn: str,
         api_user: str,
         api_password: str,
         date: str = None) -> None:
    date = date if date else datetime.strftime(datetime.now() -
                                               timedelta(1), '%Y-%m-%d')
    for i, key in enumerate(teryt.keys()):
        client = Client(url[env], wsse=UsernameToken(api_user, api_password))
        r = client.service[teryt[key]['api_method']](DataStanu=date)
        f = BytesIO(b64decode(r['plik_zawartosc']))
        load2pg(readfile(f), key, dsn, prepare_tables=i == 0)