Example #1
0
 public virtual object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     VisitElement(invokeMemberExpressionAst.Expression);
     VisitElement(invokeMemberExpressionAst.Member);
     VisitElements(invokeMemberExpressionAst.Arguments);
     return(invokeMemberExpressionAst);
 }
Example #2
0
        protected override void EndProcessing()
        {
            var closure            = ClosureRewriter.CreateNewClosure(ScriptBlock, DelegateType);
            var sbAst              = ScriptBlock.Ast as ScriptBlockAst;
            var e                  = sbAst.Extent;
            var invokeDelegateExpr = new InvokeMemberExpressionAst(
                e,
                new ConstantExpressionAst(e, closure),
                new StringConstantExpressionAst(e, nameof(Action.Invoke), StringConstantType.BareWord),
                Array.Empty <ExpressionAst>(),
                @static: false);

            var invokeDelegateStmt = new CommandExpressionAst(
                e,
                invokeDelegateExpr,
                Array.Empty <RedirectionAst>());

            var newSbAst = new ScriptBlockAst(
                e,
                sbAst.UsingStatements,
                Array.Empty <AttributeAst>(),
                null,
                null,
                null,
                new NamedBlockAst(
                    e,
                    TokenKind.End,
                    new StatementBlockAst(e, new[] { invokeDelegateStmt }, Array.Empty <TrapStatementAst>()),
                    unnamed: true),
                null);

            WriteObject(newSbAst.GetScriptBlock());
        }
Example #3
0
        public static void MeasureMethodInjection(string ScriptBlock)
        {
            Token[]        token;
            ParseError[]   error;
            ScriptBlockAst ScriptBlockAst = Parser.ParseInput(ScriptBlock, out token, out error);

            Func <Ast, bool> predicate = delegate(Ast ast)
            {
                var derpVar  = new VariableExpressionAst(ast.Extent, "Derp", splatted: false);
                var derpVar2 = new StringConstantExpressionAst(ast.Extent, "Derpvr2", StringConstantType.BareWord);
                InvokeMemberExpressionAst targetAst = new InvokeMemberExpressionAst(ast.Extent, derpVar, derpVar2, Enumerable.Empty <ExpressionAst>(), @static: false);
                if (targetAst != null)
                {
                    if (targetAst.Member is ConstantExpressionAst)
                    {
                        return(true);
                    }
                }
                return(false);
            };

            var foundNode = ScriptBlockAst.Find(predicate, true);

            if (foundNode != null)
            {
                Console.WriteLine("[+] Possible injection vulnerability found");
                Console.WriteLine(String.Format(@"Possible property access injection via dynamic member access. Untrusted input can cause arbitrary static properties to be accessed:
RuleName = InjectionRisk.MethodInjection
Severity = Warning", foundNode.Extent));
            }
        }
        public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
        {
            var args          = "";
            var argsText      = " without arguments";
            var objectOrClass = "object";
            var stat          = "";

            if (methodCallAst.Arguments != null)
            {
                args = string.Join(", ", methodCallAst.Arguments.Select(args => args.Extent.Text));
            }

            if (methodCallAst.Static)
            {
                objectOrClass = "class";
                stat          = "static ";
            }

            if (args != "")
            {
                argsText = $", with arguments '{args}'";
            }

            explanations.Add(
                new Explanation
            {
                Description = $"Invoke the {stat}method '{methodCallAst.Member}' on {objectOrClass} '{methodCallAst.Expression}'{argsText}.",
                CommandName = "Method",
                HelpResult  = HelpTableQuery("about_Methods")
            }.AddDefaults(methodCallAst, explanations));

            return(AstVisitAction.Continue);
        }
        public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
        {
            var arguments = new List <Argument>();

            if (methodCallAst.Arguments != null)
            {
                foreach (var argument in methodCallAst.Arguments)
                {
                    var arg = VisitSyntaxNode(argument);
                    var ar  = new Argument(arg);
                    arguments.Add(ar);
                }
            }


            var expression = VisitSyntaxNode(methodCallAst.Expression);

            var methodName = methodCallAst.Member.ToString();

            var memberAccess = new MemberAccess(expression, methodName);

            var argumentList = new ArgumentList(arguments);

            _currentNode = new Invocation(memberAccess, argumentList);

            return(AstVisitAction.SkipChildren);
        }
Example #6
0
 public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)  //confirmed
 {
     if (methodCallAst.ToString().Contains(symbolRef.ScriptRegion.Text))
     {
         ValidateExtend(symbolRef.ScriptRegion.Text, methodCallAst.Member.ToString(), methodCallAst);
     }
     return(base.VisitInvokeMemberExpression(methodCallAst));
 }
        public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
        {
            var expression = VisitAst(invokeMemberExpressionAst.Expression);
            var method     = VisitAst(invokeMemberExpressionAst.Member);
            var arguments  = VisitAst(invokeMemberExpressionAst.Arguments);

            return(new InvokeMemberExpressionAst(invokeMemberExpressionAst.Extent, expression, method, arguments,
                                                 invokeMemberExpressionAst.Static));
        }
 public virtual ExpressionAst VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     return(new InvokeMemberExpressionAst(
                invokeMemberExpressionAst.Extent,
                invokeMemberExpressionAst.Expression.Rewrite(this),
                invokeMemberExpressionAst.Member.Rewrite(this),
                invokeMemberExpressionAst.Arguments?.RewriteAll(this),
                invokeMemberExpressionAst.Static));
 }
        public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
        {
            var newExpression = VisitElement(invokeMemberExpressionAst.Expression);
            var newMethod     = VisitElement(invokeMemberExpressionAst.Member);
            var newArguments  = VisitElements(invokeMemberExpressionAst.Arguments);

            return(new InvokeMemberExpressionAst(invokeMemberExpressionAst.Extent, newExpression, newMethod,
                                                 newArguments, invokeMemberExpressionAst.Static));
        }
 public static InvokeMemberExpressionAst Update(
     this InvokeMemberExpressionAst ast,
     ExpressionAst expression = null,
     CommandElementAst method = null,
     IEnumerable <ExpressionAst> arguments = null,
     bool? @static = null)
 {
     return(new InvokeMemberExpressionAst(
                ast.Extent,
                expression?.Clone() ?? ast.Expression.Clone(),
                method?.Clone() ?? ast.Member.Clone(),
                arguments?.CloneAll() ?? ast.Arguments.CloneAll(),
                @static ?? ast.Static));
 }
Example #11
0
        public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
        {
            var expression = Visit(invokeMemberExpressionAst.Expression);

            var memberName = invokeMemberExpressionAst.Member.ToString();

            if (memberName.StartsWith("add_"))
            {
                if (invokeMemberExpressionAst.Arguments.Count != 1)
                {
                    return(new CodeExpression());
                }

                var codeArg = Visit(invokeMemberExpressionAst.Arguments[0]) as CodeVariableReferenceExpression;
                if (codeArg != null)
                {
                    var stubMethod = new CodeMemberMethod {
                        Name = codeArg.VariableName
                    };
                    _currentClass.Members.Add(stubMethod);

                    stubMethod.UserData.Add("DontGenerate", null);

                    var variable = new CodeDelegateCreateExpression(new CodeTypeReference(typeof(EventHandler)),
                                                                    new CodeThisReferenceExpression(), codeArg.VariableName);

                    return(new CodeAttachEventStatement(expression as CodeExpression,
                                                        memberName.Replace("add_", String.Empty), variable));
                }
            }

            var methodInvoke = new CodeMethodInvokeExpression(expression as CodeExpression,
                                                              memberName);

            if (invokeMemberExpressionAst.Arguments == null)
            {
                return(methodInvoke);
            }

            foreach (var arg in invokeMemberExpressionAst.Arguments)
            {
                var codeArg = Visit(arg);
                if (codeArg is CodeExpression)
                {
                    methodInvoke.Parameters.Add(codeArg as CodeExpression);
                }
            }

            return(methodInvoke);
        }
Example #12
0
            public void StaticMethodInvocation()
            {
                InvokeMemberExpressionAst invokeMemberExpressionAst = ParseStatement(@"[char]::IsUpper('a')")
                                                                      .PipelineElements[0]
                                                                      .Expression;

                var typeExpressionAst           = (TypeExpressionAst)invokeMemberExpressionAst.Expression;
                var stringConstantExpressionAst = (StringConstantExpressionAst)invokeMemberExpressionAst.Member;
                var argumentAst = (StringConstantExpressionAst)invokeMemberExpressionAst.Arguments.Single();

                Assert.AreEqual("char", typeExpressionAst.TypeName.Name);

                Assert.AreEqual("IsUpper", stringConstantExpressionAst.Value);

                Assert.AreEqual("a", argumentAst.Value);
            }
Example #13
0
        //public static void MeasureAddType(string ScriptBlock)
        //{
        //    Token[] token;
        //    ParseError[] error;
        //    ScriptBlockAst ScriptBlockAst = Parser.ParseInput(ScriptBlock, out token, out error);
        //
        //    Func<Ast, bool> predicate = delegate (Ast ast)
        //    {
        //        var derpVar = new VariableExpressionAst(ast.Extent, "Derp", splatted: false);
        //        CommandAst targetAst = new CommandAst(ast.Extent, new[] { derpVar }, TokenKind.Unknown, Enumerable.Empty<RedirectionAst>());
        //        if (targetAst.CommandElements[0].Extent.Text == "Add-Type")
        //        {
        //            var addTypeParameters = StaticParameterBinder.BindCommand(targetAst);
        //            var typeDefinitionParameter = addTypeParameters.BoundParameters.TypeDefinition;
        //            if (typeDefinitionParameter.ConstantValue)
        //            {
        //                if (addTypeParameters.BoundParameters.TypeDefinition.ValueSystem.Management.Automation.Language.VariableExpressionAst)
        //                {
        //                    var variableName = addTypeParameters.BoundParameters.TypeDefinition.Value.VariablePath.UserPath;
        //                    var constantAssignmentForVariable = ScriptBlockAst.FindAll(tempvar => tempvar is Ast, true);
        //                    if (assignmentAst && assignmentAst.Left.VariablePath.UserPath == variableName && assignmentAst.Right.ExpressionSystem.Management.Automation.Language.ConstantExpressionAst)
        //                    {
        //                        return true;
        //                    }
        //                    if (constantAssignmentForVariable != null)
        //                    {
        //                        return false;
        //                    }
        //                    else
        //                    {
        //                        return true;
        //                    }
        //                }
        //                return true;
        //            }
        //        }
        //        return false;
        //    };
        //
        //    var foundNode = ScriptBlockAst.Find(predicate, true);
        //    if (foundNode != null)
        //    {
        //        Console.WriteLine("[+] Possible injection vulnerability found");
        //        Console.WriteLine(String.Format(@"Possible code injection risk via the Add-Type cmdlet. Untrusted input can cause arbitrary Win32 code to be run..
//RuleName = InjectionRisk.AddType
//Severity = Warning", foundNode.Extent
        //        ));
        //    }
        //}

        public static void MeasureDangerousMethod(string ScriptBlock)
        {
            Token[]        token;
            ParseError[]   error;
            ScriptBlockAst ScriptBlockAst = Parser.ParseInput(ScriptBlock, out token, out error);

            Func <Ast, bool> predicate = delegate(Ast ast)
            {
                var derpVar  = new VariableExpressionAst(ast.Extent, "Derp", splatted: false);
                var derpVar2 = new StringConstantExpressionAst(ast.Extent, "derbvar2", StringConstantType.BareWord);
                InvokeMemberExpressionAst targetAst = new InvokeMemberExpressionAst(ast.Extent, derpVar, derpVar2, Enumerable.Empty <ExpressionAst>(), false);
                if (targetAst != null)
                {
                    if (targetAst.Member.Extent.Text.In(false, new List <string> {
                        "invokescript", "createnestedpipeline", "addscript", "newscriptblock", "expandstring"
                    }))
                    {
                        return(true);
                    }
                    if (targetAst.Member.Extent.Text.In(false, new List <string> {
                        "create"
                    }) && targetAst.Expression.Extent.Text.In(false, new List <string> {
                        "scriptblock"
                    }))
                    {
                        return(true);
                    }
                }
                return(false);
            };

            var foundNode = ScriptBlockAst.Find(predicate, true);

            if (foundNode != null)
            {
                Console.WriteLine("[+] Possible injection vulnerability found");
                Console.WriteLine(String.Format(@"Possible script injection risk via the a dangerous method. Untrusted input can cause arbitrary PowerShell expressions to be run.
The PowerShell.AddCommand().AddParameter() APIs should be used instead.
RuleName = {1}
Severity = Warning", foundNode.Extent, foundNode.Extent.Text)
                                  );
            }
        }
        /// <summary>
        /// Checks if a hashtable is created using [hashtable]::new()
        /// </summary>
        public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
        {
            if (methodCallAst == null)
            {
                return(AstVisitAction.SkipChildren);
            }

            var typeExprAst = methodCallAst.Expression as TypeExpressionAst;

            if (typeExprAst == null ||
                !presetTypeNameSet.Contains(typeExprAst.TypeName.FullName))
            {
                return(AstVisitAction.Continue);
            }

            var memberStringConstantExprAst = methodCallAst.Member as StringConstantExpressionAst;

            if (memberStringConstantExprAst == null ||
                !memberStringConstantExprAst.Value.Equals("new", StringComparison.OrdinalIgnoreCase))
            {
                return(AstVisitAction.Continue);
            }

            // no arguments provided to new OR one of the argument ends with ignorecase
            // (heuristics find to something like [system.stringcomparer]::ordinalignorecase)
            if (methodCallAst.Arguments == null ||
                !HasIgnoreCaseComparerArg(methodCallAst.Arguments))
            {
                var dr = new DiagnosticRecord(
                    Strings.UseLiteralInitilializerForHashtableDescription,
                    methodCallAst.Extent,
                    GetName(),
                    GetDiagnosticSeverity(),
                    fileName,
                    ruleId: null,
                    suggestedCorrections: GetSuggestedCorrections(methodCallAst, this.fileName));
                diagnosticRecords.Add(dr);
            }

            return(AstVisitAction.Continue);
        }
Example #15
0
            public override object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
            {
                VisitElement(invokeMemberExpressionAst.Expression);

                if (invokeMemberExpressionAst.Static)
                {
                    script_.Write("::");
                }
                else
                {
                    script_.Write(".");
                }

                VisitElement(invokeMemberExpressionAst.Member);

                script_.Write("(");
                VisitElements(invokeMemberExpressionAst.Arguments, ", ");
                script_.Write(")");

                return(invokeMemberExpressionAst);
            }
Example #16
0
        /// <summary>
        /// Add a member to the graph and if within a function definition, add an edge from the function to the member
        /// </summary>
        public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst ast)
        {
            if (ast == null)
            {
                return(AstVisitAction.SkipChildren);
            }

            var expr          = ast.Expression.Extent.Text;
            var memberExprAst = ast.Member as StringConstantExpressionAst;

            if (memberExprAst == null)
            {
                return(AstVisitAction.Continue);
            }

            var member = memberExprAst.Value;

            if (string.IsNullOrWhiteSpace(member))
            {
                return(AstVisitAction.Continue);
            }

            // Suppose we find <Expression>.<Member>, we split it up and create
            // and edge from <Expression>-><Member>. Even though <Expression> is not
            // necessarily a function, we do it because we are mainly interested in
            // finding connection between a function and ShouldProcess and this approach
            // prevents any unnecessary complexity.
            var exprVertex   = new Vertex(expr, ast.Expression);
            var memberVertex = new Vertex(memberExprAst.Value, memberExprAst);

            AddVertex(exprVertex);
            AddVertex(memberVertex);
            AddEdge(exprVertex, memberVertex);
            if (IsWithinFunctionDefinition())
            {
                AddEdge(GetCurrentFunctionContext(), exprVertex);
            }

            return(AstVisitAction.Continue);
        }
        public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst imeAst)
        {
            if (imeAst == null)
            {
                return(AstVisitAction.SkipChildren);
            }

            TypeExpressionAst typeAst = imeAst.Expression as TypeExpressionAst;

            if (typeAst == null || typeAst.TypeName == null || typeAst.TypeName.FullName == null)
            {
                return(AstVisitAction.SkipChildren);
            }

            if (typeAst.TypeName.FullName.EndsWith("console", StringComparison.OrdinalIgnoreCase) &&
                !String.IsNullOrWhiteSpace(imeAst.Member.Extent.Text) && imeAst.Member.Extent.Text.StartsWith("Write", StringComparison.OrdinalIgnoreCase))
            {
                records.Add(new DiagnosticRecord(String.Format(CultureInfo.CurrentCulture, Strings.AvoidUsingConsoleWriteError, System.IO.Path.GetFileName(fileName), imeAst.Member.Extent.Text),
                                                 imeAst.Extent, GetName(), DiagnosticSeverity.Warning, fileName));
            }

            return(AstVisitAction.Continue);
        }
Example #18
0
        public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
        {
            var expression = methodCallAst.Expression;

            Type   type;
            object obj;

            if (expression is TypeExpressionAst)
            {
                obj  = null;
                type = ((TypeExpressionAst)expression).TypeName.GetReflectionType();
            }
            else
            {
                obj = EvaluateAst(expression);
                if (obj is PSObject)
                {
                    obj = ((PSObject)obj).BaseObject;
                }
                type = obj.GetType();
            }

            var arguments = methodCallAst.Arguments.Select(EvaluateAst).Select(o => o is PSObject ? ((PSObject)o).BaseObject : o);

            if (methodCallAst.Member is StringConstantExpressionAst)
            {
                BindingFlags bindingFlags = BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static;
                var          name         = (methodCallAst.Member as StringConstantExpressionAst).Value;
                var          method       = type.GetMethod(name, bindingFlags, null, arguments.Select(a => a.GetType()).ToArray(), null);
                var          result       = method.Invoke(obj, arguments.ToArray());

                _pipelineCommandRuntime.WriteObject(result);
                return(AstVisitAction.SkipChildren);
            }

            throw new NotImplementedException(this.ToString());
        }
Example #19
0
 public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
 {
     return(AstVisitAction.SkipChildren);
 }
Example #20
0
 internal SettableInvokeMemberExpression(InvokeMemberExpressionAst expressionAst, ExecutionVisitor currentExecution)
     : base(expressionAst, currentExecution)
 {
     _expressionAst = expressionAst;
 }
Example #21
0
 public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     return(false);
 }
Example #22
0
 public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst ast)
 {
     return(DoNextAction(ast));
 }
Example #23
0
 public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
 {
     throw new NotImplementedException(); //VisitInvokeMemberExpression(methodCallAst);
 }
 public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     throw PSTraceSource.NewArgumentException("ast");
 }
Example #25
0
 public override ExpressionAst VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 => VisitExpression(base.VisitInvokeMemberExpression(invokeMemberExpressionAst));
Example #26
0
 public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
 {
     Console.WriteLine("Visited an InvokeMemberExpressionAst.");
     Console.WriteLine("    " + methodCallAst.ToString().Replace(Environment.NewLine, Environment.NewLine + "    "));
     return(AstVisitAction.Continue);
 }
Example #27
0
 public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst)
 {
     Console.WriteLine("Visited an InvokeMemberExpressionAst.");
     return(invokeMemberExpressionAst);
 }
            public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst)
            {
                // Look for [typename]::new(...) and [typename]::$dynamicMethodName syntax

                if (!_targetVersions.Contains(s_v3) && !_targetVersions.Contains(s_v4))
                {
                    return(AstVisitAction.Continue);
                }

                if (_targetVersions.Contains(s_v3) && methodCallAst.Member is VariableExpressionAst)
                {
                    string message = string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.UseCompatibleSyntaxError,
                        "dynamic method invocation",
                        methodCallAst.Extent.Text,
                        "3");

                    _diagnosticAccumulator.Add(new DiagnosticRecord(
                                                   message,
                                                   methodCallAst.Extent,
                                                   _rule.GetName(),
                                                   _rule.Severity,
                                                   _analyzedFilePath
                                                   ));
                }

                if (!(methodCallAst.Expression is TypeExpressionAst typeExpressionAst))
                {
                    return(AstVisitAction.Continue);
                }

                if (!(methodCallAst.Member is StringConstantExpressionAst stringConstantAst))
                {
                    return(AstVisitAction.Continue);
                }

                if (stringConstantAst.Value.Equals("new", StringComparison.OrdinalIgnoreCase))
                {
                    string typeName = typeExpressionAst.TypeName.FullName;

                    CorrectionExtent suggestedCorrection = CreateNewObjectCorrection(
                        _analyzedFilePath,
                        methodCallAst.Extent,
                        typeName,
                        methodCallAst.Arguments);

                    string message = string.Format(
                        CultureInfo.CurrentCulture,
                        Strings.UseCompatibleSyntaxError,
                        "constructor",
                        methodCallAst.Extent.Text,
                        "3,4");

                    _diagnosticAccumulator.Add(new DiagnosticRecord(
                                                   message,
                                                   methodCallAst.Extent,
                                                   _rule.GetName(),
                                                   _rule.Severity,
                                                   _analyzedFilePath,
                                                   ruleId: null,
                                                   suggestedCorrections: new [] { suggestedCorrection }
                                                   ));

                    return(AstVisitAction.Continue);
                }

                return(AstVisitAction.Continue);
            }
 public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) => null;
Example #30
0
 /// <summary/>
 public virtual AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) => DefaultVisit(methodCallAst);