I have a very theoretical question: Is there a way to ban the use of some methods, objects etc. inside of my application/project map in C#, .Net and/or Visual Studio?
To be more specific: I'm developing a DMS System where it should never be possible to delete files from an archive. The archived files are just files inside a Windows folder structure.
So, whenever someone tries to perform a System.IO.File.Delete() this should be forbidden. Instead I would force to use a custom-made FileDelete()-method which always ensures that the file to delete is not a file from inside an archive.
(This doesn't have to happen automatically. It's ok when there is an error/exception that informs the developer of a banned method-call.)
Another way to implement this could be to observe all calls of System.IO.File.Delete() at runtime, catch them and execute my own FileDelete()-method.
Of course these are a really theoretical questions but I would just know if there could be a way to implement this.
P.S.: I'm using C# with Visual Studio 2005. So it doesn't matter if I can realize this through my programming language or by Visual Studio (or by any other way I forgot).
Wouldn't it be simpler to control delete permissions to the archived files?
you can define methods and adorn them with declarative security attributes
http://msdn.microsoft.com/en-us/library/dswfd229.aspx
HTH
The closest I can come to a solution is to write you own System.IO.File class and keeping that in exe project. That way you'll get a ambiguity compile error that can be resolved with giving you own implementation in an alias (using File=System.IO.File, Version=[version], cultuer=[correct culture], publicKey=[public key]). If you're unsure about what to write make a break point and write something like ?typeof(System.IO.File).AssemblyQualifiedName in the immediate window.
It's not bullet proof but at least it will enforce the developer to be concious about the decision and you could even (tho I personally wouldn't do it) change the default class template to include the using directive for every class
Not for existing library functions.
For your own code, you could apply code-access-security on methods, but code running as "full trust" will breeze past this; so to check for abuse via reflection you would probably have to check the caller manually (Assembly.GetCallingAssembly) - which is painful and still not 100% robust...
There is specific file/IO permissions, but again full trust will ignore it.
I think "no" is a safer answer.
One way you could go about doing this is to create a special user account and only grant that account the permissions necessary to remove the files.
Just keep in mind that the user is in control of his computer (if he has administrative privileges ;) and while you can put some obstacles in his way there really is nothing you can do about it (and that's the way it should be).
What about writing your own FxCop rule for that case?
With such a rule it will be impossible to compile if you treat warnings as errors.
Related
Most questions of this type are seeking to alter the program behavior (things that could be decided at run time) or want to deal directly with debug printing. This is a bit different.
I have code that depends on a peripheral (like a card reader). Sometimes I don't use it, which means the library isn't present. (And I'm being nice, because "library" turns out to mean installing a 2GB software suite). When I remove the library, I can't open the device. If I can't open the device, I can't create the class member that uses it. With the class inoperative, I can't call its methods from within the code. Therefore, I can't just choose not to execute it; I need it to go away since it will not compile without the library.
Preprocessor directives like #if and all that are ok, maybe; but these things appear in more than one file, which means independently maintaining a #define at the top of each. I come from a simpler place (meaning, C) where one header file can be used to control this. I note that C# is rather hostile about #define (either the label exists, or not; no constants or calculations allowed), and that makes me think there's another way.
How do you handle this?
---Follow-up(s)---
I did read the "duplicate" Q/A's, and have a fairly good picture of what I'm dealing with. I didn't find those questions in my original search, but sometimes that's just how it is.
#Amy suggests that #define at the top is "not how it's done" but rather "put it on the command line". So, (if I realize we are sticking with this mechanism) the discussion might go to examining ways to have that happen . One does not simply drop to a terminal and do that. It happens as "IDE features" or "IDE hacks".
#Alexei Levenkov asks what I really want. I really want to (a) not get compile errors, and (b) do it by selectively leaving out the code. And, find the C# equivalent to the way I proposed.
Some more constraints are addressed by the fact that I haven't been using VS or C# for all that long. So I know a lot less than you all do. Considering I got the code from the last person and have to deal with what I see, I don't want to set up the person after me to have to figure out what "interesting" thing I might have done to make it work. Thus, things like hand-editing a project file may work but will also cause consternation down the line.
# Eric Lippert suggests "hostile" is really "sensible". I may have had my tongue too far into my cheek on that one. VS seems to be telling me I'm doing it wrong, so I sensed there's a "right way" I simply don't know about. As for the 2GB supporting application, I will go to various computers and pull down the repository and try out something, and so this "overhead" wants to propagate with it. It's worse if I'm linked through my phone to do the download. And if I build the application with everything included, the end user is then required to install that software suite before the program will run. In theory, they could be required to buy the software. If I sent you a tic-tac-toe game, and told you it wouldn't run until you installed Oracle, you'd probably pass on the whole thing.
I considered the "stub out the interface" idea, but there seemed to be more hooks into the class than I wanted to deal with. Plus, I don't know what these things do, so I have to know something about them in order to "fake" them.
In the end I decided that we're still largely using the #if scheme to get this done, and the replacement feature I imagined might exist, doesn't. And I'm using the provision in the project file(s) as cited by #Jim G. as it gets the job done and is only a little imperfect. It's good enough.
As #BJ Safdie said here:
Set them in your Compilation Properties or Build options.
You get to the build options by right-clicking the project and selecting
properties from the menu.
Here's an example of the code which will be used for the reflection:
var i = typeof(Program).Assembly.CreateInstance("test.Program");
After the software is obfuscated, the code will obviously stop working.
I'm trying to find a way around it by searching for properties of a class, which do not change after obfuscation has been done. I've tried that with type.GUID, but when I run the debug version, I get one GUID, and in the release after the obfuscation is completed, the guid is changed.
I'm using Eazfuscator.NET for obfuscation.
I would like to avoid using attributes to mark class/method if possible.
Any ideas on what would work?
I'm sure there are ways to iterate over all types and find the one you're looking for, but the things that come to mind would all produce the least maintainable code ever.
Some obfuscators (we use DeepSea, I don't know Eazfuscator) allow preventing obfuscation of specific classes, allowing reflection on those. In DeepSea's case, this is indicated by attributes but those won't/shouldn't (I never checked :o) make it to the final assembly.
If you regard reflection as "an outside process looking at your assembly" and obfuscating "preventing outside processes from looking at your assembly" you're really stopping yourself from doing what you want to do.
don't want the obfuscator to defeat the attackers. Just make the job of understanding the code more difficult. And I want this as a part of advanced piracy protection
After obfuscation; zip, encrypt and do whatever you want with your assembly. Then create another wrapper project and add your assembly as a resource into that project. Attach to AppDomain.CurrentDomain.AssemblyResolve event (in your new project) and whenever an unresolved assembly event occurs, read your resource(decrypt,unzip etc.) and return the actual assembly.
You may also try to obfuscate your final wrapper application.
How secure? At least, you can make life more harder for attackers.
I don't have exact answer, but ILSpy's source might help you.
Apologies for the shortness of the question, however I don't think it needs much elaboration.
Any there any security implications caused by using the CSharpCodeProvider and could it open a server up for attack?
It depends on how you use it. Here is a summary sorted from the safe use to a use that you certainly don't want to allow (when running the code on a server or some environment that you want to control):
If you use CSharpCodeProvider just for generating C# source code, then you only need a permission to save the generated files to some directory or to noting at all (if it is possible to get the code generated into a memory stream)
If you use it for compiling generated C# source, then you need a permission to run csc.exe (which may not be available in some limited environments such as shared hostings).
If you just generate files & compile them, then it probably won't be harmful (although someone could probably abuse your application to generate many, many files and attack the server using some kind of DOS attack.
If you also load & execute the generated code, then it depends on how you generate it. If you assume that there are no bugs in C#/CodeDOM and can guarantee that the generated code is safe, then you should be fine.
If your code contain things such as CodeSnippetExpression that can be provided by the user (in some way) than the user can write and run anything he or she wants on your server, so this would be potentially quite dangerous.
Sort of. On the surface it's not a direct risk, because you're not running code, just compiling it. However, there's nothing that says that the C# compiler doesn't contain some sort of bug that, given the right malicious input, would cause it to bail out and start executing commands directly.
However, if you later execute the compiled code (and presumably you do -- otherwise why would you compile it to begin with?), it will be running the same context as you are. Obviously, that has all kinds of unpleasant security implications, much like using the quasi-analogous eval() feature of other languages.
It depends on the source that you are compiling. If you have enough control over the source, then it might be an acceptable risk. If you are allowing someone outside of your sphere of trust supply code to the compiler, it might be an unacceptable risk.
Ok, so I was wondering how one would go about creating a program, that creates a second program(Like how most compression programs can create self extracting self excutables, but that's not what I need).
Say I have 2 programs. Each one containing a class. The one program I would use to modify and fill the class with data. The second file would be a program that also had the class, but empty, and it's only purpose is to access this data in a specific way. I don't know, I'm thinking if the specific class were serialized and then "injected" into the second file. But how would one be able to do that? I've found modifying files that were already compiled fascinating, though I've never been able to make changes that didn't cause errors.
That's just a thought. I don't know what the solution would be, that's just something that crossed my mind.
I'd prefer some information in say c or c++ that's cross-platform. The only other language I'd accept is c#.
also
I'm not looking for 3-rd party library's, or things such as Boost. If anything a shove in the right direction could be all I need.
++also
I don't want to be using a compiler.
Jalf actually read what I wrote
That's exactly what I would like to know how to do. I think that's fairly obvious by what I asked above. I said nothing about compiling the files, or scripting.
QUOTE "I've found modifying files that were already compiled fascinating"
Please read and understand the question first before posting.
thanks.
Building an executable from scratch is hard. First, you'd need to generate machine code for what the program would do, and then you need to encapsulate such code in an executable file. That's overkill unless you want to write a compiler for a language.
These utilities that generate a self-extracting executable don't really make the executable from scratch. They have the executable pre-generated, and the data file is just appended to the end of it. Since the Windows executable format allows you to put data at the end of the file, caring only for the "real executable" part (the exe header tells how big it is - the rest is ignored).
For instance, try to generate two self-extracting zip, and do a binary diff on them. You'll see their first X KBytes are exactly the same, what changes is the rest, which is not an executable at all, it's just data. When the file is executed, it looks what is found at the end of the file (the data) and unzips it.
Take a look at the wikipedia entry, go to the external links section to dig deeper:
http://en.wikipedia.org/wiki/Portable_Executable
I only mentioned Windows here but the same principles apply to Linux. But don't expect to have cross-platform results, you'll have to re-implement it to each platform. I couldn't imagine something that's more platform-dependent than the executable file. Even if you use C# you'll have to generate the native stub, which is different if you're running on Windows (under .net) or Linux (under Mono).
Invoke a compiler with data generated by your program (write temp files to disk if necessary) and or stored on disk?
Or is the question about the details of writing the local executable format?
Unfortunately with compiled languages such as C, C++, Java, or C#, you won't be able to just ``run'' new code at runtime, like you can do in interpreted languages like PHP, Perl, and ECMAscript. The code has to be compiled first, and for that you will need a compiler. There's no getting around this.
If you need to duplicate the save/restore functionality between two separate EXEs, then your best bet is to create a static library shared between the two programs, or a DLL shared between the two programs. That way, you write that code once and it's able to be used by as many programs as you want.
On the other hand, if you're really running into a scenario like this, my main question is, What are you trying to accomplish with this? Even in languages that support things like eval(), self modifying code is usually some of the nastiest and bug-riddled stuff you're going to find. It's worse even than a program written completely with GOTOs. There are uses for self modifying code like this, but 99% of the time it's the wrong approach to take.
Hope that helps :)
I had the same problem and I think that this solves all problems.
You can put there whatever code and if correct it will produce at runtime second executable.
--ADD--
So in short you have some code which you can hard-code and store in the code of your 1st exe file or let outside it. Then you run it and you compile the aforementioned code. If eveything is ok you will get a second executable runtime- compiled. All this without any external lib!!
Ok, so I was wondering how one would
go about creating a program, that
creates a second program
You can look at CodeDom. Here is a tutorial
Have you considered embedding a scripting language such as Lua or Python into your app? This will give you the ability to dynamically generate and execute code at runtime.
From wikipedia:
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution. These behaviors can be emulated in nearly any language of sufficient complexity, but dynamic languages provide direct tools to make use of them.
Depending on what you call a program, Self-modifying code may do the trick.
Basically, you write code somewhere in memory as if it were plain data, and you call it.
Usually it's a bad idea, but it's quite fun.
ReSharper Code cleanup feature (with "reorder members" and "reformat code" enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template.
Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc. ? Is there a chance that it causes many undesired conflicts ?
Thank you.
Yes, it will definitely cause problems. In addition to creating conflicts that have to be manually resolved, when you check in a file that has been reformatted, the VCS will note almost every line as having been changed. This will make it hard for you or a teammate to look back at the history and see what changed when.
That said, if everyone autoformats their code the same way (ie, you distribute that XML template to the team), then it might work well. The problems really only come in when not everyone is doing the same thing.
I'm waiting for an IDE or an editor that always saves source code using some baseline formatting rules, but allows each individual developer to display and edit the code in their own preferred format. That way I can put my open curly brace at the beginning of the next line and not at the end of the current line where all you heathens seem to think it goes.
My guess is I'll be waiting for a long time.
Just reformat the whole solution
once
AND make sure that every developer
is using Resharper
AND make sure that formatting
options are shared and versioned
(code style sharing options)
You can use StyleCop to enforce a comprehensive set of standards which pretty much forces everyone to use the same layout styles. Then all you need to do is develop a ReSharper code style specification that matches this, and distribute it to the team.
I'm still waiting for someone else to do this, and for JetBrains to clear up all the niggling details which aren't fully supported, in order to allow ReSharper to basically guarantee full StyleCop compliance.
It can definitely cause conflicts, so I would make sure you don't reformat entire files if there are people working on them in parallel.
It definitely could cause conflicts.
If you want to use this in a multi-user environment then the configuration of Resharper needs to format your code to a set of standards which are enforced in your organization regardless of whether users make use of Resharper or not.
That way you are using the tool to ensure your own code meets the standards, not blanket applying your preferences to the whole codebase.
I Agree with the previous answers that state that conflicts are possible and even likely.
If you are planning to reformat code then at least make sure that you don't mix reformat checkins with those that change the function of the actual code. This way people can skip past check-ins that are simple reformattings. It's also a good idea to make sure that everyone knows a reformat is coming up so that they can object if they have ongoing work in that area.
We're working on something to work with refactors at the source code level. We call it Xmerge, and it's now part of Plastic. It's just a first approach, since we're working on more advanced solutions. Check it here.
It might be a good idea to write a script to check out every version in your source control history, apply the code cleaning, then check it into a new repository. Then use that repository for all your work in future.