Implementing SagePay Form Integration with Ruby on Rails - ruby-on-rails

I'm using SagePay's form integration method with a Ruby on Rails/EmberJS app. I'm handling all the complex payment construction in Rails.
In short, SagePay needs an encrypted, encoded 'crypt' string, which contains data such as the user's billing address, the amount, post-payment redirects, and other transaction data.
SagePay gives an encryption password in the test environment. The form integration guide says to build the crypt as a string, then encrypt it using AES-256 and the encryption password, then Base64 encode the string for POSTing to the Sage test payments server.
Here's how I've implemented this (using the Encryptor gem):
def encryptandencode(string)
salt = Time.now.to_i.to_s
secret_key = 'test-server-secret-key-from-sage'
iv = OpenSSL::Cipher::Cipher.new('aes-256-cbc').random_iv
encrypted_value = Encryptor.encrypt(string, :key => secret_key, :iv => iv, :salt => salt)
encoded = Base64.encode64(encrypted_value).encode('utf-8')
return encoded
end
where string is the unencoded, unencrypted Crypt string containing transaction data.
The problem
Encryptor refuses to use the given secret key. It says the key is too short.
What am I missing here?

I'm struggling to do the same thing in ASP.NET. I don't know why the example 'Integration Kits' they give you on the website are so complicated. They may represent elegant pieces of code in themselves, but they obfuscate how things are working by having functions call functions call methods using settings in the web.config file. For developers new to this API a simple example with all the code in one place would be helpful.
ANYWAY, I still haven't got it working but I have managed to overcome the problem you're having, though my method may not help you since I'm working in ASP.NET. I added a reference to the SagePay.IntegrationKit.DotNet.dll to my project, after which I was able to call the function
SagePay.IntegrationKit.Cryptography.EncryptAndEncode(<name=value collection>, <Encryption Password>)
I now appear to get a valid encrypted string to send to SagePay, my problem is that their website says the encryption is wrong, so this is still a work in progress.

I was struggling with this too, and receiving the same error message.
I finally decided to try each line from the Encryptor gem directly and no longer received that error message. Therefore I have ditched that gem from my Gemfile.
BTW, you have a few things wrong in your example:
you need to use 128 bit encryption, not the default 256: :algorithm => 'aes-128-cbc'
the initialisation vector needs to be the same as the key: :iv => secret_key
you mustn't use a salt
the result needs to be hex encoded not Base64
result = encrypted_value.split('').map { |c| "%02X" % c.ord }.join

The Test and Live Encryption password differ also check your encryption password is 16 characters in length.
Sage Pay Support

Related

Send bcrypt hash as parameter

I want to send a bcrypt hash with random hash as a URL parameter. For example
hash=$2y$10$SWNoIGJpbiBkYXMgU2Fsd.t/I3wS/nUqo5eRQp8b7oakL/kQlZ5da
So my questions are:
Is this a good idea or should I remove the salt from the hash? How can I do this? Is the first dot every time the delimiter?
You really shouldn't be putting someone BCrypt'd password out on the wire. Even though BCrypt is hard to brute-force; it's better to not make it easier for someone to get ahold of it.
I suggest, as user33888366 did, that if you need a kind of security token, use the HMAC of values in the url.
Read Life in a post-database world: using crypto to avoid DB writes for examples of using crypto to trust your urls.
Short version
http://myapp.com/resetPassword?userId=johnnysmith&expirationTime=1356156000&token=%SECURITYHASH%
where %SecurityHash% is the HMAC hash of:
userId
reset expiration time
bcrypt hash
When the URL comes it, parse it:
userId=johnnysmith&expirationTime=1356156000&token=%SECURITYHASH%
^^^^^^^^^^^ ^^^^^^^^^^
and recalculate the HMAC of:
johnnysmith
1356156000
johnnysmith's bcrypt hash
if it matches the passed security token, you know you have a valid request.

encrypting session information in rails

By default, rails uses cookie storage for session information. The tutorial I followed said that it was the best way and super fast, and that it all gets encrypted. But when I base64 decode the cookie content, I can see my session info there. It's mixed into a lot of garbled characters, but it's there.
What am I missing here?
Doesn't rails use that secret token thing to encrypt the info in the cookie? How can I make it do so?
Rails uses a secret token to sign the session. The raw data is still there, but changing it will cause it to not match the signature any more, and Rails will reject it. The cookie string looks like session_data--signature, the session data is a base64-encoded marshalled object, and the signature is HMAC(session string, secret token).
The general assumption of the session data is that it is not secret (since it generally should contain only a few things, like a CSRF token and a user ID), but it should not be changeable by a user. The cookie signing accomplishes this.
If you need to actually encrypt the data so that users could never see it, you could do so using something like OpenSSL symmetric encryption, or you could switch to a non-cookie data store.
This is a variant on my own app's cookie store; I haven't tested it, but in theory this should generate actually-encrypted cookies for you. Note that this will be appreciably slower than the default cookie store, and depending on its runtime, could potentially be a DOS vector. Additionally, encrypted data will be lengthier than unencrypted data, and session cookies have a 4kb limit, so if you're storing a lot of data in your session, this might cause you to blow past that limit.
# Define our message encryptor
module ActiveSupport
class EncryptedMessageVerifier < MessageVerifier
def verify(message)
Marshal.load cryptor.decrypt_and_verify(message)
end
def generate(value)
cryptor.encrypt_and_sign Marshal.dump(value)
end
def cryptor
ActiveSupport::MessageEncryptor.new(#secret)
end
end
end
# And then patch it into SignedCookieJar
class ActionDispatch::Cookies::SignedCookieJar
def initialize(parent_jar, secret)
ensure_secret_secure(secret)
#parent_jar = parent_jar
#verifier = ActiveSupport::EncryptedMessageVerifier.new(secret)
end
end

Creating Signature and Nonce for OAuth (Ruby)

I'm looking to access SmugMug's API from my application to grab users' albums and images (the users have been authenticated via ruby's OmniAuth).
According to SmugMug's OAuth API, OAuth requires six parameters.
I can get the token with OmniAuth, and the timestamp should be easy (Time.now.to_i right?). There are two things that I don't know how to generate -- the oauth_nonce and the oauth_signature.
According to the oauth docs, I generate the nonce via the timestamp, but how exactly would I do that? Does it need to be a certain length and limited to certain characters?
And of course the signature. How would I generate a HMAC-SHA1 sig with ruby? I know the oauth gem can do it, but I'd rather generate it myself to use with OmniAuth. Looking at the code, I'm having trouble deciphering how the oauth gem generates the sig.
Thank you for any help.
For the signature:
def sign( key, base_string )
digest = OpenSSL::Digest::Digest.new( 'sha1' )
hmac = OpenSSL::HMAC.digest( digest, key, base_string )
Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
end#def
You don't have to generate the nonce from the timestamp, but it can make sense since the timestamp is obviously unique, so it makes a good starting input for any randomisation function.
I use this, (that I got from another question on here and modified)
def nonce
rand(10 ** 30).to_s.rjust(30,'0')
end#def
but you can use anything that generates a unique string.
See this gist by erikeldridge on github and Beginner’s Guide to OAuth for more
Edit
I've since found there's a better way to generate random strings in the Ruby standard library, SecureRandom.
A nonce can also be simply a large-ish, properly random number - for example, using Ruby's SecureRandom class (don't use 'rand'):
require 'securerandom'
...
nonce = SecureRandom.hex()
This generates a 16-byte random number in hex format.
Why you don't just use the Oauth ruby gems to do that ?

Signup or Invitation Email Verification w/o Database

I'd like to keep my database clean of stale almost-accounts, and I was thinking about making new signups and invitations put their data into the welcome email as an encrypted or hashed url. Once the link in the url is visited, the information is then added into the database as an account.
Is there something that currently does this? Any references, thoughts, or warnings about doing user registration this way?
Thanks!
Edit:
I've made a working example, and the url is 127 characters.
http://localhost/confirm?_=hBRCGVqie5PetQhjiagq9F6kmi7luVxpcpEYMWaxrtSHIPA3rF0Hufy6EgiH%0A%2BL3t9dcgV9es9Zywkl4F1lcMyA%3D%3D%0A
Obviously, more data = larger url
def create
# Write k keys in params[:user] as v keys in to_encrypt, doing this saves LOTS of unnecessary chars
#to_encrypt = Hash.new
{:firstname => :fn,:lastname => :ln,:email => :el,:username => :un,:password => :pd}.each do |k,v|
#to_encrypt[v] = params[:user][k]
end
encrypted_params = CGI::escape(Base64.encode64(encrypt(compress(Marshal.dump(#to_encrypt)), "secret")))
end
private
def aes(m,t,k)
(aes = OpenSSL::Cipher::Cipher.new('aes-256-cbc').send(m)).key = Digest::SHA256.digest(k)
aes.update(t) << aes.final
end
def encrypt(text, key)
aes(:encrypt, text, key)
end
def decrypt(text, key)
aes(:decrypt, text, key)
end
# All attempts to compress returned a longer url (Bypassed by return)
def compress(string)
return string
z = Zlib::Deflate.new(Zlib::BEST_COMPRESSION)
o = z.deflate(string,Zlib::FINISH)
z.close
o
end
def decompress(string)
return string
z = Zlib::Inflate.new
o = z.inflate(string)
z.finish
z.close
o
end
Thoughts:
Use true asymmetric cypher for the "cookie" to prevent bots creating accounts. Encrypt the "cookie" using public key, verify it by decoding with private key.
Rationale: If only a base64 or other algorithm was used for encoding the cookie, it would be easy to reverse-engineer the scheme and create accounts automatically. This is undesirable because of spambots. Also, if the account is password protected, the password would have to appear in the cookie. Anyone with access to the registration link would be able not only to activate the account, but also to figure out the password.
Require re-entry of the password after activation through the link.
Rationale: Depending on the purpose of the site you may want to improve the protection against information spoofing. Re-entering the password after activation protects against stolen/spoofed activation links.
When verifying the activation link, make sure the account created by it is not created already.
How do you protect against two users simultaneously creating an account with the same name?
Possible answer: Use email as the login identifier and don't require unique account name.
Verify the email first, than continue account creation.
Rationale: This will minimize the information you need to send in the cookie.
There are some e-mail clients which break URLs after 80 letters. I doubt that you can fit all the information in there.
Some browsers have limitations for the URL, Internet Explorer 8 has a limit of 2083 characters, for example.
Why don't you clean your database regularly (cron script) and remove all accounts that haven't been activated for 24 houres?
I have done pretty much the same before. I only have 2 suggestions for you,
Add a key version so you can rotate the key without breaking outstanding confirmation.
You need a timestamp or expiration so you can set a time limit on confirmation if you want to. We allow one week.
As to the shortest URL, you can do better by making following changes,
Use a stream cipher mode like CFB so you don't have to pad to the block size.
Compress the cleartext will help when the data is big. I have a flag and only use compression when it shrinks data.
Use Base64.urlsafe_encode64() so you don't have to URL encode it.
There's a few problems with your solution.
Firstly, you're not setting the IV of the cipher. In my view this has exposed a serious bug in the Ruby OpenSSL wrapper - it shouldn't let you perform an encryption or decryption until both key and iv have been set, but instead it's going ahead and using an IV of all-zeroes. Using the same IV every time basically removes much of the benefit of using a feedback mode in the first place.
Secondly, and more seriously, you have no authenticity checking. One of the properties of CBC mode is that an attacker who has access to one message can modify it to create a second message where a block in the second message has entirely attacker-controlled contents, at the cost of the prior block being completely garbled. (Oh, and note that CFB mode is just as much a problem in this regard).
In this case, that means that I could request an account with Last Name of AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA and my own email address to recieve a valid URL. I can then, without knowing the key, modify the email address to victim#victim.com (and garble the Last Name in the process, which doesn't matter), and have a valid URL which I can submit to your server and create accounts for email addresses that I don't control.
To solve this, you need to compute a HMAC over the data, keyed with a secret that only the server knows, and send that as part of the URL. Note that the only reason you need encryption at all here is to secure the user's password - other than that it could just be plaintext plus a HMAC. I suggest you simply send as the url something like:
?ln=Last%20Name&fn=First%20Name&email=foo#bar.com&hmac=7fpsQba2GMepELxilVUEfwl3%2BN1MdCsg%2FZ59dDd63QE%3D
...and have the verification page prompt for a password (there doesn't seem to be a reason to bounce the password back and forth).
I will take a crack at describing a design that may work.
Prerequisities:
Cryptography library with support for RSA and some secure hash function H (eg. SHA-1)
One pair of private and public keys
Design:
Unique user identifier is e-mail address
An account has associated password and possible other data
The activation cookie is kept as small as possible
Process:
User is asked for e-mail address and password. Upon submission of the form a cookie is computed as
cookie = ENCRYPT(CONCAT(email, '.', H(password)), public key)
E-mail is sent containing a link to the activation page with the cookie, eg.
http://example.org/activation?cookie=[cookie]
The activation page at http://example.org/activation decrypts the cookie passed as parameter: data = SPLIT(DECRYPT(cookie, private key), '.')
In the same activation page the user is asked for password (which must be hashed to the the same value as in cookie) and any other information necessary for the account creation
Upon submission of the activation page a new account is created
Please point out anything that I have missed or any improvements. I'd be glad to update the answer accordingly.

LDAP through Ruby or Rails

I've been attempting to hook a Rails application up to ActiveDirectory. I'll be synchronizing data about users between AD and a database, currently MySQL (but may turn into SQL Server or PostgreSQL).
I've checked out activedirectory-ruby, and it looks really buggy (for a 1.0 release!?). It wraps Net::LDAP, so I tried using that instead, but it's really close to the actual syntax of LDAP, and I enjoyed the abstraction of ActiveDirectory-Ruby because of its ActiveRecord-like syntax.
Is there an elegant ORM-type tool for a directory server? Better yet, if there were some kind of scaffolding tool for LDAP (CRUD for users, groups, organizational units, and so on). Then I could quickly integrate that with my existing authentication code though Authlogic, and keep all of the data synchronized.
Here is sample code I use with the net-ldap gem to verify user logins from the ActiveDirectory server at my work:
require 'net/ldap' # gem install net-ldap
def name_for_login( email, password )
email = email[/\A\w+/].downcase # Throw out the domain, if it was there
email << "#mycompany.com" # I only check people in my company
ldap = Net::LDAP.new(
host: 'ldap.mycompany.com', # Thankfully this is a standard name
auth: { method: :simple, email: email, password:password }
)
if ldap.bind
# Yay, the login credentials were valid!
# Get the user's full name and return it
ldap.search(
base: "OU=Users,OU=Accounts,DC=mycompany,DC=com",
filter: Net::LDAP::Filter.eq( "mail", email ),
attributes: %w[ displayName ],
return_result:true
).first.displayName.first
end
end
The first.displayName.first code at the end looks a little goofy, and so might benefit from some explanation:
Net::LDAP#search always returns an array of results, even if you end up matching only one entry. The first call to first finds the first (and presumably only) entry that matched the email address.
The Net::LDAP::Entry returned by the search conveniently lets you access attributes via method name, so some_entry.displayName is the same as some_entry['displayName'].
Every attribute in a Net::LDAP::Entry is always an array of values, even when only one value is present. Although it might be silly to have a user with multiple "displayName" values, LDAP's generic nature means that it's possible. The final first invocation turns the array-of-one-string into just the string for the user's full name.
Have you tried looking at these:
http://saush.wordpress.com/2006/07/18/rubyrails-user-authentication-with-microsoft-active-directory/
http://xaop.com/blog/2008/06/17/simple-windows-active-directory-ldap-authentication-with-rails/
This is more anecdotal than a real answer...
I had a similar experience using Samba and OpenLDAP server. I couldn't find a library to really do what I wanted so I rolled my own helper classes.
I used ldapbrowser to see what fields Samba filled in when I created a user the "official" way and and basically duplicated that.
The only tricky/non-standard LDAP thing was the crazy password encryption we have:
userPass:
"{MD5}" + Base64.encode64(Digest::MD5.digest(pass))
sambaNTPassword:
OpenSSL::Digest::MD4.hexdigest(Iconv.iconv("UCS-2", "UTF-8", pass).join).upcase
For the def authenticate(user, pass) function I try to get LDAP to bind to the domain using their credentials, if I catch an exception then the login failed, otherwise let them in.
Sorry, cannot comment yet... perhaps someone can relocate this appropriately.
#Phrogz's solution works well, but bind_simple (inside bind) raises an Net::LDAP::LdapError exception due to auth[:username] not being set as shown here:
https://github.com/ruby-ldap/ruby-net-ldap/blob/master/lib/net/ldap.rb
The corrected replaces:
auth: { method: :simple, email: email, password:password }
with:
auth: { method: :simple, username: email, password:password }
I began using ruby-activedirectory, and even extended it/fixed a few things, hosting judy-activedirectory in Github.
Doing the next iteration, I've discovered ActiveLdap has a much better code base, and I'm seriously contemplating switching to it. Does anyone have personal experience with this?
Have you checked out thoughtbot's ldap-activerecord-gateway? It might be something for you to consider...
http://github.com/thoughtbot/ldap-activerecord-gateway/tree/master

Resources