예제 #1
0
    def test_digest_auth_login_invalid2(self):
        response = self.client.get('/digest')
        self.assertEqual(response.status_code, 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'david:' + 'Authentication Required' + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="******",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.status_code, 401)
        self.assertTrue('WWW-Authenticate' in response.headers)
        self.assertTrue(re.match(r'^Digest realm="Authentication Required",'
                                 r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$',
                                 response.headers['WWW-Authenticate']))
예제 #2
0
    def test_digest_auth_login_bad_realm(self):
        response = self.client.get('/digest')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'john:' + 'Wrong Realm' + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="******",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.status_code, 401)
        self.assertTrue('WWW-Authenticate' in response.headers)
        self.assertTrue(re.match(r'^Digest realm="Authentication Required",'
                                 r'nonce="[0-9a-f]+",opaque="[0-9a-f]+"$',
                                 response.headers['WWW-Authenticate']))
예제 #3
0
    def test_digest_auth_login_valid(self):
        response = self.client.get("/digest")
        self.assertTrue(response.status_code == 401)
        header = response.headers.get("WWW-Authenticate")
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = "john:" + d["realm"] + ":bye"
        ha1 = md5(a1).hexdigest()
        a2 = "GET:/digest"
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ":" + d["nonce"] + ":" + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            "/digest",
            headers={
                "Authorization": 'Digest username="******",realm="'
                + d["realm"]
                + '",nonce="'
                + d["nonce"]
                + '",uri="/digest",response="'
                + auth_response
                + '",opaque="'
                + d["opaque"]
                + '"'
            },
        )
        self.assertTrue(response.data == b"digest_auth:john")
예제 #4
0
    def _test_digest_response_for_auth_request(self, header, username, password, qop, uri, body, nc=1, nonce=None):
        auth_type, auth_info = header.split(None, 1)
        self.assertEqual(auth_type, 'Digest')

        d = parse_dict_header(auth_info)

        nonce = nonce or d['nonce']
        realm = d['realm']
        opaque = d['opaque']
        if qop :
            self.assertIn(qop, [x.strip() for x in d['qop'].split(',')], 'Challenge should contains expected qop')
        algorithm = d['algorithm']

        cnonce, nc = (_hash(os.urandom(10), "MD5"), '{:08}'.format(nc)) if qop in ('auth', 'auth-int') else (None, None)

        auth_header = _make_digest_auth_header(
            username, password, 'GET', uri, nonce, realm, opaque, algorithm, qop, cnonce, nc, body)

        # make second request
        return self.app.get(
            uri,
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            },
            headers={
                'Authorization': auth_header,
            },
            data=body
        ), nonce
예제 #5
0
    def test_digest_custom_nonce_checker(self):
        @self.digest_auth.generate_nonce
        def noncemaker():
            return 'not a good nonce'

        @self.digest_auth.generate_opaque
        def opaquemaker():
            return 'some opaque'

        verify_nonce_called = []

        @self.digest_auth.verify_nonce
        def verify_nonce(provided_nonce):
            verify_nonce_called.append(provided_nonce)
            return True

        verify_opaque_called = []

        @self.digest_auth.verify_opaque
        def verify_opaque(provided_opaque):
            verify_opaque_called.append(provided_opaque)
            return True

        response = self.client.get('/digest')
        self.assertEqual(response.status_code, 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        self.assertEqual(d['nonce'], 'not a good nonce')
        self.assertEqual(d['opaque'], 'some opaque')

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest',
            headers={
                'Authorization':
                'Digest username="******",realm="{0}",'
                'nonce="{1}",uri="/digest",response="{2}",'
                'opaque="{3}"'.format(d['realm'], d['nonce'], auth_response,
                                      d['opaque'])
            })
        self.assertEqual(response.data, b'digest_auth:john')
        self.assertEqual(verify_nonce_called, ['not a good nonce'],
                         "Should have verified the nonce.")
        self.assertEqual(verify_opaque_called, ['some opaque'],
                         "Should have verified the opaque.")
예제 #6
0
    def test_digest_custom_nonce_checker(self):
        @self.digest_auth.generate_nonce
        def noncemaker():
            return 'not a good nonce'

        @self.digest_auth.generate_opaque
        def opaquemaker():
            return 'some opaque'

        verify_nonce_called = []

        @self.digest_auth.verify_nonce
        def verify_nonce(provided_nonce):
            verify_nonce_called.append(provided_nonce)
            return True

        verify_opaque_called = []

        @self.digest_auth.verify_opaque
        def verify_opaque(provided_opaque):
            verify_opaque_called.append(provided_opaque)
            return True

        response = self.client.get('/digest')
        self.assertEqual(response.status_code, 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        self.assertEqual(d['nonce'], 'not a good nonce')
        self.assertEqual(d['opaque'], 'some opaque')

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="******",realm="{0}",'
                                 'nonce="{1}",uri="/digest",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.data, b'digest_auth:john')
        self.assertEqual(verify_nonce_called, ['not a good nonce'],
                         "Should have verified the nonce.")
        self.assertEqual(verify_opaque_called, ['some opaque'],
                         "Should have verified the opaque.")
예제 #7
0
    def _test_digest_auth(self,
                          username,
                          password,
                          qop=None,
                          algorithm=None,
                          body=None):
        uri = '/digest-auth/{0}/{1}/{2}'.format(qop or 'wrong-qop', username,
                                                password)
        if algorithm:
            uri += '/' + algorithm

        unauthorized_response = self.app.get(
            uri,
            environ_base={
                # digest auth uses the remote addr to build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            })
        # make sure it returns a 401
        self.assertEqual(unauthorized_response.status_code, 401)
        header = unauthorized_response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        self.assertEqual(auth_type, 'Digest')

        d = parse_dict_header(auth_info)

        nonce = d['nonce']
        realm = d['realm']
        opaque = d['opaque']
        cnonce, nc = (_hash(os.urandom(10), "MD5"),
                      '00000001') if qop in ('auth', 'auth-int') else (None,
                                                                       None)

        auth_header = _make_digest_auth_header(username, password, 'GET', uri,
                                               nonce, realm, opaque, algorithm,
                                               qop, cnonce, nc, body)

        # make second request
        authorized_response = self.app.get(
            uri,
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            },
            headers={
                'Authorization': auth_header,
            },
            data=body)

        # done!
        self.assertEqual(authorized_response.status_code, 200)
예제 #8
0
 def encode(self, val):
   val = http.parse_dict_header(val)
   _v = ''
   for k,v in val.items():
     _v += '_' # simulate flags
     _v += self.enc_uvarint(len(k))
     _v += k
     value = self.attempt_decode(v)
     if not value is None:
       _v += self.enc_uvarint(len(value))
       _v += value
     else:
       _v += self.enc_uvarint(0)
   return _v
예제 #9
0
def enc_cookie(val, type='req'):
    val = http.parse_dict_header(val)
    _v = ''
    for k, v in val.items():
        _v += '_'  # simulate flags
        _v += enc_uvarint(len(k))
        _v += k
        value = attempt_decode(v)
        if not value is None:
            _v += enc_uvarint(len(value))
            _v += value
        else:
            _v += enc_uvarint(0)
    return _v
예제 #10
0
def enc_cookie(val, type='req'):
  val = http.parse_dict_header(val)
  _v = ''
  for k,v in val.items():
    _v += '_' # simulate flags
    _v += enc_uvarint(len(k))
    _v += k
    value = attempt_decode(v)
    if not value is None:
      _v += enc_uvarint(len(value))
      _v += value
    else:
      _v += enc_uvarint(0)
  return _v
예제 #11
0
 def encode(self, val):
     val = http.parse_dict_header(val)
     _v = ''
     for k, v in val.items():
         _v += '_'  # simulate flags
         _v += self.enc_uvarint(len(k))
         _v += k
         value = self.attempt_decode(v)
         if not value is None:
             _v += self.enc_uvarint(len(value))
             _v += value
         else:
             _v += self.enc_uvarint(0)
     return _v
예제 #12
0
    def test_digest_auth(self):
        # make first request
        unauthorized_response = self.app.get(
            "/digest-auth/auth/user/passwd",
            environ_base={
                # digest auth uses the remote addr to build the nonce
                "REMOTE_ADDR": "127.0.0.1"
            },
        )
        # make sure it returns a 401
        self.assertEqual(unauthorized_response.status_code, 401)
        header = unauthorized_response.headers.get("WWW-Authenticate")
        auth_type, auth_info = header.split(None, 1)

        # Begin crappy digest-auth implementation
        d = parse_dict_header(auth_info)
        a1 = b"user:"******"realm"].encode("utf-8") + b":passwd"
        ha1 = md5(a1).hexdigest().encode("utf-8")
        a2 = b"GET:/digest-auth/auth/user/passwd"
        ha2 = md5(a2).hexdigest().encode("utf-8")
        a3 = ha1 + b":" + d["nonce"].encode("utf-8") + b":" + ha2
        auth_response = md5(a3).hexdigest()
        auth_header = (
            'Digest username="******",realm="'
            + d["realm"]
            + '",nonce="'
            + d["nonce"]
            + '",uri="/digest-auth/auth/user/passwd",response="'
            + auth_response
            + '",opaque="'
            + d["opaque"]
            + '"'
        )

        # make second request
        authorized_response = self.app.get(
            "/digest-auth/auth/user/passwd",
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                "REMOTE_ADDR": "127.0.0.1"
            },
            headers={"Authorization": auth_header},
        )

        # done!
        self.assertEqual(authorized_response.status_code, 200)
예제 #13
0
    def test_digest_auth_login_valid(self):
        response = self.client.get('/digest')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get('/digest',
            headers = { 'Authorization': 'Digest username="******",realm="' + d['realm'] + '",nonce="' + d['nonce'] + '",uri="/digest",response="' + auth_response + '",opaque="' + d['opaque'] + '"' })
        self.assertTrue(response.data == b'digest_auth:john')
예제 #14
0
    def test_digest_auth(self):
        # make first request
        unauthorized_response = self.app.get(
            '/digest-auth/auth/user/passwd',
            environ_base={
                # digest auth uses the remote addr to build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            }
        )
        # make sure it returns a 401
        self.assertEqual(unauthorized_response.status_code, 401)
        header = unauthorized_response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)

        # Begin crappy digest-auth implementation
        d = parse_dict_header(auth_info)
        a1 = b'user:'******'realm'].encode('utf-8') + b':passwd'
        ha1 = md5(a1).hexdigest().encode('utf-8')
        a2 = b'GET:/digest-auth/auth/user/passwd'
        ha2 = md5(a2).hexdigest().encode('utf-8')
        a3 = ha1 + b':' + d['nonce'].encode('utf-8') + b':' + ha2
        auth_response = md5(a3).hexdigest()
        auth_header = 'Digest username="******",realm="' + \
            d['realm'] + \
            '",nonce="' + \
            d['nonce'] + \
            '",uri="/digest-auth/auth/user/passwd",response="' + \
            auth_response + \
            '",opaque="' + \
            d['opaque'] + '"'

        # make second request
        authorized_response = self.app.get(
            '/digest-auth/auth/user/passwd',
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            },
            headers={
                'Authorization': auth_header,
            }
        )

        # done!
        self.assertEqual(authorized_response.status_code, 200)
    def test_digest_auth(self):
        # make first request
        unauthorized_response = self.app.get(
            '/digest-auth/auth/user/passwd/MD5',
            environ_base={
                # digest auth uses the remote addr to build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            }
        )
        # make sure it returns a 401
        self.assertEqual(unauthorized_response.status_code, 401)
        header = unauthorized_response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)

        # Begin crappy digest-auth implementation
        d = parse_dict_header(auth_info)
        a1 = b'user:'******'realm'].encode('utf-8') + b':passwd'
        ha1 = md5(a1).hexdigest().encode('utf-8')
        a2 = b'GET:/digest-auth/auth/user/passwd/MD5'
        ha2 = md5(a2).hexdigest().encode('utf-8')
        a3 = ha1 + b':' + d['nonce'].encode('utf-8') + b':' + ha2
        auth_response = md5(a3).hexdigest()
        auth_header = 'Digest username="******",realm="' + \
            d['realm'] + \
            '",nonce="' + \
            d['nonce'] + \
            '",uri="/digest-auth/auth/user/passwd/MD5",response="' + \
            auth_response + \
            '",opaque="' + \
            d['opaque'] + '"'

        # make second request
        authorized_response = self.app.get(
            '/digest-auth/auth/user/passwd/MD5',
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            },
            headers={
                'Authorization': auth_header,
            }
        )

        # done!
        self.assertEqual(authorized_response.status_code, 200)
예제 #16
0
    def _test_digest_auth(self, username, password, qop=None, algorithm=None, body=None):
        uri = '/digest-auth/{0}/{1}/{2}'.format(qop or 'wrong-qop', username, password)
        if algorithm:
            uri += '/' + algorithm

        unauthorized_response = self.app.get(
            uri,
            environ_base={
                # digest auth uses the remote addr to build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            }
        )
        # make sure it returns a 401
        self.assertEqual(unauthorized_response.status_code, 401)
        header = unauthorized_response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        self.assertEqual(auth_type, 'Digest')

        d = parse_dict_header(auth_info)

        nonce = d['nonce']
        realm = d['realm']
        opaque = d['opaque']
        cnonce, nc = (_hash(os.urandom(10), "MD5"), '00000001') if qop in ('auth', 'auth-int') else (None, None)

        auth_header = _make_digest_auth_header(
            username, password, 'GET', uri, nonce, realm, opaque, algorithm, qop, cnonce, nc, body)

        # make second request
        authorized_response = self.app.get(
            uri,
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            },
            headers={
                'Authorization': auth_header,
            },
            data=body
        )

        # done!
        self.assertEqual(authorized_response.status_code, 200)
예제 #17
0
    def test_digest_auth_login_bad_realm(self):
        response = self.client.get('/digest')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get("WWW-Authenticate")
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = "john:" + 'Wrong Realm' + ":bye" 
        ha1 = md5(a1).hexdigest()
        a2 = "GET:/digest"
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ":" + d['nonce'] + ":" + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get('/digest', 
            headers = { "Authorization": 'Digest username="******",realm="' + d['realm'] + '",nonce="' + d['nonce'] + '",uri="/digest",response="' + auth_response + '",opaque="' + d['opaque'] + '"' })
        self.assertTrue(response.status_code == 401)
        self.assertTrue("WWW-Authenticate" in response.headers)
        self.assertTrue(re.match(r'^Digest realm="Authentication Required",nonce="[0-9a-f]+",opaque="[0-9a-f]+"$', response.headers["WWW-Authenticate"]))
예제 #18
0
    def _test_digest_response_for_auth_request(self,
                                               header,
                                               username,
                                               password,
                                               qop,
                                               uri,
                                               body,
                                               nc=1,
                                               nonce=None):
        auth_type, auth_info = header.split(None, 1)
        self.assertEqual(auth_type, 'Digest')

        d = parse_dict_header(auth_info)

        nonce = nonce or d['nonce']
        realm = d['realm']
        opaque = d['opaque']
        if qop:
            self.assertIn(qop, [x.strip() for x in d['qop'].split(',')],
                          'Challenge should contains expected qop')
        algorithm = d['algorithm']

        cnonce, nc = (_hash(os.urandom(10), "MD5"),
                      '{:08}'.format(nc)) if qop in ('auth',
                                                     'auth-int') else (None,
                                                                       None)

        auth_header = _make_digest_auth_header(username, password, 'GET', uri,
                                               nonce, realm, opaque, algorithm,
                                               qop, cnonce, nc, body)

        # make second request
        return self.app.get(
            uri,
            environ_base={
                # httpbin's digest auth implementation uses the remote addr to
                # build the nonce
                'REMOTE_ADDR': '127.0.0.1',
            },
            headers={
                'Authorization': auth_header,
            },
            data=body), nonce
예제 #19
0
    def _get_seconds_until_expire(cls, head_response: Mapping[str, Any]) -> float:
        """
        Get the number of seconds before a cached manifest is past its expiration.

        :param head_response: A storage service object header dict
        :return: time to expiration in seconds
        """
        # example Expiration: 'expiry-date="Fri, 21 Dec 2012 00:00:00 GMT", rule-id="Rule for testfile.txt"'
        now = datetime.now(timezone.utc)
        expiration = parse_dict_header(head_response['Expiration'])
        expiry_datetime = email.utils.parsedate_to_datetime(expiration['expiry-date'])
        expiry_seconds = (expiry_datetime - now).total_seconds()
        # Verify that 'Expiration' matches value calculated from 'LastModified'
        last_modified = head_response['LastModified']
        expected_expiry_date: datetime = last_modified + timedelta(days=config.manifest_expiration)
        expected_expiry_seconds = (expected_expiry_date - now).total_seconds()
        if abs(expiry_seconds - expected_expiry_seconds) > cls._date_diff_margin:
            logger.error('The actual object expiration (%s) does not match expected value (%s)',
                         expiration, expected_expiry_date)
        else:
            logger.debug('Manifest object expires in %s seconds, on %s', expiry_seconds, expiry_datetime)
        return expiry_seconds
예제 #20
0
    def test_digest_ha1_pw_auth_login_valid(self):
        response = self.client.get('/digest_ha1_pw')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest_ha1_pw'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest', headers={
                'Authorization': 'Digest username="******",realm="{0}",'
                                 'nonce="{1}",uri="/digest_ha1_pw",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
        self.assertEqual(response.data, b'digest_auth:john')
예제 #21
0
    def test_digest_auth_login_valid(self):
        response = self.client.get('/digest')
        self.assertTrue(response.status_code == 401)
        header = response.headers.get('WWW-Authenticate')
        auth_type, auth_info = header.split(None, 1)
        d = parse_dict_header(auth_info)

        a1 = 'john:' + d['realm'] + ':bye'
        ha1 = md5(a1).hexdigest()
        a2 = 'GET:/digest'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = self.client.get(
            '/digest',
            headers={
                'Authorization':
                'Digest username="******",realm="' + d['realm'] + '",nonce="' +
                d['nonce'] + '",uri="/digest",response="' + auth_response +
                '",opaque="' + d['opaque'] + '"'
            })
        self.assertTrue(response.data == b'digest_auth:john')
예제 #22
0
def _test_digest_response_for_auth_request(session,
                                           header,
                                           username,
                                           password,
                                           qop,
                                           uri,
                                           body,
                                           nc=1,
                                           nonce=None):
    auth_type, auth_info = header.split(None, 1)
    assert auth_type == 'Digest'

    d = parse_dict_header(auth_info)

    nonce = nonce or d['nonce']
    realm = d['realm']
    opaque = d['opaque']
    algorithm = d['algorithm']

    if qop:
        expected = [x.strip() for x in d['qop'].split(',')]
        assert qop in expected, 'Challenge should contains expected qop'

    if qop in ('auth', 'auth-int'):
        cnonce, nc = (_hash(os.urandom(10), "MD5"), '{0:08}'.format(nc))
    else:
        cnonce, nc = (None, None)

    auth_header = _make_digest_auth_header(username, password, 'GET', uri,
                                           nonce, realm, opaque, algorithm,
                                           qop, cnonce, nc, body)

    # make second request
    response = session.get(url(uri),
                           headers={'Authorization': auth_header},
                           data=body)
    return response, nonce
예제 #23
0
def enc_p3p(val, type='req'):
  val = http.parse_dict_header(val)
  _v = ''
  # policy refs
  if 'policyref' in val:
    _v += enc_uvarint(len(val['policyref']))
    _v += val['policyref']
  else:
    _v += enc_uvarint(0)
  cp = ''
  if 'CP' in val:
    tokens = val['CP'].split(' ')
    for token in tokens:
      # check for the fake P3P profiles like google produces... will ignore those nil values for now
      if not token[:3] in p3p_table:
        cp = '' 
        break
      q = (p3p_table.index(token[:3])+1) << 2
      if len(token) == 4:
        q |= ['a','i','o'].index(token[-1])
      cp += struct.pack('!B',q)
  if len(cp) > 0:
    _v += cp
  return _v
예제 #24
0
def enc_p3p(val, type='req'):
    val = http.parse_dict_header(val)
    _v = ''
    # policy refs
    if 'policyref' in val:
        _v += enc_uvarint(len(val['policyref']))
        _v += val['policyref']
    else:
        _v += enc_uvarint(0)
    cp = ''
    if 'CP' in val:
        tokens = val['CP'].split(' ')
        for token in tokens:
            # check for the fake P3P profiles like google produces... will ignore those nil values for now
            if not token[:3] in p3p_table:
                cp = ''
                break
            q = (p3p_table.index(token[:3]) + 1) << 2
            if len(token) == 4:
                q |= ['a', 'i', 'o'].index(token[-1])
            cp += struct.pack('!B', q)
    if len(cp) > 0:
        _v += cp
    return _v
예제 #25
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     self.assert_equal(d, {'foo': 'bar baz', 'blah': '42'})
예제 #26
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     assert d == {"foo": "bar baz", "blah": "42"}
예제 #27
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     assert d == {'foo': 'bar baz', 'blah': '42'}
def login(client, method, json_dict=None, url=None):

    response = client.get('/user')
    assert (response.status_code == 401)
    header = response.headers.get('WWW-Authenticate')

    auth_type, auth_info = header.split(None, 1)
    d = parse_dict_header(auth_info)

    a1 = 'admin:' + d['realm'] + ':1234'
    ha1 = md5(a1).hexdigest()

    if((method == "post") and (json_dict != None)):

        a2 = 'POST:/user'
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = client.post('/user', data=json.dumps(json_dict), content_type='application/json', headers={
            'Authorization': 'Digest username="******",realm="{0}",'
                             'nonce="{1}",uri="/user",response="{2}",'
                             'opaque="{3}"'.format(d['realm'],
                                                   d['nonce'],
                                                   auth_response,
                                                   d['opaque'])})
    elif(method == "get"):
        if(url != None):
            a2 = 'GET:' + url
            ha2 = md5(a2).hexdigest()
            a3 = ha1 + ':' + d['nonce'] + ':' + ha2
            auth_response = md5(a3).hexdigest()

            response = client.get(url, headers={
                'Authorization': 'Digest username="******",realm="{0}",'
                                 'nonce="{1}",uri={4},response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'],
                                                       url)})
        else:
            a2 = 'GET:/user'
            ha2 = md5(a2).hexdigest()
            a3 = ha1 + ':' + d['nonce'] + ':' + ha2
            auth_response = md5(a3).hexdigest()

            response = client.get('/user', headers={
                'Authorization': 'Digest username="******",realm="{0}",'
                                 'nonce="{1}",uri="/user",response="{2}",'
                                 'opaque="{3}"'.format(d['realm'],
                                                       d['nonce'],
                                                       auth_response,
                                                       d['opaque'])})
    elif((method == "delete") and (url != None)):
        a2 = 'DELETE:' + url
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = client.delete(url, data=json.dumps(json_dict), content_type='application/json', headers={
            'Authorization': 'Digest username="******",realm="{0}",'
                             'nonce="{1}",uri={4},response="{2}",'
                             'opaque="{3}"'.format(d['realm'],
                                                   d['nonce'],
                                                   auth_response,
                                                   d['opaque'],
                                                   url)})
    elif((method == "put") and (url != None) and (json_dict != None)):
        a2 = 'PUT:' + url
        ha2 = md5(a2).hexdigest()
        a3 = ha1 + ':' + d['nonce'] + ':' + ha2
        auth_response = md5(a3).hexdigest()

        response = client.put(url, data=json.dumps(json_dict), content_type='application/json', headers={
            'Authorization': 'Digest username="******",realm="{0}",'
                             'nonce="{1}",uri={4},response="{2}",'
                             'opaque="{3}"'.format(d['realm'],
                                                   d['nonce'],
                                                   auth_response,
                                                   d['opaque'],
                                                   url)})
    else:
        raise ValueError("Check the given paremeters")

    return response
예제 #29
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     assert d == {'foo': 'bar baz', 'blah': '42'}
예제 #30
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     assert d == {"foo": "bar baz", "blah": "42"}
예제 #31
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     self.assert_equal(d, {"foo": "bar baz", "blah": "42"})
예제 #32
0
 def test_dict_header(self):
     d = http.parse_dict_header('foo="bar baz", blah=42')
     self.assert_equal(d, {'foo': 'bar baz', 'blah': '42'})
예제 #33
0
 def custom_header_value_matcher(actual: str, expected: str) -> bool:
     actual_scheme, _, actual_dict_str = actual.partition(' ')
     expected_scheme, _, expected_dict_str = expected.partition(' ')
     actual_dict = parse_dict_header(actual_dict_str)
     expected_dict = parse_dict_header(expected_dict_str)
     return actual_scheme == expected_scheme and actual_dict == expected_dict