Code Monkey home page Code Monkey logo

pumasecurity / puma-scan Goto Github PK

View Code? Open in Web Editor NEW
440.0 440.0 81.0 1.3 MB

Puma Scan is a software security Visual Studio extension that provides real time, continuous source code analysis as development teams write code. Vulnerabilities are immediately displayed in the development environment as spell check and compiler warnings, preventing security bugs from entering your applications.

Home Page: https://www.pumascan.com

License: Mozilla Public License 2.0

C# 96.81% PowerShell 2.85% Dockerfile 0.08% Shell 0.26%

puma-scan's People

Contributors

aguggenberger avatar ejohn20 avatar meadisu27 avatar terribledev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

puma-scan's Issues

Intermittent warning with Microsoft.Build.Engine, Version 14.0

Receive an intermittent warning that says: Analyzer assembly \packages\Puma.Security.Rules.1.0.6\analyzers\dotnet\cs\Microsoft.Build.dll' depends on 'Microsoft.Build.Engine, Version=14.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' but it was not found. Analyzers may not run correctly unless the missing assembly is added as an analyzer reference as well.

If I uninstall and re-install the nuget - it goes away temporarily. Any ideas?

Version 2.0: AD001 Error

Debugging the release 2.0 branch to benchmark findings across the old version versus new version. Analayzers are failing to fire:

Warning AD0001 Analyzer 'Puma.Security.Rules.Suites.PathTamperingDiagnosticSuite' threw an exception of type 'System.ArgumentNullException' with message 'Value cannot be null.
Parameter name: syntax'

System.ArgumentNullException: Value cannot be null.
Parameter name: syntax
at Microsoft.CodeAnalysis.CSharp.CSharpSemanticModel.CheckSyntaxNode(CSharpSyntaxNode syntax)
at Microsoft.CodeAnalysis.CSharp.CSharpSemanticModel.GetSymbolInfo(ExpressionSyntax expression, CancellationToken cancellationToken)
at Microsoft.CodeAnalysis.CSharp.CSharpExtensions.GetSymbolInfo(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
at Puma.Security.Rules.Analyzer.Core.IdentifierNameSyntaxAnalyzer.CanIgnore(SemanticModel model, SyntaxNode syntax)
at Puma.Security.Rules.Analyzer.Core.SyntaxNodeAnalyzer.CanIgnore(SemanticModel model, SyntaxNode syntax)
at Puma.Security.Rules.Analyzer.Core.InvocationExpressionSyntaxAnalyzer.<>c__DisplayClass7_0.b__0(ArgumentSyntax p)
at System.Linq.Enumerable.All[TSource](IEnumerable1 source, Func2 predicate)
at Puma.Security.Rules.Analyzer.Core.InvocationExpressionSyntaxAnalyzer.CanSuppressArguments(SemanticModel model, ArgumentListSyntax argumentList)
at Puma.Security.Rules.Analyzer.Core.InvocationExpressionSyntaxAnalyzer.CanSuppress(SemanticModel model, SyntaxNode syntax)
at Puma.Security.Rules.Analyzer.Core.BaseCodeBlockAnalyzer.OnCompilationEnd(CompilationAnalysisContext pumaContext)
at Puma.Security.Rules.Core.BaseSyntaxDiagnosticSuite.<>c__DisplayClass2_0.b__0(CompilationAnalysisContext context)
at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.<>c.b__36_1(ValueTuple2 data) at Microsoft.CodeAnalysis.Diagnostics.AnalyzerExecutor.ExecuteAndCatchIfThrows_NoLock[TArg](DiagnosticAnalyzer analyzer, Action1 analyze, TArg argument, Nullable`1 info)

'.

VB code scan

Hi,

can Puma will analyse the project which is written in Vb coding.
i am using VS 2015

First i've written the code in C# then puma scanner is showing the vulnerability error

Severity Code Description Project File Line Suppression State
Warning SEC0110 Unvalidated redirect location is passed to the Response.Redirect method. Sample1 C:\Users\KDDuser\Desktop\Sample1\Sample1\Account\Register.aspx.cs 28 Active
Warning SEC0107 SQL Injection - ADO.NET method is passed a dynamic SQL statement. Sample1 C:\Users\KDDuser\Desktop\Sample1\Sample1\Register.aspx.cs 45 Active

i've written the code in VB it was not showing any vulnerability error

so can you please conform can puma scanner will analyse the Vb written code.

if yes please let me know steps to check why it is not scanning the Vb code.

Thanks,
Hemanth.

Version 1.0.7 does not prompt any warnings

Hi,

I'm using Puma Scan Version 1.0.7 in VS 2015 mainly. It does not prompt any warnings in my error list panel. However, it prompted errors in VS 2017 when i'm using version 2.0.0.1. It does not tally with VS 2015. Is it Cos' version 1.0.7 is depreciating?? If so, is there no fixes for it?

Thanks.

Rule Options Screen

Currently, the RuleOptions.cs file contains some hard-coded values that drives some of the rules (auth timeout, password complexity, etc.)

This needs to be editable via a configuration screen in IDE. Something like Tools > Options > Puma Scan > General. This could produce a ruleoptions.json file if we want it to.

For the NuGet package, this can be done via a ruleoptions.json file with the same configuration values.

Each rule should have an enabled / disabled flag that selects which rules run. Any rules that are taint oriented should have a list of vulnerable sinks and sources that can be configured within the rule, each one having its own enabled flag as well.

Set NuGet Package as DevelopmentDependency

The PumaScan NuGet package should set itself as a development dependency, as it is a dependency that is only useful for development and should not be required by other packages by default. This can be done by adding the following to the .nuspec file.

<developmentDependency>true</developmentDependency>

Validate Request Disabled

Check controllers, actions, and model properties for disabling validate request.

  1. Controllers / actions with [ValidateInput(false)]

  2. Model properties with [AllowHtml]

Either of those can indicate xss bypass entry points that require additional validation...

Taint Analysis

Puma gives false positives at times. In the following example:

string sq = "select * from tab";
SqlCommand sqll = new SqlCommand(sq);
SqlDataAdapter sqa = new SqlDataAdapter(sqll);

I tried modifying the SqlCommandInjectionObjectCreationExpressionAnalyzer.cs for detecting and raising warnings if the first argument of SqlCommand and SqlDataAdapter are tainted. So if they are tainted , diagnostics are raised properly. String "sq" in this case is not tainted. But still diagnostics are raised for SqlDataAdapter.

.NET Core Scanning Support

Reconfigure the reference to the netstandard20 Roslyn / code analysis packages to support the traditional framework and .NET Core in Visual Studio.

Cross-Site Scripting

Base XSS rules:

Web forms:
Label.Text =
Literal.Text =
<%= %>
<%# %>

MVC:
@Html.Raw
@{ WriteLiteral(); }

XSS - HttpResponse.Write Sink

Add a new rule covering the HttpResponse.Write sink. Currently, this is not flagged as a potential XSS issue:

try
{
...
}
catch ( Exception ex )
{
response.Write( "" + ex.Message + "" );
}

Analyze Code via .NET Core Docker File

400+ errors when the project is opened in Visual Studio for Mac Preview 1. Looks like a lot of them have to do with Visual Studio integration, not Roslyn. Will try to go through them.

SEC0019 with global AutoValidateAntiforgeryTokenAttribute

A newer pattern exists for auto validating CSRF tokens in .NET Core to protect all endpoints through global filter configuration. Is there any pattern for detecting this attribute is globally applied and disable SEC0019? Potentially here SEC0019 could apply to the use of the ignore attribute.

Filters.Add(new AutoValidateAntiforgeryTokenAttribute());

AutoValidateAntiforgeryTokenAttribute can be applied as a global filter to trigger validation of antiforgery tokens by default for an application.

Also, we should call out the usage of IgnoreAntiforgeryTokenAttribute here.

Blog explaining the topic: https://andrewlock.net/automatically-validating-anti-forgery-tokens-in-asp-net-core-with-the-autovalidateantiforgerytokenattribute/

This would be dependent on .NET Core support #36

Path Tampering

Start with Mead's example from his code review in an MVC controller.

Other areas to look File.Read, File.Write, and maybe File.Exists?

VS2017: Hanging analysis on simple project

I have VS 2017 Community. I installed Puma Scan as extension and also performed NuGet command specified here (without this command analysis failed with CA0064: No analysis was performed because the specified rule set could not be loaded or did not contain any managed code analysis rules):
PM > Get-Project -All | Install-Package Puma.Security.Rules

Now the analysis is hanging (that is, not returning for 3+ hours) on very simple project WebGoat. Looking at task manager, I see csc.exe and devenv.exe taking ~25% each all the time.
I run analysis via Analyze -> Run Code ANalysis on Solution. WIthout Puma (default rules only) this works fine.

Please let me know what other info I need to provide if any to troubleshoot this.

SEC109 False Positive

In VS2017 SEC0109 is being raised with the following example code, which pretty much mirrors what the documentation says to do to fix it.

        if (Url.IsLocalUrl(returnUrl))
        {
            return Redirect(returnUrl); //this line is flagged with SEC109
        }

Disabling Certificate Validation

String url = "https://www.stackoverflow.com";
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };

OR

ServicePointManager.ServerCertificateValidationCallback +=
(sender, cert, chain, sslPolicyErrors) => true;

OR

using (var handler = new WebRequestHandler())
{
handler.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

using (var client = new HttpClient(handler))
{
}

}

Eternal loop in GetParentLocalDeclarationStatement

It might be the cause of #39 because I found it running the same project.
There is no break at the end of while(true) in GetParentLocalDeclarationStatement as it is in SymbolInheritsFrom. This causes an eternal loop when an item is not null, not LocalDeclarationStatementSyntax and doesn't have a parent.

May I suggest also adding something similar to snippet below to prevent it in the future:

var analyzeTask = AnalyzeAsync();
var timeoutTask = Task.Delay(10000);
var completedTask = await Task.WhenAny(analyzeTask, timeoutTask);
if (completedTask == timeoutTask)
    throw new TimeoutException();

Command Injection

Look for Process.Start commands that take in non-hard coded string values (could contain user supplied values).

LDAP Injection

Look for dynamic values being created appended into LDAP filters or DN's. Examples below:

Filters:
DirectoryEntry.Filter =

OR

DN's:
DirectoryEntr de = new DirectoryEntry("LDAP://yourserver/CN=Users,dc=,dc=com");

SEC0027: Visual Studio 2015 Build Error

RE: Hkim

We were evaluating Puma.Security.Rules 1.0.6 against our old project and we are experiencing weird behavior. When you build, it says “build has started…” and just stays there… I was able to reconstruct this behavior and have created a console app to demonstrate this. Below is the snippet of code where this occurs.

I was expecting to see SEC0027 and SEC0029 warning messages but instead, it hangs during build and never finishes. Do you have any suggestions?

class Program
  {
    enum enuHashMethod : int
    {
      MD5 = 0,
      SHA1 = 1,
      SHA256 = 2,
      SHA384 = 3,
      SHA512 = 4
    }
 
    static void Main(string[] args)
    {
    }
 
    private static HashAlgorithm Algorithm(enuHashMethod hashMethod)
    {
      HashAlgorithm hashAlg = null;
 
      switch (hashMethod)
      {
        case enuHashMethod.MD5:
          hashAlg = new MD5CryptoServiceProvider();  // Build hangs… commenting out builds fine…
          break;
        case enuHashMethod.SHA1:
          hashAlg = new SHA1Managed();  // Build hangs… commenting out builds fine…
          break;
        case enuHashMethod.SHA256:
          hashAlg = new SHA256Managed();
          break;
        case enuHashMethod.SHA384:
          hashAlg = new SHA384Managed();
          break;
        case enuHashMethod.SHA512:
          hashAlg = new SHA512Managed();
          break;
      }
      return (hashAlg);
    }
  }

MSBuild - Execute Rules

Research how to execute the Roslyn extension rules during MSBuild. This could be very useful during a CI pipeline for automating the scan, retrieving the results, and making a determination on failing the build.

Redirect: AuthZ Bypass

Great find by the @absoluteappsec folks. Flag redirects that pass false into the 2nd parameter. Redirects are typically used in older web forms projects for custom authorization. It's interesting that the documentation actually says to use "false" to improve performance.

Setting false will allow execution to continue after the redirect line is executed and responses will include the view's data. E.g. Redirect to login on an admin page that has sensitive info. Revealing additional admin endpoints, which can also be invoked if the same line exists in those admin endpoints.

https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.redirect?view=netframework-4.7.2

SEC0112 false positive

Any use of a variable in the File API appears to trigger this warning. The only way I can find to satisfy the analyzer is to use a hard coded string for the file path. Even the secure example code from the documentation triggers the warning:

[HttpPost]
public HttpResponseMessage Delete(Guid fileId)
{
    string path = Path.Combine(ConfigurationManager.AppSettings["DownloadPath"], fileId.ToString());
    File.Delete(path);
    return Request.CreateResponse(HttpStatusCode.OK);
}

Is the only way prevent this warning hard coding the path or manual suppression?

SEC0108 warning with recommended overload

The rule documentation for SEC0108 recommends...

To ensure calls to vulnerable EF methods are parameterized, pass parameters into the statement using the method’s second argument: params object[] parameters.

However the following code still causes a warning for usage of ExecuteSqlCommand and SqlQuery...

public void ExecuteProcedure(string procedureName, List<SqlParameter> parameters = null)
{
    var procedure = ParameterizeProcedure(procedureName, parameters);
    var boundParams = (parameters ?? new List<SqlParameter>()).ToArray();
    this.Database.ExecuteSqlCommand(procedure, boundParams);
}

public List<TReturn> ExecuteProcedure<TReturn>(string procedureName, List<SqlParameter> parameters = null)
    where TReturn : class
{
    var procedure = ParameterizeProcedure(procedureName, parameters);
    var boundParams = (parameters ?? new List<SqlParameter>()).ToArray();
    return this.Database.SqlQuery<TReturn>(procedure, boundParams).ToList();
}

Is this a bug or are we doing something wrong?

Support for running in CI?

VS extension is really nice, but it will be even better to run it in a CI. Is that possible or planned to be supported sometime in the future?

Crypto Rules

Weak Hash Algorithms: MD2, MD4 and MD5, SHA1

Weak Crypto Algorithm: DES

Static IV's

Hard-coded Keys

Weak Key Length: Blowfish (< 128), RSA (< 2048)

ECB Mode on a block cipher

Please update Puma.Security.Rules.csproj to reference latest version of Microsoft.Net.Compilers

Hi,

I am having issues compiling a Visual Studio 2015 solution I have with project properties "Treat warnings as errors" enabled using version 1.0.5 of Puma Security because it is referencing an old version of Microsoft.Net.Compilers. The error I am recieving is:
CSC error CS8032: An instance of analyzer Puma.Security.Rules.Suites.CertificateValidationDiagnosticSuite cannot be created from ...\packages\Puma.Security.Rules.1.0.5\analyzers\dotnet\cs\Puma.Security.Rules.dll : Could not load file or assembly 'Microsoft.CodeAnalysis, Version=1.3.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Please could you provide a timeframe when this could be addressed and fixed.

Thanks.

Rule Suppression Format

@joshbw proposed a standard format for suppressing false positives using commands on a line of code in our extension tools.

Fields proposed:

  • ToolName
  • Identifier (SEC###, DS###)
  • Comment
  • Expiration Date
  • Hash code
  • Author

What other fields would be helpful?

Format could be something simple:

  • //ToolName:Identifier:HashCode:Author:Comment:EndDate

Thoughts on the format?

Identity Checks

Look for httponly, secure turned off in cookied auth mode.

Prevent SQL injection in queries with exec or execute

I'm developing a reporting web with Visual Studio 2017. All my SQL queries are parameterized and works properly. The problem is in some queries that have exec command like in a procedure.

For example: instead of select * from tabla where id=@id I put exec('select * from tabla where id=@id')

The exec case doesn't work. The message error is:

Must declare the scalar variable ""@id""." & vbCrLf & "Must declare the scalar variable ""@id""."

Anyone knows a possible solution?

Thanks a lot!

Command line test runner - Support a well known report output format

Feature request to support a common test output format from the command line test runner.

  • JUnit
  • xUnit 2
  • NUnit 2
  • NUnit 3
  • Visual Studio Test Results (TRX)
  • FxCopReport format CodeAnalysisReport.xsl (c:\program files (x86)\microsoft visual studio\2017\enterprise\team tools\static analysis tools\fxcop\Xml\CodeAnalysisReport.xsl)

This would enable test results to be reported as part of VSTS Test dashboards using CI/CD Release Pipelines

Privacy Violation

Look for data (credit card number, ssn, etc.) being stored into a backend data store. Start with database to being with.

Refactor Analyzer Code Base

Refactor code base to use the new DataFlowAnalyzer, SemanticAnalyzer, ViewMarkupAnalyzer, and ConfigurationAnalyzer base classes. Add in the new code block analyzer feature to help reduce false positives.

New Rule: Cookie Security

Puma Scan didn’t detect missing HttpOnly and Secure flags here.

Secure settings are Secure = true, HttpOnly = true, and Expires can only be set to a past date.

HttpCookie CreateCookie(string value)
{
      var ck = new HttpCookie(COOKIE_NAME, value);
      if (string.IsNullOrWhiteSpace(value)) ck.Expires = DateTime.Now.AddYears(-1);
      return ck;
}

or

```cs
Response.SetCookie(new HttpCookie("sid", sid) { Expires = DateTime.Now.AddDays(1) });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.