Repository navigation
Description
What to do
cs/web/missing-function-level-access-control does not look at methods marked [WebMethod], that is ASMX web
service operations and static ASP.NET page methods (CWE-862, CWE-285). Its ActionMethod covers only MVC
controller actions and Web Forms page event handlers. Add a query that reports a [WebMethod] method that
appears to change data and has no authorization check, with the same tests for an authorization check as the
standard query: a check in code such as User.Identity.IsAuthenticated or IsInRole, an authorization
attribute, and a <location> rule in Web.config.
Report this:
[WebMethod]
public string TransferBalance(long from, long to, double amount)
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}Do not report the same method when it checks Context.User.Identity.IsAuthenticated or calls IsInRole, when
it or its class has an authorization attribute that applies to it, or when it only reads data.
The files below are a draft of this query from another workspace. It was written for another layout and has never run in this repository. Use it as a starting point: port it, prove it with its test, and change it wherever the test or this repository's conventions disagree with it.
Decisions in the draft
- Change this for this repository: the draft copies the standard query and keeps its
@id, to replace it.
Here the query needs its own id and must report only[WebMethod]methods, so that it does not repeat what the
standard query reports. - Web methods:
WebMethodActionMethodinWebMethodActions.qllis a method with
System.Web.Services.WebMethodAttribute. - Names that change data: the standard words (
edit,delete,modify,change,admin) and, for web
methods only,transfer,withdraw,deposit,updateandremove, matched as whole camelCase words. - MVC attribute: an MVC
[Authorize]attribute does not protect a web method, because the MVC pipeline does
not run for it, so the draft still reports a web method whose only protection is that attribute. - Not reported, by design: web methods that only read data, so that not every public web method is
reported. - Metadata: the draft keeps the standard query's metadata:
@kind problem,@precision medium,
@security-severity 7.5, CWE-285, CWE-284 and CWE-862. - Test: inline expectations with local
System.Webstubs inStubs.cs, and aWeb.configwith a
<location>rule inWebConfig/.
Files
The paths below follow this repository's layout but are suggestions. The draft was written for another layout, so its .qlref and options files, and its .md query help, need adapting (most C# queries here use .qhelp).
csharp/src/security/CWE-862/MissingAccessControl.md
# Missing function level access control
Sensitive actions, such as editing or deleting content, or accessing admin pages, should have authorization checks to ensure that they cannot be used by malicious actors.
This query extends the standard CodeQL query `cs/web/missing-function-level-access-control` by additionally modeling ASP.NET web service operations: any method annotated with `[System.Web.Services.WebMethod]` (ASMX web service operations and ASP.NET page methods) is treated as a remotely invocable action. Web methods whose names indicate a transfer, withdrawal, deposit, update or removal are considered sensitive, in addition to the edit, delete and admin heuristics of the standard query.
## Recommendation
Ensure that proper authorization checks are made for sensitive actions. For ASMX web services, check `Context.User.Identity.IsAuthenticated` or `Context.User.IsInRole(...)`, or protect the service with an authorization attribute or a `<location>` configuration that denies unauthorized users.
## Example
In the following example, any remote caller can transfer funds between arbitrary accounts:
```csharp
[WebMethod]
public string TransferBalance(long from, long to, double amount)
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}
```
The method is fixed by checking that the caller is authenticated (and, ideally, owns the debited account):
```csharp
[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";
}
```
## References
- OWASP: [Broken Access Control](https://owasp.org/Top10/A01_2021-Broken_Access_Control/).
- Microsoft Learn: [WebMethodAttribute Class](https://learn.microsoft.com/en-us/dotnet/api/system.web.services.webmethodattribute).
- Common Weakness Enumeration: [CWE-285](https://cwe.mitre.org/data/definitions/285.html), [CWE-284](https://cwe.mitre.org/data/definitions/284.html), [CWE-862](https://cwe.mitre.org/data/definitions/862.html).csharp/src/security/CWE-862/MissingAccessControl.ql
/**
* @name Missing function level access control
* @description Sensitive actions should have authorization checks to prevent them from being used by malicious actors.
* @kind problem
* @problem.severity warning
* @security-severity 7.5
* @precision medium
* @id cs/web/missing-function-level-access-control
* @tags security
* 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 getWebMethodAuthBaseType(ValueOrRefType t) {
result = t.getABaseType().getUnboundDeclaration()
}
private predicate isMvcAuthorizeAttribute(Attribute attr) {
attr.getType().getABaseType*().hasFullyQualifiedName("System.Web.Mvc", "AuthorizeAttribute")
}
private predicate isOtherAuthAttribute(Attribute attr) {
attr.getType().getABaseType*().getName().toLowerCase().matches("%auth%") and
not isMvcAuthorizeAttribute(attr)
}
private predicate hasMvcAuthorizeAttribute(ActionMethod m) {
exists(Attribute attr |
isMvcAuthorizeAttribute(attr) and
(
attr = m.getOverridee*().getAnAttribute()
or
attr = getWebMethodAuthBaseType*(m.getDeclaringType()).getAnAttribute()
)
)
}
private predicate hasOtherAuthAttribute(ActionMethod m) {
exists(Attribute attr |
isOtherAuthAttribute(attr) and
(
attr = m.getOverridee*().getAnAttribute()
or
attr = getWebMethodAuthBaseType*(m.getDeclaringType()).getAnAttribute()
)
)
}
private predicate mvcAuthorizeDoesNotProtectWebMethod(ActionMethod m) {
m instanceof WebMethodActionMethod and
needsAuth(m) and
hasMvcAuthorizeAttribute(m) and
not hasOtherAuthAttribute(m) and
not hasAuthViaCode(m) and
not hasAuthViaXml(m) and
exists(m.getBody().getAChildStmt())
}
from Method m
where missingAuth(m) or mvcAuthorizeDoesNotProtectWebMethod(m)
select m, "This action is missing an authorization check."csharp/src/security/CWE-862/WebMethodActions.qll
/**
* Provides a model of ASP.NET ASMX web service operations (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 service operations that move or change funds or records
* (for example `TransferBalance`) 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)(_.*)?")
}
}csharp/test/security/CWE-862/MissingAccessControl/AccountService.asmx.cs
using System.Web.Mvc;
using System.Web.Services;
namespace Bank.WebServices
{
[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) // $ Alert
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}
// BAD: edit operation exposed as a web method without authorization.
[WebMethod]
public void DeleteAccount(long accountId) // $ Alert
{
Remove(accountId);
}
// 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);
}
// BAD: MVC authorization attributes do not protect ASMX operations.
[WebMethod]
[Authorize]
public string TransferBalanceAuthorized(long from, long to, double amount) // $ Alert
{
Withdraw(from, amount);
Deposit(to, amount);
return "OK";
}
// Not flagged: read-only operation, the query only targets sensitive (state-changing / admin) actions.
[WebMethod]
public long[] GetUserAccounts(long userId)
{
return new long[] { userId };
}
// 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) // $ Alert
{
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) // $ Alert
{
System.Console.WriteLine(from + to + amount);
}
}
}csharp/test/security/CWE-862/MissingAccessControl/MissingAccessControl.expected
| AccountService.asmx.cs:11:23:11:37 | TransferBalance | This action is missing an authorization check. |
| AccountService.asmx.cs:20:21:20:33 | DeleteAccount | This action is missing an authorization check. |
| AccountService.asmx.cs:47:23:47:47 | TransferBalanceAuthorized | This action is missing an authorization check. |
| AccountService.asmx.cs:84:21:84:30 | DeleteUser | This action is missing an authorization check. |
| AccountService.asmx.cs:94:28:94:40 | TransferFunds | This action is missing an authorization check. |
| App_Code/WebService.cs:46:31:46:45 | TransferBalance | This action is missing an authorization check. |
csharp/test/security/CWE-862/MissingAccessControl/MissingAccessControl.qlref
query: MissingAccessControl/MissingAccessControl.ql
postprocess: utils/test/InlineExpectationsTestQuery.ql
csharp/test/security/CWE-862/MissingAccessControl/Stubs.cs
// Minimal stubs for the ASP.NET (System.Web) types used by the tests.
namespace System.Web
{
public class HttpContext
{
public System.Security.Principal.IPrincipal User => throw null;
}
}
namespace System.Web.Services
{
public class WebMethodAttribute : System.Attribute
{
public string Description { get; set; }
}
public class WebServiceAttribute : System.Attribute
{
public string Namespace { get; set; }
public string Description { get; set; }
}
public class WebService
{
public System.Web.HttpContext Context => throw null;
}
}
namespace System.Web.UI
{
public class Page
{
public System.Web.HttpContext Context => throw null;
}
}
namespace System.Web.Mvc
{
public class AuthorizeAttribute : System.Attribute { }
}csharp/test/security/CWE-862/MissingAccessControl/App_Code/WebService.cs
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;
}
}
// Not flagged: 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;
}
// Not flagged: 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) // $ Alert
{
TransferResult result = new TransferResult();
result.Success = transDetails.debitAccount != transDetails.creditAccount;
result.Message = "$" + transDetails.transferAmount + " transferred.";
return result;
}
}
}csharp/test/security/CWE-862/MissingAccessControl/WebConfig/ConfiguredService.cs
using System.Web.Mvc;
using System.Web.Services;
namespace Bank.WebServices
{
[Authorize]
public class ConfiguredService : WebService
{
[WebMethod]
public void TransferFunds()
{
System.Console.WriteLine("transfer");
}
}
}csharp/test/security/CWE-862/MissingAccessControl/WebConfig/Web.config
<configuration>
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>How to check it
- Port the files and run the test of the new directory. Compare the results with what the draft expects (its
inline$ Alertand$ MISSING: Alertcomments and its.expectedfile), and explain every difference in
the pull request. - Then run the other gates of the agent profile: format, compile with warnings as errors, query help, suite
selection and id uniqueness.
Rules for the change
- Add only the new query, its library file if it has one, its query help and its test directory.
- Pull request title:
[New Query - <id>] - <what it detects>.
Activity