/* goodB2G() - use badsource and goodsink */ public static void GoodB2GSink(CWE94_Improper_Control_of_Generation_of_Code__Connect_tcp_67a.Container dataContainer) { string data = dataContainer.containerOne; int? parsedNum = null; /* FIX: Validate user input prior to compiling */ try { parsedNum = int.Parse(data); } catch (FormatException exceptNumberFormat) { IO.Logger.Log(NLog.LogLevel.Warn, exceptNumberFormat, "Number format exception parsing number."); } if (parsedNum != null) { StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); } }
/* goodG2B() - use goodsource and badsink */ public static void GoodG2BSink(CWE94_Improper_Control_of_Generation_of_Code__Connect_tcp_67a.Container dataContainer) { string data = dataContainer.containerOne; StringBuilder sourceCode = new StringBuilder(""); sourceCode.Append("public class Calculator \n{\n"); sourceCode.Append("\tpublic int Sum()\n\t{\n"); sourceCode.Append("\t\treturn (10 + " + data.ToString() + ");\n"); sourceCode.Append("\t}\n"); sourceCode.Append("}\n"); /* POTENTIAL FLAW: Compile sourceCode containing unvalidated user input */ CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp"); CompilerParameters cp = new CompilerParameters(); CompilerResults cr = provider.CompileAssemblyFromSource(cp, sourceCode.ToString()); Assembly a = cr.CompiledAssembly; object calculator = a.CreateInstance("Calculator"); Type calculatorType = calculator.GetType(); MethodInfo mi = calculatorType.GetMethod("Sum"); int s = (int)mi.Invoke(calculator, new object[] {}); IO.WriteLine("Result: " + s.ToString()); }