从websocket线程解密Rail 4会话cookie

时间:2015-01-30 09:53:15

标签: session ruby-on-rails-4 cookies encryption em-websocket

Rails 4.1.8,ruby 2.1.5p273

我尝试从EventMachine::WebSocket线程中获取会话ID。

此处无法使用

sessioncookie个对象,因此需要手动解密来自websocket握手标头的cookie。 Cookie就像这样:

SFRRZHJGZUtMQnZPeFd2QktjTVc0bVdDQUkvbjhueVczTFpZdG9Ed1ozMGN1dzFjVXhOZGwvOUJLTlZqd29hMDVha3lEN0hleUZtZDZjN2NCa3lIQ0FsWHFoMVQ0SytaV1U0UHc0emo4L2pNUC9MVVNVQVR4c01JS1FmUS9DejRkN3p4cmVEMXROS1NEZk1uNDcvbXF2VEhzMHMyVEZPZytIMDR0aDd3YUZnPS0tZENYRFVzL1psS0hZRFA5M0l4WGZuZz09--2ed3a27ad19bd19bd3b5bf12d164b53665d5323e

我尝试了thisthis个版本,但都失败了

第一种方式:

arr = handshake.headers['Cookie'].split ';'
cookies = {}
arr.each do |rec|
  key,value = rec.split '='
  cookies[key.strip] = value.strip
end
rack_cookie = Rack::Session::Cookie.new(App, { # App name changed
      :key => Rails.application.config.session_options[:key],
      :path => '/',
      :expire_after => 2592000, #30 days
      :secret => Rails.application.secrets.secret_key_base,
      :coder => Rack::Session::Cookie::Base64.new
  })
sess = cookies[Rails.application.config.session_options[:key]]
return rack_cookie.coder.decode(Rack::Utils.unescape(sess.split('--').first))

得到这样的字符串:

muHBVeeYknNJyb43HpVC3lnlDwJ+rC2NGFtBM2y4Nzu6qA+D1sNkmnQY4nRTJx1kl0znz1kkupGFe/ilRjAg1eJNaxFPJhVmBrkp+TBwu38R7+igGj2edkYkFBCandq9XuFn3ILFYwvszMV6iVc0Z2Ftfg6lyIwPfLi5UJMJM3E=--ZIy+dc//zwk/zs3qsaq9vQ==

当我尝试Marshal.load此字符串时,收到错误:

TypeError: incompatible marshal file format (can't be read)
        format version 4.8 required; 109.117 given

第二种方式:

message = URI.unescape sess # sess from prevois code block, btw sess == message
config = Rails.application.config

key_generator = ActiveSupport::KeyGenerator.new(
  Rails.application.secrets.secret_key_base, iterations: 1000
)
secret = key_generator.generate_key(
  config.action_dispatch.encrypted_cookie_salt
)
sign_secret = key_generator.generate_key(
  config.action_dispatch.encrypted_signed_cookie_salt
)

encryptor = ActiveSupport::MessageEncryptor.new(
  secret, sign_secret
)

encryptor.decrypt_and_verify message

收到此错误:

ActiveSupport::MessageEncryptor::InvalidMessage: ActiveSupport::MessageEncryptor::InvalidMessage

如何解密此Cookie?

1 个答案:

答案 0 :(得分:1)

更改

ActiveSupport::MessageEncryptor.new(secret, sign_secret, serializer: JSON)

{{1}}

它应该有效(使用默认配置)。

来源:https://gist.github.com/madwork/858316306a3ebe54a54f