Hacken is vaak een creatieve bedoeling: dat zie je terug in de diversiteit van de onderwerpen.
Volgende week: les pentesten. Zie ook slide SIE.
Wat weten we al?
Herhaling
Minimise attack surface area: restricties aanbrengen in (online)functies
Establish secure defaults: de defaults zijn zo veilig als mogelijk
The principle of least privilege: de lijst met rechten is zo klein als mogelijk maken (access)
The principle of defence in depth: verschillende type security controles (lagen) aanbrengen
Fail securely: zorg dat eventuele fouten niet tot onveilige situaties leiden (o.a. goede detectie / logging)
Don’t trust services: ga er in principe van uit dat third-party (externe) services niet te vertrouwen zijn
Separation of duties: breng een taakscheiding aan (fraude voorkomen)
Avoid security by obscurity: geen zwakke plekken in de beveiliging ‘verstoppen’
Keep security simple: complexe architecturen vergroten de kans op fouten
Fix security issues correctly: security issues (root cause) moeten grondig worden gerepareerd en getest.
Het principe is dat een hacker een URL intypt in de adresbalk van de browser
Of dat hij/zij een tool als Postman gebruikt
De URL heb je zodanig aangepast dat je meer mag dan de bedoeling is
Echt gebeurd: de miljoenennota was op die manier al een paar dagen eerder beschikbaar dan officieel de bedoeling was. Het bestand stond er al maar er was nog geen link gepubliceerd. NOS
Les: geheime URL's bestaan niet! Dwing eerst login af.
Is onmogelijk in onze ORM (EF Core) zolang we niet expliciet SQL schrijven
Is mogelijk met context.Database.ExecuteSqlCommand:
.ExecuteSqlCommand("SELECT * From Stud Where Naam = " + naam)
.ExecuteSqlCommand("SELECT * From Stud Where Naam = {0}", naam)
.ExecuteSqlCommand("SELECT * From Stud Where Naam = @x", new SqlParameter("@x", naam))
Is mogelijk met stored procedures.
CREATE PROCEDURE [dbo].[GetStudents]
@FirstName varchar(50)
AS
BEGIN
SET NOCOUNT ON;
select * from Students where FirstName like @FirstName +'%'
END
dbo is het schema
Herhaling
Bron: sheets SIE
NB: de code hoeft niet opgeslagen te zijn in de database.
@model XSS.Controllers.StudentsController.Resultaten
<!-- Dit zijn de resultaten van de zoekopdracht "Html.Raw(@Model.Zoek)": -->
Dit zijn de resultaten van de zoekopdracht "@Model.Zoek":
<table>
@foreach (var s in Model.Tonen)
{
<tr><td>@s.Id</td><td>@s.Name</td></tr>
}
</table>
<!--
<div id="zoekopdracht" data-untrustedinput="@Model.Zoek" /><div id="output" />
<script>document.getElementById("output").innerHTML =
"U zocht op: " + document.getElementById("zoekopdracht").getAttribute("data-untrustedinput");</script>
-->
Veilig, tenzij je de standaard encoders niet gebruikt (die zetten < om in <), door bijv. HtmlHelper.Raw
In het verleden is ING Direct (2008) bijvoorbeeld kwetsbaar gebleken voor CSRF: Princeton University: “We discovered CSRF vulnerabilities in ING’s site that allowed an attacker to open additional accounts on behalf of a user and transfer funds from a user’s account to the attacker’s account, the research paper noted, adding that SSL did nothing to prevent the attack.”
Herhaling
Kan ook met POST requests:
<h1>Congratulations! You're a Winner!</h1>
<form action="http://rabobank.nl/api/account" method="post">
<input type="hidden" name="Transaction" value="withdraw">
<input type="hidden" name="Amount" value="1000000">
<input type="submit" value="Click to collect your prize!">
</form>
Bij het formulier wordt een server-side gegenereerde token meegestuurd
Deze antiforgery token wordt in het formulier teruggestuurd
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">
Server-side wordt de token gecheckt met [ValidateAntiForgeryToken]:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Betaal(TransactieModel transactie)
{
// ...
}
Wordt automatisch toegevoegd (kijk maar eens in de HTML)
Wordt niet gebruikt bij API calls
Om te voorkomen dat een GET een onbedoeld effect heeft.
Man in the middle attack
Certificaat nodig om te bewijzen dat jij de échte server bent.
Voorbeeld: Russische aanval vanuit een auto buiten het OPCW gebouw in Scheveningen
OWASP principe Defence in depth: beveiliging op database-niveau.
Verschillende database gebruikers:
Administrators
Data analysten
Politie
Reclame bureaus
Hoe?
Database gebruikers/rollen
Encryptie van de database (database level, collumn level, ...)
Views
Pseudonimisatie
Encryptie van de database: ingewikkeld en ORM-afhankelijk
Gegeven een MijnContext met een Student:
[Keyless]
public class AnoniemeStudent
{
public int Id { get; set; }
public double Cijfer { get; set; }
}
View aanmaken in de database:
public partial class editUserDTO : DbMigration
{
public override void Up()
{
MijnContext ctx = new MijnContext();
ctx.Database.ExecuteSqlCommand(
@"CREATE VIEW dbo.AnoniemeStudent
AS SELECT ID, Cijfer
FROM dbo.Student"
);
}
public override void Down()
{
MijnContext ctx = new MijnContext();
ctx.Database.ExecuteSqlCommand("DROP VIEW dbo.AnoniemeStudent");
}
}
Het bijbehorende model:
[Keyless]
public class AnoniemeStudent
{
public int Id { get; set; }
public double Cijfer { get; set; }
}
Migraties zelf aanmaken is toegestaan!
Add-Migration MigrationName -IgnoreChanges
In views is het zelfs mogelijk on bepaalde omstandigheden een insert te doen
Geen zinvolle errors:
Geen app.UseDeveloperExceptionPage();
Geen app.UseDatabaseErrorPage();
Log zo veel mogelijk
Set de log-levels in appsettings.json
Gebruik de ILogger<StudentController> logger dependancy injection
Stel: je wilt je e-mail (bijvoorbeeld gmail) lezen in je browser
Of: je wilt je hotelboeking wijzigen of annuleren
Dit zijn acties die jij graag wilt uitvoeren maar het is niet de bedoeling dat anderen dat ook kunnen (zien)
Daarvoor gebruiken we een heel bekende oplossing: inloggen met een wachtwoord
ASP.NET Core 3.1 kent die mogelijkheid natuurlijk ook, maar je moet wel even het juiste vinkje zetten
Identificatie: vaststellen wie een persoon is.
Authenticatie: Aantonen dat de vastgestelde identiteit correct is.
Wie ben jij?
Authenticatie kan door een derde partij (OAuth): geen extra wachtwoord!
Toegangscontrole (access control): Beperking van wie op welke manier wat kan doen
Autorisatie: Het proces dat vaststelt wat een gebruiker wel en niet kan en mag met de applicatie (rollen/rechten/privileges)
There is a server which manages the user's data. The server is called "Resource Server".
There is a "Client Application" which wants to use the user's data.
Let's prepare a gate to pass the user's data through. The gate is called "API".
The client application requests the user's data.
The resource server returns the user's data.
What if there is a malicious client application?
Even if the client application that requests the user's data is a malicious one, ...
... the resource server returns the user's data.
Even a malicious application can get the user's data.
We need a mechanism to protect the user's data.
In the best practice, an "Access Token" is given to the client application in advance. An access token represents that the said client application has been given permissions to access the user's data.
The client application presents the access token when it requests the user's data.
The resource server extracts the access token that is included in the request, ...
... and confirms that the access token denotes that the client application has permissions to access the user's data.
After the confirmation, the resource server returns the user's data.
To make this mechanism work, an access token must be given to the client application in advance.
Consequently, we need someone who issues access tokens.
Someone who issues access tokens ...
... is called "Authorization Server".
The relationship between a client application and an authorization server is as follows.
An authorization server generates an access token ...
... and issues the access token to a client application.
Let's review what we've learned so far. Characters are an "Authorization Server", a "Client Application" and a "Resource Server".
The authorization server generates an access token ...
... and issues the access token to the client application.
The client application requests the user's data with the access token.
The resource server extracts the access token from the request, ...
... confirms that the access token has permissions to access the user's data ...
... and returns the user's data to the client application.
In the flow above, the first step is access token generation by an authorization server. However, in a real flow, the user is asked before an access token is issued.
First, the client application requests an access token.
Then, the authorization server asks the user whether to grant the requested permissions to the client application.
If the user allows the authorization server to issue an access token to the client application, ...
... the authorization server generates an access token ...
... and issues the access token to the client application.
By the way, pay attention to the part encircled by the yellow ellipse.
The part represents an access token request and a response to the request.
And, it is "OAuth 2.0" that has standardized the part. Details of OAuth 2.0 are described in the technical document, RFC 6749 (The OAuth 2.0 Authorization Framework).
De client logt dus niet in met Google gegevens in de webapplicatie, maar op Google zelf.
De applicatie vertrouwt de “notaris” (in dit geval de Google Identity Provider)
Een Identity provider is een Authorization server
Tokens zijn vaak een beperkte tijd houdbaar
Identity delegation
Google/Facebook/LinkedIn/Twitter/...
ASP.NET Core Identity is een kant-en-klare manier om inloggen/registreren te regelen:
Injection. Injection flaws, such as SQL, NoSQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker’s hostile data can trick the interpreter into executing unintended commands or accessing data without proper authorization.
Broken Authentication. Application functions related to authentication and session management are often implemented incorrectly, allowing attackers to compromise passwords, keys, or session tokens, or to exploit other implementation flaws to assume other users’ identities temporarily or permanently.
Sensitive Data Exposure. Many web applications and APIs do not properly protect sensitive data, such as financial, healthcare, and PII. Attackers may steal or modify such weakly protected data to conduct credit card fraud, identity theft, or other crimes. Sensitive data may be compromised without extra protection, such as encryption at rest or in transit, and requires special precautions when exchanged with the browser.
XML External Entities (XXE). Many older or poorly configured XML processors evaluate external entity references within XML documents. External entities can be used to disclose internal files using the file URI handler, internal file shares, internal port scanning, remote code execution, and denial of service attacks.
Broken Access Control. Restrictions on what authenticated users are allowed to do are often not properly enforced. Attackers can exploit these flaws to access unauthorized functionality and/or data, such as access other users’ accounts, view sensitive files, modify other users’ data, change access rights, etc.
Security Misconfiguration. Security misconfiguration is the most commonly seen issue. This is commonly a result of insecure default configurations, incomplete or ad hoc configurations, open cloud storage, misconfigured HTTP headers, and verbose error messages containing sensitive information. Not only must all operating systems, frameworks, libraries, and applications be securely configured, but they must be patched/upgraded in a timely fashion.
Cross-Site Scripting XSS. XSS flaws occur whenever an application includes untrusted data in a new web page without proper validation or escaping, or updates an existing web page with user-supplied data using a browser API that can create HTML or JavaScript. XSS allows attackers to execute scripts in the victim’s browser which can hijack user sessions, deface web sites, or redirect the user to malicious sites.
Insecure Deserialization. Insecure deserialization often leads to remote code execution. Even if deserialization flaws do not result in remote code execution, they can be used to perform attacks, including replay attacks, injection attacks, and privilege escalation attacks.
Using Components with Known Vulnerabilities. Components, such as libraries, frameworks, and other software modules, run with the same privileges as the application. If a vulnerable component is exploited, such an attack can facilitate serious data loss or server takeover. Applications and APIs using components with known vulnerabilities may undermine application defenses and enable various attacks and impacts.
Insufficient Logging & Monitoring. Insufficient logging and monitoring, coupled with missing or ineffective integration with incident response, allows attackers to further attack systems, maintain persistence, pivot to more systems, and tamper, extract, or destroy data. Most breach studies show time to detect a breach is over 200 days, typically detected by external parties rather than internal processes or monitoring.
Maak een model ToetsResultaat aan met tenminste een StudentNaam en Cijfer. Scaffold de Views en Controllers. Maak op de home-pagina links naar de actions van de ToetsResultaat controller.
Zorg dat mensen zich kunnen registreren als Docent of Student. Maak een knop op de home-pagina waarmee de gebruiker kan wisselen in rol.
Alleen docenten kunnen ToetsResultaten toevoegen en aanpassen. Studenten hebben die optie niet.
Maak een zoek-functie waarmee studenten en docenten kunnen zoeken op studenten en hun resultaten. Maak deze pagina expres kwetsbaar voor SQL-injectie en voor kwetsbaar voor XSS.