473,805 Members | 2,076 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

CodeDom: Runtime code evaluation and system security

balabaster
797 Recognized Expert Contributor
I don't know if anyone's got any clue about this, but I have the following expression evaluator which makes use of the CodeDom to evaluate a VB.NET expression at runtime.

This gives the system administrator the ability to add ad-hoc expressions onto the system, and when users execute these expressions, they are prompted for data for the arguments.

Expand|Select|Wrap|Line Numbers
  1. Function Evaluate(ByVal Expression As String, ByVal Args() As Object) As Double
  2.  
  3.         If Expression.Length > 0 Then
  4.  
  5.             'Replace each parameter in the calculation expression with the correct values
  6.             Dim MatchStr = "{(\d+)}"
  7.             Dim oMatches = Regex.Matches(Expression, MatchStr)
  8.             Dim DistinctCount = (From m In oMatches _
  9.                                  Select m.Value).Distinct.Count
  10.             If DistinctCount = Args.Length Then
  11.                 For i = 0 To Args.Length - 1
  12.                     Expression = Expression.Replace("{" & i & "}", Args(i))
  13.                 Next
  14.             Else
  15.                 Console.WriteLine("Invalid number of parameters passed")
  16.             End If
  17.  
  18.             Dim FuncName As String = "Eval" & Guid.NewGuid.ToString("N")
  19.             Dim FuncString As String = "Imports System.Math" & vbCrLf & _
  20.                                        "Namespace EvaluatorLibrary" & vbCrLf & _
  21.                                        "  Class Evaluators" & vbCrLf & _
  22.                                        "    Public Shared Function " & FuncName & "() As Double" & vbCrLf & _
  23.                                        "      " & Expression & vbCrLf & _
  24.                                        "    End Function" & vbCrLf & _
  25.                                        "  End Class" & vbCrLf & _
  26.                                        "End Namespace"
  27.  
  28.             'Tell the compiler what language was used
  29.             Dim CodeProvider As CodeDomProvider = CodeDomProvider.CreateProvider("VB")
  30.  
  31.             'Set up our compiler options...
  32.             Dim CompilerOptions As New CompilerParameters()
  33.             With CompilerOptions
  34.                 .ReferencedAssemblies.Add("System.dll")
  35.                 .GenerateInMemory = True
  36.                 .TreatWarningsAsErrors = True
  37.             End With
  38.  
  39.             'Compile the code that is to be evaluated
  40.             Dim Results As CompilerResults = _
  41.                 CodeProvider.CompileAssemblyFromSource(CompilerOptions, FuncString)
  42.  
  43.             'Check there were no errors...
  44.             If Results.Errors.Count > 0 Then
  45.             Else
  46.                 'Run the code and return the value...
  47.                 Dim dynamicType As Type = Results.CompiledAssembly.GetType("EvaluatorLibrary.Evaluators")
  48.                 Dim methodInfo As MethodInfo = dynamicType.GetMethod(FuncName)
  49.                 Return methodInfo.Invoke(Nothing, Nothing)
  50.             End If
  51.  
  52.         Else
  53.             Return 0
  54.  
  55.         End If
  56.  
  57.     End Function
This can be called using something like:
Expand|Select|Wrap|Line Numbers
  1. Dim Expr As String = "  If ({0} < 20000) Then" & vbCrLf & _
  2.                      "    Return MAX(15, MIN(75,0.12*{0}))" & vbCrLf & _
  3.                      "  Else" & vbCrLf & _
  4.                      "    Return MAX(75,0.05*{0})" & vbCrLf & _
  5.                      "  End If"
  6. Dim Args() As Object = New Object() {2300}
  7. Dim dblOut = Evaluate(Expr, Args)
  8. Console.WriteLine(dblOut)
  9. Console.ReadLine()
The expression could equally be extracted from the text of a RichTextBox.

Now, I'm looking at running this code on a web server, and as such, security is going to be an issue (not that I want to come across as not trusting the system administrators, but you never know what the future brings). While this code may be running in isolated memory space, it's not prevented from reading and writing to the system. Is there any way to lock it down to prevent someone from adding potentially insecure references?
Sep 5 '08 #1
0 1437

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1925
by: Ron Bullman | last post by:
Hi, I havent been able to find any documentation about @ in the CodeDom context. The problem is when generating C# code from CodeDom it will associate a @-tag with all C# specific types. Why? And how to configure the CodeDom to generate code without @-tags? Ron A short example follows whic produces following kind of output:
1
5572
by: fred_mumble | last post by:
I have been testing various techniques to run "script" code which will be stored in a SQL database and executed dynamically at runtime. The scripts are essentially business rules that result in a report being generated based on test parameters input by a user - 4 batches of scripts containing multiple functions will be run each time a user runs a new test. The reason the scripts are run in 4 batches is due to the fact that each batch is...
1
2296
by: John Livermore | last post by:
Hello, We have an application that uses CodeDom for dynamic in-memory compilation of code. The same code (library) is used by both an ASP.net web site and a Windows Service. The code runs fine in the web environment, but I get file IO errors related to temporary files when it is run in by the Service. I realize that CodeDom has to create temporary files even when doing in-memory compilation. However, by default, the service runs...
0
2162
by: Filippo Bettinaglio | last post by:
Security problem running unmanaged code (.ocx control) in a windows from control hosted in IE6 Hi, I have design a windows from control which contain a .OCX in one of its forms. Component developed in C#2005 -------- .NET2
2
1964
by: Microsoft Newsgroups | last post by:
Hi All, I'm looking for some simple examples of using the CodeDom. While the ones that I have found have been very helpful, I can't seem to find the following: How to add a control to a form. How to add an event handle to that control just was just added to the form. If anyone has any examples that they could share, it would be much
0
1332
by: Michael Jenck | last post by:
Hi All, I have been playing with the codedom and can't get it to output for option compare Binary with a CodeCompileUnit. I have searched the web and Don't now if it's possible. If it's not possible I just go with CodeSnippetCompileUnit Please email me a copy at: programmer @ jenck . net (remove the extra spaces)
2
2288
by: CodeMonkey775 | last post by:
I'm having problems passing a variable to a method which is executed and compiled using CodeDom. The situation is I have a List<CellData> with cells, each containing a formula (like Excel). I am trying to pass this list to an executable section of code which is compiled during run-time. The formulas are calculated in CodeDom and the result is returned on the same List<CellData> object I passed. The user-defined class which holds the cell data...
1
4898
by: =?Utf-8?B?QU1lcmNlcg==?= | last post by:
I may have painted myself into a corner with GenerateInMemory=true. My app need a custom user step. Users want to code (sort of - they are not programmers) some refinements to a search procedure. They can concoct a moderately complex boolean expression, and that suffices. I will take their statements, add top and bottom text, and now I can do a CodeDom compile. I generate an assembly via CodeDom with GenerateInMemory. I make a...
0
1191
by: thisismykindabyte | last post by:
Hello, I was wondering if anyone might know the easiest way to access static methods through a namespace(MyNamespace) from CodeDom generated code? Basically I have this in my MyNamespace.Form: //////// Most of this below is almost useless jargon just to give an idea of what values are set or not public CodeDom.Compiler.CodeDomProvider provider = new Microsoft.CSharp.CSharpCodeProvider();
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10368
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10107
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.