Reputation: 21
I have an Angular app + NET 8 API together hosted in an IIS site.
I'm trying to implement the Content Security Policy using 'nonce' (number used only once). This means that for each response sent to a client, I have to set a new 'nonce' in the index.html before delivering it.
Is IIS able to generate a new nonce for each HTTP request received and make the replacement in variables inside my index.html, before sending it to the client in the HTTP Response?
I was trying to do it with IIS URL Rewrite Outbound rules. But I couldn't make it so far. I didn't find a way to make the replacement in the index.html, neither the way to autogenerate a nonce for each incoming request.
Upvotes: 0
Views: 185
Reputation: 5225
This is impossible, ulr rewrite cannot modify the content of the file.
The Microsoft URL Rewrite Module enables IIS administrators to create powerful customized rules to map request URLs to friendly URLs that are easier for users to remember and easier for search engines to find.
Upvotes: 0
Reputation: 1354
This isn't really an answer (and is incomplete and un-tested and not sure nonce is the right way to go at all) but you might try adding something like this to program.cs:
app.Use((context, next) =>
{
var requestPath = context.Request.Path.Value;
if (string.Equals(requestPath, "/",
StringComparison.OrdinalIgnoreCase)
|| string.Equals(requestPath, "/index.html",
StringComparison.OrdinalIgnoreCase))
{
using (var rng = RandomNumberGenerator.Create()) {
var nonceBytes = new byte[32];
rng.GetBytes(nonceBytes);
nonce = Convert.ToBase64String(nonceBytes);
context.Response.Cookies.Append("CSP-NONCE",nonce,
new CookieOptions { HttpOnly = false });
}
return next(context);
}
});
Then in angular you'd need to read that cookie. The docs say to use:
bootstrapApplication(AppComponent, {
providers: [{
provide: CSP_NONCE,
useValue: globalThis.myRandomNonceValue
}]
});
But doesn't mention how to set globalThis.myRandomNonceValue. (but you could read the cookie to set that...) Problem is since this is a sort of XSS protection, wouldn't the potential attacker also be able to read that nonce? Because of all the complexity involved here, I think it'd be better just to set the CSP for styles to 'unsafe-inline' and skip the nonce part.
Upvotes: 0