예제 #1
0
        /// <summary>
        /// Gets the connection string.
        /// </summary>
        /// <param name="connectionString">A <see cref="string" /> containing the connection string.</param>
        /// <returns>
        /// Returns true if the connection string was fetched successfully.
        /// </returns>
        public bool TryGetConnectionString(out string connectionString)
        {
            connectionString = null;
            FileStream fs = null;

            try
            {
                fs = new FileStream(this.xmlFilePath, FileMode.Open, FileAccess.Read);
                XPathDocument   document  = new XPathDocument(fs);
                XPathNavigator  navigator = document?.CreateNavigator();
                XPathExpression query     = navigator?.Compile(this.xPath);

                object evaluatedObject = navigator?.Evaluate(query);
                connectionString = evaluatedObject as string;
                if (connectionString == null)
                {
                    var iterator = evaluatedObject as XPathNodeIterator;
                    if (iterator?.MoveNext() == true)
                    {
                        connectionString = iterator.Current?.Value;
                    }
                }

                return(connectionString != null);
            }
            catch (Exception)
            {
                Trace.TraceInformation($"Could not fetch the connection string from the file {this.xmlFilePath} with the XPath {this.xPath}.");
                return(false);
            }
            finally
            {
                fs?.Dispose();
            }
        }
 private string GetContents(string xpath_expr, XPathNavigator nav) {
     XPathNodeIterator rk_nodes = (XPathNodeIterator) nav.Evaluate(xpath_expr);
     while (rk_nodes.MoveNext()) {
         return rk_nodes.Current.ToString();
     }
     return null;
 }
        /* goodB2G1() - use badsource and goodsink by changing second PRIVATE_CONST_FIVE==5 to PRIVATE_CONST_FIVE!=5 */
        private void GoodB2G1()
        {
            string data;

            if (PRIVATE_CONST_FIVE == 5)
            {
                data = ""; /* Initialize data */
                {
                    /* read user input from console with ReadLine */
                    try
                    {
                        /* POTENTIAL FLAW: Read data from the console using ReadLine */
                        data = Console.ReadLine();
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (PRIVATE_CONST_FIVE != 5)
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
            }
            else
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    /* FIX: validate input using StringEscapeUtils */
                    string username = System.Security.SecurityElement.Escape(tokens[0]);
                    string password = System.Security.SecurityElement.Escape(tokens[1]);
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();
                    string         query    = "//users/user[name/text()='" + username +
                                              "' and pass/text()='" + password + "']" +
                                              "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
예제 #4
0
        protected static StringBuilder FormatMessage(Test source, XPathNavigator context, string msg)
        {
            StringBuilder   sb = new StringBuilder();
            XPathExpression nameExpr;
            XPathExpression selectExpr;

            // As we move on, we have to append starting from the last point,
            // skipping the <name> and <value-of> expressions: Substring(offset, name.Index - offset).
            int offset = 0;

            for (int i = 0; i < source.NameValueOfExpressions.Count; i++)
            {
                System.Text.RegularExpressions.Match name = source.NameValueOfExpressions[i];
                nameExpr   = source.NamePaths[i];
                selectExpr = source.ValueOfSelects[i];

                // Append the text without the expression.
                sb.Append(msg.Substring(offset, name.Index - offset));

                // Does the name element have a path attribute?
                if (nameExpr != null)
                {
                    nameExpr.SetContext(source.GetContext());

                    string result = null;
                    if (nameExpr.ReturnType == XPathResultType.NodeSet)
                    {
                        // It the result of the expression is a nodeset, we only get the element
                        // name of the first node, which is compatible with XSLT implementation.
                        XPathNodeIterator nodes = (XPathNodeIterator)context.Evaluate(nameExpr);
                        if (nodes.MoveNext())
                        {
                            result = nodes.Current.Name;
                        }
                    }
                    else
                    {
                        result = context.Evaluate(nameExpr) as string;
                    }

                    if (result != null)
                    {
                        sb.Append(result);
                    }
                }
                // Does the value-of element have a select attribute?
                else if (selectExpr != null)
                {
                    selectExpr.SetContext(source.GetContext());

                    string result = null;
                    if (selectExpr.ReturnType == XPathResultType.NodeSet)
                    {
                        XPathNodeIterator nodes = (XPathNodeIterator)context.Evaluate(selectExpr);
                        result = String.Empty;
                        while (nodes.MoveNext())
                        {
                            result += nodes.Current.Value;
                        }
                    }
                    else
                    {
                        result = context.Evaluate(selectExpr) as string;
                    }

                    if (result != null)
                    {
                        sb.Append(result);
                    }
                }
                // If there is no path or select expression, there is an empty <name> element.
                else
                {
                    sb.Append(context.Name);
                }

                offset = name.Index + name.Length;
            }

            sb.Append(msg.Substring(offset));
            return(sb);
        }
예제 #5
0
        public bool Evaluate(Constraint constraint)
        {
            bool valid = (bool)Node.Evaluate(constraint.Expression);

            return(valid);
        }
        public DynamicExpression(XPathNavigator expression, XmlNamespaceManager nm)
        {
            XPathNavigator scope  = expression.SelectSingleNode("parent::c:*", nm);
            XPathNavigator target = expression.SelectSingleNode("parent::c:*/parent::c:*", nm);

            if (scope.LocalName == "validate")
            {
                _scope  = DynamicExpressionScope.Field;
                _target = target.GetAttribute("name", String.Empty);
            }
            else
            if (scope.LocalName == "styles")
            {
                _scope  = DynamicExpressionScope.ViewRowStyle;
                _target = target.GetAttribute("id", String.Empty);
            }
            else
            if (scope.LocalName == "visibility")
            {
                // determine the scope and target of visibility
                if (target.LocalName == "field")
                {
                    _scope  = DynamicExpressionScope.DataFieldVisibility;
                    _target = target.GetAttribute("name", String.Empty);
                }
                else
                if (target.LocalName == "dataField")
                {
                    _scope  = DynamicExpressionScope.DataFieldVisibility;
                    _target = target.GetAttribute("fieldName", String.Empty);
                }
                else
                if (target.LocalName == "category")
                {
                    _scope  = DynamicExpressionScope.CategoryVisibility;
                    _target = target.GetAttribute("id", String.Empty);
                }
            }
            else
            if (scope.LocalName == "defaultValues")
            {
                // determine the scope and target of default values
                if (target.LocalName == "field")
                {
                    _scope  = DynamicExpressionScope.DataFieldVisibility;
                    _target = target.GetAttribute("name", String.Empty);
                }
                else
                if (target.LocalName == "dataField")
                {
                    _scope  = DynamicExpressionScope.DataFieldVisibility;
                    _target = target.GetAttribute("fieldName", String.Empty);
                }
            }
            else
            if (scope.LocalName == "readOnly")
            {
                // determine the scope and target of read-only expression
                if (target.LocalName == "field")
                {
                    _scope  = DynamicExpressionScope.ReadOnly;
                    _target = target.GetAttribute("name", String.Empty);
                }
                else
                if (target.LocalName == "dataField")
                {
                    _scope  = DynamicExpressionScope.ReadOnly;
                    _target = target.GetAttribute("fieldName", String.Empty);
                }
            }
            string expressionType = expression.GetAttribute("type", String.Empty);

            if (String.IsNullOrEmpty(expressionType))
            {
                expressionType = "ClientScript";
            }
            _type   = ((DynamicExpressionType)(TypeDescriptor.GetConverter(typeof(DynamicExpressionType)).ConvertFromString(expressionType)));
            _test   = expression.GetAttribute("test", String.Empty);
            _result = expression.GetAttribute("result", String.Empty);
            if (_result == String.Empty)
            {
                _result = null;
            }
            _viewId = ((string)(expression.Evaluate("string(ancestor::c:view/@id)", nm)));
        }
        /// <summary>
        /// Write out property syntax if supported
        /// </summary>
        /// <param name="reflection">The reflection information</param>
        /// <param name="writer">The syntax writer to which it is written</param>
        public override void WritePropertySyntax(XPathNavigator reflection,
                                                 SyntaxWriter writer)
        {
            if (this.IsUnsupported(reflection, writer))
            {
                return;
            }

            if (HasAttribute(reflection, "System.IntrinsicPropertyAttribute"))
            {
                this.WriteFieldSyntax(reflection, writer);
                return;
            }

            string identifier = ReadMemberName(reflection);
            bool   isStatic   = (bool)reflection.Evaluate(
                SyntaxGeneratorTemplate.apiIsStaticExpression);
            bool isReadProp = (bool)reflection.Evaluate(
                SyntaxGeneratorTemplate.apiIsReadPropertyExpression);
            bool isWriteProp = (bool)reflection.Evaluate(
                SyntaxGeneratorTemplate.apiIsWritePropertyExpression);

// EFW - Unused so removed
//            XPathNavigator navigator = reflection.SelectSingleNode(
//                SyntaxGeneratorTemplate.apiReturnTypeExpression);

            if (isReadProp)
            {
                if (isStatic)
                {
                    writer.WriteIdentifier(ReadFullContainingTypeName(
                                               reflection));
                    writer.WriteString(".");
                    writer.WriteString("get_");
                    writer.WriteIdentifier(identifier);
                    writer.WriteString(" = ");
                    writer.WriteKeyword("function");
                }
                else
                {
                    writer.WriteKeyword("function");
                    writer.WriteString(" ");
                    writer.WriteString("get_");
                    writer.WriteIdentifier(identifier);
                }

                WriteParameterList(reflection, writer);
                writer.WriteString(";");
                writer.WriteLine();
            }

            if (isWriteProp)
            {
                if (isStatic)
                {
                    writer.WriteIdentifier(ReadFullContainingTypeName(
                                               reflection));
                    writer.WriteString(".");
                    writer.WriteString("set_");
                    writer.WriteIdentifier(identifier);
                    writer.WriteString(" = ");
                    writer.WriteKeyword("function");
                }
                else
                {
                    writer.WriteKeyword("function");
                    writer.WriteString(" ");
                    writer.WriteString("set_");
                    writer.WriteIdentifier(identifier);
                }

                writer.WriteString("(");
                writer.WriteParameter("value");
                writer.WriteString(");");
            }
        }
 /// <summary>
 /// Read the type name from the entry
 /// </summary>
 /// <param name="reflection">The reflection information</param>
 /// <returns>The type name</returns>
 private static string ReadTypeName(XPathNavigator reflection)
 {
     return((string)reflection.Evaluate(
                SyntaxGeneratorTemplate.apiNameExpression));
 }
예제 #9
0
        // Visibility

        private void WriteVisibility(XPathNavigator reflection, SyntaxWriter writer)
        {
            string visibility = reflection.Evaluate(apiVisibilityExpression).ToString();

            WriteVisibility(visibility, writer);
        }
예제 #10
0
        /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
        private void GoodB2G2()
        {
            string data;

            if (IO.StaticReturnsTrue())
            {
                data = ""; /* Initialize data */
                {
                    try
                    {
                        /* read string from file into data */
                        using (StreamReader sr = new StreamReader("data.txt"))
                        {
                            /* POTENTIAL FLAW: Read data from a file */

                            /* This will be reading the first "line" of the file, which
                             * could be very long if there are little or no newlines in the file */
                            data = sr.ReadLine();
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (IO.StaticReturnsTrue())
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    /* FIX: validate input using StringEscapeUtils */
                    string username = System.Security.SecurityElement.Escape(tokens[0]);
                    string password = System.Security.SecurityElement.Escape(tokens[1]);
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();
                    string         query    = "//users/user[name/text()='" + username +
                                              "' and pass/text()='" + password + "']" +
                                              "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
 public ExternalDocumentedFilter(XPathNavigator configuration)
     : base(configuration)
 {
     protectedSealedVisible = (bool)configuration.Evaluate("boolean(protectedSealed[@expose='true'])");
     noPIA = (bool)configuration.Evaluate("not(boolean(noPIA[@expose='false']))");
 }
예제 #12
0
 public object Evaluate(string selector, params System.Object[] args)
 {
     return(_navigator.Evaluate(String.Format(selector, args), _resolver));
 }
예제 #13
0
        public override void Bad()
        {
            string data;

            if (PrivateReturnsTrue())
            {
                data = ""; /* Initialize data */
                /* Read data using a listening tcp connection */
                {
                    TcpListener listener = null;
                    try
                    {
                        listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                        listener.Start();
                        using (TcpClient tcpConn = listener.AcceptTcpClient())
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using a listening tcp connection */
                                data = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                    finally
                    {
                        if (listener != null)
                        {
                            try
                            {
                                listener.Stop();
                            }
                            catch (SocketException se)
                            {
                                IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                            }
                        }
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (PrivateReturnsTrue())
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    string username = tokens[0];
                    string password = tokens[1];
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();

                    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
                     *     The user input should be canonicalized before validation. */
                    /* POTENTIAL FLAW: user input is used without validate */
                    string query = "//users/user[name/text()='" + username +
                                   "' and pass/text()='" + password + "']" +
                                   "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
예제 #14
0
        public void CoreFunctionNodeSetLast()
        {
            expression = navigator.Compile("last()");
            iterator   = navigator.Select("/foo");
            Assert.AreEqual("1", navigator.Evaluate("last()").ToString(), "#1");
            Assert.AreEqual("1", navigator.Evaluate(expression, null).ToString(), "#2");
            Assert.AreEqual("1", navigator.Evaluate(expression, iterator).ToString(), "#3");
            iterator = navigator.Select("/foo/*");
            Assert.AreEqual("4", navigator.Evaluate(expression, iterator).ToString(), "#4");

            Assert.AreEqual("3", navigator2.Evaluate("string(//bar[last()]/@baz)"), "#5");
        }
예제 #15
0
        public void saveTestCoreFunctionString()
        {
            document.LoadXml("<foo>hello<bar>world</bar><baz>how are you</baz></foo>");
            navigator = document.CreateNavigator();

            Assert.AreEqual("world", navigator.Evaluate("string(/foo/*)").ToString(), "#1");
            Assert.AreEqual("NaN", navigator.Evaluate("string(0 div 0)").ToString(), "#2");

            try
            {
                navigator.Evaluate("string(+0)");
                Assert.Fail("Expected an XPathException to be thrown.");
            }
            catch (XPathException) {}

            Assert.AreEqual("0", navigator.Evaluate("string(-0)").ToString(), "#3");
            Assert.AreEqual("Infinity", navigator.Evaluate("string(1 div 0)").ToString(), "#4");
            Assert.AreEqual("-Infinity", navigator.Evaluate("string(-1 div 0)").ToString(), "#5");
            Assert.AreEqual("45", navigator.Evaluate("string(45)").ToString(), "#6");
            Assert.AreEqual("-22", navigator.Evaluate("string(-22)").ToString(), "#7");
            Assert.AreEqual("0.25", navigator.Evaluate("string(.25)").ToString(), "#8");
            Assert.AreEqual("-0.25", navigator.Evaluate("string(-.25)").ToString(), "#9");
            Assert.AreEqual("2", navigator.Evaluate("string(2.0)").ToString(), "#10");
            Assert.AreEqual("2.01", navigator.Evaluate("string(2.01)").ToString(), "#11");
            Assert.AreEqual("-3", navigator.Evaluate("string(-3.0)").ToString(), "#12");
            Assert.AreEqual("3.45", navigator.Evaluate("string(3.45)").ToString(), "#13");

            // Wonder what this will look like under a different platform.
            Assert.AreEqual("0.33333333333333331", navigator.Evaluate("string(1 div 3)").ToString(), "#14");
        }
예제 #16
0
        private void WriteDotNetObject(XPathNavigator reflection, SyntaxWriter writer,
                                       string kind)
        {
            string            name           = reflection.Evaluate(apiNameExpression).ToString();
            bool              isSerializable = (bool)reflection.Evaluate(apiIsSerializableTypeExpression);
            XPathNodeIterator implements     = reflection.Select(apiImplementedInterfacesExpression);
            XPathNavigator    baseClass      = reflection.SelectSingleNode(apiBaseClassExpression);
            bool              hasBaseClass   = (baseClass != null) && !((bool)baseClass.Evaluate(typeIsObjectExpression));

            // CLR considers interfaces abstract.
            bool isAbstract = (bool)reflection.Evaluate(apiIsAbstractTypeExpression) && kind != "interface";
            bool isSealed   = (bool)reflection.Evaluate(apiIsSealedTypeExpression);

            if (isAbstract)
            {
                WriteAttribute("T:Microsoft.FSharp.Core.AbstractClassAttribute", writer);
            }
            if (isSealed)
            {
                WriteAttribute("T:Microsoft.FSharp.Core.SealedAttribute", writer);
            }

            if (isSerializable)
            {
                WriteAttribute("T:System.SerializableAttribute", writer);
            }
            WriteAttributes(reflection, writer);

            writer.WriteKeyword("type");
            writer.WriteString(" ");
            writer.WriteIdentifier(name);
            WriteGenericTemplates(reflection, writer);
            writer.WriteString(" =  ");

            if (hasBaseClass || implements.Count != 0)
            {
                writer.WriteLine();
                writer.WriteString("    ");
            }
            writer.WriteKeyword(kind);

            if (hasBaseClass || implements.Count != 0)
            {
                writer.WriteLine();
            }

            if (hasBaseClass)
            {
                writer.WriteString("        ");
                writer.WriteKeyword("inherit");
                writer.WriteString(" ");
                WriteTypeReference(baseClass, writer);
                writer.WriteLine();
            }


            while (implements.MoveNext())
            {
                XPathNavigator implement = implements.Current;
                writer.WriteString("        ");
                writer.WriteKeyword("interface");
                writer.WriteString(" ");
                WriteTypeReference(implement, writer);
                writer.WriteLine();
            }

            if (hasBaseClass || implements.Count != 0)
            {
                writer.WriteString("    ");
            }
            else
            {
                writer.WriteString(" ");
            }

            writer.WriteKeyword("end");
        }
예제 #17
0
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G()
        {
            string data;

            while (true)
            {
                data = ""; /* Initialize data */
                /* Read data using an outbound tcp connection */
                {
                    try
                    {
                        /* Read data using an outbound tcp connection */
                        using (TcpClient tcpConn = new TcpClient("host.example.org", 39544))
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using an outbound tcp connection */
                                data = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
                break;
            }
            while (true)
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    /* FIX: validate input using StringEscapeUtils */
                    string username = System.Security.SecurityElement.Escape(tokens[0]);
                    string password = System.Security.SecurityElement.Escape(tokens[1]);
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();
                    string         query    = "//users/user[name/text()='" + username +
                                              "' and pass/text()='" + password + "']" +
                                              "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
                break;
            }
        }
예제 #18
0
        // Initial version
        private void WriteAttributes(XPathNavigator reflection, SyntaxWriter writer)
        {
            XPathNodeIterator attributes = (XPathNodeIterator)reflection.Evaluate(apiAttributesExpression);

            foreach (XPathNavigator attribute in attributes)
            {
                XPathNavigator type = attribute.SelectSingleNode(attributeTypeExpression);
                if (type.GetAttribute("api", String.Empty) == "T:System.Runtime.CompilerServices.ExtensionAttribute")
                {
                    continue;
                }

                writer.WriteString("[<");
                WriteTypeReference(type, writer);

                XPathNodeIterator arguments   = (XPathNodeIterator)attribute.Select(attributeArgumentsExpression);
                XPathNodeIterator assignments = (XPathNodeIterator)attribute.Select(attributeAssignmentsExpression);

                if ((arguments.Count > 0) || (assignments.Count > 0))
                {
                    writer.WriteString("(");
                    while (arguments.MoveNext())
                    {
                        XPathNavigator argument = arguments.Current;
                        if (arguments.CurrentPosition > 1)
                        {
                            writer.WriteString(", ");
                            if (writer.Position > maxPosition)
                            {
                                writer.WriteLine();
                                writer.WriteString("    ");
                            }
                        }
                        WriteValue(argument, writer);
                    }
                    if ((arguments.Count > 0) && (assignments.Count > 0))
                    {
                        writer.WriteString(", ");
                    }
                    while (assignments.MoveNext())
                    {
                        XPathNavigator assignment = assignments.Current;
                        if (assignments.CurrentPosition > 1)
                        {
                            writer.WriteString(", ");
                            if (writer.Position > maxPosition)
                            {
                                writer.WriteLine();
                                writer.WriteString("    ");
                            }
                        }
                        writer.WriteString((string)assignment.Evaluate(assignmentNameExpression));
                        writer.WriteString(" = ");
                        WriteValue(assignment, writer);
                    }
                    writer.WriteString(")");
                }

                writer.WriteString(">]");
                writer.WriteLine();
            }
        }
예제 #19
0
        public override void Bad()
        {
            string data;

            while (true)
            {
                data = ""; /* Initialize data */
                /* Read data using an outbound tcp connection */
                {
                    try
                    {
                        /* Read data using an outbound tcp connection */
                        using (TcpClient tcpConn = new TcpClient("host.example.org", 39544))
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using an outbound tcp connection */
                                data = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
                break;
            }
            while (true)
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    string username = tokens[0];
                    string password = tokens[1];
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();

                    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
                     *     The user input should be canonicalized before validation. */
                    /* POTENTIAL FLAW: user input is used without validate */
                    string query = "//users/user[name/text()='" + username +
                                   "' and pass/text()='" + password + "']" +
                                   "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
                break;
            }
        }
        /// <summary>
        /// Write out class syntax
        /// </summary>
        /// <param name="reflection">The reflection information</param>
        /// <param name="writer">The syntax writer to which it is written</param>
        public override void WriteClassSyntax(XPathNavigator reflection,
                                              SyntaxWriter writer)
        {
            if (this.IsUnsupported(reflection, writer))
            {
                return;
            }

            if (HasAttribute(reflection, "System.RecordAttribute"))
            {
                WriteRecordSyntax(reflection, writer);
                return;
            }

            string identifier = ReadFullTypeName(reflection);

            writer.WriteIdentifier(identifier);
            writer.WriteString(" = ");
            writer.WriteKeyword("function");
            writer.WriteString("();");
            writer.WriteLine();
            writer.WriteLine();
            writer.WriteIdentifier("Type");
            writer.WriteString(".createClass(");
            writer.WriteLine();
            writer.WriteString("\t'");
            writer.WriteString(identifier);
            writer.WriteString("'");

            bool           hasBaseClass = false;
            XPathNavigator reference    = reflection.SelectSingleNode(
                SyntaxGeneratorTemplate.apiBaseClassExpression);

            if (!(reference == null || (bool)reference.Evaluate(
                      SyntaxGeneratorTemplate.typeIsObjectExpression)))
            {
                WriteIndentedNewLine(writer);
                this.WriteTypeReference(reference, writer);
                hasBaseClass = true;
            }

            XPathNodeIterator iterator = reflection.Select(
                SyntaxGeneratorTemplate.apiImplementedInterfacesExpression);

            if (iterator.Count != 0)
            {
                if (!hasBaseClass)
                {
                    WriteIndentedNewLine(writer);
                    writer.WriteString("null");
                }

                WriteIndentedNewLine(writer);

                while (iterator.MoveNext())
                {
                    XPathNavigator current = iterator.Current;
                    this.WriteTypeReference(current, writer);

                    if (iterator.CurrentPosition < iterator.Count)
                    {
                        WriteIndentedNewLine(writer);
                    }
                }
            }

            writer.WriteString(");");
        }
예제 #21
0
        public string loadMsg(string XmlFilePath)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(XmlFilePath);


            ////Create XPathNavigator
            XPathNavigator xpathNav = null;

            xpathNav = doc.CreateNavigator();

            ////Compile the XPath expression
            XPathExpression xpathExpr = null;

            xpathExpr = xpathNav.Compile(Expression);

            ////Display the results depending on type of result
            string strOutput   = null;
            string strMsgValue = null;
            string strMsgName  = null;


            switch (xpathExpr.ReturnType)
            {
            case XPathResultType.String:
                strOutput = System.Convert.ToString(xpathNav.Evaluate(xpathExpr));

                break;

            case XPathResultType.NodeSet:
                XPathNodeIterator nodeIter = null;
                nodeIter = xpathNav.Select(xpathExpr);
                int nodecount = nodeIter.Count;
                while (nodeIter.MoveNext())
                {
                    if (nodeIter.Current.MoveToFirstChild())
                    {
                        int i = 0;
                        do
                        {
                            if (i == 0)
                            {
                                strMsgName = System.Convert.ToString(nodeIter.Current.Value);
                            }
                            else
                            {
                                strMsgValue = System.Convert.ToString(nodeIter.Current.Value);
                                switch (strMsgName)
                                {
                                case "Updated_SuccessFully":
                                    _Updated_SuccessFully = strMsgValue;
                                    break;

                                case "Update_SameAlreadyExists":
                                    _Update_SameAlreadyExists = strMsgValue;
                                    break;

                                case "Search_NoCriteria":
                                    _Search_NoCriteria = strMsgValue;
                                    break;

                                case "Insert_SameAlreadyExists":
                                    _Insert_SameAlreadyExists = strMsgValue;
                                    break;

                                case "Insert_UserAlreadyExists":
                                    _Insert_UserAlreadyExists = strMsgValue;
                                    break;

                                case "ErrorOccured":
                                    _ErrorOccured = strMsgValue;
                                    break;

                                case "Inserted_SuccessFully":
                                    _Inserted_SuccessFully = strMsgValue;
                                    break;

                                case "NoRecordExists":
                                    _NoRecordExists = strMsgValue;
                                    break;

                                case "Deleted_SuccessFully":
                                    _Deleted_SuccessFully = strMsgValue;
                                    break;

                                case "DeletedMultiple_SuccessFully":
                                    _DeletedMultiple_SuccessFully = strMsgValue;
                                    break;

                                case "Record_AlReady_Deleted":
                                    _Record_AlReady_Deleted = strMsgValue;
                                    break;

                                case "LoginFailed":
                                    _LoginFailed = strMsgValue;
                                    break;

                                case "PasswordRecovered":
                                    _PasswordRecovered = strMsgValue;
                                    break;

                                case "NoUserExists":
                                    _NoUserExists = strMsgValue;
                                    break;

                                case "ErrorOccured_ActionCancelled":
                                    _ErrorOccured_ActionCancelled = strMsgValue;
                                    break;

                                case "FromDate_Greater_Todate":
                                    _FromDate_Greater_Todate = strMsgValue;
                                    break;

                                case "Invalid_Date":
                                    _Invalid_Date = strMsgValue;
                                    break;

                                case "Password_Changed_Successfully":
                                    _Password_Changed_Successfully = strMsgValue;
                                    break;

                                case "PathNotFound":
                                    _PathNotFound = strMsgValue;
                                    break;

                                case "CannotDelete_ReferenceExists":
                                    _CannotDelete_ReferenceExists = strMsgValue;
                                    break;

                                case "Cart_Empty":
                                    _Cart_Empty = strMsgValue;
                                    break;

                                case "Please_Enter":
                                    _Please_Enter = strMsgValue;
                                    break;

                                case "Please_Select":
                                    _Please_Select = strMsgValue;
                                    break;

                                case "EmailNotFound":
                                    _EmailNotFound = strMsgValue;
                                    break;

                                case "EmailSent":
                                    _EmailSent = strMsgValue;
                                    break;

                                case "IncorrectPwd":
                                    _IncorrectPwd = strMsgValue;
                                    break;

                                case "Insert_EmailExists":
                                    _Insert_EmailExists = strMsgValue;
                                    break;

                                case "ConfirmPwd_Must_Match":
                                    _ConfirmPwd_Must_Match = strMsgValue;
                                    break;

                                case "Invalid_Email":
                                    _Invalid_Email = strMsgValue;
                                    break;

                                case "SqlInjectionMsg":
                                    _SqlInjectionMsg = strMsgValue;
                                    break;

                                case "SqlInjection_PwdLen":
                                    _SqlInjection_PwdLen = strMsgValue;
                                    break;

                                case "SqlInjection_ConfirmPwdLen":
                                    _SqlInjection_ConfirmPwdLen = strMsgValue;
                                    break;

                                case "AddEditUser_AccesRights":
                                    _AddEditUser_AccesRights = strMsgValue;
                                    break;

                                case "AddEditUser_LastSuperAdmin":
                                    _AddEditUser_LastSuperAdmin = strMsgValue;
                                    break;

                                case "Insert_UnitNoExists":
                                    _Insert_UnitNoExists = strMsgValue;
                                    break;

                                case "Not_LoggedIn":
                                    _Not_LoggedIn = strMsgValue;
                                    break;
                                }
                            }
                            i = i + 1;
                        } while (nodeIter.Current.MoveToNext());
                        nodeIter.Current.MoveToParent();
                    }
                }

                break;

            case XPathResultType.Error:
                strOutput = "Error ";

                break;
            }
            return(strOutput);
        }
예제 #22
0
        public override void Bad()
        {
            string dataCopy;
            {
                string data;
                data = ""; /* Initialize data */
                /* Read data from a database */
                {
                    try
                    {
                        /* setup the connection */
                        using (SqlConnection connection = IO.GetDBConnection())
                        {
                            connection.Open();
                            /* prepare and execute a (hardcoded) query */
                            using (SqlCommand command = new SqlCommand(null, connection))
                            {
                                command.CommandText = "select name from users where id=0";
                                command.Prepare();
                                using (SqlDataReader dr = command.ExecuteReader())
                                {
                                    /* POTENTIAL FLAW: Read data from a database query SqlDataReader */
                                    data = dr.GetString(1);
                                }
                            }
                        }
                    }
                    catch (SqlException exceptSql)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptSql, "Error with SQL statement");
                    }
                }
                dataCopy = data;
            }
            {
                string data    = dataCopy;
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    string username = tokens[0];
                    string password = tokens[1];
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();

                    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
                     *     The user input should be canonicalized before validation. */
                    /* POTENTIAL FLAW: user input is used without validate */
                    string query = "//users/user[name/text()='" + username +
                                   "' and pass/text()='" + password + "']" +
                                   "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
        private void Parse()
        {
            try
            {
                var            document  = new XPathDocument(Path);
                XPathNavigator navigator = document.CreateNavigator();

                XPathExpression expression = navigator.Compile(XPath);

                PrintDataTypeEvent((expression.ReturnType).ToString());

                PrintDataLogEvent("XPath processing...");

                switch (expression.ReturnType)
                {
                case XPathResultType.Number:
                    PrintDataResultEvent(((double)navigator.Evaluate(expression)).ToString());
                    break;

                case XPathResultType.NodeSet:
                    XPathNodeIterator iterator = navigator.Select(expression);
                    while (iterator.MoveNext())
                    {
                        XPathNavigator nav2 = iterator.Current.Clone();

                        PrintDataResultEvent(nav2.OuterXml);
                        PrintDataResultEvent("\n");
                    }
                    break;

                case XPathResultType.Boolean:
                    if ((bool)navigator.Evaluate(expression))
                    {
                        PrintDataResultEvent("True!");
                    }
                    else
                    {
                        PrintDataResultEvent("False!");
                    }
                    break;

                case XPathResultType.String:
                    PrintDataResultEvent((navigator.Evaluate(expression)).ToString());
                    break;
                }

                PrintDataLogEvent("");
            }
            catch (XmlException xExc)
            //Exception is thrown is there is an error in the Xml
            {
                PrintDataLogEvent(xExc.Message);
            }
            catch (Exception ex) //General exception
            {
                if (XPath != "")
                {
                    PrintDataLogEvent(ex.Message);
                }
            }
        }
예제 #24
0
        /// <summary>
        /// Update the Mod's information based on the Mod selected and current Rating.
        /// </summary>
        private void UpdateGearInfo()
        {
            if (_blnSkipUpdate)
            {
                return;
            }
            _blnSkipUpdate = true;
            if (!string.IsNullOrEmpty(lstMod.Text))
            {
                // Retireve the information for the selected Mod.
                // Filtering is also done on the Category in case there are non-unique names across categories.
                XmlNode objXmlMod = _objXmlDocument.SelectSingleNode("/chummer/mods/mod[name = \"" + lstMod.SelectedValue + "\"]");

                // Extract the Avil and Cost values from the Gear info since these may contain formulas and/or be based off of the Rating.
                // This is done using XPathExpression.
                XPathNavigator nav = _objXmlDocument.CreateNavigator();

                int intMinRating = 1;
                if (objXmlMod["minrating"]?.InnerText.Length > 0)
                {
                    string          strMinRating = ReplaceStrings(objXmlMod["minrating"]?.InnerText);
                    XPathExpression xprRating    = nav.Compile(strMinRating);
                    intMinRating = Convert.ToInt32(nav.Evaluate(xprRating).ToString());
                }
                // If the rating is "qty", we're looking at Tires instead of actual Rating, so update the fields appropriately.
                if (objXmlMod["rating"].InnerText == "qty")
                {
                    nudRating.Enabled   = true;
                    nudRating.Maximum   = 20;
                    nudRating.Minimum   = intMinRating;
                    lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Qty");
                }
                //Used for the Armor modifications.
                else if (objXmlMod["rating"].InnerText.ToLower() == "body")
                {
                    nudRating.Maximum   = _objVehicle.Body;
                    nudRating.Minimum   = intMinRating;
                    nudRating.Enabled   = true;
                    lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Body");
                }
                //Used for Metahuman Adjustments.
                else if (objXmlMod["rating"].InnerText.ToLower() == "seats")
                {
                    nudRating.Maximum   = _objVehicle.TotalSeats;
                    nudRating.Minimum   = intMinRating;
                    nudRating.Enabled   = true;
                    lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Qty");
                }
                else
                {
                    if (Convert.ToInt32(objXmlMod["rating"].InnerText) > 0)
                    {
                        nudRating.Maximum   = Convert.ToInt32(objXmlMod["rating"].InnerText);
                        nudRating.Minimum   = intMinRating;
                        nudRating.Enabled   = true;
                        lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Rating");
                    }
                    else
                    {
                        nudRating.Minimum   = 0;
                        nudRating.Maximum   = 0;
                        nudRating.Enabled   = false;
                        lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Rating");
                    }
                }

                // Avail.
                // If avail contains "F" or "R", remove it from the string so we can use the expression.
                string strAvail     = string.Empty;
                string strAvailExpr = string.Empty;
                if (objXmlMod["avail"].InnerText.StartsWith("FixedValues"))
                {
                    int      intRating = Convert.ToInt32(nudRating.Value - 1);
                    string[] strValues = objXmlMod["avail"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                    if (intRating > strValues.Length || intRating < 0)
                    {
                        intRating = strValues.Length - 1;
                    }
                    strAvailExpr = strValues[intRating];
                }
                else
                {
                    strAvailExpr = objXmlMod["avail"].InnerText;
                }

                XPathExpression xprAvail;
                if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R")
                {
                    strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1);
                    // Remove the trailing character if it is "F" or "R".
                    strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1);
                }
                try
                {
                    xprAvail      = nav.Compile(strAvailExpr.Replace("Rating", Math.Max(nudRating.Value, 1).ToString(GlobalOptions.InvariantCultureInfo)));
                    lblAvail.Text = Convert.ToInt32(nav.Evaluate(xprAvail)) + strAvail;
                }
                catch (XPathException)
                {
                    lblAvail.Text = objXmlMod["avail"].InnerText;
                }
                lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.Instance.GetString("String_AvailRestricted")).Replace("F", LanguageManager.Instance.GetString("String_AvailForbidden"));

                // Cost.
                int intItemCost = 0;
                if (objXmlMod["cost"].InnerText.StartsWith("Variable"))
                {
                    int    intMin  = 0;
                    int    intMax  = 0;
                    string strCost = objXmlMod["cost"].InnerText.Replace("Variable(", string.Empty).Replace(")", string.Empty);
                    if (strCost.Contains("-"))
                    {
                        string[] strValues = strCost.Split('-');
                        intMin = Convert.ToInt32(strValues[0]);
                        intMax = Convert.ToInt32(strValues[1]);
                    }
                    else
                    {
                        intMin = Convert.ToInt32(strCost.Replace("+", string.Empty));
                    }

                    if (intMax == 0)
                    {
                        intMax       = 1000000;
                        lblCost.Text = string.Format("{0:###,###,##0¥+}", intMin);
                    }
                    else
                    {
                        lblCost.Text = string.Format("{0:###,###,##0}", intMin) + "-" + string.Format("{0:###,###,##0¥}", intMax);
                    }

                    intItemCost = intMin;
                }
                else
                {
                    string strCost = string.Empty;
                    if (chkFreeItem.Checked)
                    {
                        strCost = "0";
                    }
                    else
                    {
                        if (objXmlMod["cost"].InnerText.StartsWith("FixedValues"))
                        {
                            int      intRating = Convert.ToInt32(nudRating.Value) - 1;
                            string[] strValues = objXmlMod["cost"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                            if (intRating < 0 || intRating > strValues.Length)
                            {
                                intRating = 0;
                            }
                            strCost = strValues[intRating];
                        }
                        else
                        {
                            strCost = objXmlMod["cost"].InnerText;
                        }
                        strCost = ReplaceStrings(strCost);
                    }

                    XPathExpression xprCost = nav.Compile(strCost);
                    int             intCost = Convert.ToInt32(Convert.ToDouble(nav.Evaluate(xprCost), GlobalOptions.InvariantCultureInfo));
                    intCost *= _intModMultiplier;

                    // Apply any markup.
                    double dblCost = Convert.ToDouble(intCost, GlobalOptions.InvariantCultureInfo);
                    dblCost *= 1 + (Convert.ToDouble(nudMarkup.Value, GlobalOptions.CultureInfo) / 100.0);

                    if (chkBlackMarketDiscount.Checked)
                    {
                        dblCost = dblCost - (dblCost * 0.90);
                    }

                    intCost      = Convert.ToInt32(dblCost);
                    lblCost.Text = string.Format("{0:###,###,##0¥}", intCost);

                    intItemCost = intCost;
                }

                // Update the Avail Test Label.
                lblTest.Text = _objCharacter.AvailTest(intItemCost, lblAvail.Text);

                // Slots.

                string strSlots = string.Empty;
                if (objXmlMod["slots"].InnerText.StartsWith("FixedValues"))
                {
                    string[] strValues = objXmlMod["slots"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                    strSlots = strValues[Convert.ToInt32(nudRating.Value) - 1];
                }
                else
                {
                    strSlots = objXmlMod["slots"].InnerText;
                }
                strSlots = ReplaceStrings(strSlots);
                XPathExpression xprSlots = nav.Compile(strSlots);
                lblSlots.Text = nav.Evaluate(xprSlots).ToString();

                if (objXmlMod["category"].InnerText != null)
                {
                    if (_arrCategories.Contains(objXmlMod["category"].InnerText))
                    {
                        lblVehicleCapacityLabel.Visible = true;
                        lblVehicleCapacity.Visible      = true;
                        lblVehicleCapacity.Text         = GetRemainingModCapacity(objXmlMod["category"].InnerText, Convert.ToInt32(lblSlots.Text));
                        tipTooltip.SetToolTip(lblVehicleCapacityLabel, LanguageManager.Instance.GetString("Tip_RemainingVehicleModCapacity"));
                    }
                    else
                    {
                        lblVehicleCapacityLabel.Visible = false;
                        lblVehicleCapacity.Visible      = false;
                    }

                    lblCategory.Text = objXmlMod["category"].InnerText;
                    if (objXmlMod["category"].InnerText == "Weapon Mod")
                    {
                        lblCategory.Text = LanguageManager.Instance.GetString("String_WeaponModification");
                    }
                    // Translate the Category if possible.
                    else if (GlobalOptions.Instance.Language != "en-us")
                    {
                        XmlNode objXmlCategory = _objXmlDocument.SelectSingleNode("/chummer/modcategories/category[. = \"" + objXmlMod["category"].InnerText + "\"]");
                        if (objXmlCategory != null && objXmlCategory.Attributes["translate"] != null)
                        {
                            lblCategory.Text = objXmlCategory.Attributes["translate"].InnerText;
                        }
                    }
                }

                if (objXmlMod["limit"] != null)
                {
                    // Translate the Limit if possible.
                    if (GlobalOptions.Instance.Language != "en-us")
                    {
                        XmlNode objXmlLimit = _objXmlDocument.SelectSingleNode("/chummer/limits/limit[. = \"" + objXmlMod["limit"].InnerText + "\"]");
                        if (objXmlLimit != null)
                        {
                            if (objXmlLimit.Attributes["translate"] != null)
                            {
                                lblLimit.Text = " (" + objXmlLimit.Attributes["translate"].InnerText + ")";
                            }
                            else
                            {
                                lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")";
                            }
                        }
                        else
                        {
                            lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")";
                        }
                    }
                    else
                    {
                        lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")";
                    }
                }
                else
                {
                    lblLimit.Text = string.Empty;
                }

                string strBook = _objCharacter.Options.LanguageBookShort(objXmlMod["source"].InnerText);
                string strPage = objXmlMod["page"].InnerText;
                if (objXmlMod["altpage"] != null)
                {
                    strPage = objXmlMod["altpage"].InnerText;
                }
                lblSource.Text = strBook + " " + strPage;

                tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(objXmlMod["source"].InnerText) + " " + LanguageManager.Instance.GetString("String_Page") + " " + strPage);
                _blnSkipUpdate = false;
            }
        }
예제 #25
0
        /* GoodG2B2() - use goodsource and badsink by reversing the blocks in the first switch  */
        private void GoodG2B2()
        {
            string data;

            switch (6)
            {
            case 6:
                /* FIX: Use a hardcoded string */
                data = "foo";
                break;

            default:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
                break;
            }
            switch (7)
            {
            case 7:
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    string username = tokens[0];
                    string password = tokens[1];
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();

                    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
                     *     The user input should be canonicalized before validation. */
                    /* POTENTIAL FLAW: user input is used without validate */
                    string query = "//users/user[name/text()='" + username +
                                   "' and pass/text()='" + password + "']" +
                                   "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
                break;

            default:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
                break;
            }
        }
        public DataField(XPathNavigator field, IXmlNamespaceResolver nm) :
            this()
        {
            this._name = field.GetAttribute("name", String.Empty);
            this._type = field.GetAttribute("type", String.Empty);
            string l = field.GetAttribute("length", String.Empty);

            if (!(String.IsNullOrEmpty(l)))
            {
                _len = Convert.ToInt32(l);
            }
            this._label        = field.GetAttribute("label", String.Empty);
            this._isPrimaryKey = (field.GetAttribute("isPrimaryKey", String.Empty) == "true");
            this._readOnly     = (field.GetAttribute("readOnly", String.Empty) == "true");
            this._onDemand     = (field.GetAttribute("onDemand", String.Empty) == "true");
            this._defaultValue = field.GetAttribute("default", String.Empty);
            this._allowNulls   = !((field.GetAttribute("allowNulls", String.Empty) == "false"));
            this._hidden       = (field.GetAttribute("hidden", String.Empty) == "true");
            this._allowQBE     = !((field.GetAttribute("allowQBE", String.Empty) == "false"));
            this._allowLEV     = (field.GetAttribute("allowLEV", String.Empty) == "true");
            this._allowSorting = !((field.GetAttribute("allowSorting", String.Empty) == "false"));
            this._sourceFields = field.GetAttribute("sourceFields", String.Empty);
            string onDemandStyle = field.GetAttribute("onDemandStyle", String.Empty);

            if (onDemandStyle == "Link")
            {
                this._onDemandStyle = OnDemandDisplayStyle.Link;
            }
            else
            if (onDemandStyle == "Signature")
            {
                this._onDemandStyle = OnDemandDisplayStyle.Signature;
            }
            this._onDemandHandler  = field.GetAttribute("onDemandHandler", String.Empty);
            this._contextFields    = field.GetAttribute("contextFields", String.Empty);
            this._selectExpression = field.GetAttribute("select", String.Empty);
            bool computed = (field.GetAttribute("computed", String.Empty) == "true");

            if (computed)
            {
                _formula = ((string)(field.Evaluate("string(self::c:field/c:formula)", nm)));
                if (String.IsNullOrEmpty(_formula))
                {
                    _formula = "null";
                }
            }
            this._showInSummary    = (field.GetAttribute("showInSummary", String.Empty) == "true");
            this._htmlEncode       = !((field.GetAttribute("htmlEncode", String.Empty) == "false"));
            this._calculated       = (field.GetAttribute("calculated", String.Empty) == "true");
            this._causesCalculate  = (field.GetAttribute("causesCalculate", String.Empty) == "true");
            this._isVirtual        = (field.GetAttribute("isVirtual", String.Empty) == "true");
            this._configuration    = ((string)(field.Evaluate("string(self::c:field/c:configuration)", nm)));
            this._dataFormatString = field.GetAttribute("dataFormatString", String.Empty);
            _formatOnClient        = !((field.GetAttribute("formatOnClient", String.Empty) == "false"));
            string editor = field.GetAttribute("editor", String.Empty);

            if (!(String.IsNullOrEmpty(editor)))
            {
                _editor = editor;
            }
            XPathNavigator itemsNav = field.SelectSingleNode("c:items", nm);

            if (itemsNav != null)
            {
                this.ItemsDataController   = itemsNav.GetAttribute("dataController", String.Empty);
                this.ItemsTargetController = itemsNav.GetAttribute("targetController", String.Empty);
            }
            XPathNavigator dataViewNav = field.SelectSingleNode("c:dataView", nm);

            if (dataViewNav != null)
            {
                this.DataViewController   = dataViewNav.GetAttribute("controller", String.Empty);
                this.DataViewId           = dataViewNav.GetAttribute("view", String.Empty);
                this.DataViewFilterSource = dataViewNav.GetAttribute("filterSource", String.Empty);
                this.DataViewFilterFields = dataViewNav.GetAttribute("filterFields", String.Empty);
                _allowQBE     = true;
                _allowSorting = true;
                _len          = 0;
                _columns      = 0;
                _htmlEncode   = true;
            }
        }
예제 #27
0
        /* goodB2G2() - use badsource and goodsink by reversing the blocks in the second switch  */
        private void GoodB2G2()
        {
            string data;

            switch (6)
            {
            case 6:
                data = ""; /* Initialize data */
                /* Read data using a listening tcp connection */
                {
                    TcpListener listener = null;
                    try
                    {
                        listener = new TcpListener(IPAddress.Parse("10.10.1.10"), 39543);
                        listener.Start();
                        using (TcpClient tcpConn = listener.AcceptTcpClient())
                        {
                            /* read input from socket */
                            using (StreamReader sr = new StreamReader(tcpConn.GetStream()))
                            {
                                /* POTENTIAL FLAW: Read data using a listening tcp connection */
                                data = sr.ReadLine();
                            }
                        }
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                    finally
                    {
                        if (listener != null)
                        {
                            try
                            {
                                listener.Stop();
                            }
                            catch (SocketException se)
                            {
                                IO.Logger.Log(NLog.LogLevel.Warn, se, "Error closing TcpListener");
                            }
                        }
                    }
                }
                break;

            default:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
                break;
            }
            switch (7)
            {
            case 7:
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    /* FIX: validate input using StringEscapeUtils */
                    string username = System.Security.SecurityElement.Escape(tokens[0]);
                    string password = System.Security.SecurityElement.Escape(tokens[1]);
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();
                    string         query    = "//users/user[name/text()='" + username +
                                              "' and pass/text()='" + password + "']" +
                                              "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
                break;

            default:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
                break;
            }
        }
예제 #28
0
        private IEnumerable <GoogleAddress> ParseAddresses(XPathNodeIterator nodes)
        {
            while (nodes.MoveNext())
            {
                XPathNavigator nav = nodes.Current;

                GoogleAddressType type             = EvaluateType((string)nav.Evaluate("string(type)"));
                string            placeId          = (string)nav.Evaluate("string(place_id)");
                string            formattedAddress = (string)nav.Evaluate("string(formatted_address)");

                var components = ParseComponents(nav.Select("address_component")).ToArray();

                double   latitude    = (double)nav.Evaluate("number(geometry/location/lat)");
                double   longitude   = (double)nav.Evaluate("number(geometry/location/lng)");
                Location coordinates = new Location(latitude, longitude);

                double   neLatitude    = (double)nav.Evaluate("number(geometry/viewport/northeast/lat)");
                double   neLongitude   = (double)nav.Evaluate("number(geometry/viewport/northeast/lng)");
                Location neCoordinates = new Location(neLatitude, neLongitude);

                double   swLatitude    = (double)nav.Evaluate("number(geometry/viewport/southwest/lat)");
                double   swLongitude   = (double)nav.Evaluate("number(geometry/viewport/southwest/lng)");
                Location swCoordinates = new Location(swLatitude, swLongitude);

                var viewport = new GoogleViewport {
                    Northeast = neCoordinates, Southwest = swCoordinates
                };

                GoogleLocationType locationType = EvaluateLocationType((string)nav.Evaluate("string(geometry/location_type)"));

                Bounds bounds = null;
                if (nav.SelectSingleNode("geometry/bounds") != null)
                {
                    double   neBoundsLatitude    = (double)nav.Evaluate("number(geometry/bounds/northeast/lat)");
                    double   neBoundsLongitude   = (double)nav.Evaluate("number(geometry/bounds/northeast/lng)");
                    Location neBoundsCoordinates = new Location(neBoundsLatitude, neBoundsLongitude);

                    double   swBoundsLatitude    = (double)nav.Evaluate("number(geometry/bounds/southwest/lat)");
                    double   swBoundsLongitude   = (double)nav.Evaluate("number(geometry/bounds/southwest/lng)");
                    Location swBoundsCoordinates = new Location(swBoundsLatitude, swBoundsLongitude);

                    bounds = new Bounds(swBoundsCoordinates, neBoundsCoordinates);
                }

                bool isPartialMatch;
                bool.TryParse((string)nav.Evaluate("string(partial_match)"), out isPartialMatch);

                yield return(new GoogleAddress(type, formattedAddress, components, coordinates, viewport, bounds, isPartialMatch, locationType, placeId));
            }
        }
예제 #29
0
        public override void WriteOperatorSyntax(XPathNavigator reflection, SyntaxWriter writer)
        {
            string name = (string)reflection.Evaluate(apiNameExpression);
            string identifier;

            bool isStatic = (bool)reflection.Evaluate(apiIsStaticExpression);

            switch (name)
            {
            // unary math operators
            case "UnaryPlus":
                identifier = "+";
                break;

            case "UnaryNegation":
                identifier = "-";
                break;

            case "Increment":
                identifier = "++";
                break;

            case "Decrement":
                identifier = "--";
                break;

            // unary logical operators
            case "LogicalNot":
                identifier = "not";
                break;

            case "True":
                identifier = "true";
                break;

            case "False":
                identifier = "false";
                break;

            // binary comparison operators
            case "Equality":
                identifier = "=";
                break;

            case "Inequality":
                identifier = "<>";
                break;

            case "LessThan":
                identifier = "<";
                break;

            case "GreaterThan":
                identifier = ">";
                break;

            case "LessThanOrEqual":
                identifier = "<=";
                break;

            case "GreaterThanOrEqual":
                identifier = ">=";
                break;

            // binary math operators
            case "Addition":
                identifier = "+";
                break;

            case "Subtraction":
                identifier = "-";
                break;

            case "Multiply":
                identifier = "*";
                break;

            case "Division":
                identifier = "/";
                break;

            case "Modulus":
                identifier = "%";
                break;

            // binary logical operators
            case "BitwiseAnd":
                identifier = "&&&";
                break;

            case "BitwiseOr":
                identifier = "|||";
                break;

            case "ExclusiveOr":
                identifier = "^^^";
                break;

            // bit-array operators
            case "OnesComplement":
                identifier = null;    // No F# equiv.
                break;

            case "LeftShift":
                identifier = "<<<";
                break;

            case "RightShift":
                identifier = ">>>";
                break;

            // unrecognized operator
            default:
                identifier = null;
                break;
            }
            if (identifier == null)
            {
                writer.WriteMessage("UnsupportedOperator_" + Language);
            }
            else
            {
                if (isStatic)
                {
                    writer.WriteKeyword("static");
                    writer.WriteString(" ");
                }

                writer.WriteKeyword("let");
                writer.WriteString(" ");
                writer.WriteKeyword("inline");
                writer.WriteKeyword(" ");

                writer.WriteString("(");
                writer.WriteIdentifier(identifier);
                writer.WriteString(")");

                WriteParameters(reflection, writer);
                writer.WriteString(" : ");
                WriteReturnValue(reflection, writer);
            }
        }
        public override void Bad()
        {
            string data;

            if (PRIVATE_CONST_FIVE == 5)
            {
                data = ""; /* Initialize data */
                {
                    /* read user input from console with ReadLine */
                    try
                    {
                        /* POTENTIAL FLAW: Read data from the console using ReadLine */
                        data = Console.ReadLine();
                    }
                    catch (IOException exceptIO)
                    {
                        IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                    }
                }
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (PRIVATE_CONST_FIVE == 5)
            {
                string xmlFile = null;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    /* running on Windows */
                    xmlFile = "..\\..\\CWE643_Xpath_Injection__Helper.xml";
                }
                else
                {
                    /* running on non-Windows */
                    xmlFile = "../../CWE643_Xpath_Injection__Helper.xml";
                }
                if (data != null)
                {
                    /* assume username||password as source */
                    string[] tokens = data.Split("||".ToCharArray());
                    if (tokens.Length < 2)
                    {
                        return;
                    }
                    string username = tokens[0];
                    string password = tokens[1];
                    /* build xpath */
                    XPathDocument  inputXml = new XPathDocument(xmlFile);
                    XPathNavigator xPath    = inputXml.CreateNavigator();

                    /* INCIDENTAL: CWE180 Incorrect Behavior Order: Validate Before Canonicalize
                     *     The user input should be canonicalized before validation. */
                    /* POTENTIAL FLAW: user input is used without validate */
                    string query = "//users/user[name/text()='" + username +
                                   "' and pass/text()='" + password + "']" +
                                   "/secret/text()";
                    string secret = (string)xPath.Evaluate(query);
                }
            }
        }
예제 #31
0
        // DONE
        public override void WritePropertySyntax(XPathNavigator reflection, SyntaxWriter writer)
        {
            string name       = (string)reflection.Evaluate(apiNameExpression);
            bool   isGettable = (bool)reflection.Evaluate(apiIsReadPropertyExpression);
            bool   isSettable = (bool)reflection.Evaluate(apiIsWritePropertyExpression);

            bool isStatic   = (bool)reflection.Evaluate(apiIsStaticExpression);
            bool isVirtual  = (bool)reflection.Evaluate(apiIsVirtualExpression) && !(bool)reflection.Evaluate(apiIsAbstractProcedureExpression);
            int  iterations = isVirtual ? 2 : 1;

            for (int i = 0; i < iterations; i++)
            {
                WriteAttributes(reflection, writer);
                WriteVisibility(reflection, writer);

                if (isStatic)
                {
                    writer.WriteKeyword("static");
                    writer.WriteString(" ");
                }

                if (isVirtual)
                {
                    if (i == 0)
                    {
                        writer.WriteKeyword("abstract");
                        writer.WriteString(" ");
                    }
                    else
                    {
                        writer.WriteKeyword("override");
                        writer.WriteString(" ");
                    }
                }
                else
                {
                    WriteMemberKeyword(reflection, writer);
                }

                writer.WriteIdentifier(name);
                writer.WriteString(" : ");
                WriteReturnValue(reflection, writer);

                if (isSettable)
                {
                    writer.WriteString(" ");
                    writer.WriteKeyword("with");
                    writer.WriteString(" ");

                    string getVisibility = (string)reflection.Evaluate(apiGetVisibilityExpression);
                    if (!String.IsNullOrEmpty(getVisibility))
                    {
                        WriteVisibility(getVisibility, writer);
                    }

                    writer.WriteKeyword("get");
                    writer.WriteString(", ");

                    string setVisibility = (string)reflection.Evaluate(apiSetVisibilityExpression);
                    if (!String.IsNullOrEmpty(setVisibility))
                    {
                        WriteVisibility(setVisibility, writer);
                    }

                    writer.WriteKeyword("set");
                }
                if (i == 0)
                {
                    writer.WriteLine();
                }
            }
        }