Error while changing identity for application pool - c#

I try change identity for application pool on Windows Azure. My project uses this application pool when works on Windows Azure. By default application pool uses NetworkService identity, but I must use another identity. I try change it in OnStart() event of WebRole by this way:
using (ServerManager serverManager = new ServerManager())
{
string appPoolName =
serverManager.Sites[RoleEnvironment.CurrentRoleInstance.Id + "_Web"]
.Applications.First().ApplicationPoolName;
var appPool = serverManager.ApplicationPools[appPoolName];
appPool.ProcessModel.UserName = Environment.MachineName + "\\UserName";
appPool.ProcessModel.IdentityType = ProcessModelIdentityType.SpecificUser;
appPool.ProcessModel.Password = "UserPassword";
serverManager.CommitChanges();
}
But I get exception with next message:
System.Runtime.InteropServices.COMException (0x80090016):
Keyset does not exist (Exception from HRESULT: 0x80090016)
at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.CommitChanges()
at Microsoft.Web.Administration.Configuration.CommitChanges()
at Microsoft.Web.Administration.ConfigurationManager.CommitChanges()
at Microsoft.Web.Administration.ServerManager.CommitChanges()
at Project.Web.WebRole.OnStart() in E:\Projects\...\Web\WebRole.cs:line 57
If I change identity in IIS manager I don't get any error. What is wrong with my code and why do I get this error?

Updates to the applicationHost.config require administrative privileges. When you run locally, you are an administrator. In the cloud, your RoleEntryPoint runs as a normal user unless you elevate the role. Have you done so?
Check to see if you have <Runtime executionContext="elevated"/> specified inside your role declaration in ServiceDefinition.csdef.
Edit: Wade also showed how to do this using a slightly different method (check the comments). Try this as well

ok, here is my answer. This error occurs because NetworkService identity doesn't have Read access on the iisWasKey key. More information and how to resolve this problem I found here: "Keyset does not exist" error message when you try to change the identity of an application pool

Related

Access to path is denied in Production, works in Dev

This is frustratingly weird. I'm suddenly getting this error in Production, but not locally in development.
Specs:
.Net Core 3.1
IIS 10
Access to the path '\\[network share]\Files\Video' is denied.
It occurs when this method is called:
public Task<bool> UploadAsync()
{
if (request.Metadata.ChunkIndex == 0)
{
if (!Directory.Exists(request.Metadata.UploadLocation))
{
Directory.CreateDirectory(request.Metadata.UploadLocation);
}
}
var fixedFileName = FileManager.FixFileName(request.Metadata.FileName);
var basePath = Path.Combine(request.Metadata.UploadLocation, PARTIALS);
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
var filePath = Path.Combine(basePath, fixedFileName);
AppendToFile(filePath, request.File);
return Task.FromResult(true);
}
... and this line is called:
Directory.CreateDirectory(request.Metadata.UploadLocation)
It seems like it's due to some missing permission with IIS and the web application, since it works when I run the application in IISExpress.
And this is important, the application in both cases is pointing to the same network share location to drop the video file.
So it seems like any permissions on the network share folder is correct, but IIS can't access it. That's my theory, but my network administrator says he hasn't changed anything with the application's app pool, so I don't have any other ideas.
Any ideas what is causing this issue?
According to your description and error codes, it seems this is related with permission issue.
To solve this issue, I suggest you could firstly modify the IIS application pool identity with a user which have the enough permission to access the network share and try again. If this is working well, this is related with the application pool identity account permission.
More details about how to modify the application pool identity permission, you could refer to this answer.

Access to the path 'Global\{xxx}_YYY-YYY:13552' is denied. Hangfire?

As the title says I encounter a "Access to the path" error in my MVC web application. The sites application pool is DefaultAppPool with identity Network Service. I have set Full Control to the Network Service user with no luck, I then tried to give Everyone full control but it still does not work. I'm running another application from the same folder (C:\Users\YYY\Documents\Visual Studio 2015\Projects) and it works without a problem.
The file that fails contains the method that starts Hangfire. Could this have something to do with it?
I'm running Windows 10 Pro with IIS 10.0.
public void Start()
{
lock (_lockObject)
{
if (_started) return;
_started = true;
HostingEnvironment.RegisterObject(this);
GlobalConfiguration.Configuration
.UseSqlServerStorage("connection string");
// Specify other options here
_backgroundJobServer = new BackgroundJobServer();
}
}
http://docs.hangfire.io/en/latest/deployment-to-production/making-aspnet-app-always-running.html
Current permissions for
C:\Users\YYY\Documents\Visual Studio 2015\Project
Server Error in '/' Application.
Access to the path
'Global{4deecd4f-19f6-426b-xxxx-xxxxxxxxxxxx}_YYY-YYY:13552' is
denied.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Access to the
path
'Global{4deecd4f-19f6-426b-xxxx-xxxxxxxxxxxx}_YYY-YYY:13552' is
denied.
ASP.NET is not authorized to access the requested resource. Consider
granting access rights to the resource to the ASP.NET request
identity. ASP.NET has a base process identity (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
the configured application pool identity on IIS 7.5) that is used if
the application is not impersonating. If the application is
impersonating via , the identity will be
the anonymous user (typically IUSR_MACHINENAME) or the authenticated
request user.
To grant ASP.NET access to a file, right-click the file in File
Explorer, choose "Properties" and select the Security tab. Click "Add"
to add the appropriate user or group. Highlight the ASP.NET account,
and check the boxes for the desired access.
Source Error:
Line 36: _backgroundJobServer = new BackgroundJobServer();
Found the problem, I had two websites with Hangfire running on the same application pool. When I created a new application pool for each website everything started working.
It seems as both instances of Hangfire when running on the same application pool tried to communicate through the same port and because of this the application that got started first was the only one to be working. The reason they were on the same application pool to start with was pure laziness, I only created a virtual directory from within Visual Studio at my local IIS to run the project.

DirectoryEntry IIS access permission

I have one console application which list website binding in IIS
using (var directoryEntry = new DirectoryEntry("IIS://localhost/w3svc/" + GetWebSiteId())) {
var bindings = directoryEntry.Properties["ServerBindings"];
}
I call this console application from ASP.NET via process
var process = new Process {
StartInfo = new ProcessStartInfo {
FileName = "c:/app.exe",
Arguments = "check",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};
Everything works fine on development machine under Widows 7 / IIS 7.5, but when i test on Windows 2012 / IIS 8 im getting "Access is denied" error.
Error log
"System.Runtime.InteropServices.COMException (0x80070005): Access is denied.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_IsContainer()
at System.DirectoryServices.DirectoryEntries.ChildEnumerator..ctor(DirectoryEntry container)
at System.DirectoryServices.DirectoryEntries.GetEnumerator()
at IISSubdomainManagement.Program.GetWebSiteId()
at IISSubdomainManagement.Program.TotalBindings()
at IISSubdomainManagement.Program.Main(String[] args)"
p.s Application pool identity is "ApplicationPoolIdentity"
I forget to mention, my console app works fine on my server when I run it from CMD
You need to give permission to the IUSR account to access and execute C:\app.exe. This link should provide you with the necessary information to find the right account.
You have probably granted the permission to 'ApplicationPoolIdentity' rather than to the virtual account that actually corresponds to that Application Pool. Read through the Microsoft's description or search online for virtual identity IIS, etc.
On your development machine, you probably have some sort of Full Admin rights, so it is not as restricted.
If you still have problems after that, I would recommend replicating the error with a Process Monitor running, so you can see exactly what process is accessing which resource with which identity. However, I would recommend replicating the issue on your development machine rather than running Process Monitor on the production. It takes a little bit of learning to be able to run it efficiently.
In IIS 7/8 go Control Panel / Program And Features / Turn Windows features on or off, and check all items from: Web Managment Tools, (it's include: IIS Managment Service, II 6 Managment Compatibility)
This Solution worked for me ==>
http://blogs.msdn.com/b/jpsanders/archive/2009/05/13/iis-7-adsi-error-system-runtime-interopservices-comexception-0x80005000-unknown-error-0x80005000.aspx?CommentPosted=true#commentmessage

PrincipalContext.ValidateCredentials stops validating after IIS deployment works fine in cassini

I have the following code snippet to test a plain-text username/password against the AD, which works fine if I hit F5 in visual studio and try it via the WCFTestClient, but once I deploy to IIS and try the same function, it will never return true for ValidCredentials; is there something security wise that needs to be set for the Identity that the Application Pool runs under?
I tried setting the App Pool identity to my own account (domain admin) just to test if this was the problem, but that didn't help either, so I'm a bit lost as to how to fix this.
The site (Custom API) has anonymous access set up.
try
{
// create a "principal context" - e.g. your domain (could be machine, too)
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, DomainName))
{
// validate the credentials
if (pc.ValidateCredentials(UserName, Password))
{
IsValid = true;
break;
}
}
}
catch (Exception)
{
LoggingControler.LogWarning(null, "Unreachable Domain: " + Domain);
}
I've gone over things again, and it's all due to Rights in Windows. Network Service somehow doesn't have enough rights to execute PrincipalContext.ValidateCredentials. If I change the Application Pool Identity to the identity of a Domain Administrator, the code works.
If someone can tell me how to set up a Limited User account with the proper rights to execute PrincipalContext.ValidateCredentials, I can finish this.
Ok, I've finally found my own answer via https://stackoverflow.com/questions/5140377/query-activedirectory-sometimes-not-working-asp-net-c and https://elgg.leeds.ac.uk/webteam/weblog/15385.html
As I've discovered, "Network Service" application pool identity holds the key to this problem...
Adding the read rights didn't work; so there's still something else wrong.
Did you enable Windows Authentication in IIS

"Access Denied" when trying to connect to remote IIS server - C#

I receive an "Access Deined" COMException when I try to connect to a remote IIS 6 server from my C# application that is running under IIS 5.1.
Any ideas? I am experiencing all the same issues with the original questions.
Update - 4/1/09
I found this solution (http://www.codeproject.com/KB/cs/Start_Stop_IIS_Website.aspx) that consists of a window application connecting to an IIS server to start and stop web sites. I am able to run it on my workstation and connect to the IIS server.
Ugh....why can I run this stand alone application but not my ASP.NET application?
Original
I receive an "Access Denied" COMException when I try to connect to IIS from a remote machine using the DirectoryEntry.Exist method to check to see if the IIS server is valid.
string path = string.Format("IIS://{0}/W3SVC", server);
if(DirectoryEntry.Exist(path))
{
//do something is valid....
}
I am a member of an active directory group that has been added to the Administrators groups to the IIS server I am trying to connect to.
Has anyone experience this issue and know how to resolve it?
UPDATE:
#Kev - It is an ASP.NET application. Also, I can connect without an username and password to the remote server through IIS6 Manager.
#Chris - I am trying to connect to the remote server to display the number of virtual directorys and determine the .NET framework version of each directory. See this SO question.
#dautzenb - My ASP.NET application is running under IIS 5.1 trying to connect to an IIS 6 server. I can see fault audits in the security log for my local ASPNET account on the remote server. When I try to debug the application, I am running under my domain account and still get the Access is denied.
UPDATE 2:
#Kev - I was able to establish to create a DirectoryEntry object using the following overload:
public DirectoryEntry
(
string path,
string username,
string password
)
But, all of the properties contain a " threw an exception of type 'System.Runtime.InteropServices.COMException'" while I debug the app.
Also, the AuthenticationType property is set to Secure.
UPDATE 3:
The following two failure audit entries were in the remote IIS server's security event log every time I tried to establish a connection:
First event:
Event Category: Account Logon
Event ID: 680
Log attempt by: MICROSOFT_AUTHENTICATION_PACKAGE_V1_0
Logon account: ASPNET
Source Workstation:
Error Code: 0xC0000234
Second event:
Event Category: Logon/Logoff
Event ID: 529
Logon Failure:
Reason: Unknown user name or bad password
User Name: ASPNET
Domain: (MyDomain)
Logon Type: 3
Logon Process: NtLmSsp
Authentication Package: NTLM
Workstation Name: (MyWorkstationId)
Caller User Name: -
Caller Domain: -
Caller Logon ID: -
Caller Process ID: -
Transited Services: -
Source Network Address: 10.12.13.35
Source Port: 1708
Impersonation is set to true and the username and password are blank. It is using the ASPNET account on the remote IIS server.
If it is an identity problem, you could try setting your IIS 5.1 application to use Integrated Windows Authentication, and then add the following to you web.config on your IIS5.1 web site under system.web to enable impersonation.
<identity impersonate="true"/>
<authentication mode="Windows" />
Since this is an ASP.NET application, it runs in an Application Pool of IIS. This Application Pool runs using a specific user("Local System", "Network Service" or another user).
Does this user have enough rights to connect to a remote server ?
See MSDN for more info.
This looks like it may be a double-hop issue. If you are impersonating the current user of a website using NTLM, that impersonation is only valid on that server (your IIS 5.1 server in this case). If you try to connect to another server using the web site, you are actually going to have issues as it cannot pass the token to another server that was used during impersonation. The same is true if you are debugging your site through your machine, going to another box. Your local machine is authenticating you, but it cannot impersonate you to another server.
All of the solutions I have used in the past require you to hard code the app pool to use an account that has permissions, set the annony. account to a domain account with permissions on the other machine, or use a windows service running on the IIS 5.1 machine, under a domain account, to connect to the other server.
If you are using Kerberos, this wouldn't apply, but AD uses NTLM by default.
Where exactly are you trying to read too? Is it in under the same path as your application?
When I had this problem, I found that simply authenticating my self on a Windows file share solved the problem. From experience, I think that WMI/ADSI/COM doesn't have great support for not-already-authenticated users. I believe this issue occurs when you're not associated with a Windows domain.
If it is indeed a NTLM doublehop issue you could use the SETSPN utility to create service principal named instances for your target IIS servers.
Then you could go into Active Directory, and then allow the computer object (basically the NETWORK SERVICE or LOCAL SERVICE principals) to delegate its credentials to a correctly registered SPN.
Then you could hop-hop-hop all over the place! But, be warned! People can hurt themselves on sharp pointy things when you enable double-hop!
Good KB articles to read:
http://support.microsoft.com/kb/929650
I believe that DirectoryEntry.Exists silently ignores any credentials supplied and uses the creds of the authenticated user. This seems to match the behaviour you've described. For AD work, we never use it for this reason.
I'm sort of stumped at the moment as to why you can't get this working. There is a temporary work around you could try. When instantiating the DirectoryEntry object you could use one of the following constructor overloads:
public DirectoryEntry(
string path,
string username,
string password
)
Documented at: MSDN: DirectoryEntry Constructor (String, String, String)
...or...
public DirectoryEntry(
string path,
string username,
string password,
AuthenticationTypes authenticationType
)
Documented at: MSDN: DirectoryEntry Constructor (String, String, String, AuthenticationTypes)
As it happens I'm building a test AD environment on my virtual server box for a new project to do similar stuff. When I get it up and running I'll have a play around to see if I can reproduce the problem you're encountering. In the meantime let us know what happens if you try these constructor overloads referenced above.
Update (In answer to Michaels comment):
For reasons that evade me just now, we couldn't use DirectoryEntry.Exists() in a particular scenario, there is this snippet of code that gets called now and again in one of our apps:
public static bool MetabasePathExists(string metabasePath)
{
try
{
using(DirectoryEntry site = new DirectoryEntry(metabasePath))
{
if(site.Name != String.Empty)
{
return true;
}
return false;
}
}
catch(COMException ex)
{
if(ex.Message.StartsWith("The system cannot find the path specified"))
{
return false;
}
LogError(ex, String.Format("metabasePath={0}", metabasePath));
throw;
}
catch(Exception ex)
{
LogError(ex, String.Format("metabasePath={0}", metabasePath));
throw;
}
}
You could replace the constructor with one of the ones from above. Admittedly it's a stab in the dark :).

Categories