PayPal API With ActiveMerchant (Legacy Code) - ruby-on-rails

I've inherited some legacy Rails code (2.1.3) and there appears to be a public_cert as well as a signature. I thought PayPal used one or the other, but my configuration seems to have both:
config.app_config.pay_pal.merge!(
:password=>"WHATEVER",
:public_key=>"-----BEGIN CERTIFICATE-----\nMIICmTCCAgKgAwIBAgIDEcmhMA0GCSqGSIb3DQEBBQUAMIGZMQswCQYDVQQGEwJV\nUzETMBEGA1UECBMKQ2FsaWZvcm5pYTERMA8GA1UEBxMIU2FuIEpvc2UxFTATBgNV\nBAoTCHANGEDSTUFFqe0RzCDhQmVhgtNWZxeqzjVbVrCx80jF1\nWi/+ksJQLPViFj9+F4WS5i4MjMeCIwIDAQABow0wCzAJBgNVHRMEAjAAMA0GCSqG\nSIb3DQEBBQUAA4GBAMwavx4Eh2JCOCOc/WvL7zdRL07So48mQ9aJr4Bxdgib+/z2\nkqX0ZPJv9T6NQ1h9lcwohIuaJMXtLAysJMjvKcvPdzcHqB6Xv+OGpi2REJjUdB39\n9amutkxQVhKBfK3hCP4+8UlM1yzxejyK8SVWSJCbc5zvJFoLV4SZcbNevtw9\n-----END CERTIFICATE-----\n",
:business=>"me#site.com",
:business_id=>"4WSDFSFSDF",
:login=>"me_api1.site.com",
:cert_id=>"AAAA",
:private_key=>"-----BEGIN RSA PRIVATE KEY-----\nMIICXAIBAAKBgQDm5fXKcp6ht6+Be4Y7VOaNvEPZwVqRt0CHANGEDMORESTUFFKTF7Mozcg12qiq1VDqFYwQF\n8gteGGLFy3GKPWlpqtJzAI4xfpI07d2ivgfXkk4Q74np+P8udulM0bEA+WAoGO6e\nHZ7g0/EbutA0+H5TTSp3gUYa5xcUhSrMiYN/r6HK+aeKnNECQQD8D/oBjEsZwsAB\n2KxDLZfEcrmFiLxjqQSBKPtMJP0Lrhl7OyB2v1o3QDA5+QdbDFbRxA1RNQfw+ZXo\nPuP49DRpAkEA6oFYlNnGvNWlHxDmVob5q88HEgP/ZEWFJXzZcSsAkJNrbdyPCdSj\nxN2M0duJlegJlfsr6l9OyBeFcSXnrVSAqwJBAO7BP2FJ/zUGeJMHJpx3SkOFG9+1\nliScSy0AoZANlTcEERTd+7EfLZgaD9RJ40LF3FLTbn3WSpBiCTG0qIH+5skCQF4K\n5SU8eJC99OwScOz+UB3wdltpMwBZSN4RxXm2zxErrYdvTgWZOtv2JUT7j5+IYF+/\nTIs/EW74z9DibJh8LOUCQEsMclIUTorjVVtAgI5LiSwenDSCgf9Ra0r3CoL3dAGz\n1RskSziPqfQyA2QDFfSPkmycgxPlZvP0G8fwuBs6sjI=\n-----END RSA PRIVATE KEY-----\n",
:signature=>"AwhNvKUCHANGEDSTUFF9xveB4"
)
I'm using PayPal Payments Standard I believe with Rails ActiveMerchant.
Any help would be greatly appreciated

PayPal only allows you to use one or the other. It may have been that the previous person generated the cert or signature and added it to the code, only to switch over to the other method at a later date and never removed it from the code. If it's currently working and processing payments on the PayPal account, you could log into the PayPal account and see which one is currently active on the account. You are only going to see one or the other. Which ever one you are seeing, means the other one would not be being used. If it's not showing, it would not be valid anymore.
Another option, would be you could walk thru the code and see where the API call is being made, and check which one it is sending across to PayPal.

Related

How to test two-factor authentication with QR images

I'm currently in the process of adding two-factor authentication to a rails app. I added a process that lets users enable two-factor authentication, by using a QR code to verify themselves. I'm using this gem: https://github.com/Houdini/two_factor_authentication, which lets you generate a provisioning uri that can be turned into a QR code. The user can then scan this with apps like Authy or Google authenticator, to get a one-time password.
I'm now at the point where I need to write tests for this, and I therefore need to be able to automate the process of getting security codes from the provisioning uri, without the need to scan it with an app.
So my question is: Is it possible to get the secret key, that you would get by scanning the QR code, programmatically and if so, how?
The app is based on Ruby on rails 5.2.
When you want to test a feature from a specific gem, in the most cases you can find some clues in the original repo. Popular gems usually are well tested. Take a look here https://github.com/Houdini/two_factor_authentication/blob/master/spec/lib/two_factor_authentication/models/two_factor_authenticatable_spec.rb#L182
You have two options:
Find a way to read the QR in Ruby. This would most resemble what the user has to do, but may be hard (I don’t know — I've never done it).
Generate the 6-digit code (the "TOTP code") yourself. This feels a little more hacky (and dives into some implementation details, I suppose) but is easier to do than option 1.
For option 2, you can use the rotp gem (which Houdini uses itself) and the secret key you generate through Houdini.
secret_key = user.generate_totp_secret
# then...
totp = ROTP::TOTP.new(secret_key)
totp.now # --> the 6-digit code
(You can see how Houdini uses the rotp gem here.)

Setting up third-party server to interact with Game Center

I'm thinking of adding a feature to my iOS game to allow players to create their own game levels, share them with other players, rate them, etc. There'd be a public repository of user-created levels, sortable by creation date, rating, difficulty, or other criteria.
This kind of functionality would necessitate a third-party server. I was thinking I'd create a RESTful API using Sinatra and run it on Heroku. My question is: what would be the best way to authenticate requests to this API? I would prefer not to require players to create a username and password. I'd like to just use Game Center's ID system.
Any suggestions? I've never done any server-side stuff before so any help is appreciated!
Clarification
Yes, I'm aware that Apple doesn't provide its own system. But it does give developers access to unique Game Center identifiers (developer.apple.com/library/mac/#documentation/…) and I was hoping I could use that somehow to roll my own authentication system without requiring users to sign on via Facebook/Twitter/etc. If that's possible.
Looks like as of iOS 7, this is possible with Game Center using:
[localPlayer generateIdentityVerificationSignatureWithCompletionHandler]
Once you have verified the identity of the player using the generateIdentity call,
Associate the player id with a user on your server's db
Use whatever access token / authentication pattern your REST framework provides for subsequent calls
https://developer.apple.com/library/ios/documentation/GameKit/Reference/GKLocalPlayer_Ref/Reference/Reference.html
Also for reference, here is the dictionary that we end up sending off to our server based on the response from generateIdentityVerificationSignatureWithCompletionHandler
NSDictionary *paramsDict = #{
#"publicKeyUrl":[publicKeyUrl absoluteString],
#"timestamp":[NSString stringWithFormat:#"%llu", timestamp],
#"signature":[signature base64EncodedStringWithOptions:0],
#"salt":[salt base64EncodedStringWithOptions:0],
#"playerID":localPlayer.playerID,
#"bundleID":[[NSBundle mainBundle] bundleIdentifier]
};
edit: as if when I posted this there was no official solution from Apple, but there is now. See the other answers for that, or read on purely for historical / backwards-compatibility interest.
Apple doesn't provide any sort of system for using Apple ID authentication (which includes Game Center) with third-party services. You're on your own for authentication, though you could look into OAuth for allowing single-sign-on via Facebook/Twitter/etc. (Just beware that not everyone has a Facebook/Twitter/etc identity, or one that they want to use for your game.)
In theory, the playerID property on GKPlayer is unique, constant, and not known to anyone else. So, in theory, you could use it for "poor man's authentication": present it to your server, and that's all the server needs to look up and provide player-specific stuff. But this is like authentication by UDID, or by user name only -- the only security it provides is obscurity. And what happens when you have a user who's not signed into Game Center?
Andy's answer is on the right track, but to finish the story: in those docs that he links to, there's an explanation of how to actually authenticate against Apple services that the GameCenter user actually is who he is claiming to be. Link to that part of the docs is below. Basically, the call on the client to generateIdentityVerificationSignatureWithCompletionHandler gives your some data including a URL. You give that data and the URL to your own server, and then from your server you can hit that URL to authenticate the user with the rest of the data that was provided by the call to generateIdentityVerificationSignatureWithCompletionHandler.
https://developer.apple.com/library/ios/documentation/GameKit/Reference/GKLocalPlayer_Ref/index.html#//apple_ref/occ/instm/GKLocalPlayer/generateIdentityVerificationSignatureWithCompletionHandler:
I had a heck of a time figuring this out. I finally used a few hints from this answer, a couple of other SO answers, the php docs and some lucky guessing to come up with this complete answer.
NOTE: This method seems very open to hacking, as anyone could sign whatever they want with their own certificate then pass the server the data, signature and URL to their certificate and get back a "that's a valid GameCenter login" answer so, while this code "works" in the sense that it implements the GC algorithm, the algorithm itself seems flawed. Ideally, we would also check that the certificate came from a trusted source. Extra-paranoia to check that it is Apple's Game Center certificate would be good, too.

How to debug failed transactions with PayPal Express Checkout?

We're using PayPal Express Checkout (implemented in Ruby, Active Merchant gem)
A few transactions failed recently, while majority work fine.
I have looked at our log file and identified the user who had failed transactions.
I have the transaction token, PayerID, user's email address, correlation ID.
I have contacted PayPal technical support about this and provided them with the above details.
But I wonder if it's possible to get more information about these failed transactions myself.
Does the Ruby gem Active Merchant provide an easy way to get it from PayPal?
Thanks
The only information you really get back, is just basically what comes back in the API response. Sometimes this is enough to determine what the cause of the issue is, other times it requires a little bit more looking into and PayPal MTS would need to look into it.
There are a few things you can do here to harden the Express Checkout implementation:
Monitoring Error Code Responses
Express Checkout will send back a series of error codes on failed transactions. What you can do is monitor these specific error responses and that will give you an idea of what the problem with the transaction is, and in doing so you'll be able to respond accordingly (such as trying to transaction again). Here are the error code responses for Express Checkout: http://www.paypalobjects.com/en_US/ebook/PP_APIReference/Appx-ErrorCodes_and_Messages.html#2270815
Looking up Transaction Data
Besides the error codes, you can also use a GetTransactionDetails API operation to grab information about some transaction that might have had a problem. This will return some useful information that would help you to handle these cases as well. This information is available here: https://www.x.com/developers/paypal/documentation-tools/api/gettransactiondetails-api-operation-nvp
Hope that helps,
Jon

Activemerchant ogone => Merchant not active

I'm trying to implement a ogone test account in my rails development application, but I keep getting the error message 'Merchant not active'
After some investigation I believe it has something to do with the SHA encoding?
Problem is I don't really get how this works, Ogone has multple SHA parameters to fill out and I haven't found a way in activemerchant to put it in there.
Someone with some experience in this matter?
The reason you are getting the Merchant not active error is because your account is not configured to be able to use Direct Link or several other options. To activate this you should get a higher subscription or contact their support and ask them to activate it for you.
As for SHA, you need to configure a secret passphrase by which you separate the parameters you're sending. For instance:
Passphrase: ogonepass123
Post variables: CN=JohnDoeogonepass123AMOUNT=1000ogonepass123CURRENCY=EURogonepass123PSPID=MyPSPID
Eventually you Hash your post variables to SHA-1 and add that key to your post parameters as
....ogonepass123SHASIGN=<40-characters-SHA-key>
This way you secure your data and make sure nobody can tamper with those variables.
Also make sure that when you get a response from Ogone you re-form a SHA hash using the parameters they've send you and you then compare this own-formed SHA hash with the one sent to you by Ogone. If these two match you can be sure that the parameters have not been messed with.
Hope this helps you or others who come across this question.
to work with Ogone Direct Link with an account created after Mai 10, 2010 you will need this patches : https://github.com/Shopify/active_merchant/pull/85
(This also works with accounts created before this date.)
This will also give you more details on the aliases usage, fix some issues with new updates from Ogone, ... make sure to read the inline doc within the ogone gateway code : https://github.com/ZenCocoon/active_merchant/blob/master/lib/active_merchant/billing/gateways/ogone.rb
As of today, the SHA1 is supported and to be used.

Implementing a 2 Legged OAuth Provider

I'm trying to find my way around the OAuth spec, its requirements and any implementations I can find and, so far, it really seems like more trouble than its worth because I'm having trouble finding a single resource that pulls it all together. Or maybe it's just that I'm looking for something more specialized than most tutorials.
I have a set of existing APIs--some in Java, some in PHP--that I now need to secure and, for a number of reasons, OAuth seems like the right way to go. Unfortunately, my inability to track down the right resources to help me get a provider up and running is challenging that theory. Since most of this will be system-to-system API usage, I'll need to implement a 2-legged provider. With that in mind...
Does anyone know of any good tutorials for implementing a 2-legged OAuth provider with PHP?
Given that I have securable APIs in 2 languages, do I need to implement a provider in both or is there a way to create the provider as a "front controller" that I can funnel all requests through?
When securing PHP services, for example, do I have to secure each API individually by including the requisite provider resources on each?
Thanks for your help.
Rob, not sure where you landed on this but wanted to add my 2 cents in case anyone else ran across this question.
I more or less had the same question a few months ago and hearing about "OAuth" for the better part of a year. I was developing a REST API I needed to secure so I started reading about OAuth... and then my eyes started to roll backwards in my head.
I probably gave it a good solid day or 2 of skimming and reading until I decided, much like you, that OAuth was confusing garbage and just gave up on it.
So then I started researching ways to secure APIs in general and started to get a better grasp on ways to do that. The most popular way seemed to be sending requests to the API along with a checksum of the entire message (encoded with a secret that only you and the server know) that the server can use to decide if the message had been tampered with on it's way from the client, like so:
Client sends /user.json/123?showFriends=true&showStats=true&checksum=kjDSiuas98SD987ad
Server gets all that, looks up user "123" in database, loads his secret key and then (using the same method the client used) re-calculates it's OWN checksum given the request arguments.
If the server's generated checksum and the client's sent checksum match up, the request is OK and executed, if not, it is considered tampered with and rejected.
The checksum is called an HMAC and if you want a good example of this, it is what Amazon Web Services uses (they call the argument 'signature' not 'checksum' though).
So given that one of the key components of this to work is that the client and server have to generate the HMAC in the same fashion (otherwise they won't match), there have to be rules on HOW to combine all the arguments... then I suddenly understood all that "natural byte-ordering of parameters" crap from OAuth... it was just defining the rules for how to generate the signature because it needed to.
Another point is that every param you include in the HMAC generation is a value that then can't be tampered with when you send the request.
So if you just encode the URI stem as the signature, for example:
/user.json == askJdla9/kjdas+Askj2l8add
then the only thing in your message that cannot be tampered with is the URI, all of the arguments can be tampered with because they aren't part of the "checksum" value that the server will re-calculate.
Alternatively, even if you include EVERY param in the calculation, you still run the risk of "replay attacks" where a malicious middle man or evesdropped can intercept an API call and just keep resending it to the server over and over again.
You can fix that by adding a timestamp (always use UTC) in the HMAC calculation as well.
REMINDER: Since the server needs to calculate the same HMAC, you have to send along any value you use in the calculation EXCEPT YOUR SECRET KEY (OAuth calls it a consumer_secret I think). So if you add timestamp, make sure you send a timestamp param along with your request.
If you want to make the API secure from replay attacks, you can use a nonce value (it's a 1-time use value the server generates, gives to the client, the client uses it in the HMAC, sends back the request, the server confirms and then marks that nonce value as "used" in the DB and never lets another request use it again).
NOTE: 'nonce' are a really exact way to solve the "replay attack" problem -- timestamps are great, but because computers don't always have in-sync timestamp values, you have to allow an acceptable window on the server side of how "old" a request might be (say 10 mins, 30 mins, 1hr.... Amazon uses 15mins) before we accept or reject it. In this scenario your API is technically vulnerable during the entire window of time.
I think nonce values are great, but should only need to be used in APIs that are critical they keep their integrity. In my API, I didn't need it, but it would be trivial to add later if users demanded it... I would literally just need to add a "nonce" table in my DB, expose a new API to clients like:
/nonce.json
and then when they send that back to me in the HMAC calculation, I would need to check the DB to make sure it had never been used before and once used, mark it as such in the DB so if a request EVER came in again with that same nonce I would reject it.
Summary
Anyway, to make a long story short, everything I just described is basically what is known as "2-legged OAuth". There isn't that added step of flowing to the authority (Twitter, Facebook, Google, whatever) to authorize the client, that step is removed and instead the server implicitly trusts the client IF the HMAC's they are sending match up. That means the client has the right secret_key and is signing it's messages with it, so the server trusts it.
If you start looking around online, this seems to be the preferred method for securing API methods now-adays, or something like it. Amazon almost exactly uses this method except they use a slightly different combination method for their parameters before signing the whole thing to generate the HMAC.
If you are interested I wrote up this entire journey and thought-process as I was learning it. That might help provide a guided thinking tour of this process.
I would take a step back and think about what a properly authenticated client is going to be sending you.
Can you store the keys and credentials in a common database which is accessible from both sets of services, and just implement the OAuth provider in one language? When the user sends in a request to a service (PHP or Java) you then check against the common store. When the user is setting up the OAuth client then you do all of that through either a PHP or Java app (your preference), and store the credentials in the common DB.
There are some Oauth providers written in other languages that you might want to take a look at:
PHP - http://term.ie/oauth/example/ (see bottom of page)
Ruby - http://github.com/mojodna/sample-oauth-provider
.NET http://blog.bittercoder.com/PermaLink,guid,0d080a15-b412-48cf-b0d4-e842b25e3813.aspx

Resources