Cannot retrieve session key from Betfair WebAPI c# - c#

I have been trying to log in to a Betfair account following these steps and using this source code. This works fine and I am returned a session key, however if I try to repeat the steps to get a session key in another project I receive a "CERT_AUTH_REQUIRED" error, implying that there is something wrong with the client certificate I am sending with my request.
Odder still, if I create another project that references the working Betfair project and get this new project to simply run the Program.Main method in the Betfair project I get the "CERT_AUTH_REQUIRED" message again?
When the Betfair application is the Launch project for the solution it works, but if I set the second project that launches the betfair console app as the startup project it doesn't return a success response (although the code runs fine and goes through all the same steps, it is just the web response that fails).
Does anyone have any idea why this might be?

I managed to get that code working for non-interactive log ins. I did make this change though. It sounds vaguely familiar as I remember having that error.
private WebRequestHandler getWebRequestHandlerWithCert(string certFilename)
{
var cert = new X509Certificate2(certFilename, "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(cert);
return clientHandler;
}

Another thing that I've just found can cause the same error is if you enter an export password during the step below. That may have changed since you created your key because it marks it as exportable so I didn't need to add X509KeyStorageFlags.Exportable in the code:
openssl pkcs12 -export -in client-2048.crt -inkey client-2048.key -out client-2048.p12
I assumed the export password was what the sample application was prompting for but it wasn't so the export password should be left blank.

Related

Identityserver fails to load selfsigned certificate

I'm trying to set a Certificate for identityserver and it keeps failing with a "no access to private key error".
Taking it out of identityserver, the following code throws an access denied error
static X509Certificate2 GetCertificateFromDisk()
{
using (var stream = File.Open(#"patht-to-pfx", FileMode.Open))
{
var cert = new X509Certificate2(ReadStream(stream), "password", X509KeyStorageFlags.MachineKeySet);
return cert;
}
}
When running the code as administrator it works fine, not when running it under my own account. Eventually I want to run it as localsystem.
I even added 'Everyone' under the certificates private key permissions in my local computer certificate store,
screenprint here
... still I get the exception.
What is wrong here? Going Crazy about it
Update
Great tips from CryptoGuy in the answer below. Important note: Opening the file is not correct only Identityserver3 still failed when getting the certificate from the store. What made it work was to regenerate the certificate using Keith Sparkjoy's tool SerfCert. My previous certificate was generated using powershell. So keep in mind that powershell certificates have issues with accessibility of private key. Thanks to Keith for the tool!
There are few things to consider.
1) you are performing write access to Local Machine store. X509KeyStorageFlags.MachineKeySet attempts to save private key to Local Machine store. Therefore, you need administrator permissions to write there. You should remove this flag to perform read-only access
2)
Documentation says that adding permissions in MMC (manage private key-option on a certificate) should allow this, but it doesn't seem to work
it works on an already saved private keys.
What you really should do is to import certificate and private key to Local Machine store and then configure your application to reference installed certificate.
3) if your application runs under unpriveleged account and the key don't need to be shared, then you should use Current User store.

Could not create SSL/TLS secure channel - works as exe but not in asp.net mvc

I have a problem with connectiong to an api over https. I wrote a little console application:
var handler = new WebRequestHandler();
X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly);
foreach (X509Certificate2 mCert in store.Certificates)
{
// add my locale certificate
if (mCert.FriendlyName == "some_identifier_name")
handler.ClientCertificates.Add(mCert);
}
var httpClient = new HttpClient(handler);
var response= httpClient.GetAsync("https://url-to-my.com/api/something").Result;
var result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
This little script works fine, I get a statuscode 200 and also the json data from the api. As you can see I have a certificate installed on my local machine, which I add in the code.
I tried the same script on my webserver and everything works fine there too!
But if I run the script in my mvc application I still get the message "The request was aborted: Could not create SSL/TLS secure channel".
Where is the difference with the same code if I run it as an exe or as a mvc website?
PS: This code is not the answer to my question, I already tried it:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Solution: IIS > Applications Pools > Chose your Apppool > Advanced Settings > Identity > Change to LocalSystem
Seems like you have to give your application pool enough rights to read the certificate from your local machine.
After spending 2 to 3 days for above issue, found following solution and you don't want to change "Identity" to "LocalSystem" (In Apppool Advance setting),
run up mmc.exe and choose File->Add/Remove Snap-in, select certificates on the left-hand list and when it asks you, choose Computer Account and Local Computer. Click OK to exit the selection page.
Open up the Personal->Certificates folder under the snap-in you just enabled. It is possible, that the Certificates folder doesn't exist (if it is empty).
Right-click in the contents pane of Personal or Certificates and choose All Tasks->Import
Go through the wizard to import your certificate and select the option to "mark it exportable" which is usually needed for SSL usage (I think it includes the private key only when this is ticked).
With the certificate imported, select it, choose All Tasks->Manage Private Keys
You will get a familiar security dialog where you can add users who can access the private key. Add the account for the user that is running the application pool for your web site.
If you are using "App Pool Identity", then the users are found with IIS Apppool\app.pool.name Note that if you are running some versions of Windows Server, you will need to change the "location" parameter to point to the local machine rather than the domain which is selected by default, otherwise the user won't be found.
Reference : http://lukieb.blogspot.com/2015/04/the-request-was-aborted-could-not.html

PushSharp APNS Service Stop working after windows shutdown

I can send notifications to my iPhone device succeffully using Push Sharp via sandbox APNS server but I am having a problem.
I have generated .cer and .p12 files and then installed them on my windows 8 development machine successfully.
I used this tutorial to install the certificates on my windows 8 machine.
Yesterday things were working fine and I was sending the notification successfully. I shutdown my system and then next day when I try to run the code I was getting following exception:
the message was unexpected or badly formatted pushsharp
I tried different solution available on Google but nothing helped. Then I delete the certificates from my machine and then re-install them and things started to work again.
In order to make the service fool proof I shutdown the system to check if notification sending fails or not, and yes it fail again with the same exception.
I again deleted the certificates and re-install them to correct the issue. I do not know whats the actuall problem? what makes PUSHSharp to stop sending notification after shutdown.
Note: Windows firwall is disabled.
Any idea?
I have been working with PushSharp for the past few weeks and have not had this problem. My environment is Windows 7 however. After you've created the appropriate Push Notification Certificate in iPhone Developer Program Portal you should have downloaded a file named something like apn_developer_identity.cer. If you have not done so already, you should open/import this file into Keychain, into your login section.
Finally, if you filter Keychain to show your login container's Certificates, you should see your Certificate listed. Expand the certificate, and there should be a Key underneath/attached to it.
Right Click or Ctrl+Click on the appropriate Certificate and choose Export. Keychain will ask you to choose a password to export to. Pick one and remember it. You should end up with a .p12 file. You will need this file and the password you picked to use the Notification and Feedback Libraries here.
OpenSSL
Here is how to create a PKCS12 format file using open ssl, you will need your developer private key (which can be exported from the keychain) and the CertificateSigningRequest??.certSigningRequest
Convert apn_developer_identity.cer (der format) to pem:
openssl x509 -in apn_developer_identity.cer -inform DER -out apn_developer_identity.pem -outform PEM}
Next, Convert p12 private key to pem (requires the input of a minimum 4 char password):
openssl pkcs12 -nocerts -out private_dev_key.pem -in private_dev_key.p12
(Optional): If you want to remove password from the private key:
openssl rsa -out private_key_noenc.pem -in private_key.pem
Take the certificate and the key (with or without password) and create a PKCS#12 format file:
openssl pkcs12 -export -in apn_developer_identity.pem -inkey private_key_noenc.pem -certfile CertificateSigningRequest??.certSigningRequest -name "apn_developer_identity" -out apn_developer_identity.p12
Once you generate the p12 file using these steps you will not really need to snap it to your console. You will just need to make changes in your code as follows:
var appleCert = File.ReadAllBytes("C:/Certificate/aps_dev_identity.p12");
Hope this helps.
I have been working on MOON APNS since 2012 and it's working fine but from last few days i am getting below error message
Error Message : System.Security.Authentication.AuthenticationException: A Call to SSPI failed, see inner exception.
System.ComponentModel.Win32Exception: The message received was
unexpected or badly formatted
Solution : in PushNotification.cs file replace
_apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Ssl3, false);
with
_apnsStream.AuthenticateAsClient(host, certificates, System.Security.Authentication.SslProtocols.Tls, false);
As, I didn't find any confirmation from apple side but from github.com I found solution for this and it's work for us.
It's seems that apple depricate "unsafer" protocol SSL.
Check first if you can do the notifications with C# code like this one first, then worry about the installation. I had the same message when I was trying to execute the code, I didn't care about installation, and solved it by making sure that I use a certificate of type .p12 and not .pem and to make sure that the .p12 had a password. I can now send notifications to my iPhone from a console C# app in my pc.

SSL Certificates doesn't work

My problem is that I have an application on .net is mvc
The application make "Facturas Electronicas" for the company that I work.
If I run the application on my computer from the visual studio, the application works fine.
But if I publish the app to another server the application doesn't make the "Factura Electronica", but before this erros the application works fine on other servers.
All started when I publish another app with the same code, and needs the same certificates but it is to other product and i need the two applications.
After checking all the code I realize that the problem was the certificate a pfx file,
when the app try to execute this
X509Certificate2 cert = new X509Certificate2(certificadoDemo, claveCertificadoDemo);
the navigator return this
This webpage is not available
the expiration of the pfx file is until july 2014
Do anyone knows what is going on?
adding this
X509KeyStorageFlags.MachineKeySet
to that line of code i resolved the problem
this is the new line of code
X509Certificate2 cert = new X509Certificate2(certificadoDemo, claveCertificadoDemo, X509KeyStorageFlags.MachineKeySet);
thanks
Your question cannot be answered without a detailed exception. Either turn off customErrors in the web.config file (in which case, the entire exception will be sent to the browser) or catch errors in Global.asax Application_Error event handler and log the errors to a file somehow (using System.Diagnostics preferably). Without more sample code, we can't even know which constructor you're calling because X509Certificate2 has 5 constructors which take two parameters. See http://sscce.org/ on how to ask questions.

Accessing Impersonated users key store

I am impersonating a service user account in order to connect to a webservice that requires a cert to connect. I have installed the client cert on the service account on the machine which is running the code however I receive the error System.Security.Cryptography.CryptographicException: The system cannot find the file specified.
using (var ctx = new ImpersonationContext("svcAcctUserName", "domain", "password"))
{
var clientCert = new X509Certificate2("filePath", "certPassword");
}
The impersonation code works, for brevity I have left it out but I check to make sure my context is switched to the svcAcctUserName user by logging the Environment.UserName, which shows that I am running as svcAcctUserName. The filePath is correct, again I left it out, but I open and close the file before I create the X509Certificate2 object to make sure I have both access to the file and that my path is correct.
The error is confusing since I provide the path as a parameter and I know for certain the user running the code has access.
EDIT:
Also tried to do this: How to call a Web service by using a client certificate for authentication in an ASP.NET Web application
Although I am not using an asp.net application, I gave it a try anyway. I added the certificates add-in to the mmc, added the "local computer" certificates add in and then imported the cert into the Personal store of the local machine.
I then ran:
WinHttpCertCfg.exe -g -c LOCAL_MACHINE\My -s issuedToName -a domain\svcAcctUserName
Tried running the operation again, still same problem.
What am I missing?
So, as Alex pointed out, I do not understand the underlying architecture of certificate system in windows. However, after performing the above steps and modifying my code to use the X509Store, I have it working. Hopefully this will help someone:
using (var ctx = new ImpersonationContext("svcAcctUserName", "domain", "password"))
{
var store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var clientCert = store.Certificates.Find(X509FindType.FindByIssuerName, "IssuerNameHere", false);
var clientCert2 = new X509Certificate2(clientCert[0]);
}

Categories

Resources