EventLog permission failing in ASP.Net on Win7 - asp.net

I have an ASP.Net app .net 3.5 SP1, running in Win7 . During the login process, something within the ASP.Net login control is causing a write to the security log (this sounds acceptable to me) in the event log. The problem is that it seems the app doesn't have permission to do this. There error is:
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Diagnostics.EventLogPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
The stack trace doesn't show a single line of code from my application, its all in the framework.
The last 5 lines are:
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +61
System.Diagnostics.EventLog..ctor(String logName, String machineName, String source) +125
System.Diagnostics.EventLog..ctor() +24
System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData) +52
This same app works fine on XP SP2. I've hunted around and can't find how to give permissions. I've tried running hte app pool as LocalSystem and ApplicationPoolIdentity.
Whats the easiest way to get this running? Its my local dev machine and I don't care if I open up security holes, as long as I don't have to modify code (ie I need the solution to be an INETMGR change or web.config or some local permissions, etc).
Thanks!

This link appears to discuss the issue you are having.
I am not sure about the differences between the default CAS (code access security) on XP vs. win 7, however the assembly writing to the event log (and all calling assemblies) must have EventLogPermission.
You can add the AllowPartiallyTrustedCallers attribute or sign the assembly with a strong name key.

If you are writing to the default Application log you need to provide permisson to the LocalSystem before using it inside app pool.
Open RegistryEdit and goto
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet002\services\eventlog\Application
RightClick over the Applicatuion and click permissions
If the user(LOCALSYSTEM) is not present in the list then Add and Allow full Control

Related

Uploading files: Access to path denied

I've given IUSR full control over the folder but when i upload files it gives me this error:
Access to the path 'C:\inetpub\wwwroot\vivaweb\usr_up_img\Desert.jpg' 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 'C:\inetpub\wwwroot\vivaweb\usr_up_img\Desert.jpg' 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) that is used if the application is not impersonating. If the application is impersonating via <identity impersonate="true"/>, 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 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:
The source code that generated this unhandled exception can only be shown when compiled in debug mode. To enable this, please follow one of the below steps, then request the URL:
1. Add a "Debug=true" directive at the top of the file that generated the error. Example:
<%# Page Language="C#" Debug="true" %>
or:
2) Add the following section to the configuration file of your application:
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
Note that this second technique will cause all files within a given application to be compiled in debug mode. The first technique will cause only that particular file to be compiled in debug mode.
Important: Running applications in debug mode does incur a memory/performance overhead. You should make sure that an application has debugging disabled before deploying into production scenario.
Stack Trace:
[UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\vivaweb\usr_up_img\Desert.jpg' is denied.]
System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +7716783
System.IO.File.Delete(String path) +7577512
ASP.vivaweb_dwzupload_resizeaspnet_aspx.ResizeImage(String oldPathImage, String newPathImage, Int32 Width, Int32 Height, Int32 imgQuality, Boolean keep, Boolean isThumb) +217
ASP.vivaweb_dwzupload_resizeaspnet_aspx.Page_Load(Object sender, EventArgs e) +379
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
It is clear your application is using "ASP.NET" user
So give permission to this user or simply give permission to user everyone
There are a few unanswered questions in this post that I'll have to make a few assumptions on. First, I have no idea how you have your site deployed and thus don't know what identity it's using. If you are running it directly through visual studio, depending on your version, it should be either using "ApplicationPoolIdenity" or "NetworkService".
If you are running your site through IIS, you can figure that out easily (and change it if you like). Just open up application pools under the IIS instance and you should see them in an "identity" column.
After that, you will need to make sure to give permissions the same as the identity used to your site. Get the root folder used to house the site and give it appropriate permissions. Right click the folder and go to Properties -> Security -> Edit. Add in the identity that your site is using and you should be done.
A final note, you may actually want to turn on the debug configuration setting in your web.config file if you are in a local/debugging environment. It will give more information to work with to solve your issue.

Key not valid for use in specified state. After IIS Reset

I tried this:
runas /user: domain\user cmd with no luck
This seems to only occur now when IIS is reset and I try to resume my browsing session. So I am logged into the application, I reset IIS on the server, refresh the page and see the error.
I am building an application in .NET 4.0 MVC with a Secure Token Service that is using WIF 4.0. Everything works as expected, except this case. I even tried to use a custom error page, but the error is happening there as well. Because of that, I can't get the custom page to show either. Also, This is using a certificate that is located on both load balanced servers. This happens in my dev environment whihc consists of only one server (app, wfe, db operated there)
One thing I noticed is that if I switch my IIS APP Pool user back to Network Service account it doesn't throw the error any more. We have some restrictions (mostly network related) in the application that we need to use an account in our AD for the app pool sections
Anybody have any experience with this issue?
Key not valid for use in specified state.
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.Security.Cryptography.CryptographicException: Key not valid for
use in specified state.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[CryptographicException: Key not valid for use in specified state. ]
System.Security.Cryptography.ProtectedData.Unprotect(Byte[]
encryptedData, Byte[] optionalEntropy, DataProtectionScope scope) +428
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[]
encoded) +54
[InvalidOperationException: ID1073: A CryptographicException occurred
when attempting to decrypt the cookie using the ProtectedData API (see
inner exception for details). If you are using IIS 7.5, this could be
due to the loadUserProfile setting on the Application Pool being set
to false. ]
Microsoft.IdentityModel.Web.ProtectedDataCookieTransform.Decode(Byte[]
encoded) +146
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ApplyTransforms(Byte[]
cookie, Boolean outbound) +113
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(XmlReader
reader, SecurityTokenResolver tokenResolver) +647
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler.ReadToken(Byte[]
token, SecurityTokenResolver tokenResolver) +105
Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[]
sessionCookie) +262
Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken&
sessionToken) +76
Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object
sender, EventArgs eventArgs) +53
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+148 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
This issue is related to session cookies.
WIF protects session cookies using Data Protection API (DPAPI) by default, and the DPAPI is closely related to machine keys.
If the keys used to encrypt the session cookies change, it throws this exception.
It could be also related to your app hosting infrastructure.
if your app is running in an Network Load Balancer (NLB) environment
if you change the app pool settings (e.g., change the pool’s user)
More details about this scenario on the MSDN blog entry:
WIF 1.0 – ID1073 A CryptographicException occurred when attempting to decrypt the cookie using the ProtectedData API Archive.Today Shortlink
Todd Foust (October 29, 2012)
So, if your app runs in NLB environment, you could :
Configure your load balancer to use sticky sessions. This means that your user will be directed to the same server during the session duration. (I’m not very fond of that one)
Use a certificate to encrypt the session cookies
set all web.config files to use the same machine key in system.web
If you are not running the app in a NLB env, you could try:
set the machinekey in your web.config to use a pre-defined value instead of auto-generated values
Regarding auto-generated machinekey setting, please see:
How unique is your machine key?Archive.Today Shortlink

Cause for ASP.NET Security Exception

My application is throwing a Security Exception with the following details:
Description: The application attempted to perform an operation not allowed by the security policy
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
[SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +58
System.Net.ServicePointManager.set_CertificatePolicy(ICertificatePolicy value) +54
com.paypal.sdk.core.APICallerBase.SetTrustManager() +114
The application's trust level is set to medium and I've added to the [assembly: AllowPartiallyTrustedCallers] attribute to my project's assembly.
What can I do to address this issue? Does the System.dll allow partial trusted callers?
In digging a bit, the paypal method SetTrustManager() may attempt to reassign the ServicePointManager's Certificate Policy. This is OK, but it requires UnmanagedCode permission for the underlying code group.
I suggest you provide this permission in the .Net Framework Config console, and see if that helps.
Alternatively you can set the application's config "TrustAll" parameter to False so that SetTrustManager doesn't mess with the Certificate policy (assuming of course that the said Certificate policy is readily ok for whatever certs you'll need to use, in other words, this TrustAll thing may move past this permission error, but fail later if the Certificates)
In similar situations, I've found that the tools on this MDSN page can be very useful.
(in resp. to javacavaj note) To allow calls to unmanaged code for some assemblies:
Disclosure: I'm not an expert on .NET security model; the following should allow you alter permissions granted to some of your assemblies for diagnostic purposes for the issue at hand. For production purposes, please have your .NET configuration reviewed by a qualified admin as he/she may both ensure that the configuration is safe and suggest some way to structure the code groups, permission sets and other elements in ways that facilitate administration and deployment.
You can alter the .NET security policy with Mscorcfg.msc, i.e. the .Net Framework Configuration console. The details may vary with the .NET version and Windows host, but in general:
start mscorcfg (Ctrl panel | Admin Tools | Msft .Net Framework Configuration)
Run Time Policy node, then Manchine (or Enterprise, but better mess w/ local cfg first...)
Permission Sets node, Click "Create New Permission Set) on right panel
Provide name/description, next
Security | Add
Select Enable Assy execution, Allow calls to unmanaged assemblies and other permissions you may need | OK
Pick Code Groups Nodes, and navigate down to the group the assembly in question may belong (easier, yet create a group for it; in general you know who qualifies for a given group by seeing the "membership condition" tab in the group properties. Try and use Strong Name or GAC when possible.
In the Code Group properties's select the desired Permission set; optinally verify that this set is as desired for a given permission with the "View Permission" button.
Et voila...
Rather than the above, I wish I knew of a web site where such procedure can be [better] described. Maybe this Overview of the .NET Security Model can be of help. Googling several of the keywords provided can probably yield relevant pointers as well.

System.Web.AspNetHostingPermission SecurityException when trying to use ManagedFusion Rewriter on Goddaddy

I wonder if someone could help me out with an issue I'm experiencing trying to get my site up and running on Goddaddy.
I'm trying to get extension-less url rewriting working using the ManagedFusion Rewriter (http://www.codeplex.com/urlrewriter/) Unfortunately I'm getting the following error:
Server Error in '/' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: Request for the permission of type 'System.Web.AspNetHostingPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +59
System.Web.Hosting.HostingEnvironment.get_ApplicationID() +61
IIS7Injector.TraceManager.TraceEvent(TraceEventType eventType, String message) +62
IIS7Injector.ConfigManager.IsSkippedUrl(HttpRequest request, String ContentType) +38
IIS7Injector.InjectedContentStream.Write(Byte[] buffer, Int32 offset, Int32 count) +153
ManagedFusion.Rewriter.FormActionFilter.Write(Byte[] buffer, Int32 offset, Int32 count) +485
System.Web.HttpWriter.FilterIntegrated(Boolean finalFiltering, IIS7WorkerRequest wr) +265
System.Web.HttpResponse.FilterOutput() +80
System.Web.CallFilterExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +54
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +64
Version Information: Microsoft .NET Framework Version:2.0.50727.1434; ASP.NET Version:2.0.50727.1434
I'm runnung using IIS 7 in integrated mode. I've modified my web.config file by following the instructions in the readme file here:
http://www.codeplex.com/urlrewriter/Release/ProjectReleases.aspx?ReleaseId=22618
Thank very much in advance.
I hit this same exception on a new install, changing the App pool identity to NetworkService / aspnet fixed it.
Additionally, enabling Load User Profile on the app pool also worked.
Try the following:
App Pool -> Advanced Settings -> Load Users Profile = True
for me it was:
1. unblock all files
http://nicholasrogoff.wordpress.com/2010/09/01/how-to-bulk-unblock-files-in-windows-7-or-server-2008/
2.restart application pool
One cause for this problem is when you have done the totally odd thing of publishing you application on the server by using the server to download the application from the Internet. The files will then be marked as originating from the Internet, and security settings then prevent them from running.
The "downloaded-from-Internet" mark is stored in the file system as an NTFS alternative data stream. Use the "Streams" tool to display and remove the flags:
http://technet.microsoft.com/en-us/sysinternals/bb897440.aspx
Then restart the application pool.
This is actually a known issue with GoDaddy's Medium Trust environment. However with the latest release of URL Rewriter 3.0 all these issues are now gone. Please get the latest release and let me know if you have any issues.
I had a similar issue with GoDaddy. Even though it didn't seem related at first since it's not in the stack trace (and may not apply to you since you're using third party code), removing Response.End() calls solved the issue in my case.
I had this issue because of a networked drive at work.When i moved my project to my desktop it started working again.

Another Security Exception on GoDaddy after Login attempt

Host: GoDaddy Shared Hosting
Trust Level: Medium
The following happens after I submit a valid user/pass. The database has read/write permissions and when I remove the login requirement on an admin page that updates the database work as expected.
Has anyone else had this issue or know what the problem is?
Anyone?
Server Error in '/' Application.
Security Exception
Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[SecurityException: Request for the permission of type 'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.]
System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet) +0
System.Security.CodeAccessPermission.Demand() +59
System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) +684
System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +114
System.Configuration.Internal.InternalConfigHost.StaticOpenStreamForRead(String streamName) +80
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForRead(String streamName, Boolean assertPermissions) +115
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.OpenStreamForRead(String streamName) +7
System.Configuration.Internal.DelegatingConfigHost.OpenStreamForRead(String streamName) +10
System.Configuration.UpdateConfigHost.OpenStreamForRead(String streamName) +42
System.Configuration.BaseConfigurationRecord.InitConfigFromFile() +437
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
http://www.codeproject.com/Questions/586223/SecurityplusExceptionpluscomingplusinplusaplusrunn
Solution 4
System.Security.SecurityException: Request for the permission of type 'System.Net.SocketPermission, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed
following solution of above error
<system.web>
<customErrors mode="Off"/>
<trust level="Full" />
</system.web>
Works for my en godady hosting
If you're using any third party components you might want to check to see if the components are performing some type of security action. A year or so ago I ran into an issue with GoDaddy and the SubSonic ORM, it had a problem with a particular line of code that was requesting a level of security. I cracked open the code in reflector, took a look , verified it.
This can be a problem. If the component is causing you the pain try downloading the code and removing the suspect code, recompiling and run with that. That is exactly what I had to do w/ the SubSonic code a year or two back.
Have you tried playing around with the permissions of the files and folders in your site? I've had an error on godaddy where a new file couldn't be written because the directory had no write permission. You could try setting your whole root to read/write to see if that fixes your problem. To get to your permissions settings:
Login to GoDaddy
Click "My Hosting Account" and "Manage Account" next to your site name
Click "My Files"
Check the boxes next to files that are getting accessed then click the Permissions icon at the top
I am currently moving my website to GoDaddy and hit this error. I have a custom Membership Provider that uses hashed passwords based on the machinekey in the web.config. So it was this block of code that was causing the error:
// Get encryption and decryption key information from the configuration.
Configuration cfg =
WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
machineKey = (MachineKeySection)cfg.GetSection("system.web/machineKey");
if (machineKey.ValidationKey.Contains("AutoGenerate"))
if (PasswordFormat != MembershipPasswordFormat.Clear)
throw new ProviderException("Hashed or Encrypted passwords are not supported with auto-generated keys.");
So the problem was trying to open the web.config using WebConfigurationManager.OpenWebConfiguration, which I fixed by replacing the OpenWebConfiguration and GetSection lines with the following:
machineKey = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection("system.web/machineKey");

Resources