System.Security.SecurityException when writing to Event Log
Asked Answered
E

24

201

I’m working on trying to port an ASP.NET app from Server 2003 (and IIS6) to Server 2008 (IIS7).

When I try and visit the page on the browser I get this:

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: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and the location of the exception can be identified using the exception stack trace below.

Stack Trace:

[SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.]

System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly) +562 System.Diagnostics.EventLog.SourceExists(String source, String machineName) +251

[snip]

These are the things I’ve done to try and solve it:

  1. Give “Everyone” full access permission to the key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Security. This worked. But naturally I can’t do this in production. So I deleted the “Everyone” permission after running the app for a few minutes and the error re-appeared.

  2. I created the source in the Application log and the Security log (and I verified it exists via regedit) during installation with elevated permissions but the error remained.

  3. I gave the app a full trust level in the web.config file (and using appcmd.exe) but to no avail.

Does anyone have an insight as to what could be done here?

PS: This is a follow up to this question. I followed the given answers but to no avail (see #2 above).

Exorbitant answered 13/8, 2009 at 19:15 Comment(5)
I was getting this when trying to write to a custom source in a .Net service that was running as NetworkService. I just changed the event log source to match the service name that was setup via the .Net Service Setup package and it worked without setting registry permissions. I noticed it by seeing the service name as a key already in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\ApplicationProstate
Related: #286560Antiphonal
Another possible answer: Right click exe and choose "Run As Administrator"Fossorial
You have to temporarily disable impersonation in the code, for more details Check this The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.Nowell
This error can be the result of a custom event source that has not yet been created. Notice that the error doesn't mention what source it cannot find. Try creating your source log first because this misleading error is not always due to the Security log or sufficient permissions that's missing. See also https://mcmap.net/q/129612/-how-do-i-avoid-this-securityexception-when-writing-to-the-event-log.Toscanini
E
48

The solution was to give the "Network Service" account read permission on the EventLog/Security key.

Exorbitant answered 27/8, 2009 at 4:1 Comment(5)
I see similar solutions around. But I'm just wondering why it is like this. Because I can see that a lot of services are logged on as NetworkService and they must be able to read the event log /security. So why is it needed to add the permission for NetworkService ?Wotton
For those of us who don't normally crawl through the registry, this link may be helpful: social.msdn.microsoft.com/forums/en-US/…Deception
Nice link Allan. Point #3 by the accepted answer is important and has already bitten me once. i.e. Granting permission at the parent EventLog registry key does NOT propagate to "inaccessible logs" such as Security and Virtual Server, even though they are child keys in the registry. If you want full event log access you have to grant permission at BOTH the parent event log level and the child Security levels.Abecedarian
The changes take only effect after you restart your aplication on IISComma
For those who tried to Copy/Paste, make sure there is a space between the words "Network Service".Stilliform
G
174

To give Network Service read permission on the EventLog/Security key (as suggested by Firenzi and royrules22) follow instructions from Link

  1. Open the Registry Editor: Select Start then Run. Enter regedt32 or regedit
  2. Navigate/expand to the following key:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security
3. Right click on this entry and select Permissions

  1. Add the Network Service user

  2. Give it Read permission

UPDATE: The steps above are ok on developer machines, where you do not use deployment process to install application.
However if you deploy your application to other machine(s), consider to register event log sources during installation as suggested in SailAvid's and Nicole Calinoiu's answers.

I am using PowerShell function (calling in Octopus Deploy.ps1)

function Create-EventSources() {
    $eventSources = @("MySource1","MySource2" )
    foreach ($source in $eventSources) {
            if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
                [System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
            }
    }
}

See also Microsoft KB 2028427 Fail to write to the Windows event log from an ASP.NET or ASP application

Gymnast answered 29/6, 2010 at 6:13 Comment(9)
In IIS7 you can assign the "NETWORK SERVICE" as the identity for an App Pool (you might find that ApplicationPoolIdentity is the default) or instead you can create a new user per Application Pool and set permissions on that "Custom account". see Specify an Identity for an Application Pool (IIS 7)Melanymelaphyre
The changes take only effect after you restart your aplication on IISComma
I gave IIS_IUSRS permission to read/write the eventlog key, and read the Security key. My product needed write access on the eventlog key because it creates its own event source.Sporogony
duck9 i correct for IIS8, see here for more details : #712703Sinus
Also look at serverfault.com/a/81246/219898 regarding App Pool Users and related permissions - for this solution. Thanks @Michael Freidgeim - was a big help.Bravo
This is not a right solution, especially for end-user.Cly
I followed steps 1-5 using a local account. It now has read access for the whole Security folder and sub-folders in the registry, but now I get an access error in RegistryKey.OpenSubKey().Knave
@needfulthing, better to raise a new question and provide as much details as possible. Refer to this question when describing what you’ve done already.Gymnast
Did so here: #63393730Knave
B
65

The problem is that the EventLog.SourceExists tries to access the EventLog\Security key, access which is only permitted for an administrator.

A common example for a C# Program logging into EventLog is:

string sSource;
string sLog;
string sEvent;

sSource = "dotNET Sample App";
sLog = "Application";
sEvent = "Sample Event";

if (!EventLog.SourceExists(sSource))
    EventLog.CreateEventSource(sSource, sLog);

EventLog.WriteEntry(sSource, sEvent);
EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 234);

However, the following lines fail if the program hasn't administrator permissions and the key is not found under EventLog\Application as EventLog.SourceExists will then try to access EventLog\Security.

if (!EventLog.SourceExists(sSource))
    EventLog.CreateEventSource(sSource, sLog);

Therefore the recommended way is to create an install script, which creates the corresponding key, namely:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\dotNET Sample App

One can then remove those two lines.

You can also create a .reg file to create the registry key. Simply save the following text into a file create.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Application\dotNET Sample App]
Berth answered 23/2, 2013 at 17:44 Comment(4)
This is exactly what I do for all my services. I believe that this is the right thing to do. In every service where I use the event log I have a .reg file like the one above. One little note the file must be saved as Unicode-32 (cp 1200.)Mixer
This answer describes the real reason behind the error. The check exists tries to enumerate the whole key. if it exists, checkExists works fine.Krishna
EventLog\Security this is the key to function, make sure you have permission on that.Neary
This is one cause of the error message. Another is simply a custom source log not existing.Toscanini
E
48

The solution was to give the "Network Service" account read permission on the EventLog/Security key.

Exorbitant answered 27/8, 2009 at 4:1 Comment(5)
I see similar solutions around. But I'm just wondering why it is like this. Because I can see that a lot of services are logged on as NetworkService and they must be able to read the event log /security. So why is it needed to add the permission for NetworkService ?Wotton
For those of us who don't normally crawl through the registry, this link may be helpful: social.msdn.microsoft.com/forums/en-US/…Deception
Nice link Allan. Point #3 by the accepted answer is important and has already bitten me once. i.e. Granting permission at the parent EventLog registry key does NOT propagate to "inaccessible logs" such as Security and Virtual Server, even though they are child keys in the registry. If you want full event log access you have to grant permission at BOTH the parent event log level and the child Security levels.Abecedarian
The changes take only effect after you restart your aplication on IISComma
For those who tried to Copy/Paste, make sure there is a space between the words "Network Service".Stilliform
D
8

For me ony granting 'Read' permissions for 'NetworkService' to the whole 'EventLog' branch worked.

Deflective answered 3/12, 2009 at 12:22 Comment(1)
that is not very relevant, because the for the sub-keys like "Security" or "Virtual Server" need to grant read access individually, as permissions have been set to not inherity from the parent key.Ternion
M
8

This exception was occurring for me from a .NET console app running as a scheduled task, and I was trying to do basically the same thing - create a new Event Source and write to the event log.

In the end, setting full permissions for the user under which the task was running on the following keys did the trick for me:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog
Mistook answered 21/9, 2011 at 15:26 Comment(1)
You saved my day. BTW, read permission was sufficient on eventlog\Application and eventlog\Security; full control required on the eventlog root only.Benny
U
7

I had a very similar problem with a console program I develop under VS2010 (upgraded from VS2008 under XP) My prog uses EnLib to do some logging. The error was fired because EntLib had not the permission to register a new event source.

So I started once my compiled prog as an Administrator : it registered the event source. Then I went back developping and debugging from inside VS without problem.

(you may also refer to http://www.blackwasp.co.uk/EventLog_3.aspx, it helped me

Uhlan answered 18/10, 2011 at 17:2 Comment(0)
A
7

I try almost everything in here to solve this problem... I share here the answer that help me:

Another way to resolve the issue :

  • in IIS console, go to application pool managing your site, and note the identity running it (usually Network Service)
  • make sure this identity can read KEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog (rigth-click, authorisations)
  • now change the identity of this application pool to Local System, apply, and switch back to Network Service

Credentials will be reloaded and EventLog reacheable

in Link , thanks Michael Freidgeim

Argyrol answered 30/1, 2012 at 16:41 Comment(1)
Changing the app pool from "ApplicationPoolIdentity" to "LocalSystem" solved the issue of creating/reading event logs for me.Crocein
K
6

A new key with source name used need to be created under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application in the regEdit when you use System.Diagnostics.EventLog.WriteEntry("SourceName", "ErrorMessage", EventLogEntryType.Error);

So basically your user does not have permission to create the key. The can do the following depending of the user that you are using from the Identity value in the Application Pool Advanced settings:

  1. Run RegEdit and go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog
  2. Right click in EventLog key and the select Permissions... option 3.Add your user with full Control access.

    -If you are using "NetworkService" add NETWORK SERVICE user

    -If you are usinf "ApplicationPoolIdentity" add IIS APPPOL{name of your app pool} (use local machine location when search the user).

    -If you are using "LocalSystem" make sure that the user has Administrator permissions. It is not recommend for vulnerabilities.

  3. Repeat the steps from 1 to 3 for HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security

For debugging with Visual Studio I use "NetworkService" (it is ASP.NET user) and when the site is published I used "AppicationPoolIdentity".

Knitting answered 28/3, 2016 at 18:25 Comment(0)
D
5

Same issue on Windows 7 64bits. Run as administrator solved the problem.

Dysentery answered 8/6, 2011 at 15:40 Comment(0)
M
4

I ran into the same issue, but I had to go up one level and give full access to everyone to the HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\ key, instead of going down to security, that cleared up the issue for me.

Markettamarkey answered 25/5, 2011 at 21:14 Comment(1)
Also try setting the application to run as LocalSystem, so the registry key is created, then you can change back to NetworkService afterwards.Sherrod
D
4

There does appear to be a glaringly obvious solution to this that I've yet to see a huge downside, at least where it's not practical to obtain administrative rights in order to create your own event source: Use one that's already there.

The two which I've started to make use of are ".Net Runtime" and "Application Error", both of which seem like they will be present on most machines.

Main disadvantages are inability to group by that event, and that you probably don't have an associated Event ID, which means the log entry may very well be prefixed with something to the effect of "The description for Event ID 0 from source .Net Runtime cannot be found...." if you omit it, but the log goes in, and the output looks broadly sensible.

The resultant code ends up looking like:

EventLog.WriteEntry(
    ".Net Runtime", 
    "Some message text here, maybe an exception you want to log",
    EventLogEntryType.Error
    );

Of course, since there's always a chance you're on a machine that doesn't have those event sources for whatever reason, you probably want to try {} catch{} wrap it in case it fails and makes things worse, but events are now saveable.

Duodenal answered 19/4, 2017 at 17:10 Comment(0)
G
3

FYI...my problem was that accidently selected "Local Service" as the Account on properties of the ProcessInstaller instead of "Local System". Just mentioning for anyone else who followed the MSDN tutorial as the Local Service selection shows first and I wasn't paying close attention....

Ginsberg answered 8/2, 2012 at 21:54 Comment(0)
N
2

I'm not working on IIS, but I do have an application that throws the same error on a 2K8 box. It works just fine on a 2K3 box, go figure.

My resolution was to "Run as administrator" to give the application elevated rights and everything works happily. I hope this helps lead you in the right direction.

Windows 2008 is rights/permissions/elevation is really different from Windows 2003, gar.

Nonanonage answered 20/8, 2009 at 17:10 Comment(0)
S
2

Hi I ran into the same problem when I was developing an application and wanted to install it on a remote PC, I fixed it by doing the following:

1) Goto your registry, locate: HKLM\System\CurrentControlSet\Services\EventLog\Application(???YOUR_SERVICE_OR_APP_NAME???)

Note that "(???YOUR_SERVICE_OR_APP_NAME???)" is your application service name as you defined it when you created your .NET deployment, for example, if you named your new application "My new App" then the key would be: HKLM\System\CurrentControlSet\Services\EventLog\Application\My New app

Note2: Depending on which eventLog you are writing into, you may find on your DEV box, \Application\ (as noted above), or also (\System) or (\Security) depending on what event your application is writing into, mostly, (\Application) should be fine all the times.

2) Being on the key above, From the menu; Select "FILE" -> "Export", and then save the file. (Note: This would create your necessary registry settings when the application would need to access this key to write into the Event Viewer), the new file will be a .REG file, for the argument sake, call it "My New App.REG"

3) When deploying on PRODuction, consult the Server's System's administrator (SA), hand over the "My New App.REG" file along with the application, and ask the SA to install this REG file, once done (as admin) this would create the key for your applicaion.

4) Run your application, it should not need to access anything else other than this key.

Problem should be resolved by now.

Cause:

When developing an application that writes anything into the EventLog, it would require a KEY for it under the Eventlog registry if this key isn't found, it would try to create it, which then fails for having no permissions to do so. The above process, is similar to deploying an application (manually) whereas we are creating this ourselves, and no need to have a headache since you are not tweaking the registry by adding permissions to EVERYONE which is a securty risk on production servers.

I hope this helps resolving it.

Soucy answered 4/10, 2011 at 5:59 Comment(0)
P
2

Though the installer answer is a good answer, it is not always practical when dealing with software you did not write. A simple answer is to create the log and the event source using the PowerShell command New-EventLog (http://technet.microsoft.com/en-us/library/hh849768.aspx)

Run PowerShell as an Administrator and run the following command changing out the log name and source that you need.

New-EventLog -LogName Application -Source TFSAggregator

I used it to solve the Event Log Exception when Aggregator runs issue from codeplex.

Pindus answered 12/12, 2014 at 23:23 Comment(0)
P
1

I hit similar issue - in my case Source contained <, > characters. 64 bit machines are using new even log - xml base I would say and these characters (set from string) create invalid xml which causes exception. Arguably this should be consider Microsoft issue - not handling the Source (name/string) correctly.

Peripteral answered 19/4, 2011 at 14:51 Comment(0)
M
1

Had a similar issue with all of our 2008 servers. The security log stopped working altogether because of a GPO that took the group Authenticated Users and read permission away from the key HKLM\System\CurrentControlSet\Services\EventLog\security

Putting this back per Microsoft's recommendation corrected the issue. I suspect giving all authenticated users read at a higher level will also correct your problem.

Mcdade answered 10/11, 2011 at 23:31 Comment(0)
A
0

My app gets installed on client web servers. Rather than fiddling with Network Service permissions and the registry, I opted to check SourceExists and run CreateEventSource in my installer.

I also added a try/catch around log.source = "xx" in the app to set it to a known source if my event source wasn't created (This would only come up if I hot swapped a .dll instead of re-installing).

Amorist answered 22/7, 2013 at 14:31 Comment(0)
S
0

Solution is very simple - Run Visual Studio Application in Admin mode !

Slue answered 26/8, 2013 at 5:18 Comment(2)
When troubleshooting in VS and got this error, this did fix it for meFervency
This would error out because it's not VS that's invoking this call, it's the application which is likely running under a different security context.Coact
G
0

I had a console application where I also had done a "Publish" to create an Install disk.
I was getting the same error at the OP: Error Message

The solution was right click setup.exe and click Run as Administrator

This enabled the install process the necessary privilege's.

Gnash answered 22/1, 2021 at 22:42 Comment(0)
M
0

Ran into this getting raised by Microsoft.Azure.AzureApplicationSettings using VS2022. Adding read permissions to IIS_IUSR did not help... two things worked:

  1. Running Visual Studio as Admin
  2. Adding READ permissions to the user running visual studio on HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\Security
Metropolis answered 20/2 at 17:44 Comment(0)
K
-1

I had this issue when running an app within VS. All I had to do was run the program as Administrator once, then I could run from within VS.

To run as Administrator, just navigate to your debug folder in windows explorer. Right-click on the program and choose Run as administrator.

Kyrstin answered 13/12, 2011 at 15:8 Comment(0)
C
-1

try below in web.config

 <system.web>

<trust level="Full"/>

</system.web>
Clatter answered 10/5, 2016 at 9:55 Comment(0)
Y
-3

Rebuilding the solution worked for me

Yowl answered 9/12, 2011 at 11:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.