Debugging TrustNotGrantedException in VSTO word addin - c#

I'm getting TrustNotGrantedException thrown for some specific users of our VSTO word addin.
These users have the certificate installed correctly.
The exception is being thrown when the app checks for updates:
try
{
ApplicationDeployment.CurrentDeployment.CheckForUpdate()
}
catch(TrustNotGrantedException ex)
{
Log(ex);
}
The stack trace is logged as follows:
User has refused to grant required permissions to the application.
at System.Deployment.Application.ApplicationTrust.RequestTrust(SubscriptionState subState, Boolean isShellVisible, Boolean isUpdate, ActivationContext actCtx, TrustManagerContext tmc) at System.Deployment.Application.DeploymentManager.DetermineTrustCore(Boolean blocking, TrustParams tp) at System.Deployment.Application.DeploymentManager.DetermineTrust(TrustParams trustParams) at System.Deployment.Application.ApplicationDeployment.CheckForDetailedUpdate(Boolean persistUpdateCheckResult) at System.Deployment.Application.ApplicationDeployment.CheckForUpdate() at iReport.iReportAddIn.CheckForUpdates()
Has anyone experienced this or knows how to prevent this in the code or with any workarounds?
Edit:
I have read through this blog post on the issues and it seems like it could be an issue with CAS Permissions for the problem users.
I'll try and give a problem user access to the update URL using this and will follow up in a bit, although I would much prefer to be able to prevent this in the code instead of fixing individual client machines. Something like:
caspol -m -ag 1 -url "http://machinename/application/*" FullTrust -exclusive on
Edit2:
Using caspol.exe worked! Does anyone know a way to prevent this from happening in the code?
Or can anyone explain why it could only be happening to select users?
Edit3:
I'm going to try add
<system.web>
<!-- level="[Full|High|Medium|Low|Minimal]" -->
<trust level="Full" originUrl=""/>
</system.web>
to the app.config
Edit4:
Adding full CAS trust to the app.config didn't help. Can anyone show me if its possible to achieve what CASPOL is doing in code?
Edit5:
If it isn't possible to do this in code, is there a easy way to run the CASPOL command as part of the clickonce install?

In recent versions of Windows, downloaded files are flagged as blocked and have security restrictions imposed on them that can cause breakage when consumed by other apps due to the sandboxing.
The implementation uses NTFS alternate streams. If the file is blocked you can tell by right clicking on the file, viewing properties and seeing the unblock button. Clicking unblock removes the stream and releases the extra security restrictions.
It can also be removed using sysinternals streams.exe. Test whether this is your issue by downloading your plugin on a Windows 7 machine, and then install without unblocking to see if it reproduces the issue.

Related

System.Security.SecurityException when writing to Event Log C#

My application is in C#.NET and it is deployed on different machines. Users of my application have normal access rights ( no ADMIN rights). On a few system I am getting System.Security.SecurityException. It says "System.Security.SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security"
I did a few workarounds :-
on one machine I launched my app with admin rights, It worked fine - No issue.
I added user group in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Security.
It worked fine.
I dont want to go to every machine and do above workarounds. I need any generic workaround that can be applied once in all machine.
Any help?
Writing down a few lines of code :-
Config file :-
<add key="E_Source" Value="ABC">
C# code
Public static readonly string E_Source = ConfigManager.GetString("E_Source");
EventLog.writeEntry(E_Source, logtext, logtype);
Thanks in advance
To find the Source you want to write, .NET enumerates through all event logs. If it doesn't exist, .NET will eventually try enumerating through the Security log, for which you don't even have read rights as normal user. Thus, you get a SecurityException.
So you have to make sure that the event log exists (which AFAIK you can't do without triggering the exception). Normally, you would do that as part of your setup/install. Then, when writing, catch the SecurityException and handle it as appropriate (ex. show an error message that you couldn't write to the log).
If you're writing to the EventLog programmatically, you will need to create an event source with elevated permissions, as noted in the documentation on the EventLog class:
https://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28v=vs.110%29.aspx

Disabling certificate revocation checking for an application on Windows

I have a .NET 3.5 desktop application that had been showing periodic slow downs in functionality whenever the test machine it was on was out of the office.
I managed to replicate the error on a machine in the office without an internet connection, but it was only when i used ANTS performance profiler that i got a clearer picture of what was going on.
In ANTS I saw a "Waiting for synchronization" taking up to 16 seconds that corresponded to the delay I could see in the application when NHibernate tried to load the System.Data.SqlServerCE.dll assembly.
If I tried the action again immediately it would work with no delay but if I left it for 5 minutes then it would be slow to load again the next time I tried it.
From my research so far it appears to be because the SqlServerCE dll is signed and so the system is trying to connect to get the certificate revocation lists and timing out.
Disabling the "Automatically detect settings" setting in the Internet Options LAN settings makes the problem go away, as does disabling the "Check for publishers certificate revocation".
But the admins where this application will be deployed are not going to be happy with the idea of disabling certificate checking on a per machine or per user basis so I really need to get the application level disabling of the CRL check working.
There is the well documented bug in .net 2.0 which describes this behaviour, and offers a possible fix with a config file element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
<generatePublisherEvidence enabled="false"/>
</runtime>
</configuration>
This is NOT working for me however even though I am using .net 3.5.
The SQLServerCE dll is being loaded dynamically by NHibernate and I wonder if the fact that it's dynamic could somehow be why the setting isn't working, but I don't know how I could check that.
Can anyone offer suggestions as to why the config setting might not work?
Or is there another way I could disable the check at the application level, perhaps a CAS policy setting that I can use to set an exception for the application when it's installed?
Or is there something I can change in the application to up the trust level or something like that?
You can specify in code if you want to check the revocation list per application:
ServicePointManager.CheckCertificateRevocationList = false;
In this blog posting (which cites another source) you have two options: disable CRL checking system wide or per app:
Disable CRL Checking Machine-Wide Control Panel -> Internet Options ->
Advanced -> Under security, uncheck the Check for publisher's
certificate revocation option
Disable CRL Checking For a Specific .Net Application See this
Microsoft KB Article: http://support.microsoft.com/kb/936707
What solved the problem for me:
I (think I) had a problem with online revocation before, so I explicitly switched to offline. Due to to warning, I now had to change...
_ = builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(
options =>
{
options.AllowedCertificateTypes = CertificateTypes.All;
options.RevocationMode = X509RevocationMode.Offline;
}
);
... to ...
_ = builder.Services.AddAuthentication(CertificateAuthenticationDefaults.AuthenticationScheme)
.AddCertificate(
options =>
{
options.AllowedCertificateTypes = CertificateTypes.All;
options.RevocationMode = X509RevocationMode.NoCheck;
}
);

C# WPF OpenFileDialog causing crash in XP, not in Vista

I have a WPF application that runs fine on my Vista development machine, but not on the production XP boxes. The only problem is with a call to OpenFileDialog.Show(). As soon as I call the method, the application is terminated on the XP box.
The problem does not trigger an exception. (I've surrounded the block in a try-catch block to no avail.) When I click on File->Open the application just up and quits in XP. Interestingly, I can write files to disk with File->Save and using the Save As dialog. I've tried building it to .Net 3.0 and 3.5 but it doesn't make a difference.
I've tried both Microsoft.Win32.OpenFileDialog and System.Windows.Forms.OpenFileDialog and get the exact same symptom.
The code block for the Microsoft.Win32 variant:
try
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog().Value)
{
//do something
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error!");
}
The only clues I have is the following (partial) entry from the security event log.
Event Type: Failure Audit
Event Source: Security
Event Category: Object Access
Event ID: 560
Description:
Object Open:
Object Server: Security
Object Type: Key
Object Name: \REGISTRY\MACHINE\SOFTWARE\Microsoft\EnterpriseCertificates\Disallowed
Accesses: DELETE
READ_CONTROL
WRITE_DAC
WRITE_OWNER
Query key value
Set key value
Create sub-key
Enumerate sub-keys
Notify about changes to keys
Create link
Any ideas? (Pleeeease!)
Thanks for the advice. I verified both the registry permissions and the full-trust issue. It turns out that, although I specifically built my application to .Net 3.0 (based on the standard organizational image), there was a dependency on .Net 3.5 SP1 that I still don't fully understand. The solution to my problem was to install .Net 3.5 SP1 on all the affected computers.
I just wanted to close the loop. Thanks, again, to all who contributed ideas.
It seems there is a permission problem with the registry key. My first suggestion would be to check the permissions on that key and verify that the ACL's are correct (best compare them to another XP box where the app is working).
If the permissions are OK, then you should try reinstalling .NET (maybe the installer will reset some required permissons on the registry keys).
If all else fails, reinstall XP on problematic machines, unless someone has a better idea.
It doesn't appear your production assembly is running under full trust. Are you running from a network share?

C# console app that does Excel Interop - failing when running as scheduled Task -System.UnauthorizedAccessException

As the title states, I have a C# console app which uses interop to open Excel and create a new workbook. The code works fine when running the console app via command line. However this exception is thrown when running the console app via a scheduled task:
System.UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80070005
It is thrown from the following call:
_xlApp = new Excel.Application()
The scheduled task is setup to use my credentials (I am an administrator). Based on other forums I have made sure I have granted full control to my account at Component Services --> Computers --> My Computer --> DCom Config --> Microsoft Excel Application, but no luck.
I'm on Windows 7 Enterprise 64 bit. Not sure what the next step should be, any help is appreciated
The error 80070005 is a COM Access Denied error.
Are you sure that your credentials have the ability to instantiate the Interop Library?
Check this link and follow some of the debug steps.
(I know you said you did the DCOMConfig thing already, but there are more test scenarios in this link and hopefully something here will help you)
I ended up writing a windows service to call out to a library containing the Excel generation code. That fixed the error. However there was another COM exception when calling the workbook.Save() method. No matter what I tried that error would not go away. I read another post which stated that this was a security precaution and therefore by design.
However, calling workbook.SaveAs() will produce the same result and works fine when called from a windows service.
Thanks for the input funkymushroom. Hopefully this post will be helpful to someone else struggling with Excel Interop automation.
I had the similar issue, I have resolved the issue by performing the following steps.
DCOM Configuration
Click Start -> Run
Enter DCOMCNFG and press OK. This will open the DCOMCNFG window.
Browse down the tree to Console Root -> Component Services -> Computers -> My Computer
right-click on "My Computer" and select properties
Select the "Default Properties" tab
Enable Distributed COM on this computer - Option is checked
Default Authentication Level - Set to Connect
Default Impersonation Level - Set to Identify
Select the "COM Security" tab
Click on Access Permissions ' Edit Default
a. Add "Anonymous", "Everyone", "Interactive", "Network", "System" with Local and Remote access permissions set.
Click on Launch and Activation Permissions ' Edit Default
a. Add "Anonymous", "Everyone", "Interactive", "Network", "System" with Local and Remote access permissions set.
Click on OK
Close the DCOMCNFG window
Later I got an exception while opening the Excel. So please make sure that the following paths are available on the server.
C:\Windows\SysWOW64\config\systemprofile\Desktop
C:\Windows\SysWOW64\config\systemprofile\AppData\Roaming\Microsoft
C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft
This might help guys like me.
I also had this problem - it turned out that on the scheduled task I needed to tick the box "Run with highest privileges" on the General tab of the task set-up. This resolved the problem - it was so simple! Hope it helps someone else too.

Start External Process with Impersonate Issue

Im deploying my website onto my new server (windows 2003) from my local pc (windows 7) and my local homeserver (windows 2008) and have run in to a issue.
I have a process that starts up with the below code. It is passed a video file which gets converted.
System.Diagnostics.ProcessStartInfo StartInfo = new System.Diagnostics.ProcessStartInfo(Command, Parameters);
Them problem I have is on my new windows 2003 server it fails to work. No error or anything. Looking at the server and its taskmgr.exe I see the Process start but nothing happens.
Looking into it, everyone seems to say I need to have impersonate="true" in the webconfig which I do have, I currently have it set to the Administrator account which I use to log into remote desktop (I assume this is fine???)
<identity impersonate="true" userName="Administrator" password="********" />
This still doesn't work.. Looking in the taskmgr.exe the process is started with the username ="NETWORK SERVICE" ...
Any ideas???
A concrete solution i can't provide, but maybe this can help:
Take a low level look with Process Monitor to find if it is security related (missing permissions etc.)
Build a Debug Version of your programm and insert some Debug.Print() statements to narrow the problem. These messages can be seen bei Debug Viewer.
Maybe it's a problem with a wrong or missing assembly. To find these problem take a look into the Fusion Log Viewer.
Maybe one of these techniques will help you to tackle down your problem.

Categories

Resources