Reading a caller's IP address in WCF (OperationContext is null)? - wcf

I am validating users using the UserNamePasswordValidator.Validate(string username, string password) and the service is hosting itself (e.g. no IIS).
The problem I have is that if the user fails the validation I want to track the users IP address. This works fine of the user gets validated, because then the OperationContext has been initialized (it is null inside the validate method and not created until later).
Does anyone know how to get the clients IP address either in the validate method or before the validate method has been executed?
Yes, I know about how to get the IP address using RemoteEndpointMessageProperty but like I said, it never get that far if validation fails :-)

I've researched this to death all week, and I can't come up with a single blog entry or MSDN article that deals with the issue.
As far as I can tell, you cannot log IP address during the Validate stage.
The only workaround I can suggest is to host in IIS and use the weblogs there, which do log IP address. It's painful, unfortunately, but it may be the only way.

If you're hosting in IIS then this becomes much more simple. This chunk of config comes straight from my hosting web project and forces ASP.NET requests to come down the IIS pipeline rather than being dispatched straight to the ASP err bits of IIS.
aspNetCompatibilityEnabled: When this attribute is set to
true, requests to Windows Communication Foundation (WCF) services
flow through the ASP.NET HTTP pipeline, and communication over
non-HTTP protocols is prohibited.
See: http://msdn.microsoft.com/en-us/library/ms731336.aspx
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
I use the AuthenticationService and make use of the HttpContext to get at all the interesting stuff about the client, much of it is useful for things like ensuring a user isn't logging in from six different subnets as well as playing around with cookies.
Although I think this is applied to the MS AuthenticationService, any other services you have will need this attrib:
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
If you want to pursue your non-IIS hosted service route, then I'd see what stuff is available inside the MS API using reflection, poking around on a WCF with the debugger while stopped, unfolding all those Non-public members.
I suppose the problem will be getting a reference to a bit of WCF which is initialized from which to start poking. You might have to register some kind of listener to one of the dispatchers when you setup the service host.
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.channeldispatcher.aspx
Edit:
Adding this link as my thoughts are that you'd need to get at stuff in WCF that's right down the stack before it gets to your code:
http://blogs.msdn.com/sonuarora/archive/2007/06/11/passing-soap-actions-to-adapter-inbound-handler-for-filtering-type-of-listeners.aspx

Related

WCF Service hosted in Worker Role on Windows Azure that acts like a proxy and needs to call other services hosted in other Worker Roles

as you can see, I am relatively new on SO please don't kill me after posting this question :) I will do my best to describe the dilemma I am currently in.
I am creating something like a "Guardian Service" that is hosted on Windows Azure inside a Worker Role. This service has external ports, that can be accessed via HTTPS to allow clients to call it's service methods.
The WCF service is meant to call other services hosted in other Worker Roles that have only internal ports open, and which can be accessed only through the use of the Guardian Service. That's the main idea. Similar to a proxy or something.
I read already an excellent article from Jim O'Neil, what the caveats are when you try to access internal service points from within other WCF Services hosted in worker Roles:
His blog Troubleshooting Endpoints on a WCF Web Role
This is not the point for this question, and totally clear to me how to do that.
I have no idea at the moment, how I could do this, without implementing every contract from every single service I want to make accessible from within the Guardian Service to the outside world.
There must be a better way to decouple those things.
Any tips are appreciated.
Thank you.
I do not know the exact requirements for your project but I would say that what you are looking for is WCF Routing. I've used it in the past to redirect requests for different versions of Workflow instances.
The way it works is completely transparent to the client connecting to its endpoint. The router implementation must decide where to send the requests to, based on the request data (message headers and body).
In your case, if you are using SOAP and namespaces correctly, you might be able to base your decision on the message soap address and then send the request to the correct endpoint. You could also look at the Action property of the message.
Some links that might be useful:
http://msdn.microsoft.com/en-us/library/ee517423.aspx
http://www.codeproject.com/Articles/227699/RoutingService-on-Azure

WCF Service Accounts

I have a WCF self-hosted as a Windows Service.
When I start the service (under the NETWORK_SERVICE account), I can consume the service from my ASP.NET application on a different server.
However, the business rules have changed. Now I need to run the service under my own account. I am able to stop the service, and start it again under my account. No problem there.
Until I try to consume the service from my ASP.NET application on the other service. I get:
A call to SSPI failed, see inner exception
I'm relatively certain there's something I need to do security wise to eliminate this error, being new to all this I just don't know what.
Any help is greatly appreciated.
Thanks,
Jason
Usually this is a sign of a missing or misconfigured SPN, which gets in the way when you're using windows authentication (at the transport or message level) and Kerberos is being negotiated.
Notice that how/when the error manifests itself might depend on the way the hostname (or IP address) of the service host is used in the URL used by the client, since WCF will try, by default, to deduce the right SPN to use based on the URL information, unless you explicitly override it by setting the endpoint identity.
So likely all you need to do is register an SPN (using setspn.exe) for your new service and make sure your client uses an appropriate identity.
There's some more extra information on how WCF uses service identities here, here and here.

Security of WCF endpoints

For the sake of argument, lets say that I've got a basicHttp WCF service. Besides implementing authentication (login/logout methods), what is stopping someone from just cracking open Visual Studio, adding a web reference to my website's service, and then playing playing around with my service? I'm not familiar with a method of stopping someone from doing this. The idea of someone downloading all of my Data/Operation contracts and then start playing around is keeping me up at night, and I like my sleep!
Discoverability is the driving factor behind Web Services and especially SOAs. The ability of anyone at all who can reach the service to pull up the WSDL, generate a proxy in Visual Studio (or some other tool), and start using the service is one of the main reasons to create a web service!
I suppose you could generate all the client proxies and then disable the mex endpoint, but that pretty much cripples WCF, and even then it's only security through obscurity.
If you don't want any miscreant to start hitting your web service then either don't use the basicHttpBinding (which is designed for the express purpose of immediate and anonymous consumption) or host the service on a private network which only trusted clients can reach.
Some form of authentication or encryption is the only thing that can prevent this. You have to distinguish between those you want give access to, and those you don't. Give the ones you want to have access the certificate necessary to do encryption, or the username and password.
Don't give anything to the others.

Way to tell if WCF service is called via HTTP or HTTPS?

Let's say you've got a WCF service that is accessible via HTTP and HTTPS, but you want only certain methods to be available with HTTPS-- how can I check if the current request is HTTPS? Since HttpContext is empty, you can't simply check HttpContext.Current.Request.IsSecureConnection -- any other ideas? Thanks in advance.
Consider that WCF applications can also be hosted as a Windows service, with no ASP.NET at all, in which case there is no such thing as "secure" vs. "insecure." That is one reason why WCF does not attempt to make this information available.
One option would be to run the WCF service in ASP.NET Compatibility Mode, where you do have access to the HttpContext.Current instance.
My choice, however, would simply be to create a different, SSL-only service for the secure operations. I really think you'd want to do this anyway, so the contract is explicit; otherwise you're left doing runtime checks and clients may have no idea that the methods they're trying to use aren't allowed.
"Best practice" in a web service is to make these types of restrictions as explicit as possible, and having a separate service available only over SSL is by far the clearest means of describing your service's restrictions.
( Building on comment from #Aaronaught within answer by Matt Ellen... )
It looks like
OperationContext.Current.RequestContext.RequestMessage.Headers.To.Scheme
contains "http" or "https" among others (msdn).
HTTPS is served over a different port to HTTP. Assuming you know the ports, perhaps checking that would suffice.
How about:
var iwrc = WebOperationContext.Current.IncomingRequest;
var isHttps = iwrc.UriTemplateMatch.BaseUri.Scheme.Equals("https", StringComparison.InvariantCultureIgnoreCase);
This is very easy, does not rely on port numbers and works just fine in a self-host WCF server (with no IIS in site sight).

What are my binding options for a self hosted cross domain WCF service with remote thick clients?

I'm trying to build a WCF self hosted service (eventually in a windows service) that will receive binary and text base messages from remote thick clients that have no accounts on my hosted machine. I'm trying to figure out both my binding options and security options, and in reading the patterns and practices guides, my head has completely spun around at least once.
The clients would be authenticated against a custom SQL based method, so I'd like to be able to pass that info in the initial login request and then set an authorization token of some kind. (This part of the problem is probably outside the scope of the question, but I included it in case it might make a difference.)
Any thoughts at all would be very helpfull.
Ryan
The choice of binding and security option depends on the usage of your WCF service. Is it just for your rich client or are you planning to expose it to the world as API? If it's just for your rich app, does it run on LAN or over untrusted, unreliable Internet?
With WCF you can configure the service to expose multiple endpoints with different bindings, for example both SOAP and REST. In general, I'd start with something stateless and lightweight like basicHttpBinding and webHttpBinding, passing user and password on every request. Once you have that up and running you can optimize cache authentication, provide binary endpoint etc.. only if it actually helps.
There's no need to have just one binding. Having said that if it's self hosted you're "on your own" here. I've never looked at what's involved.