Skip to content

Instantly share code, notes, and snippets.

@t11a
Created June 13, 2015 01:58
Show Gist options
  • Save t11a/1bb0dcef2bcf71ab470d to your computer and use it in GitHub Desktop.
Save t11a/1bb0dcef2bcf71ab470d to your computer and use it in GitHub Desktop.
CloudFront - Signed Cookies Using a Custom Policy
#!/usr/bin/env ruby
require 'json'
require 'base64'
require 'openssl'
### CloudFront Key Pair
KEY_PAIR_ID = "XXXXX"
PRIVATE_KEY = "pk-XXXXX.pem"
### Destination URL and RESOURCE for Policy
DST_URL = "https://xxxx.cloudfront.net/index.html"
RESOURCE = "http*://xxxx.cloudfront.net/index.html"
start_time = (Time.now - 60).to_i
expire_time = (Time.now + 60*60*24*10).to_i
condition = { "DateLessThan" => {"AWS:EpochTime" => expire_time }, "DateGreaterThan" => {"AWS:EpochTime" => start_time } }
policy = { "Statement" => ["Resource" => RESOURCE, "Condition" => condition] }
puts "------- policy -------"
p policy = policy.to_json
encoded_policy = Base64.encode64(policy).tr('+=/','-_~')
puts "------- encoded_policy -------"
p encoded_policy.gsub!(/(\r\n|\r|\n)/, "")
# cat policy.json | openssl sha1 -sign pk.pem | openssl base64 | tr '+=/' '-_~'
pkey = OpenSSL::PKey::read(File.read(PRIVATE_KEY))
signature = pkey.sign(OpenSSL::Digest::SHA1.new, policy)
encoded_signature = Base64.encode64(signature).tr('+=/','-_~')
puts "------ encoded_signature --------"
p encoded_signature.gsub!(/(\r\n|\r|\n)/, "")
header = "Cookie:CloudFront-Expires=#{expire_time}; CloudFront-Policy=#{encoded_policy}; CloudFront-Signature=#{encoded_signature}; CloudFront-Key-Pair-Id=#{KEY_PAIR_ID}"
puts "-------- header -------"
p header
puts "---------------"
puts `curl -vH '#{header}' #{DST_URL}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment