Skip to content

Commit 747113d

Browse files
committed
Added labs
0 parents  commit 747113d

8 files changed

+379
-0
lines changed

2.1 Lab - Recon.md

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
Let's see what we can figure out about a company, just by poking around.
2+
3+
Visit [dnsdumpster](https://dnsdumpster.com/) and query the main domain for your company
4+
5+
* What hosts are there? What software are they running?
6+
* Does any of the detected version have a vulnerability?
7+
*You can google for the software and version to find known issues*
8+
* Can you connect to ports that you shouldn't be able to?
9+
* Are there any tests sites online?
10+
* What cloud or hosting providers are used?
11+
* Where is the company e-mail hosted?
12+
13+
Browse around the site
14+
* What technologies does the company use? Good sources are job openings and linkedIn profiles of employees.
15+
* Are there active parts on the site? What APIs do they call?
16+
* What CMS does the site use? Is it WordPress?

3.1 Lab - Code review.md

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# Lab - Code review
2+
3+
Consider the following login method. Find (at least) 3 points to improve in this code
4+
```csharp
5+
public static async Task<IResult> Login([FromBody]LoginRequest model, [FromServices]Database db)
6+
{
7+
// We don't store plaintext passwords in the database, obviously
8+
var hashedPassword = Users.HashPassword(model.Password);
9+
var command = new SQLiteCommand(
10+
// Use parameterized queries to prevent SQL injection
11+
"SELECT * FROM users WHERE name = @name and hashedpassword = @pw",
12+
db.Db);
13+
14+
command.Parameters.AddWithValue("@name", model.Name);
15+
command.Parameters.AddWithValue("@pw", hashedPassword);
16+
17+
await using (var reader = command.ExecuteReader())
18+
{
19+
while (reader.Read())
20+
{
21+
return Results.Text($"User {reader["name"] as string} logged in.");
22+
}
23+
}
24+
return Results.Unauthorized();
25+
}
26+
```

3.2 Lab - Bad API.md

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Lab : Bad API
2+
3+
The [BadAPI github repo](https://github.com/alanta/BadApi) demonstrates a bunch of the common OWASP issues. It also has some tests. We're going to add some more tests to validate that improved version of the code behaves correctly.
4+
5+
The test should be an out-side-in test; simulate calling the API and verify that the response is correct. This demonstrated in the test called []()
6+
7+
Keep in mind that good tests follow a couple of guidelines:
8+
* Use the Arrange / Assert / Act pattern : test only one thing at a time
9+
* Don't use branching logic
10+
* Keep the test short
11+
* Test names should use human readable language to express what the test is doing
12+
13+
Assignment:
14+
* Pick one of the scenarios
15+
* Define what would be considered a _good_ response to various inputs
16+
* Implement these scenarios as tests
17+

5.1 Lab - Caesars cipher.md

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Lab: Caesar's cipher
2+
3+
Use [CyberChef](https://gchq.github.io/CyberChef/#recipe=ROT13(true,true,false,12)) to 'encrypt' a chunk of text, use the `ROT13` operation. (See the end of this lab for an example text)
4+
5+
* Play around with the settings to see what changes
6+
* Change one or more letters in the input, what does that do to the output?
7+
8+
## Cracking Caesars cipher
9+
It took 800 years before the vulnerability of this cipher was widely known and described. Let's see if we can do better!
10+
11+
* Can you figure out how to crack it before trying the next step?
12+
---
13+
* Add a `Frequency Distribution` operation after the `ROT13` Operation.
14+
*The chart show how often each value appears in the encoded text*
15+
* Now increase and decrease the `Amount` field, observe what happens to the frequency distribution
16+
17+
### Explanation
18+
Each language has a characteristic pattern letter frequency. It may differ a bit but given enough text, the spikes will always be the same. For Dutch, the letter e is by far the most common letter.
19+
20+
* What would be a way to improve the strength of this 'encryption'
21+
22+
### Sample text
23+
24+
```
25+
Duurzaamheid in ons dagelijks leven
26+
27+
In de moderne wereld is duurzaamheid een steeds belangrijker onderwerp geworden. De opwarming van de aarde, de afname van biodiversiteit en de uitputting van natuurlijke hulpbronnen dwingen ons om bewuster na te denken over onze keuzes. Duurzaamheid is niet langer alleen een verantwoordelijkheid van overheden en grote bedrijven, maar ook van ons als individuen.
28+
29+
Een van de eenvoudigste manieren om bij te dragen aan duurzaamheid is door bewuster om te gaan met energie. Door bijvoorbeeld LED-lampen te gebruiken, elektrische apparaten uit te schakelen wanneer ze niet in gebruik zijn, en gebruik te maken van hernieuwbare energiebronnen zoals zonnepanelen, kunnen we onze ecologische voetafdruk aanzienlijk verkleinen. Het verminderen van energieverspilling heeft niet alleen een positief effect op het milieu, maar ook op onze portemonnee.
30+
31+
Daarnaast speelt het verminderen van afval een cruciale rol. Plasticvervuiling is wereldwijd een groot probleem geworden. We kunnen onze bijdrage aan dit probleem verkleinen door herbruikbare producten te gebruiken, zoals boodschappentassen, flessen en rietjes. Het scheiden van afval en het recyclen van materialen helpt ook om de afvalberg te verminderen. Bovendien kunnen we composteren om organisch afval om te zetten in nuttige voedingsstoffen voor de tuin.
32+
33+
Een ander belangrijk aspect van duurzaamheid is bewuste consumptie. De keuzes die we maken met betrekking tot voedsel en kleding hebben een grote impact op het milieu. Door lokaal en seizoensgebonden voedsel te kopen, ondersteunen we niet alleen lokale boeren, maar verminderen we ook de CO2-uitstoot die gepaard gaat met transport. Het kiezen voor biologische producten zonder schadelijke pesticiden draagt bij aan het behoud van de biodiversiteit.
34+
35+
Wat kleding betreft, is de zogenaamde "fast fashion"-industrie een grote vervuiler. Door te investeren in kwalitatief hoogwaardige kledingstukken die langer meegaan, tweedehands kleding te kopen, of kapotte kleding te repareren in plaats van weg te gooien, kunnen we de negatieve impact van onze kledingkeuzes verminderen.
36+
37+
Ook mobiliteit speelt een grote rol in duurzaamheid. Door vaker de fiets te pakken, gebruik te maken van het openbaar vervoer, of elektrisch te rijden, kunnen we bijdragen aan schonere lucht en minder verkeersopstoppingen. Daarnaast is het delen van ritten via carpooling een effectieve manier om het aantal voertuigen op de weg te verminderen.
38+
39+
Ten slotte is bewustwording en educatie essentieel. Het informeren van vrienden, familie en de gemeenschap over het belang van duurzaamheid kan leiden tot een groter collectief effect. Kleine acties van velen maken immers een groot verschil.
40+
41+
Duurzaamheid is geen modewoord, maar een noodzaak. Door kleine veranderingen in onze dagelijkse gewoontes te maken, kunnen we een enorme impact hebben op de planeet. Samen kunnen we een meer duurzame en leefbare toekomst creëren voor onszelf en voor de generaties die nog komen.
42+
```

6.1 Lab - Your own CA.md

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
## 1. Setup your own CA
2+
* Install [Step CLI](https://smallstep.com/docs/step-cli/installation/)
3+
> You may need to restart your terminal after installing this tool to update the path variable. If you have Chocolatey installed, you can run `refreshenv` to update the path variable.
4+
5+
* Open a powershell terminal, preferably PowerShell 7
6+
* Create a new folder for this lab and cd into it.
7+
* Initialize your CA.
8+
9+
> 👉️ Make sure to keep the password, we'll need it again in the next steps.
10+
```powershell
11+
step ca init --deployment-type standalone --name MyLocalDomain --dns mycompany.local --address 127.0.0.1:443 --provisioner MyCompany
12+
```
13+
This generates a root and intermediate certificate under the `.step/certs` folder in your home directory. The corresponding keys are stored in the `.step/secrets` folder.
14+
15+
Use [CyberChef](https://gchq.github.io/CyberChef/) to explore the certificate (_Parse X.509 Certificate_).
16+
17+
You should be able to see all the parts of the certificate; it's extensions, it's public key and signature.
18+
19+
🔍️ What type of key does the certificate use?
20+
🔍️ What are the differences between the root and intermediate certificate?
21+
22+
## 2. Generate leaf certificates
23+
24+
```powershell
25+
step certificate create api1.localhost api1.crt api1.key `
26+
--profile leaf --not-after=48h `
27+
--ca ~/.step/certs/intermediate_ca.crt `
28+
--ca-key ~/.step/secrets/intermediate_ca_key
29+
```
30+
31+
Use [CyberChef](https://gchq.github.io/CyberChef/) to explore the leaf certificate (_Parse X.509 Certificate_).
32+
33+
🔍️ What are the differences between the CA certs and the leaf cert?
34+

6.2 Lab - TLS.md

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
## 1. Create a pfx file
3+
4+
For ASP.NET it's easiest to create a PKCS#12 file from the key and the certificate chain. To build the chain, we need to include both the intermediate and the root ca cert in the file. Make sure you set a password for the output file.
5+
```powershell
6+
step certificate p12 api1.pfx api1.crt api1.key `
7+
--ca ~/.step/certs/intermediate_ca.crt `
8+
--ca ~/.step/certs/root_ca.crt
9+
```
10+
11+
### 2. Create a server
12+
13+
Create a new dotnet web api:
14+
```
15+
dotnet new webapi --name server
16+
```
17+
18+
Edit the `appsettings.development.json` file to add the following section to instruct the built-in web server, Kestrel, to use our certificate
19+
```json
20+
"Kestrel": {
21+
"Certificates": {
22+
"Default": {
23+
"Path": "../api1.pfx"
24+
}
25+
}
26+
}
27+
```
28+
Since we've set a password on the certificate file, we need to specify that as well.
29+
We're obviously NOT going to store the certificate password in source code. Instead we'll use [user secrets](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets)
30+
31+
Change into the folder where the server project is: `cd server`
32+
33+
First, initialize user secrets for the project:
34+
```powershell
35+
dotnet user-secrets init
36+
```
37+
Then store the password for the certificate:
38+
```powershell
39+
dotnet user-secrets set Kestrel:Certificates:Default:Password TopSecret
40+
```
41+
Make sure you replace `TopSecret` with the password for your .pfx file.
42+
43+
You should now be able to run the project:
44+
```powershell
45+
dotnet run --launch-profile https
46+
```
47+
48+
The output shows you what port is used for HTTPS, open a browser and navigate to https://api1.localhost:PORT/weatherforecast
49+
50+
`PORT` is different for each project you create, so you'll have to look at the console output to find the https port.
51+
52+
Your browser will show a warning. You should be able to bypass this using the `advanced` button.
53+
54+
🔍️ Inspect the certificate by clicking on the lock icon.
55+
56+
Alternatively, you can use `curl` to view the certificate:
57+
58+
``` powershell
59+
curl -v https://api1.localhost:PORT/weatherforecast --insecure
60+
```
61+
62+
🔍️ Why is the certificate not accepted by the browser or curl? What would be a way to resolve the issue?
63+

6.3 Lab - mTLS.md

+153
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
2+
Setting up mTLS with a client certificate is a bit more involved than just using a server certificate. In this lab, we'll create a client certificate and use it to authenticate the client to the server, and vice versa.
3+
4+
## 1. Create a pfx file
5+
6+
Go back to the CA you created earlier. Generate another certificate:
7+
8+
```powershell
9+
step certificate create api1.localhost app.crt app.key `
10+
--profile leaf --not-after=48h `
11+
--ca ./certs/intermediate_ca.crt `
12+
--ca-key ./secrets/intermediate_ca_key
13+
```
14+
15+
```powershell
16+
step certificate p12 app.pfx api1.crt app.key `
17+
--ca ~/.step/certs/intermediate_ca.crt `
18+
--ca ~/.step/certs/root_ca.crt
19+
```
20+
21+
### 2. Create a client application
22+
23+
Create a new dotnet console application:
24+
```
25+
dotnet new console --name client
26+
```
27+
28+
We'll use user secrets to store the password for the certificate.
29+
30+
Change into the folder where the server project is: `cd server`
31+
32+
First, initialize user secrets for the project:
33+
```powershell
34+
dotnet user-secrets init
35+
```
36+
Then store the password for the certificate:
37+
```powershell
38+
dotnet user-secrets set Certificates:Password TopSecret
39+
```
40+
Make sure you replace `TopSecret` with the password for your .pfx file.
41+
42+
### 3. Load the certificate
43+
44+
This is a simple console application so we need to setup the configuration to get the password from user secrets.
45+
46+
Add the following packages to the project:
47+
```
48+
Microsoft.Extensions.Configuration
49+
Microsoft.Extensions.Configuration.Binder
50+
Microsoft.Extensions.Configuration.EnvironmentVariables
51+
Microsoft.Extensions.Configuration.Json
52+
Microsoft.Extensions.Configuration.UserSecrets
53+
```
54+
55+
Then add the following code to the `Program.cs` file:
56+
57+
```csharp
58+
using System.Net.Security;
59+
using System.Security.Cryptography.X509Certificates;
60+
using Microsoft.Extensions.Configuration;
61+
62+
var configuration = new ConfigurationBuilder()
63+
.SetBasePath(Directory.GetCurrentDirectory())
64+
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
65+
.AddEnvironmentVariables()
66+
.AddUserSecrets<Program>()
67+
.Build();
68+
69+
// configure the client to use the certificate in ../api2.pfx
70+
var certificateCollection = X509CertificateLoader.LoadPkcs12CollectionFromFile("path_to/app.pfx",
71+
configuration.GetValue<string>("Certificates:Password") ?? throw new InvalidOperationException("Setting Certificates:Password not found in configuration"));
72+
```
73+
74+
👉️ Make sure you update the path to the certificate
75+
76+
Now let's call the server.
77+
78+
```csharp
79+
// Create an HTTP client with the certificate
80+
var client = new HttpClient(new HttpClientHandler
81+
{
82+
ClientCertificateOptions = ClientCertificateOption.Manual,
83+
ClientCertificates = { clientCertificate },
84+
})
85+
{
86+
BaseAddress = new Uri("https://api1.localhost:7033")
87+
};
88+
89+
// Call the server
90+
var forecast= await client.GetAsync("/weatherforecast");
91+
92+
var content = await forecast.Content.ReadAsStringAsync();
93+
94+
// Print the result
95+
Console.WriteLine(content);
96+
```
97+
98+
Now, run the client application and see if you get a response from the server.
99+
100+
🔍️ This fails. The server accepted the client certificate, but the client is not accepting the server certificate. Why is that?
101+
102+
## 4. Accept the server certificate
103+
104+
To accept the server certificate, we could install the root certificate in the trusted root store. However, that is not a workable solution in a production environment where certificates may be rotated frequently.
105+
Instead, we can use a custom certificate validation callback to accept the server certificate.
106+
107+
Add the following code to the `Program.cs` file to get the root and intermediate certificates:
108+
109+
```csharp
110+
var intermediateCaCertificate = certificateCollection.FirstOrDefault(c => c.Subject.Contains("Intermediate"))
111+
?? throw new InvalidOperationException("Intermediate cert not found");
112+
var rootCaCertificate = certificateCollection.FirstOrDefault(c => c.Subject.Contains("Root"))
113+
?? throw new InvalidOperationException("Root cert not found");
114+
```
115+
116+
Then add a `ServerCertificateCustomValidationCallback` to the `HttpClientHandler` to accept the server certificate:
117+
118+
```csharp
119+
ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
120+
{
121+
if (errors == SslPolicyErrors.None)
122+
{
123+
// Basic validation passed, the server used a valid, trusted certificate
124+
return true;
125+
};
126+
127+
bool validateLocalChain = (errors == SslPolicyErrors.RemoteCertificateChainErrors
128+
&& chain!.ChainStatus.Length == 1
129+
&& chain.ChainStatus[0].Status == X509ChainStatusFlags.PartialChain);
130+
131+
if (!validateLocalChain)
132+
{
133+
return false;
134+
}
135+
136+
var customChain = new X509Chain();
137+
// Can't do a revocation check, our CA is not online
138+
customChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
139+
// Our CA is not in the trusted root store
140+
customChain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
141+
142+
// Add the intermediate and root CA to the chain policy
143+
customChain.ChainPolicy.ExtraStore.Add(intermediateCaCertificate);
144+
customChain.ChainPolicy.ExtraStore.Add(rootCaCertificate);
145+
146+
// Validate the server certificate
147+
bool isValid = customChain.Build(cert!);
148+
149+
return isValid;
150+
}
151+
```
152+
153+
🔍️ Take a moment to understand what this code does.

7.1 Lab - Threat modeling.md

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
How would you break into your own application?
2+
What’s the worst thing that can happen?
3+
Is there anything you are secretly worried about?
4+
How would you try to abuse your system?
5+
Are there undocumented workarounds?
6+
If you were an evil version of yourself, what’s the worst you could do?
7+
8+
## What are we working on?
9+
Pick a service or asset to model.
10+
11+
For example:
12+
* An API recently built
13+
* An older system that you worry about
14+
* Something more personal, like your mailbox or bank account
15+
## What can go wrong?
16+
Assess risks and potential impact
17+
18+
* What if the service becomes unresponsive?
19+
* Is there sensitive data? What happens if that data is deleted or exfiltrated?
20+
* What can a bad actor do if he gets in?
21+
22+
## What are we going to do about it?
23+
- Accept: decide that the business impact is acceptable, and document who has chosen to accept the risk
24+
- Eliminate: remove components that make the vulnerability possible
25+
- Mitigate: add checks or controls that reduce the risk impact, or the chances of its occurrence
26+
- Transfer: Transfer risk to an insurer or customer.
27+
28+
## Did we do a good job?

0 commit comments

Comments
 (0)