[Authorize]
attribute with the use of an [AllowAnonymous]
attribute at the class or method level.[Authorize]
attribute to a class or a method. Additionally, the specified authorization requirement of an application class or method can be bypassed by adding the [AllowAnonymous]
attribute. When both are specified, the [AllowAnonymous]
attribute takes precedence and bypasses the [Authorize]
attribute. This can result in the arbitrary and anonymous access of sensitive data and actions by an attacker.[AllowAnonymous]
attribute at the class level overriding an [Authorize]
attribute set on the method. The secretAction()
method does not require authorization despite having the [Authorize]
attribute.Example 2: The following example shows the
...
[AllowAnonymous]
public class Authorization_Test
{
[Authorize]
public IActionResult secretAction()
{
}
}
...
[AllowAnonymous]
attribute at the class level of a superclass overriding an [Authorize]
attribute set on the method of a subclass. Due to the inherited class Inherit_AA
having the [AllowAnonymous]
attribute, the secretAction()
method does not require authorization despite specifying the [Authorize]
attribute.Example 3: The following shows the
...
[AllowAnonymous]
public abstract class Inherit_AA
{
}
public class Authorization_Test:Inherit_AA
{
[Authorize]
public IActionResult secretAction()
{
}
}
...
[AllowAnonymous]
attribute overriding an [Authorize]
attribute at the method level with inheritance. Due to the inherited method secretAction()
having the [AllowAnonymous]
attribute, the secretAction()
method does not require authorization despite specifying the [Authorize]
attribute on the overriding method.
...
public abstract class Inherit_AA
{
[AllowAnonymous]
public abstract IActionResult secretAction()
{
}
}
public class Authorization_Test:Inherit_AA
{
[Authorize]
public override IActionResult secretAction()
{
}
}
...
BinaryFormatter
class.BinaryFormatter
class to turn an object into a binary stream that contains both the object itself and the necessary metadata to reconstruct it during deserialization.BinaryFormatter
class can lead to insecure deserialization scenarios where attackers can execute arbitrary code, abuse application logic, or trigger a denial of service condition. BinaryFormatter
type is dangerous and is not recommended for data processing, as it cannot be made secure.BinaryFormatter
class by setting the config property EnableUnsafeBinaryFormatterSerialization
to true
in the runtimeConfig.json file.
...
AppContext.SetSwitch("System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization", true);
...
BinaryFormatter
class.BinaryFormatter
class to turn an object into a binary stream that contains both the object itself and the necessary metadata to reconstruct it during deserialization.BinaryFormatter
class can lead to insecure deserialization scenarios where attackers can execute arbitrary code, abuse application logic, or trigger a denial of service condition. BinaryFormatter
class is dangerous and is not recommended for data processing, as it cannot be made secure.BinaryFormatter
class by setting the config property EnableUnsafeBinaryFormatterSerialization
to true
in the runtimeConfig.json file.
{
"configProperties": {
"System.Runtime.Serialization.EnableUnsafeBinaryFormatterSerialization": true
}
}
DirectoryEntry de
using an anonymous bind.
...
de = new DirectoryEntry("LDAP://ad.example.com:389/ou=People,dc=example,dc=com");
...
de
will be performed without authentication and access control. An attacker may be able to manipulate one of these queries in an unexpected way to gain access to records that would otherwise be protected by the directory's access control mechanism.ldap_simple_bind_s()
to bind anonymously to an LDAP directory.
...
rc = ldap_simple_bind_s( ld, NULL, NULL );
if ( rc != LDAP_SUCCESS ) {
...
}
...
ld
will be performed without authentication and access control. An attacker may be able to manipulate one of these queries in an unexpected way to gain access to records that would otherwise be protected by the directory's access control mechanism.DirContext ctx
using an anonymous bind.
...
env.put(Context.SECURITY_AUTHENTICATION, "none");
DirContext ctx = new InitialDirContext(env);
...
ctx
will be performed without authentication and access control. An attacker may be able to manipulate one of these queries in an unexpected way to gain access to records that would otherwise be protected by the directory's access control mechanism.
...
$ldapbind = ldap_bind ($ldap, $dn, $password = "" );
...
DATA: id TYPE i.
...
id = request->get_form_field( 'invoiceID' ).
CONCATENATE `INVOICEID = '` id `'` INTO cl_where.
SELECT *
FROM invoices
INTO CORRESPONDING FIELDS OF TABLE itab_invoices
WHERE (cl_where).
ENDSELECT.
...
ID
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
var params:Object = LoaderInfo(this.root.loaderInfo).parameters;
var id:int = int(Number(params["invoiceID"]));
var query:String = "SELECT * FROM invoices WHERE id = :id";
stmt.sqlConnection = conn;
stmt.text = query;
stmt.parameters[":id"] = id;
stmt.execute();
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.inputID
value is originated from a pre-defined list, and a bind variable helps to prevent SOQL/SOSL injection.
...
result = [SELECT Name, Phone FROM Contact WHERE (IsDeleted = false AND Id=:inputID)];
...
inputID
. If the attacker is able to bypass the interface and send a request with a different value he will have access to other contact information. Since the code in this example does not check to ensure that the user has permission to access the requested contact, it will display any contact, even if the user is not authorized to see it.
...
int16 id = System.Convert.ToInt16(invoiceID.Text);
var invoice = OrderSystem.getInvoices()
.Where(new Invoice { invoiceID = id });
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
CMyRecordset rs(&dbms);
rs.PrepareSQL("SELECT * FROM invoices WHERE id = ?");
rs.SetParam_int(0,atoi(r.Lookup("invoiceID").c_str()));
rs.SafeExecuteSQL();
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
ACCEPT ID.
EXEC SQL
DECLARE C1 CURSOR FOR
SELECT INVNO, INVDATE, INVTOTAL
FROM INVOICES
WHERE INVOICEID = :ID
END-EXEC.
...
ID
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.deleteDatabase
method that contains a user-controlled database name can allow an attacker to delete any database.
...
id := request.FormValue("invoiceID")
query := "SELECT * FROM invoices WHERE id = ?";
rows, err := db.Query(query, id)
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
id = Integer.decode(request.getParameter("invoiceID"));
String query = "SELECT * FROM invoices WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setInt(1, id);
ResultSet results = stmt.execute();
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.Example 1
to the Android platform.
...
String id = this.getIntent().getExtras().getString("invoiceID");
String query = "SELECT * FROM invoices WHERE id = ?";
SQLiteDatabase db = this.openOrCreateDatabase("DB", MODE_PRIVATE, null);
Cursor c = db.rawQuery(query, new Object[]{id});
...
...
var id = document.form.invoiceID.value;
var query = "SELECT * FROM invoices WHERE id = ?";
db.transaction(function (tx) {
tx.executeSql(query,[id]);
}
)
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Invoices" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(id = %@)", invoiceId.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
status.text = @"No records found.";
} else {
matches = [objects objectAtIndex:0];
invoiceReferenceNumber.text = [matches valueForKey:@"invRefNum"];
orderNumber.text = [matches valueForKey:@"orderNumber"];
status.text = [NSString stringWithFormat:@"%d records found", [objects count]];
}
[request release];
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
$id = $_POST['id'];
$query = "SELECT * FROM invoices WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('ss',$id);
$stmt->execute();
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
procedure get_item (
itm_cv IN OUT ItmCurTyp,
id in varchar2)
is
open itm_cv for ' SELECT * FROM items WHERE ' ||
'invoiceID = :invid' ||
using id;
end get_item;
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
id = request.POST['id']
c = db.cursor()
stmt = c.execute("SELECT * FROM invoices WHERE id = %s", (id,))
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
id = req['invoiceID'].respond_to(:to_int)
query = "SELECT * FROM invoices WHERE id=?"
stmt = conn.prepare(query)
stmt.execute(id)
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
def searchInvoice(value:String) = Action.async { implicit request =>
val result: Future[Seq[Invoice]] = db.run {
sql"select * from invoices where id=$value".as[Invoice]
}
...
}
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Invoices", inManagedObjectContext: managedContext)
fetchRequest.entity = entity
let pred : NSPredicate = NSPredicate(format:"(id = %@)", invoiceId.text)
fetchRequest.setPredicate = pred
do {
let results = try managedContext.executeFetchRequest(fetchRequest)
let result : NSManagedObject = results.first!
invoiceReferenceNumber.text = result.valueForKey("invRefNum")
orderNumber.text = result.valueForKey("orderNumber")
status.text = "\(results.count) records found"
} catch let error as NSError {
print("Error \(error)")
}
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.
...
id = Request.Form("invoiceID")
strSQL = "SELECT * FROM invoices WHERE id = ?"
objADOCommand.CommandText = strSQL
objADOCommand.CommandType = adCmdText
set objADOParameter = objADOCommand.CreateParameter("id" , adString, adParamInput, 0, 0)
objADOCommand.Parameters("id") = id
...
id
. Although the interface generates a list of invoice identifiers that belong to the current user, an attacker might bypass this interface to request any desired invoice. Because the code in this example does not check to ensure that the user has permission to access the requested invoice, it will display any invoice, even if it does not belong to the current user.aspnet:UseLegacyFormsAuthenticationTicketCompatibility
setting to allow unvalidated input to be passed to the native APIs and may lead to an attacker being able to bypass authentication. An attacker who successfully exploites this vulnerability would be able to bypass ASP.NET forms authentication for any known username without its password. The attacker could then take any action in the context of the victim user, including executing arbitrary commands on the site.aspnet:UseLegacyFormsAuthenticationTicketCompatibility
is set to true
.
...
<appSettings>
<add key="aspnet:UseLegacyFormsAuthenticationTicketCompatibility" value="true" />
</appSettings>
...
static string AllowlistVerify(string name) {
Regex pattern = new Regex(@"^[a-zA-Z\-\.']+$");
if (pattern.IsMatch(name)) {
return name;
}
return null;
}
...
string verifiedName = AllowlistVerify(managerName.Text.trim());
if(verifiedName != null) {
DirectorySearcher src = new DirectorySearcher("(manager=" + verifiedName + ")");
src.SearchRoot = de;
src.SearchScope = SearchScope.Subtree;
foreach(SearchResult res in src.FindAll()) {
...
}
}
empName
. Although the interface automatically submits the employee ID of the current user, an attacker could submit an alternative value as part of a malicious request. Because the code in this example executes the query under an anonymous bind, it will return the directory entry for any valid employee ID, regardless of the identity of the current authenticated user.
char* allowlist_verify(char* name) {
const char *error;
int errOffset;
char* regex = "^[a-zA-Z\\-\\.']+$";
pcre* re = pcre_compile(regex, 0, &err, &errOffset, NULL);
int rc = pcre_exec(re, NULL, name, strlen(name), 0, 0, NULL, 0);
if (rc == 1)
return name;
return NULL;
}
...
fgets(managerName, sizeof(managerName), socket);
char* verified_name = allowlist_verify(managerName);
if(verified_name != NULL) {
snprintf(filter, sizeof(filter), "(manager=%s)", verified_name);
if ( ( rc = ldap_search_ext_s( ld, FIND_DN, LDAP_SCOPE_BASE,
filter, NULL, 0, NULL, NULL, LDAP_NO_LIMIT,
LDAP_NO_LIMIT, &result ) ) == LDAP_SUCCESS ) {
...
}
}
username
. Because the code in this example executes the query under an anonymous bind, it will return the directory entry for any valid employee ID, regardless of the identity of the current authenticated user.
...
env.put(Context.SECURITY_AUTHENTICATION, "none");
DirContext ctx = new InitialDirContext(env);
String empID = request.getParameter("empID");
try
{
int id = Integer.parseInt(empID);
BasicAttribute attr = new BasicAttribute("empID", empID);
NamingEnumeration employee =
ctx.search("ou=People,dc=example,dc=com",attr);
...
empID
. Although the interface automatically submits the employee ID of the current user, an attacker could submit an alternative value as part of a malicious request. Because the code in this example executes the query under an anonymous bind, it will return the directory entry for any valid employee ID, regardless of the identity of the current authenticated user.DangerousEnableCompression
to true
in order to enable the 'per-message-deflate' extension:Example 2: The following code uses
app.Run(async context => {
using var websocket = await context.WebSockets.AcceptWebSocketAsync(new WebSocketAcceptContext() { DangerousEnableCompression = true });
await websocket.SendAsync(...);
await websocket.ReceiveAsync(...);
await websocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, default);
});
DangerousDeflateOptions
to set the options for the 'per-message-deflate' extension:
using ClientWebSocket ws = new() {
Options = {
CollectHttpResponseDetails = true,
DangerousDeflateOptions = new WebSocketDeflateOptions() {
ClientMaxWindowBits = 10,
ServerMaxWindowBits = 10
}
}
};
HttpSessionState
attribute can damage application reliability.HttpSessionState
object, its attributes and any objects they reference in memory. This model limits active session state to what can be accommodated by the system memory of a single machine. In order to expand capacity beyond these limitations, servers are frequently configured to persistent session state information, which both expands capacity and permits the replication across multiple machines to improve overall performance. In order to persist its session state, the server must serialize the HttpSessionState
object, which requires that all objects stored in it be serializable.[Serializable]
attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable
interface.
public class DataGlob {
String GlobName;
String GlobValue;
public void AddToSession(HttpSessionState session) {
session["glob"] = this;
}
}
...
<script src="http://applicationserver.application.com/lib/jquery/jquery-1.4.2.js" type="text/javascript"></script>
...
ModelState.IsValid
to check if model validation passes.WindowsIdentity.Impersonate()
method.
using System.Security.Principal;
...
//Get the identity of the current user
IIdentity contextId = HttpContext.Current.User.Identity;
WindowsIdentity userId = (WindowsIdentity)contextId;
//Temporarily impersonate
WindowsImpersonationContext imp = userId.Impersonate();
//Perform tasks using the caller's security context
DoSecuritySensitiveTasks();
//Clean up and restore our old security context
impersonate.Undo();
Example 1
impersonates the current user's security context and uses it to perform a privileged operation. After calling DoSecuritySensitiveTasks()
, the code attempts to restore the original security context, but if DoSecuritySensitiveTasks()
throws an exception, the Undo()
method will never be called and the program will continue to use the impersonated security context.UseCookiePolicy()
method adds the cookie policy middleware to the middleware pipeline, allowing for customized cookie policies. When specified in the wrong order as shown, any cookie policy stated by the programmer will be ignored.
...
var builder = WebApplication.CreateBuilder(...);
var app = builder.Build(...);
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
...
}
app.UseCookiePolicy();
...
UseHttpsRedirection()
method adds HTTPS redirection middleware to the middleware pipeline, which allows for redirection of insecure HTTP requests to a secure HTTPS request. When specified in the wrong order as shown, no meaningful HTTPS redirection will occur before processing the request through the middleware listed before the redirect. This will allow for HTTP requests to be processed by the application before being redirected to the secure HTTPS connection.
...
var builder = WebApplication.CreateBuilder(...);
var app = builder.Build(...);
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
...
}
app.UseHttpsRedirection();
...
UseHttpLogging()
method adds HTTP logging middleware to the middleware pipeline which allows middleware components to log. When specified in the wrong order as shown, no middleware added to the pipeline before the call to UseHttpLogging()
will log.Example 2: The
...
var builder = WebApplication.CreateBuilder(...);
var app = builder.Build(...);
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
...
}
app.UseHttpLogging();
...
UseWC3Logging()
method adds W3C logging middleware to the middleware pipeline which allows middleware components to log. When specified in the wrong order as shown, no middleware added to the pipeline before the call to UseWC3Logging()
will log.
...
var builder = WebApplication.CreateBuilder(...);
var app = builder.Build(...);
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
...
}
app.UseWC3Logging();
...
None
disables the entire certification validation process, which exposes the application to Man-in-the-Middle attacks. This mode should never be used in production environments.debug
attribute of the <compilation>
tag defines whether compiled binaries should include debugging information.Example 2: The following server page directive disables event validation.
...
<system.web>
...
<pages enableEventValidation="false">
...
</pages>
</system.web>
<%@ Page ... EnableEventValidation="false" %>
...
<configuration>
<system.web>
<authentication>
<forms
timeout="60" />
</authentication>
</system.web>
</configuration>
...