Skip to content

Instantly share code, notes, and snippets.

@mbyczkowski
Created March 10, 2017 07:25
Show Gist options
  • Save mbyczkowski/9b64652e3472ec8a463069db8b84ae7f to your computer and use it in GitHub Desktop.
Save mbyczkowski/9b64652e3472ec8a463069db8b84ae7f to your computer and use it in GitHub Desktop.
session cookie decrypter for Rails 4.2+ (in OpenResty Lua)
local aes = require("resty.aes")
local str = require("resty.string")
local sha1 = require("bgcrypto.sha1")
local cjson = require("cjson")
function verify_and_decrypt_session_cookie(cookie, secret_key_base)
local rounds = 1000
local secret_length = 32
local sign_secret_length = 64
local cookie = ngx.unescape_uri(cookie)
local salt = "encrypted cookie"
local signed_salt = "signed encrypted cookie"
local secret = sha1.pbkdf2(secret_key_base, salt, rounds, secret_length)
local sign_secret = sha1.pbkdf2(secret_key_base, signed_salt, rounds, sign_secret_length)
local data, digest = string.match(cookie, "([^-]+)--([^-]+)")
if digest ~= str.to_hex(ngx.hmac_sha1(sign_secret, data)) then
print("invalid message")
return {}
end
local encrypted_message = ngx.decode_base64(data)
local encrypted_data, iv = string.match(encrypted_message, "([^-]+)--([^-]+)")
encrypted_data = ngx.decode_base64(encrypted_data)
iv = ngx.decode_base64(iv)
local aes_256_cbc = aes:new(secret, salt, aes.cipher(256,"cbc"), {iv=iv})
local decrypt = aes_256_cbc:decrypt(encrypted_data)
return cjson.decode(decrypt)
end
local secret_key_base = "dev_secret"
local raw_cookie = "aHVHR0dqelNGa2VzMTIrd3lBMkJJcFl3cGg3MnZMc0xlc1VieG43TllLTzFwNFJCU1hHSUdRV1BXZFQrNXhkdkV1U2JkSjA5VTJlWnEwcVk3TmJZOGRCRDQ4WW1hMlp1SE5SeGg5NlFKYThHVkE0WVNqN1RRS3lwdHlyRG1SUDBKbDVmN1N6amhLL0hTRmZtZEhscGs5WnBjOU9jeU1iN1diQW9XM05aL2ZDZlZEMGhobjFna0VBMFZ3RU40NU12bldmbVFlSmgxZFlIaldySmRGSGJLcjJ1dVhRbE5pMTdSYnVnczJsemdSUEowb0tFSVFYbzhzSmxURHJNME93MkZRVXV5dlJDQlpoQi91dThSYXVTN0NaS0JBUENvL0NpWFZFbVVCbDZibG5IZ3ZkUVBXQXUrOEMxT24wUCtPejItLWxWUHR1RTdVeXNpRWJSb1l2NXBGb3c9PQ%3D%3D--09a4efa72ca38fcbb641372db055b7f252fb0df5"
json = verify_and_decrypt_session_cookie(raw_cookie, "dev_secret")
print(cjson.encode(json))
-- {"logged_in_at":"2017-03-01T18:04:41.318-06:00","session_id":"d613b82cbc23b8cfcbadab8e439e7315","user_id":1,"return_to":"http:\/\/localhost:3000\/sites\/fly-dev\/edit","_csrf_token":"LvNDMv7eYl9IC0pVUQL8fMEQM+24JD45ceUi5CFZWHo="}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment