具有更改签名的安全HMAC授权

2024-06-16 12:21:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Rails应用程序,它提供了一个由python脚本使用的jsonapi。安全性很重要,我一直在用HMAC来做到这一点。rails应用程序和python脚本都知道密钥,它们用它加密的签名是URL和请求的主体。你知道吗

我的问题是请求的签名不会每次都更改。如果它被截获,那么攻击者就可以发送具有相同摘要的完全相同的请求,我认为它可以进行身份验证,即使攻击者不知道密钥。你知道吗

所以我想我需要在签名中包含请求的时间戳之类的东西——问题是我不知道如何在python和ruby中获得它。你知道吗

这是我的python代码:

import hmac
import hashlib
import requests

fetch_path = url_base + '/phone_messages/pending'
fetch_body = '{}'
fetch_signature = fetch_path + ':' + fetch_body
fetch_hmac = hmac.new(api_key.encode('utf-8'), fetch_signature.encode('utf-8'), haslib.sha1).hexdigest()

这是我的ruby代码:

signature = "#{request.url}:#{request.body.to_json.to_s}"
hmac_digest = OpenSSL::HMAC.hexdigest('sha1', secret_key, signature)

Tags: pathkey代码import脚本应用程序url密钥
2条回答

Question: I need to have something like a timestamp of the request included in the signature

例如:

import hmac, hashlib, datetime

api_key = 'this is a key'
fetch_path = 'http://phone_messages/pending'
fetch_body = '{}'
fetch_data = fetch_path + ':' + fetch_body


for n in range(3):
    fetch_signature = fetch_data + str(datetime.datetime.now().timestamp() )
    fetch_hmac = hmac.new(api_key.encode('utf-8'), fetch_signature.encode('utf-8'), hashlib.sha1).hexdigest()
    print("{}:{} {}".format(n, fetch_signature, fetch_hmac))

Output:

0:http://phone_messages/pending:{}1538660666.768066 cfa49feaeaf0cdc5ec8bcf1057446c425863e83a
1:http://phone_messages/pending:{}1538660666.768358 27d0a5a9f33345babf0c824f45837d3b8863741e
2:http://phone_messages/pending:{}1538660666.768458 67298ad0e9eb8bb629fce4454f092b74ba8d6c66

我建议在security.stackexchange.com讨论安全性
作为起点,阅读:what-is-a-auth-key-in-the-security-of-the-computers

我通过将时间戳(自epoch起的秒数)放入post请求的主体或get请求的参数来解决这个问题。我只是使用时间戳作为编码的签名,这意味着HMAC哈希对于每一个以不同的秒来的请求都是不同的。你知道吗

然后,为了防止攻击者仅仅使用以前看到的时间戳,我在服务器上验证了时间戳不超过当前时间之前5秒。你知道吗

一个能够快速截获通信并发送攻击的攻击者仍然可以通过,但是我不能将超时时间降到5秒以下,因为它已经收到一些超时的请求。你知道吗

由于整个事情是在SSL下完成的,我认为它应该足够安全。你知道吗

相关问题 更多 >