I am researching Code Access Security. It's taking some effort to get my head around, so I thought that I would finally make some use of Reflector and start investigating how .NET 4.0 uses security attributes.
Observations
The System.IO.File.Delete method is decorated with the [SecuritySafeCritical] attribute.
The System.IO.File.Delete method delegates to an internal method InternalDelete which is decorated with the [SecurityCritical] attribute.
I have a method in one of my MVC app classes called DeleteFile that is running as SecurityTransparent (which I've verified by checking DeleteFile's MethodInfo.IsSecurityCritical property)
Permissions
From my current understanding that would mean that:
System.IO.File.Delete can call InternalDelete because [SecuritySafeCritical] methods can call [SecurityCritical] so no SecurityException is thrown.
DeleteFile can call System.IO.File.Delete because [SecurityTransparent] can call [SecuritySafeCritical]
So basically, without adjusting any of the out of the box security settings, this code will succesfully delete a dummy file called test.txt
namespace MyTestMvcApp
{
public class FileHelpers()
{
// Has SecurityTransparent
public void DeleteFile()
{
// Will succesfully delete the file
File.Delete("test.txt");
}
}
}
Confusion
Inside the InternalDelete method of System.IO.File.Delete, it uses the CodeAccessPermission.Demand method to check that all callers up the stack have the necessary permissions. What I don't quite understand is this line in the MSDN docs of CodeAccessPermission.Demand:
The permissions of the code that calls this method are not examined; the check begins from the immediate caller of that code and proceeds up the stack.
So my question is, if the DeleteFile method of my application is SecurityTransparent, how come it is allowed to call a SecurityCritical method?
This is probably a broken example perhaps with some missing concepts, but as I said I'm still getting my head around it and any insight people can give the more I'll develop my understanding.
Thanks
You're mixing up two CAS enforcement mechanisms. While they do interact a bit, it's not in quite the same way you seem to be worrying about. For the purposes of full permission demands, as represented by Demand, they're essentially independent.
The CLR applies the transparency verification before executing the code. If this passes, the CLR would then verify any declarative CAS demands applied via attributes. If these pass (or are absent), the CLR would then execute the code, at which time the imperative (inline) demand would run.
The Demand documentation note about "the permissions of the code that calls this method are not examined" apply to the Demand method itself. In other words, if you have a method Foo that calls Demand, the verified call stack starts will Foo's caller, not Foo itself. For example, if you have the call chain A -> B -> C -> Foo -> Demand, only A, B, and C will be verified to check if they have the granted permission.
Related
I have some DLL from third party that I need to license. It has some method that I must call from my own DLL. My DLL is referenced in couple of projects and I don't want to make changes to every hoster. Is there any method that I can use within my DLL which will call some method in my DLL? Like add some static class or constructor but without explicit call to that class from hosters? I am not sure if I am explaining it clearly. Please ask questions if needed.
ThirdPartyType license = new ThirdPartyType();
license.Load("license.xml");
This is a piece of licensing code that I want to place in my DLL and call it within the same DLL.
At the low level, the runtime supports "module initializers". However, C# does not provide any way of implementing them, so the closest you can manage is a static constructor ("type initializer") or just a regular constructor.
However, it is probably a bad idea to hook your licencing into either a module initializer or a type initializer, as you don't know when they will run, and it could impact code that wasn't going to access your lib. It is somewhat frowned upon to take someone's app down because your licensing code decided it was unhappy - especially if your library wasn't actively being invoked at the time.
As such: I suggest the most appropriate place to do this is in either a constructor, or a post-construction Initialize(...) method (with the tool refusing to work unless supplied with valid details).
scaning the internet , im having trouble understanding in a simple manner - the term call-site (#dlr).
ive been reading here that CallSite is :
one site says
The location in which the method is called.
one book say :
call site . This is the sort of atom of the DLR - the smallest piece
of codewhich can be considered as a single unit. One expression may
contain a lot of call sites, but the behavioris built up in the
natural way, evaluating one call site at a time. For the rest of the
discussion, we'll onlyconsider a single call site at a time. It's
going to be useful to have a small example of a call site to refer
to,so here's a very simple one, where d is of course a variable of
type dynamic
d.Foo(10); The call site is represented in code as a
System.Runtime.CompilerServices.CallSite.
another book says :
the compiler emits code that eventually results in an expression tree
that describes the operation, managed by a call site that the DLR will
bind at runtime. The call site essentially acts as an intermediary
between caller and callee.
sorry , I cant see where those 3 explanations are combining into one simple explanation.
i'll be happy to get a simple explanation :
HOw can I explain my wife -what are call-sites ?
The first explanation has nothing to do with the dlr or the dynamic type: simply speaking, a call site is a location (or site) in the source code where a method is called.
In implementing the dynamic type, it is necessary to store information about the dynamic method calls contained in your code, so they can be invoked at runtime (the dlr needs to look up the method, resolve overloads, etc.). It seems natural that the object representing this information should also be called a ”call site”.
Ok this is how I see it.
For this example call is simply like a method or function that executes some code and returns.
For a static language runtime program (C, or CLR etc) a call site is essentially where a function call takes place. It's the location that the call will return to in a normal (non exceptional) flow. Since this is a static program the call site is simply a memory location, pushed on the stack.
For a dynamic language program (Ruby, Python, etc) , the code you are calling is not worked out until runtime. This means that some form of logic is needed to manage the process of making the correct function call and then cleaning up after the call (if needed). If the dynamic language program is on .NET 4 this is done using dlr (dynamic language runtime) objects of type System.Runtime.CompilerServices.CallSite. So the call will return to a method within the CallSite object and then on to location of the original call.
So the answer is that it depends upon how you doing the call and thus what platform you are using.
I want to restrict other application from using dll functions that I have written.
Eg.
If i hav database.dll containg two functions.
public void InsertInToDatabse();
public void ClearDatabase();
Now If my application has called InsertInToDatabse() and is doing some other work,till this time if some other application calls ClearDatabase() by referencing database.dll , The databse would be cler out.So how can I restrict calls to these functions form third party application ?
if your dll is a class library the actual configuration file will be the one of the client application (web.config or app.exe.config) and in there only authorized applications will have proper connection string with username, password, db server and db name.
Now, even if unauthorized apps would be prevented to call you dll's methods in the way you are looking for, in case those bad apps have direct access to the database by knowing the connection string, they can still mess around.
this would to say that in fact as long as the configuration is outside your dll you shouldn't worry because only authorized apps will be accessing the proper database.
if this approach still does not satisfy you, then you should be using security check like CAS which allows you to specify which class or assembly can be calling a certain method so even if your dll is referenced by another application it won't work. Beware that in .NET 4 (you tagged it in the question) the whole security layer has been changed and works differently from older .NET Framework versions, check this article for more details: http://msdn.microsoft.com/en-us/library/dd233103.aspx
You cannot stop people from calling your functions, but you are free to implement your functions to protect against such circumstances.
For instance, you could put a lock around database accesses so that the call blocks until the previous call has finished, or you could have a flag that causes the Clear() call to return immediately with an error code or exception.
EDIT: I may have misunderstood the question. If you NEVER want third party code to call your functions then use internal (and/or InternalsVisibleTo) as Marcus suggests.
You could use internal access on the methods you want to protect (instead of public), then mark your projects as Friend Assemblies. This is the same way you allow unit test projects to access internal methods.
Here's a description from MSDN's Friend Assemblies article...
Only assemblies that you explicitly specify as friends can access Friend (Visual Basic) or internal (C#) types and members. For example, if assembly B is a friend of assembly A and assembly C references assembly B, C does not have access to Friend (Visual Basic) or internal (C#) types in A.
As Marcus mentioned you could use the internal keyword. And then apply the InternalsVisibleToAttribute to your class library with the assemblyname of your application assembly and your public key if you are using strong assemblynames.
MSDN link
If you're asking about security:
Another technique would be to make the client pass in a parameter, such as a password or an encrypted connection string for example.
If you're asking about restriction by caching (eg. only allow this method to be called once every minute) - then look at either [AspNetCacheProfile] for services or Cache.Insert for application code.
If I remember correctly, the internal keyword is for exactly these types of situations.
Edit: As said in comments, if class A is in assembly B, then class C in assembly D won't have access to A.
Also, as pointed out in other answers, you can (and probably should) have some form of authentication in the ClearDatabase().
Edit 2: It just dawned on me that these sort of permissions should be on a database-level, which means that if the following user (with those privileges):
A: Insert, Update, Create
tried to Drop Table, then the application would throw an exception (or however you handle errors), which, obviously, would prevent them from just doing that.
This is not to say that you shouldn't set ClearDatabase() as internal, but if the user (the third-party is using) has permissions to Drop Table then s/he would be able to regardless.
Edit 3:
The problem is not how to secure your code, the problem is how to secure your database.
– Huusom
I'm developing a class library and I need to provide a way to set configuration parameters. I can create a configuration section or I can expose static properties. My concern about static properties is security. What prevents a malicious component from making changes at runtime? For instance, in ASP.NET MVC you configure routes using a static property. Is this secure? Can a malicious component add/remove routes?
How would the "untrusted component" get in my application in the first place? NuGet for example. We don't know what's out there, who did it, and if it contains small bits of undesired state changes.
How would the "untrusted component" run? In ASP.NET all you need is PreApplicationStartMethodAttribute to run some code when the application is starting.
When you consider something as a security threat, you should also think about from whom you are trying to protect.
In order for "malicious code" to alter the values of your static properties, this code would need to be loaded into your AppDomain and run. Now think that a malicious attacker has managed to get his code to run in your AppDomain - are your static properties really your major concern? Such an attacker can probably do a lot worst.
Unless you have a scenario where you need to load an assembly/code originating from external untrusted sources, I think you don't really need to defend against your user accessing your properties (Not from security perspective anyway - usability is another thing).
EDIT - about external untrusted code
I still think this is not really your concern. If I understand correctly, you are developing and providing a library, to be used by some 3rd party in their application.
If the application owner decided to take some external library which he does not trust, add it to his application, and allow it to run, then this is not your concern, it is the application owner's concern.
In this scenario, everything I said above still applies. The malicious code can do much worse then setting your properties. It can mess with memory, corrupt data, flood the thread pool, or even easily crash the AppDomain.
The point is, if you don't own the application because you are only providing a class library, you don't need to defend from code running inside the AppDomain where you classes are loaded.
Note: Re. NuGet, I wouldn't be too worried about that. NuGet is sort of a static tool. If I understand correctly, it doesn't do things in runtime such as downloading code and running it. It is only used in design time to download binaries, add references, and possibly add code. I think it's perfectly reasonable to assume that an application owner that uses NuGet to download a package will do his due diligence to ensure that the package is safe. And he has to do it only once, during development.
As the previous answers note, there isn't really much of a difference here.
Malicious code could set a static property, and malicious code could change a configuration file. The latter is probably a bit easier to figure out from the outside, and can be done no matter what way the code is run (it wouldn't have to be .NET, wouldn't have to be run in your app domain, and indeed wouldn't have to be code, should someone gain the ability to change the file manually), so there's a bit of a security advantage in the use of a static property, though it's a rather bogus one considering that we may well have just moved the issue around a bit, since the calling code could very well be using configuration itself to decide what to set the properties to!
There's a third possibility, which is that you have an instance with instance members that set the properties, and it's the calling code that makes that instance static. This might be completely irrelevant to what you are doing, but it can be worth considering cases where someone might want to have your code running with two sets of configuration parameters in the same app domain. As a matter of security, it is much the same as the matter of static members, except that it could affect serialisation concerns.
So, so far there's the disadvantage of configuration files in that they can be attacked by code completely separate to yours, but with the noted caveat that the information might end up in a configuration file somewhere else anyway.
Whichever approach you take, the safety of access comes down to the way that you load in partially-trusted code.
The code should be loaded into its own app domain, and the security on that app domain set appropriately to how well it can be trusted. If at all possible, it shouldn't be your library that is doing so, but left to the calling code to decide upon the policies to be set by any partially-trusted code it loads in. Of course, if it's inherent to your libraries purpose that it loads in partially-trusted code, then it must do so, but generally it should remain agnostic as to whether the code is fully or partially trusted except in demanding certain permissions when appropriate. If it is up to your library to load in this code, then you will need to decide upon the appropriate permissions to give the app domain. Really, this should be the lowest amount of permission where it is still possible to do the job it was loaded in for. This would presumably not include FileIOPermission, hence preventing it from writing to a config file.
Now, whether your library or the calling code has loaded the partially trusted code, you need to consider what permissions are necessary on your exposed classes and their members. This covers the static setter properties, but would still be necessary if you took the config-file approach given that your scenario still involves that there is partially-trusted code accessing your library.
In some cases, the methods won't need any more protection, because they inherently have it due to what they do. For example, if you try to access a file but the calling code does not have permission to do so, then your code will fail with a security exception that will be passed up to the calling code. Indeed, you may have to do the opposite and take measures to allow the partially-trusted code to call your method (if you access a file in a way that is safe because the caller cannot affect which file is accessed or how, you may want to Assert file-access permissions at that point).
In other cases, you may need to add protection because calling code won't do anything that immediately attempts a security-restricted operation but which may cause trusted code to behave in an inappropriate manner. For example, if your code stores paths that are used by later operations, then essentially calling that code allows for file access to happen in a particular way. E.g.:
public string TempFilePath{get;set;}
public void WriteTempData(string data)
{
using(sw = new StreamWriter(TempFilePath, true))
sw.Write(data);
}
Here if malicious code set TempDirPath it could cause a later call by trusted code to WriteTempData to damage an important file by over-writing it. An obvious approach here is to call Demand on an appropriate FileIOPermission object, so that the only code that could set it would be code that was already trusted to write to arbitrary locations anyway (this could of course be combined by both restricting the possible values for TempDirPath and demanding the ability to write within the set of locations that allowed).
You can also demand certain unions of permission, and of course create your own permissions, though using unions of those defined by the framework has an advantage of better fitting in with existing code.
What prevents a malicious component from making changes at runtime?
This depends on the definition of "malicious component". Configuration is really intended to allow changes at runtime.
If you handle this via code (whether static or instance properties, etc), you do have the distinct advantage of controlling the allowable settings directly, as your property setter can control this however you wish. You could also add some form of security, if your application requires it, as you'd control the way this was set.
With a configuration section, your only control would be in reading the values - you couldn't control the writing, but instead would have to validate settings on read.
For sure, it can be changed by underlying classes which provide those abstractions, even in case of being defined as private members.
Think of a security interceptor that provision every request against defined privileges of authenticated or anonymous users.
I generally use Config file and Static variables together. I define static variable as private, and i make only "get" method to expose value. so it is can not be changed out of class.
I create a class to handle configuration implementing "IConfigurationSectionHandler" interface. My implementation is for ASP.NET Web applications.
Step 1: Create a section in web.config file to process later.
<configuration>
<configSections>
<section name="XXXConfiguration" type="Company.XXXConfiguration, Company"/>
...
</configSections>
<XXXConfiguration>
<Variable>Value to set static variable</Variable>
</XXXConfiguration>
...
<configuration>
Step 2: Create a class to handle previous configuration section.
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
using System.Configuration;
namespace Company{
public class XXXConfiguration : IConfigurationSectionHandler
{
/// <summary>
/// Initializes a new instance of LoggingConfiguration class.
/// </summary>
public XXXConfiguration() {}
private static string _variable;
public static string Variable
{
get {return XXXConfiguration._variable; }
}
public object Create(object parent, object configContext, XmlNode section)
{
// process config section node
XXXConfiguration._variable = section.SelectSingleNode("./Variable").InnerText;
return null;
}
}
}
Step 3: Use GetSection method of System.Configuration.ConfigurationManager at startup of application. In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
System.Configuration.ConfigurationManager.GetSection("LoggingConfiguration");
...
}
I'm allowing users of my application to run snippets of C# to be able to directly manipulate certain objects in my assemblies without me having to write a big scripting interface layer to explicitly expose everything.
This code will be injected into a dynamically compiled assembly, so I can control the assembly itself, but I need to stop the code accessing my private methods using reflection.
I tried calling securityPermissionObject.Deny() just before running the code, but this blocks methods on my objects from using reflection (which some do) when they are called by the user's code.
Is there a way to restrict the permissions only on the suspicious assembly without affecting the public methods it calls on my trusted assemblies?
Try to create a new appdomain. And use it as a sandbox. Within this sandbox you can load your assembly in.
Here is an example.
Of course because you now have two appdomains it complicates communictiaon a bit. You might consider a Webservice through a pipe or other communication mechanisms.
Here is an article of how two appdomains can communicate.
(An old question, not sure whether you still need an answer)
When calls are coming back into your public methods, then the first thing you need to do is carefully sanitize the parameters, and reject any bad calls. After that, you can add a call to Assert for RelectionPermission. This basically allows any code you call which requires reflection to be satisfied, and not see the Deny higher up in the call stack.