Web Services with x.509 certificates. Porting C# code to Rails - c#

I am currently in the process of building a new web-based system in rails to replace a legacy .NET solution (stand-alone Win32 app). The system allows analysts to perform a number of actions. In many cases, the users request is actually served by a call to a third-party web-service. The web services are secured using X.509 certificates issued by the third-party. The .NET code to make the calls is below:
(In Visual Studio, I have declared a web/service reference called 'ProductionServices' at the corresponding URL)
X509Certificate2 c = new X509Certificate2("filepath", "password");
using (ProductionServices.Items items = new ProductionServices.Items())
{
try
{
//specify client certificate if needed
if (c != null)
items.ClientCertificates.Add(c);
XmlNode node = null;
node = items.getItemList();
XmlDocument xd = new XmlDocument();
xd.AppendChild(xd.ImportNode(node, true));
.......
}
So, at this point we have our rails app looking nice and polished. However, I now need to replicate the .NET logic above in rails so that I can pull that web service data into my views as well. I have found very basic examples of how to do this, but never a good example using client certificates. Can anyone point me in the right direction?
Any help is greatly appreciated.
Thanks.

Assuming you're using Net::HTTP, take a look here:
http://www.rubyinside.com/nethttp-cheat-sheet-2940.html
and about halfway down the page there's an example entitled "SSL/HTTPS request with PEM certificate".
If you're using some kind of wrapper around Net::HTTP (HTTParty, Typhoeus, etc.) that'll depend on the library in question. Is that the case?

Related

How does one create a TranslationServiceClient using a json as authentication?

Hello and thanks for reading my question.
I'm working on transitioning some code from Google.Cloud.Translation.V2 to Google.Cloud.Translate.V3 because we need to make use of the api advanced features.
We are using a TranslationClient to get us the translations (from the V2 library) but we need to instead use the TranslationServiceClient (from the V3 library.)
I'm having trouble instantiating a TranslationServiceClient with our credentials. The way to do it in V2 is straightforward:
TranslationClient.Create(GoogleCredential.FromJson("{\"the credentials\"}"));
From reading the documentation it is clear to me that to create a TranslationServiceClient without the default settings you need to use a TranslationServiceClientBuilder and give that the credentials. I couldn't find any examples, all of the code snippets use TranslationServiceClient.Create() which doesn't allow for any arguments.
Since the goal is to create a TranslationServiceClient using a json as authentication, one way to do this is as follows:
TranslationServiceClient client = new TranslationServiceClientBuilder {
JsonCredentials = "{\"the credentials\"}"
}.Build()
More info at https://cloud.google.com/docs/authentication/production#passing_the_path_to_the_service_account_key_in_code

asp.net .asmx web service ishow XXE vulnerability - External DNS

We have uncovered an XML External Entity vulnerability in our asp.net asmx web service.
We are testing an asp.net .asmx web service using burp suite, to check for XML External Entity Processing vulnerabilities. See:
https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html#net
We see that when a DTD is included in the request like this:
<!DOCTYPE soapenv:envelope PUBLIC "-//B/A/EN" "http://1234565.cigitalcollaborator.com">
A DNS request is sent to for cigitalcollaborator.com. This indicates the asmx web service is processing the DTD in request.
We are using .net version 4.5.2.
According to this link, XXE vulnerabilities should be implicitly blocked for .net 4.5.2 and later:
https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Prevention_Cheat_Sheet#.NET_4.5.2_and_later
But it's not... We ge this DNS lookup.
The underlying .net framework is handling XML deserialization/serialization for this asmx web service, so there's no code for us to really fix here. We cannot alter the behavior right, because it's somewhere in the underlying framework?
How we can fix this XXE vulnerability for our ASMX web service?
Thank you
Jon Paugh
I think that it is important to consider two different points here:
First - An automated scan designed to work across web applications using all manner of different technologies does not prove that a vulnerability is present. A DNS lookup is not the same as fully processing the Entity in question. If a subsequent request is made to the url in question, and data from that is processed then you have a vulnerability. You can configure your application use a proxy like Fiddler to verify if such a request is made.
Secondly, .NET has been secure since 4.5.2 by default. This is not the same as guaranteed secure. If an application requires DTD processing it can be enabled in the settings:
var xmlReaderSettings = new XmlReaderSettings();
xmlReaderSettings.DtdProcessing = DtdProcessing.Parse;
var xmlReader = XmlReader.Create(new StringReader("EvilXml", xmlReaderSettings));
Or
var xmlTextReader = new XmlTextReader(new StringReader("EvilXml");
xmlTextReader..DtdProcessing = DtdProcessing.Parse;
And with an XDocument resolver implementations process DTDs
var xmlDocument = new XmlDocument();
// Implementations of XmlResolver are probably unsafe
xmlDocument.XmlResolver = new MyCustomResolver();
// xmlDocument.XmlResolver = null is safe - should be the default from 4.5.2
xmlDocument.LoadXml("EvilXml");
I would probably search the source code for the two relevant text strings "DtdProcessing.Parse" and "XmlResolver" to rule this out.
ASXM web services are considered legacy and don't receive all bug fixes as they have limited extension points. You probably want to re-write this or at least put a facade in front of it using like WCF or WebAPI...
Sadly the connect articles referring to this have been taken down with connect retiring but there are references from people to linking to them:
"They are based on the old XML Serialization technology, which is not getting bug fixes. (see Microsoft comment on 1/11/2010)"
https://johnwsaunders3.wordpress.com/

Consuming a web service using POST instead of the going the usual WSDL route

This is how I have currently managed to consume a particular Microsoft web service. Notice that it is located on an HTTPS server and that it requires a username, a password, and a .cer file to be installed in the operating system's "root certificate authorities".
WSHttpBinding binding = new WSHttpBinding();
binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
binding.Security.Message.NegotiateServiceCredential = true;
binding.Security.Message.AlgorithmSuite
= System.ServiceModel.Security.SecurityAlgorithmSuite.Default;
binding.Security.Message.EstablishSecurityContext = true;
EndpointAddress endpoint = new EndpointAddress("https://address.of.service");
//"GreatClient" was created for me automatically by running
//"svcutil.exe https://address.of.service?wsdl"
GreatClient client = new GreatClient(binding, endpoint);
//Username and password for the authentication. Notice that I have also installed
//the required .cer certificate into the system's "root certificate authorities".
client.ClientCredentials.UserName.UserName = "username";
client.ClientCredentials.UserName.Password = "password";
//Now I can start using the client as I wish.
My question is this: How can I obtain all the information necessary so that I can consume the web service with a direct POST to https://address.of.service, and how do I actually perform the POST with C#? I only want to use POST, where I can supply raw XML data using POST directly to https://address.of.service and get back the result as raw XML data. The question is, what is that raw XML data and how exactly should I send it using POST?
(The purpose of this question: The reason I ask is that I wish to consume this service using something other than C# and .NET (such as Ruby, or Cocoa on Mac OS X). I have no way of knowing how on earth to do that, since I don't have any easy-to-use "svcutil.exe" on other platforms to generate the required code for me. This is why I figured that just being able to consume the service using regular POST would allow me to more easily to consume the service on other platforms.)
What you are attempting to do sounds painful to do now and painful to maintain going forwards if anything changes in the server. It's really re-inventing the wheel.
If you haven't considered it already, I would:
(a) Research whether you can use the metadata you have for the service and use a proxy generator native to your target plaform. There aren't many platforms that don't have at least some tooling that might get you part of the way if not all of it. Perhaps repost a question targetting Ruby folk asking what frameworks exist to consume an HTTPS service given it's WSDL?
(b) Failing that, if your scenario allows it I would consider using a proxy written in C# that acts as a facade for the service which translates it into something easier to consume (for example, you might use something like ASP.NET MVC WebAPI which is flexible and can easily serve up standards compliant responses over which you can maintain total control).
I suspect one of these may prove easier and more valuable than the road you are on at the moment.
I had to go through something similar when porting .NET WCF code to other platforms. The easiest approach I found was to enable message logging on the WCF client. This can be configured to save both envelope and body and once everything is working on the .NET side of the house, you can use the message log to have "known-good" XML request/response to port to other platforms.
I found this approach to be more elegant since I didn't have to add an additional behavior to log messages, and it can be easily enabled/disabled/tweaked in the config. The Service Trace Viewer Tool that ships with Visual Studio is also handy for reviewing the log files.
I think when you say that the service should be consumed from other platforms, which do not have proxy class generation logic, you can go with REST services. This will allow you to create input as simple string concatenation instead of complex XML. Though its applicability depends on the situation.
Check this discussion : http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/6907d765-7d4c-48e8-9e29-3ac5b4b9c405/
As far as the certificate is concerned, refer http://msdn.microsoft.com/en-us/library/ms733791.aspx on how to configure it.
I know this is not a very precise answer, but you will be the best person to evaluate above procedure, hence posted. Hope it helps.
What I'll do:
1- Create a small c# app that can post on this webservice (using svcutil). And modify it to show the XML send/received. To view the xml there are several ways: logging, wireshark etc. To add it directly to the small app there is another question here that give a good answer.
2- Once you know what you have to send, you can do it in c# like this:
// implement GetXmlString() to return the XML to post
string xml = GetXmlString();
// create the url
string url = new UriBuilder("http","address.of.service",80).ToString();
// create a client object
using(System.Net.WebClient client = new System.Net.WebClient()) {
// performs an HTTP POST
client.UploadString(url, xml);
}
I'm not a .NET programmer but I've had to interoperate with a few .NET services and have lots of SOAP/WSDL experience. Sounds like you've captured the XML for your service. The other problem you'll face is authentication. OOTB, .NET web services use NTLM for authentication. Open-source language support for NTLMv2 can be hit and miss (although a quick google search pulled up a few possibilities for ruby), and using NTLM auth over HTTP may be something that you have to wire together yourself. To answer a question above: where are the auth creds? If the service is using NTLM over the wire, authentication is happening at some layer below HTTP. If the service is using NTLM to authenticate HTTP, your NTLM creds are in the HTTP Authorization header. You should be able to tell with wireshark where they are. You'll also probably need a SOAPAction header; this can also be sniffed with wireshark. For the C# client, I'm sure there are docs explaining how to add headers to your request.

C# Amazon Product Advertising API

As of August 15, Amazon made it compulsory to sign all requests made to their Product Advertising API. I thought I had got everything working just fine but when the 15th finally came around, my web application stopped working and pretty much ever since I have been trying to find out how to sign the SOAP requests.
Amazon has an outdated sample code for signing requests that doesn't appear to work here
Basically, I need to know how to add a signature to the my requests using the most current C# SOAP API and .NET 3.5.
I hope I have given enough details, if I haven't please feel free to ask me to elaborate.
Thank You
The_Lorax
UPDATE:
I am using MVC and need to know how to add the Signature to the the ItemLookup or AWSECommerceService object. Is there an attribute that contains the signature value? How does it get attached to the request?
On this page, they say that I must include the Signature and TimeStamp parameters but the intellisense does now show any such attributes.
Check out http://flyingpies.wordpress.com/2009/08/01/17/. It has a walkthrough and a sample visual studio solution using C#, SOAP, WCF on .NET 3.5.
This library automatic sign the requests (Install-Package Nager.AmazonProductAdvertising)
https://www.nuget.org/packages/Nager.AmazonProductAdvertising/
Example:
var authentication = new AmazonAuthentication("accesskey", "secretkey");
var client = new AmazonProductAdvertisingClient(authentication, AmazonEndpoint.US);
var result = await client.SearchItemsAsync("canon eos");

ICerfiticatePolicy and ServicePoint

So I'm using the PayPal API. They require bigger companies to send an X509Certificate along with each SOAP API request. I've never heard of using a cert, it's always been just send the API signature along with an API request.
So I first created a class called Cerficate that implements the .NET ICerfiticatePolicy. One of the member methods, really the only one you have to implement is:
System.Net.ICertificatePolicy.CheckValidationResult(System.Net.ServicePoint, System.Security.Cryptography.X509Certificates.X509Certificate, System.Net.WebRequest, int)
So far I'm having trouble really understanding what to pass to this method. I guess the method simply validates that the Cerfiticate is valid. So I'm not sure what ServicePoint is and what to pass into it. I assumed it was my web service reference and a proxy class within such as the PayPalAPIAAInterfaceClient
I also see a very old example using ServicePointManager.S for something but I don't understand it, even after looking at MSDN. So I guess you are to use ServicePointManager.ServerCertificateValidationCallback and I suppose set the callback to the CheckValidationResult? If so, when do you do this? It's just very confusing to me.
Also, So I guess I create an instance of my Certificate class and set the certificate properties by reading the P12 certificate from my disk and then pass in that to this method to check if it's valid? I guess that's right.
I'm still trying to figure out this whole thing and I'm really stuck on the ServicePoint as well as WebRequest because really I'm using a proxy class in PayPal which does the under the hood sending of the request. So I don't see how I can even pass in type WebRequest because I'm using a proxy method for that anyway. So what would I even pass for the WebRequest param? I'm using a SOAP API WSDL, not NVP here so I'm not for example creating an HttpWebRequest variable like you do with REST services in order to send the API request over Http.
so far here's what I've tried:
PayPalAPIAAInterfaceClient client = new PayPalAPIAAInterfaceClient();
Certificate x509Certificate = new Certificate();
ServicePointManager.ServerCertificateValidationCallback = x509Certificate.CheckValidationResult();
client.ClientCredentials.ClientCertificate.Certificate = x509Certificate;
the problem is, what do I pass in for the ServicePiont and the rest of the params for CheckValidationResult?? I don't even know if I'm calling this right.
It's certainly not unheard of and in fact fairly common to secure SOAP services with X.509 certificates using the WS-Security spec - in fact, we do this for all of our internal and external web services. All web service frameworks including WCF are specifically designed to make this as easy as possible.
You should never have to use the ServicePointManager or ICertificatePolicy with a SOAP service using WS-Security. Unless there's something truly bizarre about PayPal's API, I think you're on the wrong track with that. All you have to do in WCF is this:
var client = new PayPalAPIInterfaceClient();
X509Certificate2 certificate = (...);
client.ClientCredentials.ClientCertificate.Certificate = certificate;
client.AddressVerify(...); // or whatever method you want to call
You don't even really need to write this code; if you have the certificate installed in the server's certificate store then you just edit the binding and behavior elements of the app.config - or use the WCF Service Configuration Editor, which is a lot easier.
Of course, in order to do this you have to have an X.509 certificate, and PayPal has to know about it. You can't just write new X509Certificate2(). You need to have a .pfx or .p12 file somewhere or, as mentioned above, have the certificate physically installed (this is the easiest way and the most secure because you're not hard-coding a password). And you need to upload the public key to PayPal.
You might be able to use OpenSSL to create a cert. PayPal's EWP page suggests that they'll accept these and gives instructions on how to create them, although it's not entirely clear whether or not the same process can be used for their SOAP API. It could be that they require a "real" certificate from Verisign, Thawte, etc. - I would try OpenSSL first and see, or just ask them.
There's a pretty comprehensive guide to the whole process here - you'll probably want to skip the sections on generating the certificate unless you have a Microsoft CA somewhere. Again, for that part, you'll probably want to try using the OpenSSL utility instead and follow PayPal's instructions, then install the cert on your server and skip to step 7 of that guide.

Categories

Resources