Passing security exception back to client when using role based authorisation in WCF - wcf-security

I am creating a WCF (with callbacks) service currently hosted as a process but will be a service eventually.
I am using netTCP binding in a Windows Domain environment and the client is on another machine within the domain (windows forms client).
I have all the binding, methods etc working with Windows security at transport level and an SPN in place.
I am now implementing security and am attempting to use this pattern on some methods (not all need to be secured):
<PrincipalPermission(SecurityAction.Demand, Role="MyDomain\DataReader")>
public Function GetData() As String
return "Test String"
End Function
(example)
This correctly allows users and blocks those not in role.
My problem is that an exception is raised at the service end (I can see this in VS as the process is run from there). The client does not get an security exception but times out instead.
How do I correctly pass back to the caller that a security exception occurred so that the I can then pass a message to the user.

Related

Cannot reconfigure DbContext more than once

I have a .Net Core 2.1 Web API talking to a MySQL database, using the Pomelo provider (version 2.1.0-rc1-final). Because this is a multi-tenant application, the API needs to change databases depending on which tenant is connecting. The front end web app tells the API which tenant is doing the request by including a TenantId header in the HTPP request.
When the API receives an HTTP request from the front end, I have a service in the API's pipeline that reads the TenantId from the request, and then this is used to determine which database the API must connect to.
To connect to various databases, I change the connection string of the DbContext. I do this in the OnConfiguring event:
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
string connectionString = CreateConnectionString();
optionsBuilder.UseMySql(connectionString);
base.OnConfiguring(optionsBuilder);
}
My problem is that this works the first time, but the second time this event fires, when it executes the optionsBuilder.UseMySql(connectionString); line, it throws this exception:
An item with the same key has already been added. Key: Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal.MySqlOptionsExtension
It's only letting me configure the DbContext once. I need to reconfigure it every time an API action endpoint gets called. Any ideas?
I'm not 100% sure what I did - but it's working now. The process is as follows: I created middleware to identify the tenant making the request (i.e. consuming the API). This is done by reading a "tenantId" that the client app sends in the header of the request, and then saving that tenantId into a global variable (I used HttpContext). Because middleware executes before pretty much most other things, by the time the OnConfiguring event of the dbContext fires, I already know which tenant this is So then, on the OnConfiguring event of the dbContext, I set the connectionString of the dbContext to whatever it should be (depending on the tenantId). I can't post the code in this comment because comments don't allow line breaks and they are too short, but If you want to, send me your email address and I'll email you the code.

need application url from console application

I have a MVC web application and a console application created as a separate project inside my web application. I want this console application to be run as a windows service at specified intervals. The console application is for sending mail to some persons. I need to include my application URL in the mail content body which redirect to my application login page. Since i am running this service for more than one instance i could't hard code the URL in code. Someone please help. I tried the below code. But it is returning null value.
var site = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath.TrimEnd('/');
var url = string.Format("<a href='{0}'>Login</a>", site);
I converted this from the comment to the question.
You are trying to obtain information from HttpContext.Current in situation when there is no HttpContext available at all - because your console application is launched directly by the operating system and not on the event of incoming http request (as oposed to request handling in your MVC application) - so there simply is no http context to use (hence HttpContext.Current is null in your console application).
You have to establish your own application logic for your console application that determines which URL to use in your emails. What would that be depends on the answer to the question "what does the url to be used in each email depend on specifically"? In other words - "how should each email know what URL to use"? Once you figure out the answer to that question then you can think of how to pass that dependency to your windows service.
Example (I do not know if it describes your case):
there are several web applications on different URLs
each of these web applications can add email to the queue to be send
windows service (console app) is scheduled to run once in a while and process the queue by sending the emails. Each email has to have an URL of the application from where it was added.
Assuming the example above you can just add the email together with the URL of the application to the queue (insted of just the email) and then retrieve that information from the queue in your console application. So then each of the emails has associated URL. It is irrelevant how would the queue itself be implemented (SQL, file, ...).

Incorrect windows identity in Cassini-Dev when hosted in Windows Service

I am hosting CassiniDev 4.0 in my windows service running an MVC 3.0 configuration site for my service.
I have the web.config setup to use windows authentication. When I look at the HttpContext.User in the web site, it shows the identity that the service is running under, not the itentity of the user making the request. The User.AuthenticationType is NTLM, which is correct, BTW.
This seems pretty clearly to be a bug, but wanted to run it by the community to see if there is some configuration I am missing.
It seems like it might be a variation on this issue postedlast week:
SecurityIdentifiers in Cassini-dev's NTLM authentication
This is definitely a bug in Cassini Dev. It looks like this method is returning the wrong token: Request.GetUserToken(). The code:
public override IntPtr GetUserToken()
{
return _host.GetProcessToken();
}
And here _host.GetProcessToken() is a pointer to a security token belonging to the user who owns the Cassini process, it is not the token belonging to the user that's logged in. What needs to happen is the NtlmAuth object needs to pass the security token back to the Request object so that it can be returned when this method is called instead of the host's token. Not really sure what the best way to do this is but you can see in the NtlmAuth class, the security token is acquired here:
IntPtr phToken = IntPtr.Zero;
if (Interop.QuerySecurityContextToken(ref _securityContext, ref phToken) != 0)
{
return false;
}
phToken is the security token but it needs to get back to the Request object and not call Interop.CloseHandle(phToken); later in that method, where it frees the token. Note that CloseHandle() needs to be called on the token eventually, otherwise a new one will be issued for every request made by a logged in user but unused ones will never get freed. One possible place to do this is in the Request object, which subclasses SimpleWorkerRequest and you can override the EndOfRequest method to call CloseHandle() on the security token.

File permissions with FileSystemObject - CScript.exe says one thing, Classic ASP says another

I have a classic ASP page - written in JScript - that's using Scripting.FileSystemObject to save files to a network share - and it's not working. ("Permission denied")
The ASP page is running under IIS using Windows authentication, with impersonation enabled.
If I run the following block of code locally via CScript.exe:
var objNet = new ActiveXObject("WScript.Network");
WScript.Echo(objNet.ComputerName);
WScript.Echo(objNet.UserName);
WScript.Echo(objNet.UserDomain);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = "\\\\myserver\\my_share\\some_path";
if (fso.FolderExists(path)) {
WScript.Echo("Yes");
} else {
WScript.Echo("No");
}
I get the (expected) output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
Yes
If I run the same code as part of a .ASP page, substituting Response.Write for WScript.Echo I get this output:
MY_COMPUTER
dylan.beattie
MYDOMAIN
No
Now - my understanding is that the WScript.Network object will retrieve the current security credentials of the thread that's actually running the code. If this is correct - then why is the same user, on the same domain, getting different results from CScript.exe vs ASP? If my ASP code is running as dylan.beattie, then why can't I see the network share? And if it's not running as dylan.beattie, why does WScript.Network think it is?
Your problem is clear. In the current implementation you have only impersonation of users and no delegation. I don't want to repeat information already written by Stephen Martin. I only want to add at least three solutions. The classical way of delegation which Stephen Martin suggests is only one way. You can read some more ways here: http://msdn.microsoft.com/en-us/library/ff647404.aspx#paght000023_delegation. I see three practical ways of you solving your problem:
Convert the impersonation token of the user to a token with delegation level of impersonation or to a new primary token. You can do this with respect of DuplicateToken or DuplicateTokenEx.
Use S4U2Self (see http://msdn.microsoft.com/en-us/magazine/cc188757.aspx and http://msdn.microsoft.com/en-us/library/ms998355.aspx) to receive a new token from the old one with respect of one simple .NET statement WindowsIdentity wi = new WindowsIdentity(identity);
You can access another server with respect of one fixed account. It can be a computer account on an account of the application pool of the IIS. It can be another fixed defined account which one will only use for access to the file system.
It is important to know which version of Windows Server you have on the server where IIS is running and which Domain Function Level you have in Active Directory for your Domain (you see this in "Active Directory Domain and Trusts" tool if you select your domain and choose "Raise Domain Functional Level"). It is also interesting to know under which account the application pool of the IIS runs.
The first and the third way will always work. The third way can be bad for your environment and for the current permission in the file system. The second one is very elegant. It allows control of which servers (file server) are accessed from IIS. This way has some restrictions and it needs some work to be done in Active Directory.
Because you use classic ASP, a small scriptable software component must be created to support your implementation.
Which way do you prefer?
UPDATED based on the question from comment: Because you use classic ASP you can not use a Win32 API directly, but you can write a small COM component in VB6 or in .NET which use APIs which you need. As an example you can use code from http://support.microsoft.com/kb/248187/en. But you should do some other things inside. So I explain now which Win32 API can help you to do everything what you need with tokens and impersonation.
First of all a small explanation about impersonation. Everything works very easy. There are always one primary token under which the process runs. To any thread another token (thread token) can be assigned. To do this one needs to have a token of a user hUserToken and call API ImpersonateLoggedOnUser(hUserToken);.
To go back to the original process token (for the current thread only) you can call RevertToSelf() function. The token of user will be received and already impersonated for you by IIS, because you so configured your Web Site. To go back to the original process token you should implement calling of the function RevertToSelf() in your custom COM component. Probably, if you need to do nothing more in the ASP page, it will be enough, but I recommend you be more careful and save current users token in a variable before operation with files. Then you make all operations with file system and at the end reassign users token back to the current thread. You can assign an impersonation token to a thread with respect of SetThreadToken(NULL,hUserToken);. To give (save) current thread token (user token in your case) you can use OpenThreadToken API. It must work.
UPDATED 2: Probably the usage of RevertToSelf() function at the end of one ASP page would be already OK for you. The corresponding C# code can be so:
Create a new Project in C# of the type "Class Library" with the name LoginAdmin. Paste the following code inside
using System;
using System.Runtime.InteropServices;
namespace LoginAdmin {
[InterfaceTypeAttribute (ComInterfaceType.InterfaceIsDual)]
public interface IUserImpersonate {
[DispId(1)]
bool RevertToSelf ();
}
internal static class NativeMethods {
[DllImport ("advapi32.dll", SetLastError = true)]
internal static extern bool RevertToSelf ();
}
[ClassInterface (ClassInterfaceType.AutoDual)]
public class UserImpersonate : IUserImpersonate {
public UserImpersonate () { }
public bool RevertToSelf () {
return NativeMethods.RevertToSelf();
}
}
}
Check in project properties in "Build" part "Register for COM interop". In "Signing" part of the project check Sign the assembly and in "Choose a strong name key file" choose <New...>, then type any filename and password (or check off "protect my key..."). At the end you should modify a line from AssemblyInfo.cs in Properties part of the project:
[assembly: ComVisible (true)]
After compiling this project you get two files, LoginAdmin.dll and LoginAdmin.tlb. The DLL is already registered on the current computer. To register if on the other computer use RegAsm.exe.
To test this COM DLL on a ASP page you can do following
<%# Language="javascript" %>
<html><body>
<% var objNet = Server.CreateObject("WScript.Network");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var objLoginAdmin = Server.CreateObject("LoginAdmin.UserImpersonate");
var isOK = objLoginAdmin.RevertToSelf();
if (isOK)
Response.Write("RevertToSelf return true<br/>");
else
Response.Write("RevertToSelf return false<br/>");
Response.Write("One more time after RevertToSelf()<br/>");
Response.Write("Current user: ");Response.Write(objNet.UserName);Response.Write("<br/>");
Response.Write("Current user's domain: ");Response.Write(objNet.UserDomain);Response.Write("<br/>");
var fso = Server.CreateObject("Scripting.FileSystemObject");
var path = "\\\\mk01\\C\\Oleg";
if (fso.FolderExists(path)) {
Response.Write("Yes");
} else {
Response.Write("No");
}%>
</body></html>
If the account used to run the IIS application pool has access to the corresponding network share, the output will be look like following
Current user: Oleg
Current user's domain: WORKGROUP
RevertToSelf return true
One more time after RevertToSelf()
Current user: DefaultAppPool
Current user's domain: WORKGROUP
Yes
Under impersonation you can only access securable resources on the local computer you cannot access anything over the network.
On Windows when you are running as an impersonated user you are running under what is called a Network token. This token has the user's credentials for local computer access but has no credentials for remote access. So when you access the network share you are actually accessing it as the Anonymous user.
When you are running a process on your desktop (like CScript.exe) then you are running under an Interactive User token. This token has full credentials for both local and remote access, so you are able to access the network share.
In order to access remote resources while impersonating a Windows user you must use Delegation rather then Impersonation. This will involve some changes to your Active directory to allow delegation for the computer and/or the users in your domain. This can be a security risk so it should be reviewed carefully.

Passing windows credentials through web application, to WCF [duplicate]

i have some code that tries impersonate the callers windows security settings and then connect to another WCF service on a different machine
WindowsIdentity callerWindowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
using (callerWindowsIdentity.Impersonate())
{
NetTcpBinding binding = new NetTcpBinding();
binding.Security.Mode = SecurityMode.Message;
binding.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
EndpointAddress endpoint = new EndpointAddress(new Uri("net.tcp://serverName:9990/TestService1"));
ChannelFactory<WCFTest.ConsoleHost.IService1> channel = new ChannelFactory<WCFTest.ConsoleHost.IService1>(binding, endpoint);
WCFTest.ConsoleHost.IService1 service = channel.CreateChannel();
return service.PrintMessage(msg);
}
But I get the error:
"the caller was not authenticated by the service"
System.ServiceModel .... The request for security token could not be satisfied because authentication failed ...
The credentials I am trying to impersonate are valide windows credential for the box the service is on.
Any ideas why?
In order to support your scenario, you need to have an understanding of how Protocol Transition and Constrained Delegation work. You will need to configure both Active Directory and your WCF service endpoint(s) to support this. Note the use of the Service Principal Name (SPN). Take a look at the following link and see if they help you. The article has a sample to demonstrate the complete end-to-end configuration required to make this work.
How To: Impersonate the Original Caller in WCF Calling from a Web Application
Agree with marc_s this is the double-hop problem.
You need to get the windows authentication all the way through, therefore:
The request must be made in the context of a windows users
IIS must be configured to use windows authentication
Web.config must be set up for windows authentication with impersonate = true
The user that your application pool is running as, must be allowed to impersonate a user. This is the usual place where the double-hop problem occurs.
There is a right called "Impersonate a client after authentication"
http://blogs.technet.com/askperf/archive/2007/10/16/wmi-troubleshooting-impersonation-rights.aspx
Impersonation from you service to the next is a tricky issue, known as "double-hop" issue.
I don't have a final answer for that (I typically avoid it by using an explicit service account for the service that needs to call another service).
BUT: you should definitely check out the WCF Security Guidance on CodePlex and search for "Impersonation" - there are quite a few articles there that explain all the ins and outs of impersonating an original caller and why it's tricky.
Marc
If you are sure you have the credentials right on both hops, the next thing that could be causing the issue is the lack of the EndpointDnsIdentity being set on the endpoint.
DnsEndpointIdentity identity = new DnsEndpointIdentity("localhost"); // localhost is default. Change if your service uses a different value in the service's config.
Uri uri = new Uri("net.tcp://serverName:9990/TestService1");
endpoint = new EndpointAddress(uri, identity, new AddressHeaderCollection());

Resources