Protect WCF from fiddler (MITM) (PCL XAMARIN FORMS) - wcf

I have xamarin forms project using portable class library.
In that PCL I reference my WCF service which is hosted in some server.
The wcf binding is Basichttpbinding with security transport as PCL does not support wshttpbinding.
Also the wcf is use https and i have a valid certificate for that.
I want to secure the messages because now if i install some kind of application fiddler or packed monitor in my android every call to my service i can see the xml data in readable format.
I thought by using https i was protecting that.
I try use wcf TransportWithMessageCredential but it failed to login to my service because xamarin does not yet support this combination
So: ( after research i found out that )
PCL does not support wshttpbinding only basicHttpBinding
Xamarin.Forms basicHttpBinding does not support message security but only
TransportCredentialOnly
And
Xamarin does not support TransportWithMessageCredential but only
transport security but transport security not protecting the data from MITM.
How others working with xamarin forms and protect these data?
Do i missed anything?
Any suggestions?
EDITED
I am trying to encrypt the xml request before send to service but fails every time i change the message e.g from xml to encoded characters (i guess because the server fails to recognize the schema )
I have implement IClientMessageInspector at the client Side as also IDispatchMessageInspector at the server side.
I need some help how i can send the xml request encrypted to the server.. if i do it here then i can decode it from service side ( server)
At the client side i have the following
Public Function BeforeSendRequest(ByRef request As Message, channel As IClientChannel) As Object Implements IClientMessageInspector.BeforeSendRequest
Dim Binding As New BasicHttpBinding(BasicHttpSecurityMode.Transport)
Dim ms As MemoryStream = New MemoryStream(System.Text.Encoding.UTF8.GetBytes(EncryptedData(request.ToString)))
Dim RQuotas As Xml.XmlDictionaryReaderQuotas = Binding.ReaderQuotas
Dim reader = Xml.XmlDictionaryReader.CreateTextReader(ms, RQuotas)
request = Message.CreateMessage(reader, Int32.MaxValue, request.Version)
Return Nothing
End Function
I am not sure if i do it correctly. Any help welcome.

Fiddler only decrypts Https Traffic if you accept its certificate, it basically acts a man in the middle and handles all the calls from the service to your app, there is some useful info here https://docs.telerik.com/fiddler/Configure-Fiddler/Tasks/DecryptHTTPS ,
On your second update of the question, you would need to create a container that will house all your messages,
that way you can decrypt and encrypt the data as you see fit,
A simple example can be found at https://misaxionsoftware.wordpress.com/2011/07/29/secure-restful-web-service-by-wcf-web-api-no-https-seriously/
You can customise it as much as possible
Here is the message that is defined in the link above
Message
public class Message
{
public string AppId { get; set; }
public string Data { get; set; }
public string Id { get; set; }
public string TimeStamp { get; set; }
public byte[] GenerateFingerprint();
public bool ValidateHash(byte[] fingerprint);
}
Encrypted Message
public class EncryptedMessage
{
public string AppId { get; set; }
public byte[] Fingerprint { get; set; }
///<summary>
/// The 3DES key used to encrypt/decrypt the message
/// </summary>
public byte[] Key { get; set; }
///<summary>
/// Encrypted message
/// </summary>
public byte[] Message { get; set; }
}
IEncryptionHelper
public interface IEncryptionHelper
{
EncryptedMessage Encrypt(Message message);
Message Decrypt(EncryptedMessage encryptedMessage);
}

Related

Limit connection in RESTful web service

Is there a way to configure a rest web service to allow only one connection at a time?
I am using Wildfly 9.0.1-Final with the resteasy 3.0.11.Final implementation.
You can use synchronized block on static field:
private static final Object LOCK = new Object();
#GET
#Path("find")
#Produces(MediaType.APPLICATION_JSON)
public Response find(){
synchronized(LOCK){
//your code
}
}

WCF: how to choose which type an interface will be serialize into?

When using WCF,
how can you choose which type an interface will be serialized into?
for example, the CarA type is used in the server, and they are sent to client over WCF as ICars, and the client should receive them as CarBs.
public interface ICar
{
int Size { get; set; }
int Price { get; set; }
}
public class CarA : ICar
{
//ICar implementations...
}
public class CarB : ICar
{
//ICar implementations...
}
[ServiceContract]
public interface ICarManager
{
[OperationContract]
ICar GetMyCar(int userID);
}
"which type an interface will be serialized into" - this makes zero sense. If you send CarA's to your client the client will receive CarA's.
I think you may be asking about how to tell WCF that your service contract contains types which are derived from another type. To do this you can use ServiceKnownTypeAttribute.
UPDATE
If you want to return a type of ICar in your service operation you need to specify the concrete types which will be available on your endpoint. You do this by using the ServiceKnownTypeAttribute like so:
[ServiceKnownType(typeof(CarA))]
[ServiceKnownType(typeof(CarB))]
[ServiceContract]
public interface ICarManager
{
[OperationContract]
ICar GetMyCar(int userID);
}
You could look at customize reply message by implement custom extension using IDispatchMessageFormatter
try this link if help you
IDispatchMessageFormatter – How to customize reply Messages on the server side
From Your server side you can only expose unique endpoint so you will expose only one endpoint as ICar and then you will choose which implementation of ICar you want to host via ServiceHost ,it can be CarA or CarB.
Now on client side you will just have a only interface as ICar and you should not be confused with which type should be serialized using your interface Icar. You will be only calling server side to get the service not the implementation.
More on ServiceHost
Use the ServiceHost class to configure and expose a service for use by
client applications when you are not using Internet Information
Services (IIS) or Windows Activation Services (WAS) to expose a
service. Both IIS and WAS interact with a ServiceHost object on your
behalf

WCF MesageContract - customizing outgoing SOAP message - multiple bodies

I have to call a Web service that is extremely demanding (unstandard) regarding the SOAP message format that it chooses to process. I have no control over the server side implementation and there is no WSDL available, all I have is an intercepted message attached bellow.
My first thought was WCF+MessageContract, but whatever I do with the last, I can't seem to get the right result. Outgoing messages should look like the one bellow. The most tricky part seems to be multiple body contents ("ProxyInfo" and "PayloadInfo" bellow). Besides that I also can not get WCF to remove "Action" element from SOAP message header. I realize that it is a vital element to WCF, but I doubt that I could persuade Web service to accept it. The reply will probably be another story, but I will cross that bridge when I get to it.
Currently I am considering custom serialization and post-/pre- processing of outgoing/incoming messages. In the worst case I guess I will have to do Web requests as well as serialization manually. Please help, I am getting realy desperate...
<?xml version="1.0" encoding="UTF-8" ?>
<e:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsse="http://docs.oasisopen.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<e:Header>
<ServiceHeader xmlns="http://services/serviceheader" e:actor="http://services/loadbalancer" >
<ServiceLevel>
<Type>HIGH</Type>
<Method>FIFO</Method>
</ServiceLevel>
</ServiceHeader>
</e:Header>
<e:Body>
<ProxyInfo xmlns="http://services/proxyinfo">
<Server>
<Address>proxy1:8080</Address>
<AppId>case_delegator</AppId>
</Server>
</ProxyInfo>
<PayloadInfo xmlns="http://services/payload">
<GetConfirmation>
<CaseId>
<Id>9728DFC889874CC8B1505D91E33FCFCD</Id>
</CaseId>
</GetConfirmation>
</PayloadInfo>
</e:Body>
</e:Envelope>
If you don't want to use Address header you have to use binding without WS-Addressing. In your case use BasicHttpBinding. It will not use WS-Addressing and Action SOAP header but instead it will use SOAPAction HTTP header.
For your message contract try to use something like this:
[DataContract]
public class ServiceHeader
{
...
}
[DataContract]
public class ProxyInfo
{
...
}
[DataContract]
public class PayloadInfo
{
...
}
[MessageContract(IsWrapped = false)]
public class Request
{
[MessageHeader(Namespace="http://services/serviceheader")]
public ServiceHeader ServiceHeader { get; set; }
[MessageBodyMember(Namespace="http://services/proxyinfo")]
public ProxyInfo ProxyInfo { get; set; }
[MessageBodyMember(Namespace="http://services/payload")]
public PayloadInfo PayloadInfo { get; set; }
}
The strange thing is the actor attribute in ServiceHeader. Your message doesn't define namespace for prefix e so the message is not valid XML.

Calling WebClient within WebService

I started developing an application in Silverlight that was dealing with downloading the HTML of a website and then parsing it. With Silverlight 4 this can be achieved easily by simply requesting elevated permissions. With Silverlight 3, however, the only way to get the HTML of a website is via a WebService call. My initial idea was to do the following:
public class Service1
{
[OperationContract]
public void GetHtml()
{
Uri targetUri = new Uri("http://www.google.com", UriKind.RelativeOrAbsolute);
WebClient webClient = new WebClient();
webClient.DownloadStringCompleted += this.WebClient_DownloadStringCompleted;
webClient.DownloadStringAsync(targetUri);
}
private void WebClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
}
}
However, I realized that as soon as I make the call, which is async as well, from my Silverlight application, there is no way for me to retrieve the HTML of the website. That is why I changed to the following:
public class Service1
{
[OperationContract]
public string GetHtml()
{
Uri targetUri = new Uri("http://www.google.com", UriKind.RelativeOrAbsolute);
WebClient webClient = new WebClient();
return webClient.DownloadString(targetUri);
}
}
I believe the last approach is not that fine since it will freeze the thread. So, my question, is there a way to achieve the first approach a.k.a. make async call from an async call :). Any help would be greatly appreciated.
Best Regards,
Kiril
You can achieve your goal by implementig a Duplex Service. There is some useful information about it on the msdn site and a wonderful podcast entry by Mike Taulty. In general, you would have to modify your operation contract by splitting it into two parts. First part would initiate your WebClient download on the server. Then, on the server, after the html has been downloaded, the server would call back a contract that is implemented on the client side with the payload consisting of the required html content.

RESTful framework alternatives to WCF

Looking for alternatives to the WCF REST start kit, ideally OSS frameworks.
Anyone got a list?
Cheers
Ollie
OpenRASTA is the most mature
ASP.NET MVC is a good alternative when it comes to generating REST XML and JSON feeds.
To build a rest architecture in .net you can use GenericHandlers. You can create a GenericHandler that will receive a HTTP message (POST, GET or..) and return a message of the content-type you specify.
For example I create a generic handler on the url:
http://site/getpeople.ashx?gender=female
And call it with the parmeter gender=female, as above the handler will return the following
<people>
<person>...</person>
...
<people>
And the content type would be text/xml.
This is the simplest way to implement REST web services in .NET
I also provide ServiceStack, a modern, code-first, DTO-driven, WCF replacement web services framework encouraging code and remote best-practices for creating DRY, high-perfomance, scalable REST web services.
There's no XML config, or code-gen and your one clean C# web service is enabled on all JSON, XML, SOAP, JSV, CSV, HTML endpoints out-of-the-box, automatically. It includes generic sync/async service clients providing a fast, typed, client/server communication gateway end-to-end.
It also includes generic sync/async service clients providing a fast, typed, client/server communication gateway end-to-end.
This is the complete example of all the code needed to create a simple web service, that is automatically without any config, registered and made available on all the web data formats on pre-defined and custom REST-ful routes:
public class Hello {
public string Name { get; set; }
}
public class HelloResponse {
public string Result { get; set; }
}
public class HelloService : IService<Hello> {
public object Execute(Hello request) {
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Above service can be called (without any build-steps/code-gen) in C# with the line below:
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
Console.WriteLine(response.Result); // => Hello, World
And in jQuery with:
$.getJSON('hello/World!', function(r){
alert(r.Result);
});