Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions csharp/src/security/CWE-862/WebMethodActions.qll
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* Provides a model of ASP.NET web methods (methods annotated with
* `[System.Web.Services.WebMethod]`) as action methods for access control queries.
*/

import csharp
private import semmle.code.csharp.frameworks.system.web.Services
private import semmle.code.csharp.security.auth.ActionMethods

/**
* A method annotated with `[System.Web.Services.WebMethod]`, which is remotely invocable
* either as an ASMX web service operation or as an ASP.NET page method.
*/
class WebMethodActionMethod extends ActionMethod {
WebMethodActionMethod() {
this.getAnAttribute().getType() instanceof SystemWebServicesWebMethodAttributeClass
}

/**
* Holds if this method may represent a stateful action. In addition to the generic
* edit-like names, web methods whose names contain `transfer`, `withdraw`, `deposit`,
* `update` or `remove` as a whole camelCase word are considered stateful.
*/
override predicate isEdit() {
super.isEdit()
or
this.getName()
// separate camelCase words
.regexpReplaceAll("([a-z])([A-Z])", "$1_$2")
.regexpMatch("(?i)(.*_)?(transfer|withdraw|deposit|update|remove)(_.*)?")
}
}
95 changes: 95 additions & 0 deletions csharp/src/security/CWE-862/WebMethodMissingAccessControl.qhelp
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>

<overview>
<p>
A method marked with <code>[System.Web.Services.WebMethod]</code> is an ASMX web service operation
or, when it is a static method of a page, an ASP.NET page method. Any client that can reach the
service can call it. A web method that changes data, such as one that transfers, withdraws,
deposits, updates, removes, edits or deletes something, or that performs an administrative action,
should check that the caller is allowed to do so.
</p>
<p>
This query reports such a web method when it has no authorization check in its code, no
authorization attribute that applies to it, and no <code>&lt;location&gt;</code> rule in a
<code>Web.config</code> file that denies access to it. The standard query
<code>cs/web/missing-function-level-access-control</code> does not consider web methods.
</p>
<p>
The MVC and Web API <code>Authorize</code> attributes (<code>System.Web.Mvc.AuthorizeAttribute</code>
and <code>System.Web.Http.AuthorizeAttribute</code>) are filters of their own pipelines. They do
not run for a web method, so they do not protect it.
</p>

</overview>
<recommendation>

<p>
Check that the caller is authenticated and authorized before changing data, for example with
<code>Context.User.Identity.IsAuthenticated</code> or <code>Context.User.IsInRole(...)</code>. Alternatively,
deny access to unauthorized users with an <code>authorization</code> element in a
<code>&lt;location&gt;</code> element of <code>Web.config</code> that covers the service.
</p>

</recommendation>
<example>

<p>
In the following example, any caller can transfer funds between arbitrary accounts:
</p>

<sample language="csharp"><![CDATA[
[WebMethod]
public string TransferBalance(long from, long to, double amount)
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}
]]></sample>

<p>
The method is fixed by checking that the caller is authenticated (and, ideally, owns the debited
account):
Comment on lines +54 to +55
</p>

<sample language="csharp"><![CDATA[
[WebMethod]
public string TransferBalance(long from, long to, double amount)
{
if (!Context.User.Identity.IsAuthenticated)
return "Unauthorized";
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}
]]></sample>

<p>
The following <code>Web.config</code> file denies anonymous users access to the service:
</p>

<sample language="xml"><![CDATA[
<configuration>
<location path="AccountService.asmx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
]]></sample>

</example>
<references>
<li>OWASP: <a href="https://owasp.org/Top10/A01_2021-Broken_Access_Control/">Broken Access Control</a>.</li>
<li>Microsoft Learn: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.web.services.webmethodattribute">WebMethodAttribute Class</a>.</li>
<li>Microsoft Learn: <a href="https://learn.microsoft.com/en-us/troubleshoot/developer/webapps/aspnet/www-authentication-authorization/authorization-permissions">Control authorization permissions in an ASP.NET application</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/285.html">CWE-285</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/284.html">CWE-284</a>.</li>
<li>Common Weakness Enumeration: <a href="https://cwe.mitre.org/data/definitions/862.html">CWE-862</a>.</li>
</references>
</qhelp>
53 changes: 53 additions & 0 deletions csharp/src/security/CWE-862/WebMethodMissingAccessControl.ql
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/**
* @name Missing function level access control on a web method
* @description A web method that changes data or performs an administrative action
* without an authorization check can be invoked by any caller.
* @kind problem
* @problem.severity warning
* @security-severity 7.5
* @precision medium
* @id githubsecuritylab/cs/web/web-method-missing-access-control
* @tags security
* experimental
* external/cwe/cwe-285
* external/cwe/cwe-284
* external/cwe/cwe-862
*/

import csharp
import semmle.code.csharp.security.auth.MissingFunctionLevelAccessControlQuery
import WebMethodActions

private ValueOrRefType getAnUnboundBaseType(ValueOrRefType t) {
result = t.getABaseType().getUnboundDeclaration()
}

/**
* Holds if `attr` is an MVC or Web API authorization filter. These filters run only in
* their own pipelines, so they do not protect a web method.
*/
private predicate isPipelineAuthorizeAttribute(Attribute attr) {
attr.getType()
.getABaseType*()
.hasFullyQualifiedName(["System.Web.Mvc", "System.Web.Http"], "AuthorizeAttribute")
Comment on lines +30 to +32
}

/** Holds if `m` has an authorization attribute that applies to a web method. */
private predicate hasWebMethodAuthViaAttribute(WebMethodActionMethod m) {
exists(Attribute attr |
attr.getType().getABaseType*().getName().toLowerCase().matches("%auth%") and
not isPipelineAuthorizeAttribute(attr)
|
attr = m.getOverridee*().getAnAttribute() or
attr = getAnUnboundBaseType*(m.getDeclaringType()).getAnAttribute()
)
}

from WebMethodActionMethod m
where
needsAuth(m) and
not hasAuthViaCode(m) and
not hasAuthViaXml(m) and
not hasWebMethodAuthViaAttribute(m) and
exists(m.getBody().getAChildStmt()) // exclude empty methods
select m, "This web method is missing an authorization check."
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
using System.Web.Mvc;
using System.Web.Services;

namespace Bank.WebServices
{
public class RequireAuthorizationAttribute : System.Attribute { }

[WebService(Namespace = "http://example.com/")]
public class AccountService : WebService
{
// BAD: state-changing web method without any authorization check.
[WebMethod]
public string TransferBalance(long from, long to, double amount)
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}

// BAD: edit operation exposed as a web method without authorization.
[WebMethod]
public void DeleteAccount(long accountId)
{
Remove(accountId);
}

// BAD: `update` is a whole camelCase word of the name.
[WebMethod]
public void UpdateEmail(long accountId, string email)
{
System.Console.WriteLine(accountId + email);
}

// GOOD: checks that the caller is authenticated.
[WebMethod]
public string TransferBalanceChecked(long from, long to, double amount)
{
if (!Context.User.Identity.IsAuthenticated)
return "Unauthorized";
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}

// GOOD: checks the caller's role.
[WebMethod]
public void DeleteAccountChecked(long accountId)
{
if (Context.User.IsInRole("Admin"))
Remove(accountId);
}

// GOOD: an authorization attribute that is not an MVC or Web API filter.
[WebMethod]
[RequireAuthorization]
public void WithdrawAll(long accountId)
{
Withdraw(accountId, 0);
}

// BAD: MVC authorization attributes do not protect ASMX operations.
[WebMethod]
[Authorize]
public string TransferBalanceAuthorized(long from, long to, double amount)
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}

// BAD: Web API authorization attributes do not protect ASMX operations.
[WebMethod]
[System.Web.Http.Authorize]
public void DepositAll(long accountId)
{
Deposit(accountId, 0);
}

// GOOD: read-only operation, the query only targets sensitive (state-changing / admin) actions.
[WebMethod]
public long[] GetUserAccounts(long userId)
{
return new long[] { userId };
}

// GOOD: `updated` is not the whole word `update`.
[WebMethod]
public string GetLastUpdated(long accountId)
{
return accountId.ToString();
}

// GOOD: not a web method, so not remotely invocable.
public void TransferInternal(long from, long to, double amount)
{
Withdraw(from, amount);
Deposit(to, amount);
}

// GOOD: empty web method.
[WebMethod]
public void TransferNothing() { }

private void Withdraw(long account, double amount) { }

private void Deposit(long account, double amount) { }

private void Remove(long account) { }
}

[Authorize]
public class AdminService : WebService
{
// BAD: MVC authorization attributes do not protect ASMX operations.
[WebMethod]
public void DeleteUser(long userId)
{
System.Console.WriteLine(userId);
}
}

[RequireAuthorization]
public class ProtectedService : WebService
{
// GOOD: the class has an authorization attribute that applies to its web methods.
[WebMethod]
public void RemoveUser(long userId)
{
System.Console.WriteLine(userId);
}
}

public class TransfersPage : System.Web.UI.Page
{
// BAD: ASP.NET page method (static [WebMethod]) without authorization.
[WebMethod]
public static void TransferFunds(long from, long to, double amount)
{
System.Console.WriteLine(from + to + amount);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
namespace Bank
{
using System;
using System.Web.Services;

public struct TransferResult
{
public bool Success;
public string Message;
}

// Variant: SOAP service in App_Code with a fully qualified base type and
// `[WebMethod(Description = ...)]` named arguments, taking a request object.
[WebService(Namespace = "http://example.com/bank/ws/", Description = "Core bank services.")]
public class Services : System.Web.Services.WebService
{
public class MoneyTransfer
{
public string debitAccount;
public string creditAccount;
public double transferAmount;

public bool setAmount(double amt)
{
this.transferAmount = amt;
return true;
}
}

// GOOD: read-only lookup (not considered sensitive by name).
[WebMethod(Description = "Determine if a UserId is valid and exists.")]
public bool IsValidUser(string userId)
{
return userId.Length > 0;
}

// GOOD: read-only lookup (not considered sensitive by name).
[WebMethod(Description = "Retrieve accounts by UserId.")]
public int[] GetUserAccounts(int userId)
{
return new int[] { userId };
}

// BAD: anonymous callers can move funds between arbitrary accounts.
[WebMethod(Description = "Transfer funds from one account to another.")]
public TransferResult TransferBalance(MoneyTransfer transDetails)
{
TransferResult result = new TransferResult();
result.Success = transDetails.debitAccount != transDetails.creditAccount;
result.Message = "$" + transDetails.transferAmount + " transferred.";
return result;
}
}
}
Loading