Here you can find the slides that accompany my “SPA Secure Coding Guide”, this presentation go through a set of security best practices specially targeted towards developing Angular applications with ASP.Net Web Api backends.
It comes with a WebApi example project available on GitHub that provides several code examples of how to defend yourself. The example app is based on the famous "Tour of Heroes" Angular app used throughout the Angular documentation.
It first introduce general threat modelling before explaining the most current type of attacks Asp.Net Web API are vulnerable to .
It is designed to serve as a secure coding reference guide, to help development teams quickly understand Asp.Net Core secure coding practices.
7. Owasp top 10
• Open Web Security Project
• Top10
• Guidelines
8. OWASP 2017 Top 10 Application Security Risk
1. Injection
2. Broken Authentication
3. Sensitive Data Exposure
4. XML External Entities (XXE)
5. Broken Access Control
6. Security Misconfiguration
7. Cross-Site Scripting (XSS)
8. Insecure Deserialization
9. Using Components with Known Vulnerabilities
10. Insufficient Logging&Monitoring
9. Injection
• Attacker sends text-based attacks that exploits the syntax of their
target interpreter
• Most common: SQL Injection
• Demo checkout ‘sqlinjection-before’
12. Untrusted data everywhere
• Common sources of untrusted data
• HTTP
• Get: URL or Query string
• Post, Put, Delete payload
• Cookies
• Request headers
• Config Files
• Databases
13. Is the application Vulnerable?
• User-supplied data is not validated, filtered, or sanitized by the application.
• Dynamic queries or non-parameterized calls without context-aware escaping are used
directly in the interpreter.
• Hostile data is used within object-relational mapping (ORM) search parameters to extract
additional, sensitive records.
• Hostile data is directly used or concatenated, such that the SQL or command contains
both structure and hostile data in dynamic queries, commands, or stored procedures.
• Some of the more common injections are SQL, NoSQL, OS command, Object Relational
Mapping (ORM), LDAP, and Expression Language (EL) or Object Graph Navigation Library
(OGNL) injection. The concept is identical among all interpreters. Source code review is
the best method of detecting if applications are vulnerable to injections, closely followed
by thorough automated testing of all parameters, headers, URL, cookies, JSON, SOAP,
and XML data inputs. Organizations can include static source (SAST) and dynamic
application test (DAST) tools into the CI/CD pipeline to identify newly introduced
injection flaws prior to production deployment.
14. Mitigations
• Parametrize untrusted data
• Use least privileged accounts
• Never use detailed error messages in production
• Never concatenate string data in your query (also not using stored
procedures)
• Better:
• Validate your data (Whitelisting)
• Respect the REST API design
• Test your API for SqlInjection vulnerabilities with a tool like Havij
15. Broken Authentication
• authentication and session management are often not implemented
correctly, allowing attackers to compromise passwords, keys, or
session tokens, or to exploit other implementation flaws to assume
other users’ identities.
17. Windows Integrated Authentication
• Local Dev=> IISExpress / IIS
• Properties page's Debug
• When Develop
• !Angular CLI Proxy does not support
Windows Integrated Authentication
• Hard to debug
• When deploy:
Windows Authentication = Enable
Anonymous = Disabled!!!
18. Demo: WindowsAuththentication
• Git-checkout WindowsAuthentication
• Create Website on port 7000 in IIS pointing to TOHWebAPI
• Launch IIS – Release
• Test App on http://localhost:7000
• Launch angular app on http://localhost:4200
• dev server => .toh-client>npm start
• App gets 401 Unhaurorized
• Open IIS MMC, enable Anonymous & disable Windows Authentication
• Refresh http://localhost:4200
• Your app runs without any authentication => risk of Security misconfiguration!
19. Authentication ASP.NET Core App
• Windows Authentication
• Pure Intranet
• Only domain users
• Bound to Active Directory
• Token Based Authentication
• Flexible
• Better protection (e.g. 2FA)
20. Token Based Authentication
• JWT
open standard that allows transmitting data between parties as a
JSON object in a compact and secure way.
• Header: meta-info => type, hash algo
• Payload: actual data encoded in claims
• Signature: verify the integrity
• Encoded in Base64
• Authorization based on Bearer token
24. Demo Token Based Auth
• Demo has many vulnerabilities
• Token can be intercepted
• Weak Password
• Password as sole factor
• See guidelines => NIST 800-63
• Authentication is up to client implementation
• What if you want to authorize the app for public data?
• …
Authentication process and system should be made by specialist, don’t
implement Authentication yourself!
25. Best practices to harden your authentication
• Do not ship with anonymous authentication enabled for the entire
app, only allow for specific request when needed.
• When possible enable multi-factor authentication.
• When possible, use authentication system provided by TAO.
• Align password length, complexity, rotation => NIST 800-63.
• Log all login faillures.
• Validate your authentication system/configuration by SECOFF
29. Use HSTS header
• MITM Attack
• Instruct browser to allways use HTTPS => initial request is HTTPS
Add this header: Strict-Transport-Security: max-age=31536000
• Use HTTPS Redirection Middleware (UseHttpsRedirection) to redirect HTTP
requests to HTTPS.
https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-
ssl?view=aspnetcore-2.2&tabs=visual-studio
30. Cross Site Request Forgery (CSRF)
1. User is authenticated (Session Cookie) on initial site.
2. User is directed to Malicious Site.
3. Malicious Site Post data to initial site (e.g. transfer Money)
with sevrets included. It can perform any action that an
authenticated user is allowed to perform.
ASP.NET MVC protect you if you use default setting
https://docs.microsoft.com/en-us/aspnet/core/security/anti-
request-forgery?view=aspnetcore-2.2
Angular also provide basic protection see:
https://angular.io/guide/security
<h1>Congratulations! You're a Winner!</h1>
<form action="http://good-banking-site.com/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>
31. XSS
• enables attackers to inject client-side
scripts into web pages viewed by other
users
• => Using CSP will limit what content can
be run (e.g. no inline js) or from which
domain it can be run.
app.Use(async (context, next) =>
{
context.Response.Headers.Add(
"Content-Security-Policy",
"script-src 'self'; " +
"style-src 'self'; " +
"img-src 'self'");
await next();
});
Hacktivism is meant to call the public's attention to something the hacktivist believes is an important issue or cause, such as freedom of information or human rights. It can also be a way for the hacktivists to express their opposition to something by, for instance, displaying messages or images on the website of an organization they believe is doing something wrong.
Hacktivists are typically individuals, but there are also groups of hacktivists that operate in coordinated efforts, such as Anonymous or LulzSec. The majority of hacktivists work anonymously.
A hacktivist uses the same tools and techniques as a hacker, but does so in order to disrupt services and bring attention to a political or social cause. For example, hacktivists might leave a highly visible message on the homepage of a website that gets a lot of traffic or embodies a point-of-view that is being opposed. Hacktivists also often use denial-of-service(DoS) attacks to disrupt traffic to a particular site.
Typical attacks performed by hacktivists:
Changing the code for websites -- such as government websites -- or software is done to display errors or specific messages to anyone who visits the site or uses the software.
Website mirroring is when hacktivists replicate a legitimate website's content, but with a slightly different URL. This technique is often used to get around censorship that blocks a particular site. If a website has been censored, the hacktivist will duplicate the content and attach it to a different URL on a mirror site so the content is still accessible.
Geo-bombing, in which internet users add a geo-tag to YouTube videos to enable display of the location of the video on Google Earth and Google Maps, has been used by hacktivists to display the location of videos posted by political prisoners and human rights activists.
Blogging anonymously is a tactic used by activists, whistleblowers and journalists. This protects the blogger while providing a platform to speak out about an issue, such as human rights violations and oppressive government regimes.
The use of the software RECAP lets users search for free copies of documents that are otherwise only accessible by paying a fee to the United States federal court database known as PACER (Public Access to Court Electronic Records).
Leaking information is a popular tactic with activists. Typically an insider source will access sensitive or classified information -- which implicates an individual, organization or government agency in some kind of malicious activity -- and make it publicly available. WikiLeaks has become a popular site for publishing leaked data.
Doxing is the gathering of information -- through hacking or social engineering -- about a specific person or organization and making it public. The information is typically sensitive and is sometimes used in extortion schemes.
Denial-of-service attacks and distributed denial-of-service attacks have become popular with hacktivists who use them to prevent users from accessing targeted computer systems, devices or networks. DoS and DDoS attacks flood systems with traffic and overwhelm resources and make them difficult to access.
Online criminals will typical use cyberextortion
Cyberextortion occurs when a website, e-mail server, or computer system is subjected to or threatened with repeated denial of service or other attacks by malicious hackers. These hackers demand money in return for promising to stop the attacks and to offer "protection". According to the Federal Bureau of Investigation, cybercrime extortionists are increasingly attacking corporate websites and networks, crippling their ability to operate and demanding payments to restore their service. More than 20 cases are reported each month to the FBI and many go unreported in order to keep the victim's name out of the public domain. Perpetrators typically use a distributed denial-of-service attack.[11] However, other cyberextortion techniques exist such as doxing extortion and bug poaching.
An example of cyberextortion was the attack on Sony Pictures of 2014.[12]
a spoofing attack is a situation in which a person or program successfully masquerades as another by falsifying data, to gain an illegitimate advantage.
One user spoofs the identify of another user by brute-forcing username/password credentials.
A malicious, phishing host is set up in an attempt to trick users into divulging their credentials.
Tampering can refer to many forms of sabotage but the term is often used to mean intentional modification of products in a way that would make them harmful to the consumer.
A user performs bit-flipping attacks on data in transit.
A user modifies data at rest/on disk.
A user performs injection attacks on the application.
Non-repudiation refers to a situation where a statement's author cannot successfully dispute its authorship or the validity of an associated contract.
Proof of data integrity is typically the easiest of these requirements to accomplish. A data hash such as SHA2 usually ensures that the data will not be changed undetectably. Even with this safeguard, it is possible to tamper with data in transit, either through a man-in-the-middle attack or phishing. Because of this, data integrity is best asserted when the recipient already possesses the necessary verification information.[citation needed]
Common methods to provide non-repudiation in the context of digital communications or storage are Message Authentication Codes (MAC)
A user denies performing a destructive action (e.g. deleting all records from a database).
Attackers commonly erase or truncate log files as a technique for hiding their tracks.
Administrators unable to determine if a container has started to behave suspiciously/erratically.
Information disclosure privacy breach or data leak
Information disclosure
Most web sites will disclose some amount of information. The more information that an attacker learns about a web site, the easier the system will be to compromise.
e.g. Banner or error pages, vulnerabilities of OS/Webservers => automated bots
A user is able to eavesdrop, sniff, or read traffic in clear-text.
A user is able to read data on disk in clear-text.
A user attacks an application protected by TLS but is able to steal x.509 (SSL/TLS certificate) decryption keys and other sensitive information. Yes, this happened.
A user is able to read sensitive data in a database.
Denial of Service
a denial-of-service attack (DoS attack) is a cyber-attack in which the perpetrator seeks to make a machine or network resource unavailable to its intended users by temporarily or indefinitely disrupting services of a host connected to the Internet. Denial of service is typically accomplished by flooding the targeted machine or resource with superfluous requests in an attempt to overload systems and prevent some or all legitimate requests from being fulfilled.[1]
In a distributed denial-of-service attack (DDoS attack), the incoming traffic flooding the victim originates from many different sources. This effectively makes it impossible to stop the attack simply by blocking a single source.
A DoS or DDoS attack is analogous to a group of people crowding the entry door of a shop, making it hard for legitimate customers to enter, disrupting trade.
Elevation of privilege
is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. The result is that an application with more privileges than intended by the application developer or system administrator can perform unauthorized actions.
Some Windows services are configured to run under the Local System user account. A vulnerability such as a buffer overflow may be used to execute arbitrary code with privilege elevated to Local System. Alternatively, a system service that is impersonating a lesser user can elevate that user's privileges if errors are not handled correctly while the user is being impersonated (e.g. if the user has introduced a malicious error handler)
Under some legacy versions of the Microsoft Windows operating system, the All Users screensaver runs under the Local System account – any account that can replace the current screensaver binary in the file system or Registry can therefore elevate privileges.
In certain versions of the Linux kernel it was possible to write a program that would set its current directory to /etc/cron.d, request that a core dump be performed in case it crashes and then have itself killed by another process. The core dump file would have been placed at the program's current directory, that is, /etc/cron.d, and cron would have treated it as a text file instructing it to run programs on schedule. Because the contents of the file would be under attacker's control, the attacker would be able to execute any program with root privileges.
Cross Zone Scripting is a type of privilege escalation attack in which a website subverts the security model of web browsers, thus allowing it to run malicious code on client computers.
There are also situations where an application can use other high privilege services and has incorrect assumptions about how a client could manipulate its use of these services. An application that can execute Command line or shell commands could have a Shell Injection vulnerability if it uses unvalidated input as part of an executed command. An attacker would then be able to run system commands using the application's privileges.
Texas Instruments calculators (particularly the TI-85 and TI-82) were originally designed to use only interpreted programs written in dialects of TI-BASIC; however, after users discovered bugs that could be exploited to allow native Z-80 code to run on the calculator hardware, TI released programming data to support third-party development. (This did not carry on to the ARM-based TI-Nspire, for which jailbreaks using Ndless have been found but are still actively fought against by Texas Instruments.)
Some versions of the iPhone allow an unauthorised user to access the phone while it is locked.[1]
1:2017-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.
A2:2017-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.
A3:2017-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.
A4:2017-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.
A5:2017-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.
A6:2017-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.
A7:2017-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.
A8:2017-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.
A9:2017-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.
A10:2017-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.
SqlInjection is the number one attack since allways. The reason why this attack is so common is because it’s easy to use, the number of websites that has sql injection has allways be high andfinding sites that suffer from this exploit are so easy to find tha even a child can find them. In contradiction the impact of a sqlinjection attack can be disastrous. Credit card and passwords can be stolen and data can even be changed.
Those familiar with Active Directory will see similarities as it also provides Authentication, user management, SSO, federation to other ADs ... Active Directory however is not internet friendly. Using Kerberos outside the context of the company network is cumbersome, often involves writing custom code that deals with the complex Kerberos protocol. Relying on the browser to handle this might work for IE, but not necessarily for Chrome. The setup is also brittle. OpenId Connect is the standard protocol to do authentication across the internet.
JSON Web Token (JWT), pronounced "jot", is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object.
Compact: Because of its relatively small size, a JWT can be sent through a URL, through a POST parameter, or inside an HTTP header, and it is transmitted quickly.
Self-contained: A JWT contains all the required information about an entity to avoid querying a database more than once. The recipient of a JWT also does not need to call a server to validate the token.
If you give Bearer ( Default on most implementation), an access_token is generated and sent back to you. Bearer can be simply understood as "give access to the bearer of this token." One valid token and no question asked. On the other hand if you choose Mac and sign_type(default hmac-sha-1 on most implementation), the access token is generated and kept as secret in Key Manager as a attribute, and an encrypted secret is sent back as access_token
Docs:
AuthenticationScheme
https://docs.microsoft.com/en-us/aspnet/core/security/authorization/limitingidentitybyscheme?view=aspnetcore-2.2&tabs=aspnetcore2x
Look at :
Startup.cs
AddAuthentication e.g.:services.AddAuthentication()
.AddCookie(options => { options.LoginPath = "/Account/Unauthorized/"; options.AccessDeniedPath = "/Account/Forbidden/"; })
.AddJwtBearer(options => { options.Audience = "http://localhost:5001/"; options.Authority = "http://localhost:5000/"; });
Audience: The audience of a token is the intended recipient of the token.
There are two forms of MITM attacks: those based on physical proximity to the target (like a hacker sitting in a coffee shop that offers free Wi-Fi, waiting for unsuspecting patrons to log on), and malware-related attacks (also known as Man-in-the-middle browser attacks or MITBs), where hackers inject malware into users’ computers. The malware installs itself into the user’s browser (covertly) and begins to record all data transmitted between the victim and any targeted websites.MITM attacks can also use many different methods to intercept communications (for example, email, session, or IP hijacking, Wi-Fi® eavesdropping, Trojan attacks, DNS spoofing, or HTTP injections).
If Elizabeth and David attempt to send each other messages, but Jessica initiates an MITM attack, it could use the following process:
Jessica locates a security hole that will allow her to intercept Elizabeth and David's communications.
Elizabeth sends a message to David, which Jessica intercepts: You were right! Stargate is almost as good as Star Trek. Could you please send me your public key?
Jessica sends this message to David.
David responds with his public key, which Jessica receives: Just wait until you watch Atlantis! Here's my private key.
Jessica replaces the public key with her own key, and then she sends the message to Elizabeth.
Elizabeth encrypts a message with the key that she believes is David's:Because I trust you completely, here's the information for my new bank account. Why don't you withdraw a few bucks?
Jessica intercepts the message and, because she sent Elizabeth her key instead of David's, is able to decrypt it.
Jessica saves Elizabeth's bank information, and then she sends the message to David.
Jessica goes to the bank and withdraws $20,000 of Elizabeth's money.
David arrives at the bank later in the day and finds that the account is overdrawn.
Elizabeth blames David for taking all of her money, and they never speak again.
To ensure all request are made under HTTPS you could redirect all traffic from HTTP to HTTPS.
Nevertheless an attacker could replace your redirect by returning is own website clone.