This repository was archived by the owner on Nov 13, 2023. It is now read-only.
- Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathclient.py
More file actions
Latest commit
163 lines (140 loc) · 6.14 KB
/
Copy pathclient.py
File metadata and controls
163 lines (140 loc) · 6.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
importargparse
importhashlib
importjson
fromdatetimeimportdatetime
fromuuidimportuuid1
fromhashlibimportsha512
fromjwkest.jweimportJWE
fromjwkest.jwkimportSYMKey
fromjwkest.jwsimportJWS
fromrequestsimportRequest, Session
parser=argparse.ArgumentParser(description='Make an API request')
parser.add_argument('name', type=str, nargs='?', help='Name to send to the API')
parser.add_argument('-v', '--verbose', help='Verbose output', default=False, dest='verbose', action='store_true')
parser.add_argument('--no-nonce', help='Send no unique nonce with the request', default=False, dest='no_nonce', action='store_true')
parser.add_argument('--no-jwt', help='Send no JWT with the request', default=False, dest='no_jwt', action='store_true')
parser.add_argument('--no-encryption', help='Send the request without encryption', default=False, dest='no_encryption',
action='store_true')
parser.add_argument('--key-id', help='Encryption/Signature Key ID', default='key1', dest='key_id')
parser.add_argument('--key', help='Encryption/Signature Key ID', default='bc926745ef6c8dda6ed2689d08d5793d7525cb81',
dest='key')
parser.add_argument('--base-url', help='Base URL for the request', default='http://localhost:5000', dest='base_url')
parser.add_argument('--leeway', help='Number of seconds to allow for time differential', default=1, type=int,
dest='leeway')
parser.add_argument('--issuer', help='JWT Issuer', default='valid-client', dest='issuer')
parser.add_argument('--audience', help='JWT Audience', default='api-server', dest='audience')
config=parser.parse_args()
sig_keys= [SYMKey(use='sig', kid=config.key_id, key=config.key)]
enc_keys= [SYMKey(use='enc', kid=config.key_id, key=config.key)]
issuer='valid-client'
audience='api-server'
def_get_request_token(method: str, path: str, body: str, jti: str, iss: str, aud: str):
now=int(datetime.utcnow().timestamp())
claims= {
'jti': jti,
'iat': now,
'nbf': now,
'exp': now,
'iss': iss,
'aud': aud,
'request': {
'method': method,
'path': path
}
}
ifbodyisnotNone:
claims['request']['body_hash_alg'] ='S512'
claims['request']['body_hash'] =sha512(body.encode('utf8')).hexdigest()
ifconfig.verbose:
print("Request JWT Claims:")
print(json.dumps(claims, indent=2))
print()
jws=JWS(json.dumps(claims), alg="HS256")
signed_content=jws.sign_compact(keys=sig_keys)
returnsigned_content
def_get_request_data():
ifconfig.nameisNone:
method='GET'
body=None
headers=dict()
print("=== No Request ===")
else:
method='POST'
data=json.dumps({'name': config.name}, indent=2)
print("Unencrypted Body:")
print(data)
print()
ifconfig.no_encryption:
body=data
headers= {'content-type': 'application/json'}
else:
jwe=JWE(data, alg='A256KW', enc='A256CBC-HS512', cty='application/json')
body=jwe.encrypt(enc_keys)
headers= {'content-type': 'application/jose'}
path='/'
jti=Noneifconfig.no_nonceelsestr(uuid1())
ifconfig.no_jwt:
headers['Authorization'] ='Nonce {}'.format(jti)
else:
jwt=_get_request_token(method, path, body, jti, config.issuer, config.audience)
headers['Authorization'] ='EX-JWT {}'.format(jwt)
ifconfig.verbose:
print(method, path, "HTTP/1.1")
forkey, valueinheaders.items():
print("{}: {}".format(key, value))
ifbodyisnotNone:
print("\n"+body)
returnmethod, config.base_url+path, headers, body, jti
def_verify_response(response):
ifnotconfig.no_jwtandresponse.status_code<300:
now=datetime.utcnow().timestamp()
jwt_token=response.headers.get('X-JWT')
ifjwt_tokenisNone:
raiseException("No response header X-JWT")
jwt=JWS().verify_compact(jwt_token, sig_keys)
ifconfig.verbose:
print("Response JWT Claims:")
print(json.dumps(jwt, indent=2))
print()
ifjwt['jti'] !=jti:
raiseException("Unexpected response jti. Expected {} but received {}".format(jti, jwt['jti']))
ifjwt['iss'] !=config.audience:
raiseException("Unexpected response issuer. Expected {} but received {}".format(audience, jwt['iss']))
ifjwt['aud'] !=config.issuer:
raiseException("Unexpected response audience. Expected {} but received {}".format(issuer, jwt['aud']))
ifjwt['nbf'] <now-config.leeway:
raiseException("Response nbf is out of bounds.")
ifjwt['exp'] >now+config.leeway:
raiseException("Response is expired.")
ifjwt['response']['status_code'] !=response.status_code:
raiseException("Unexpected response stats_code. Expected {} but received {}"
.format(response.status_code, jwt['response']['status_code']))
hashes=dict(S256='sha256', S384='sha384', S512='sha512')
hasher=hashlib.new(hashes[jwt['response']['body_hash_alg']])
hasher.update(response.content)
body_hash=hasher.hexdigest()
ifjwt['response']['body_hash'] !=body_hash:
raiseException("Unexpected response body_hash")
print("REQUEST:")
print()
method, url, headers, body, jti=_get_request_data()
request=Request(method, url, headers, None, body)
prepared=request.prepare()
response=Session().send(prepared)
print()
print("RESPONSE:")
print()
ifconfig.verbose:
print(u"HTTP/1.1 {} {}".format(response.status_code, response.reason))
forheaderinresponse.headers.items():
print(u'{}: {}'.format(*header))
print(u'\n{}\n'.format(response.content.decode()))
_verify_response(response)
ifresponse.headers.get('content-type') =='application/jose':
jwe=JWE()
decrypted=jwe.decrypt(response.content, enc_keys)
decoded=decrypted.decode()
print("Decrypted Body:")
print(decoded)
elifnotconfig.verbose:
print(response.text)