Code Access Security when programing Windows Services in .Net

So, I’ve been bad about blogging for a while – busy as at work trying to learn things. Anyhoo, I’ve been writing a Windows Service using the .NET framework’s ServiceBase class, and I found something interesting when I tried to add Code Access Security (CAS) to it.

My service connects to a SharePoint 2007 service every so often, queries a List, sends a few emails, and logs some information. The main additional assemblies it uses are Microsoft.SharePoint and Log4NET for the SharePoint and Logging parts respectively.

I tried adding CAS like so:

[assembly: FileIOPermission(SecurityAction.RequestOptional,Unrestricted=true)]

I knew I’d need other permissions, and that I definitely wanted this one; my plan was that as RequestOptional would cause all other permissions not requested by RequestOptional or RequestMinimum to be denied, I would get permissions errors. I’d then work my way through my code, adding the minimum set of permissions I required.

What I got was the security exception “That assembly does not allow partially trusted callers”. This wasn’t the failed permission that I’d expected, but that one of the assemblies couldn’t be called as from a partially trusted assembly (which my assembly was, as soon as I started added CAS).

I was surprised. I didn’t think that the SharePoint or Log4NET dlls would complain about being called from a partially trusted context. At the suggestion of Dominick Baier on Google groups, I used the Lutz Reflector to look inside the assemblies, and checked for the [AllowPartiallyTrustedCallers] attribute.

Both the Log4NET and SharePoint DLLs had this attribute. So they weren’t causing the exception. Then I tried the System.ServiceProcess dll, which contains the ServiceBase class I was subclassing. Tada! It didn’t allow partially trusted callers. Thus, when my code was run, naturally, it made calls of it’s parent class. That parent class existed in an assembly that I couldn’t access from a partially trusted context.

I guess that makes sense – I mean, quite when would you want something to interact with your services from a partially trusted position? They’re a bit, well, important for that.

Guess I won’t be applying CAS that way. Probably don’t have to, then. If my code can only be called from a Full Trust context, why would an attacker have to abuse my code? Their app would be fully trusted too – it could abuse the machine directly.

Advertisement
Code Access Security when programing Windows Services in .Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.