Configuration vs. static properties, security concerns - c#

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");
...
}

Related

Settings specific to a class

I have a class where I retrieve certain settings from a database (usernames and passwords). This database is sitting on a network, and it means that if the passwords are changed, I can simply change it in the database, and all the applications that use this class will still work.
I am fully aware of the pros and cons of storing usernames and passwords in a database and in a separate location. I don't want to discuss those, please.
The class has a hard-coded static string that is the path to the database. It is a fully qualified network name (not just the drive letter). I did this because we had an issue where our network DNS got screwed up, and drive letter mappings stopped working, and some people have different drive mappings anyway.
We recently had our server moved, so I now need to go through and change these hard-coded strings.
I was thinking that I should store the path in a settings / configuration file instead. I considered "application.settings", but it is not an application setting; its specific to the class. Is there a preferred way of doing this in the existing .Net framework (this is a C# issue)?
I could simply have a small text or XML file that sits in the application directory, which is probably fine... is there an existing framework namespace or open-source code snippet that someone knows of that I can use?
I think, if you want class specific configuration, you should try to have those class instances, configuration driven. Another way of thinking but; Defining a something in a configuration file, will create an instance of the defined classname.
For example: Create a section, and call it, <Modules> and create items in like: <module type="<namespace>.DBConvertor" param="username=root;passwd=whatever"> This type will be created at startup (you need some coding here). And it's even possible to create more than one instance simultaneously with it's specific configurations.
This kind of configuration is already implemented:
You might take a look at this: "How to: Create Custom Configuration Sections Using ConfigurationSection" https://msdn.microsoft.com/en-us/library/2tw134k3.aspx
And creating instances from typenames, use the Activator class.
Besides that, there are many module/plugin libraries, (like Managed Extensibility Framework (MEF) https://msdn.microsoft.com/en-us/library/dd460648(v=vs.110).aspx but could be a little over the top in this case).

how to secure dll functions from being used outside of my application?

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

How can I restrict an assembly's security permissions, but not those of its callees?

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.

Using HttpContext.Current.Application to store simple data

I want to store a small list of a simple object (containing three strings) in my ASP.NET MVC application. The list is loaded from the database and it is updated rarely by editing some values in the site's admin area.
I'm thinking of using HttpContext.Current.Application to store it. This way I can load it in the Global.asax:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
HttpContext.Current.Application["myObject"] = loadDataFromSql(); // returns my object
}
And then can easily reference it from any controllers or views as needed. Then in the event, the admin area calls the updateMyObject controller action, I can just update the DB and load it in again and replace HttpContext.Current.Application["myObject"].
Are there any cons to doing this? It seems like it will work fine for what I am trying to achieve, however does anyone know of a better way to do this, assuming there is some major disadvantage to the method I've laid out?
What you actually do is Caching, and it's great, since you reduce calls to an external storage (a database or a file, whatever). The trade-off is memory usage, of course. Now, almost any modern web framework, including ASP.NET, includes some kind of a caching mechanism. Either you use it, or you use some kind of a global variable.
Storing data in ASP.NET's built-in Cache object has some significant advantages, since this mechanism actually checks the memory usage and removes the cached data according to some rules.
However, if the data you want to cache is intensively used across the application, and its size is not too large (say, smaller than 1 MB), you may want to store it in as a global variable.
In ASP.NET, global variables are achieved by either using the Application object, like you described in your question, or by writing public static properties/fields in an internal/public class.
Here's my solution to static properties. Note that I use a locking object, to protect the inner data from corruption. It looks like this:
public class WhateverClass
{
private static object theLocker = new object();
private static YourDataType theData;
public static YourDataType TheData
{
get
{
lock (theLocker)
{
return theData;
}
}
set
{
lock (theLocker)
{
theData = value;
}
}
}
}
The usage is very simple:
First time, in Application_Start:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
WhateverClass.TheData = loadDataFromSql();
}
In any controller:
var myData = WhateverClass.TheData;
This approach is better because you have type safety, since this public static property can be explicitly declared with the exact type. In addition, this kind of storage is more testable since it doesn't depend on the web context.
HTH!
HttpContext.Current.Application is essentially a hangover that is needed for backwards compatibility with classic ASP. It's essentially a static Hashtable with classic ASP locking semantics (Application.Lock / Application.UnLock).
As a weakly-typed Hashtable, you will need to cast objects you retrieve:
MyObject myObject = (MyObject) HttpContext.Current.Application["myObject"];
In an ASP.NET application that is not a migration from classic ASP, I would prefer using other standard .NET stuff, such as:
A static field, using .NET locking semantics if you need locking (e.g. the C# lock keyword, or a ReaderWriterLockSlim instance, depending on your requirements):
static MyObject myObject = LoadFromSql();
The ASP.NET Cache - which has rich functionality for managing expiration, dependencies, ...
Yes, using HttpContext.Current.Application will work fine for what you are doing. No problems.
HttpContext.Current.Application is simply a reference to the static global HttpApplicationState object in .NET for your Web Application, of which there should be one global instance per web application. By storing data there, you provide fast, thread-safe access to your global variables. Be sure to lock them when updating values, as in this example:
System.Web.HttpContext.Current.Application.Lock();
System.Web.HttpContext.Current.Application["WebApplicationPath"] = MyWebApplicationPath;
System.Web.HttpContext.Current.Application.UnLock();
As others have mentioned, you can also create a series of static classes in your App_Code or other folder and there store global static values as well as your HttpContext.Current.Application values, where they can be safely checked for values or updated from the database, or update and check each other, working in tandem. I usually create a static global class to assist in the management and retrieval of the Application variables I store. In this way you have both the state dictionary of the HttpApplicationState class and the web application static objects working together to share and maintain global values. (Keep in mind each static class is assigned per worker process and there may be as many as 10 WP on average by default on many IIS web servers/web applications. So keep data in static types to a minimum.)
Keep in mind as some mentioned server farms do not share Application state. There are many ways to manage this. I'm not a fan of cache because of the ways in which it can expire, fail, become stale, or get corrupted. A simpler solution is to simply use use the database and URL querystrings to communicate across servers and maintain state. Good luck!
If you're deploying to a single web server the approach would work. Consider the Cache object for this as it provides more options for expiration if you need such functionality. (See a comparison, albeit an aged one, here.)
If you're ever going to deploy to a web server farm or equivalent you should use memcached or another web farm friendly caching mechanism. Both the Application and Cache objects only typically exist in a single server context; if your user could be hitting multiple web servers during their session (and the cache needs to be identical) you'll need a shared cache that can be seen from each of the potential web servers.
Regardless of which path you take you will need to invalidate/reload your cache whenever the underlying data changes, which is custom code that varies by app.
This approach works well and can speed things considerably but it's a bit more work than you may realize at first glance...
Application_Start really only gets fired on App Pool Recylce's, IIS Resets or reboots. If your updating these values that infrequently, why not store them in your web.config and access them that way?
That being said, I don't think there is anything wrong with your approach. Though more typically I've seen people using config files for rarely changed values.

Other than testing, how is Dependency Injection any better than static classes/methods?

Other than testability, what's the big advantage of utilizing D.I. (and I'm not talking about a D.I. framework or IoC) over static classes? Particularly for an application where you know a service won't be swapped out.
In one of our c# application, our team is utilizing Dependency Injection in the web web GUI, the service layer, and the repository layer rather than using static methods. In the past, we'd have POCOs (busines entity objects) that were created, modified, passed around, and saved by static classes.
For example, in the past we might have written:
CreditEntity creditObj = CreditEntityManager.GetCredit(customerId);
Decimal creditScore = CreditEntityManager.CalculateScore(creditObj);
return creditScore;
Now, with D.I., the same code would be:
//not shown, _creditService instantiation/injection in c-tors
CreditEntity creditObj = _creditService.GetCredit(customerId);
Decimal creditScore = _creditService.CalculateScore(creditObj);
return creditScore;
Not much different, but now we have dozens of service classes that have much broader scope, which means we should treat them just as if they were static (i.e. no private member variables unless they are used to define further dependencies). Plus, if any of those methods utilize a resource (database/web service/etc) we find it harder to manage concurrency issues unless we remove the dependency and utilize the old static or using(...) methods.
The question for D.I. might be: is CreditEntityManager in fact the natural place to centralize knowledge about how to find a CreditEntity and where to go to CalculateScore?
I think the theory of D.I. is that a modular application involved in thing X doesn't necessarily know how to hook up with thing Y even though X needs Y.
In your example, you are showing the code flow after the service providers have been located and incorporated in data objects. At that point, sure, with and without D.I. it looks about the same, even potentially exactly the same depending on programming language, style, etc.
The key is how those different services are hooked up together. In D.I., potentially a third party object essentially does configuration management, but after that is done the code should be about the same. The point of D.I. isn't to improve later code but to try and match the modular nature of the problem with the modular nature of the program, in order to avoid having to edit modules and program logic that are logically correct, but are hooking up with the wrong service providers.
It allows you to swap out implementations without cracking open the code. For example, in one of my applications, we created an interface called IDataService that defined methods for querying a data source. For the first few production releases, we used an implementation for Oracle using nHibernate. Later, we wanted to switch to an object database, so we wrote and implementation for db4o, added its assembly to the execution directory and changed a line in the config file. Presto! We were using db4o without having to crack open the code.
This has been discussed exactly 1002 times. Here's one such discussion that I remember (read in order):
http://scruffylookingcatherder.com/archive/2007/08/07/dependency-injection.aspx
http://ayende.com/Blog/archive/2007/08/18/Dependency-Injection-More-than-a-testing-seam.aspx
http://kohari.org/2007/08/15/defending-dependency-injection
http://scruffylookingcatherder.com/archive/2007/08/16/tilting-at-windmills.aspx
http://ayende.com/Blog/archive/2007/08/18/Dependency-Injection-IAmDonQuixote.aspx
http://scruffylookingcatherder.com/archive/2007/08/20/poking-bears.aspx
http://ayende.com/Blog/archive/2007/08/21/Dependency-Injection-Applicability-Benefits-and-Mocking.aspx
About your particular problems, it seems that you're not managing your services lifestyles correctly... for example, if one of your services is stateful (which should be quite rare) it probably has to be transient. I recommend that you create as many SO questions about this as you need to in order to clear all doubts.
There is a Guice video which gives a nice sample case for using D.I. If you are using a lot of 3-rd party services which need to be hooked upto dynamically D.I will be a great help.

Categories