diff --git a/modules/1-introduction.livemd b/modules/1-introduction.livemd index ca9ea5d..f6f4de8 100644 --- a/modules/1-introduction.livemd +++ b/modules/1-introduction.livemd @@ -4,13 +4,13 @@ Found in this series of modules is a curriculum for teaching Secure Coding concepts and ideas centered around the Elixir ecosystem. Core principles of Application Security have been sourced from other available resources within the community and pieced together into this Elixir Livebook format to allow for an interactive spin. -It is worth stating that this material is a work in progress and is open to contributions in order to make this the one-stop shop for Developer Secure Coding Training (for Elixir). The initial training material was originally crafted by the Product Security team at [Podium](https://www.podium.com/) and as such, contains very opinionated lessons to help contribute to the Secure SDLC of Podium's engineers. The more general this material can be made through outside contributors, the more secure we can make the Elixir community. +It is worth stating that this material is a work in progress and is open to contributions in order to make this the one-stop shop for Developer Secure Coding Training (for Elixir). The initial training material was originally crafted by the Product Security team at [Podium](https://www.podium.com/), but is now maintained by the [Erlang Ecosystem Foundation](https://erlef.org). ## Who This Is For This curriculum is for any Software Developer / Engineer / Maker / Hacker looking to better their own knowledge of the Web Application Security space, especially as it pertains to Elixir Phoenix applications. -This Training material is also ideally used in an educational environment for organizations to level up their Engineering teams Security knowledge. Quiz questions have been crafted within and an auto-grader that can be deployed in the CI/CD pipeline for local forks of this repo will be made available soon. +This Training material is also ideally used in an educational environment for organizations to level up their Engineering teams Security knowledge. Quiz questions have been crafted within and are graded directly within each Livebook. ## How To Use This Livebook diff --git a/modules/11-authentication.livemd b/modules/11-authentication.livemd index 91e3368..93859a8 100644 --- a/modules/11-authentication.livemd +++ b/modules/11-authentication.livemd @@ -1,16 +1,17 @@ -# ESCT: Part 11 - Authentication +# ESCT: Part 11 - Authentication ## Introduction -Authentication is the process of establishing that an entity, whether person or machine, is who they say they are. In this process the entity starts by "knocking on the door", and presenting their id card and credentials when prompted. +Authentication is the process of establishing that an entity, whether person or machine, is who they say they are. In this process the entity starts by "knocking on the door", and presenting their id card and credentials when prompted. -One of two things follow: -- The authentication attempt is successful and further communication including the granting of access can proceed. -- Authentication fails and other that notifying the entity of the failure, no further communication proceeds and no access is granted. +One of two things follow: -Imagine you get a knock on your door. You ask who it is, and the person on the other side says you have a package delivery. In fact, you're not expecting a package and you can see the person is not wearing a uniform and doesn't have a package in their hands. Something doesn't match. They don't seem to be who they say they are and so, you don't open the door. +* The authentication attempt is successful and further communication including the granting of access can proceed. +* Authentication fails and other that notifying the entity of the failure, no further communication proceeds and no access is granted. -Authentication is the mechanism that helps guard the front door of an application. It's the mechanism that helps control who gets into your system and if they are there legitimately. +Imagine you get a knock on your door. You ask who it is, and the person on the other side says you have a package delivery. In fact, you're not expecting a package and you can see the person is not wearing a uniform and doesn't have a package in their hands. Something doesn't match. They don't seem to be who they say they are and so, you don't open the door. + +Authentication is the mechanism that helps guard the front door of an application. It's the mechanism that helps control who gets into your system and if they are there legitimately. ## Table of Contents @@ -26,19 +27,19 @@ Authentication is the mechanism that helps guard the front door of an applicatio ### Description -Thinking back to the example above, authentication is establishing an entity is who they say they are. For applications, this means, the user who is attempting to login, is the user who created and has control over the account. But most applications have multiple levels of users, those with maximum access/privileges to move around and modify the application freely, and those with more restricted access. +Thinking back to the example above, authentication is establishing an entity is who they say they are. For applications, this means, the user who is attempting to login, is the user who created and has control over the account. But most applications have multiple levels of users, those with maximum access/privileges to move around and modify the application freely, and those with more restricted access. -Once an entity has been authenticated, then they are granted access but when implemented in an application/system, this often appears to happen in a single step. Users login and if you get a successful response you also get access to the application. Access immediately follows Authentication, but how much access an entity is allowed and the actions they are permitted to, is authorized, to perform are governed by a set of permissions or access controls referred to as Authorization, which is often managed by a token or similar credentials. +Once an entity has been authenticated, then they are granted access but when implemented in an application/system, this often appears to happen in a single step. Users login and if you get a successful response you also get access to the application. Access immediately follows Authentication, but how much access an entity is allowed and the actions they are permitted to, is authorized, to perform are governed by a set of permissions or access controls referred to as Authorization, which is often managed by a token or similar credentials. During the authentication and authorization process, validity of credentials and level of access are checked. Then, depending on the architecture of the system or application, once an entity is authenticated, is granted access, subsequent activity/interactions need to be tracked/attributed to the same entity. This functions like a hand stamp for re-entry to an event or amusement park accept it is unique to you. For applications, this means setting up and tracking an authenticated user's session, and this is often done using some kind of token, sometimes the same token that gets issued for access. -Authorization, Identity, Credentials, Access, Access Controls, Permissions, Session and Session Management are all terms you will come across when implementing Authentication in applications. While each has distinct definitions, consider them as mutually interactive contributors to an integrated system that works to allow into an application only what is verified and trusted, tracks and monitors the activity of what's been allowed in, and ensures what does get in, only has access to what they absolutely need in order to perform their specific function. How these are implemented and their specific configuration is unique to the design of each application. +Authorization, Identity, Credentials, Access, Access Controls, Permissions, Session and Session Management are all terms you will come across when implementing Authentication in applications. While each has distinct definitions, consider them as mutually interactive contributors to an integrated system that works to allow into an application only what is verified and trusted, tracks and monitors the activity of what's been allowed in, and ensures what does get in, only has access to what they absolutely need in order to perform their specific function. How these are implemented and their specific configuration is unique to the design of each application. ## Multi-factor Authentication ### Description -Multi-factor Authentication (MFA) is a way of implementing authentication so that more than one aspect of an entity is checked when it presents itself. from the initial simple example, checking both the information on the id card (something they have) and asking the entity to verbally state their name (something they know), for instance. +Multi-factor Authentication (MFA) is a way of implementing authentication so that more than one aspect of an entity is checked when it presents itself. from the initial simple example, checking both the information on the id card (something they have) and asking the entity to verbally state their name (something they know), for instance. When implemented in applications, these aspects are referred to as factors and Authentication can be implemented using one of these factors (single-factor) or 2 or more (multi-factor): @@ -52,18 +53,19 @@ Authentication mechanism can be simple or complex. Security industry best pract ### Description -We mentioned earlier how both authorization (access) and sessions can be handled using tokens. Access Tokens are built so that they contain information about what an authenticated user does and does not have access to, for how long, and they can also be used to manage the user's persistence/ongoing interactions with the application in a session. +We mentioned earlier how both authorization (access) and sessions can be handled using tokens. Access Tokens are built so that they contain information about what an authenticated user does and does not have access to, for how long, and they can also be used to manage the user's persistence/ongoing interactions with the application in a session. Tokens are long strings of random characters used to identify an entity, session, as a badge for access and are usually generated by some token generating code, service or server. In token-based implementations, at a highlevel the application or service generates tokens, assign token to users after they have been authenticated, check token validity as users access and use application functionality/features, and end/renew sessions by expiring and refresh tokens. ### OAuth + Open Authorization(OAuth) is a protocol in which a multi-step arrangement generates a token for a specific users, the user presents as a credential in lieu of a password. There is an extra server (authorization/token generating service or server) that after a user authenticates with it, it generates a token, and brokers authentication/authorization between initial entity and a resource. Originally built for authorization, as its name suggests, it has evolved for use in the authentication and authorization mechanisms. A very good resource that describes the OAuth in context of its history and current implementations is here: https://www.youtube.com/watch?v=996OiexHze0 -Why use OAuth? When users need access to third party services, outside of your environment where you don't want to share your credentials with those third parties. In OAuth protocol/architecture, an authorization service brokers access and grants users an access token to present, in place of credentials. +Why use OAuth? When users need access to third party services, outside of your environment where you don't want to share your credentials with those third parties. In OAuth protocol/architecture, an authorization service brokers access and grants users an access token to present, in place of credentials. -### Example +### Example There are four primary entities involved with the OAuth protocol: requesting, service one, service 2, intermediary server that handles issuing tokens that get presented in lieu of credentials. At a very high level, the flow looks something like @@ -73,14 +75,11 @@ There are four primary entities involved with the OAuth protocol: requesting, se -Authorization Server/Service Generates Access Token -Service X sends Token for limited access to Social Media Account (instead of sharing credentials) - -``` -[OAuth2.Client module ](https://hexdocs.pm/oauth2/OAuth2.Client.html) - -``` +[OAuth2.Client module](https://hexdocs.pm/oauth2/OAuth2.Client.html) ### JWT -JSON Web Tokens (abbreviated JWT, pronounced "jot") are multi-use tokens for authentication and session management. JWTs have three components, header contains information identifying type of token and algorithm used for the signature, payload/body that contains data about the disposition of the token, signature - which serves as an integrity check to establish if the token has been modified or tampered with. + +JSON Web Tokens (abbreviated JWT, pronounced "jot") are multi-use tokens for authentication and session management. JWTs have three components, header contains information identifying type of token and algorithm used for the signature, payload/body that contains data about the disposition of the token, signature - which serves as an integrity check to establish if the token has been modified or tampered with. Tokens, like other authentication credentials, etc. must be protected in transit and at rest and can be Base64 encoded and cryptographically signed @@ -89,35 +88,38 @@ Why use JWT? For post authentication authorization, JWTs can be signed and encry ### Example / Quiz Create/Generate Token + ``` ``` Validate Token + ``` def connect(%{"authorize" => token}, socket, _connect_info) do // case JwtChecker.validate_token(token)do ... ... ``` + ### References + https://dev.to/onpointvn/implement-jwt-authentication-with-phoenix-token-n58 (https://hexdocs.pm/guardian/Guardian.Token.Jwt.html) https://elixirschool.com/blog/jwt-auth-with-joken/ - ## Sessions ### Description -Authentication is the first step a user must complete to access a secure application/data. Once an entity is authenticated, subsequent activity/interactions need to be tracked as belonging to the same entity. +Authentication is the first step a user must complete to access a secure application/data. Once an entity is authenticated, subsequent activity/interactions need to be tracked as belonging to the same entity. -Some applications do this by establishing and managing a session. Other applications are "session-less" and required a different approach for keeping the application's "knowledge" of what a user is doing while they use an application. +Some applications do this by establishing and managing a session. Other applications are "session-less" and required a different approach for keeping the application's "knowledge" of what a user is doing while they use an application. For session-less applications, once a user authenticates, the server assigns and sends a token to their client. For any following requests, the client sends their token in each request, like with JWTs discussed previously. The server only checks the validity of the token. -In session oriented applications, one the user authenticates, information in subsequent requests are compared to session information kept on the server. +In session oriented applications, one the user authenticates, information in subsequent requests are compared to session information kept on the server. In a way, this is like a museum visit. A session is like showing your membership card or ticket for the day. Generally you can come and go on your day pass (they'll probably stamp you hand if you leave but you can get back in no problem). Once the museum closes, the session is over and you have to leave and come back another day. If you have a membership or ticket for multiple visits, you have to show your card/ticket at the door again. @@ -125,7 +127,7 @@ Session-less, sometimes referred to as "fire and forget it" is like purchasing a ## Authentication and Security Concerns -An application's authentication mechanism is a critical component. If not securely designed, it can provide an attack vector for malicious actors to gain access to legitimate user accounts, privileged application features, and sensitive data. +An application's authentication mechanism is a critical component. If not securely designed, it can provide an attack vector for malicious actors to gain access to legitimate user accounts, privileged application features, and sensitive data. -Authentication, credentials, should never be stored in cleartext, nor hardcoded in source code Credential Stuffing Attacks @@ -138,15 +140,17 @@ Authentication Issues, Weaknesses, Failures make an appearance on multiple lists OWASP Top 10 for Web Applications A07:2021-Identification and Authentication Failures (used to be called Broken Authenticication ## Prevention and Countermeasures -Use built and tested authentication mechanisms in your code language framework. -Authentication is a key component of an application but given its integration with some of the other concepts mentioned in this module, its implementation in your products can become complex. This module touched on some of the highlights but please refer to the references below for extensive explanations of authentication and related. +Use built and tested authentication mechanisms in your code language framework. + +Authentication is a key component of an application but given its integration with some of the other concepts mentioned in this module, its implementation in your products can become complex. This module touched on some of the highlights but please refer to the references below for extensive explanations of authentication and related. ### Quiz **Which of the following OWASP Top 10 Web Application Security Risks are related to the abuse of credentials or flaws in mult-factor authentication implementation?** *Uncomment the line with your answer* + ``` # A02:2021-Cryptographic Failures @@ -185,6 +189,7 @@ IO.puts(answer) ``` ### References + https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html https://owasp.org/www-project-web-security-testing-guide/stable/4-Web_Application_Security_Testing/06-Session_Management_Testing/README diff --git a/modules/12-cryptography.livemd b/modules/12-cryptography.livemd index cbc4c47..2929371 100644 --- a/modules/12-cryptography.livemd +++ b/modules/12-cryptography.livemd @@ -1,16 +1,16 @@ -# ESCT: Part 12 - Cryptography +# ESCT: Part 12 - Cryptography ## Introduction -Cryptography is the process of transforming information or data from its original form into one that is unreadable by systems, tools, or people unless they have a key. The part of the process that converts source data/information into the unreadable version is called encryption. Reversing that process is called decryption. +Cryptography is the process of transforming information or data from its original form into one that is unreadable by systems, tools, or people unless they have a key. The part of the process that converts source data/information into the unreadable version is called encryption. Reversing that process is called decryption. Like many concepts/technologies in security, cryptography is not new. Centuries of devisings ways to send messages between and among known and trusted senders/receivers while making those messages unreadable for enemies or anyone else for whom the message is not intended. -Secret codes, etc. +Secret codes, etc. Cryptography, like speaking or writing in code, is used whenever there something that needs to be kept secret in an environment where there are multiple other parties who could see or hear the secret but are not the intended recipient. The sender and receiver agree upon a code to exchange messages. Additionally, written notes can be stored and unless a reader has the code, won't know what the actual message is. -Cryptography is used throughout applications to protect sensitive information that while is needed for the operation of the application and its components, is not intended to be openly shared. This module highlights how cryptography is applied +Cryptography is used throughout applications to protect sensitive information that while is needed for the operation of the application and its components, is not intended to be openly shared. This module highlights how cryptography is applied ## Table of Contents @@ -32,28 +32,29 @@ There are two categories of cryptography, symmetric and asymmetric and within th In symmetric encryption, which is also called secret key encryption, a single key used for both encryption and decryption. Symmetric cryptography is bested used when performance and efficiency are important to the application component using/accessing the data to be secured. -In asymmetric encryption, which is also called public-key cryptography, two related but separate keys are generated and then one is used for encrypting while the other for decrpyting. The keys include one that is meant to be shared (pubic key) and one that must always be kept secret(private) but in this public key infrastructure (PKI) system, both keys work to secure client-server interactions, secure VPN connectsion, certificates, digital signatures, and help ensure the technology and data in the system is only accessible by authenticated, and authorized entities with keys. +In asymmetric encryption, which is also called public-key cryptography, two related but separate keys are generated and then one is used for encrypting while the other for decrpyting. The keys include one that is meant to be shared (pubic key) and one that must always be kept secret(private) but in this public key infrastructure (PKI) system, both keys work to secure client-server interactions, secure VPN connectsion, certificates, digital signatures, and help ensure the technology and data in the system is only accessible by authenticated, and authorized entities with keys. -When selecting an algorithm, best practice is to never build your own, and to always use established and proven algorithms, vetted and recommended by industry experts like NIST. +When selecting an algorithm, best practice is to never build your own, and to always use established and proven algorithms, vetted and recommended by industry experts like NIST. [symmetric cryptography](https://developer.mozilla.org/en-US/docs/Glossary/Symmetric-key_cryptography) [NIST](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-77r1.pdf) -### Example / Quiz +### Example / Quiz ## Implementation in Modern Applications ### Description -Modern applications have many components that store, process, transmit a variety of information and data. Often that information/data consists of "secrets" or is otherwise sensitive. This includes things like personal information on customers, user credentials, of anything else application developers would like to keep secret. -API keys, database credentials, tokens, admin passwords and other credentials to access privileged components and features, senstivitve data (PII, healthcare), private keys, signing certificates, are all examples of information that should not be available for every users and indeed, kept internal to the organization. +Modern applications have many components that store, process, transmit a variety of information and data. Often that information/data consists of "secrets" or is otherwise sensitive. This includes things like personal information on customers, user credentials, of anything else application developers would like to keep secret. -To secure this data, look to implement cryptography both at rest and in transit. +API keys, database credentials, tokens, admin passwords and other credentials to access privileged components and features, senstivitve data (PII, healthcare), private keys, signing certificates, are all examples of information that should not be available for every users and indeed, kept internal to the organization. -In-transit, ensure all requests/responses are sent using the secure version of the HTTP protocol, HTTPS. HTTP over TLS. Additionally, For remote access into development environments, SSH, VPN - for access to sensitive development environment internal to an organization/remote accessover a network. +To secure this data, look to implement cryptography both at rest and in transit. +In-transit, ensure all requests/responses are sent using the secure version of the HTTP protocol, HTTPS. HTTP over TLS. Additionally, For remote access into development environments, SSH, VPN - for access to sensitive development environment internal to an organization/remote accessover a network. + +### Example (Draft) -### Example (Draft) ``` For elixir, ExCrypto module[ExCrypto](https://hexdocs.pm/ex_crypto/ExCrypto.html) @@ -75,7 +76,7 @@ use HTTPS which implements encryption over a channel. Diffie-Hellman ### Description -Hashing is sometimes implemented alongside encryption but has a different purpose. Cryptography used for confidentiality; keeping information secret except for intended recipient/audience. +Hashing is sometimes implemented alongside encryption but has a different purpose. Cryptography used for confidentiality; keeping information secret except for intended recipient/audience. Hashes are used to ensure the integrity of the data, meaning ensuring from its creation/generation to its final state, it remains unmodified and untampered with. Hash algorithms are one way functions that - compare starting hash from known good data, to end hash which will indicate changes. Hashing passwords is a common application. Comparing hashes to determine if correct password entered. Hash Algorithms - SHA1, SHA2, MD5 (obsolete) - follow recommendations from NIST [Approved Hash Algorithms](https://csrc.nist.gov/Projects/Hash-Functions) @@ -92,7 +93,7 @@ Most of the concerns around cytography amount to data being inadvertently being Follow NIST Recommendations for configuring the most secure algorithms when building your applications and securing secrets and data. -Beware of hardcoding keys, private keys, in source code where they can be discovered by malicious actors. Avoid building your own cryptographic mechanisms or using outdated protocols. +Beware of hardcoding keys, private keys, in source code where they can be discovered by malicious actors. Avoid building your own cryptographic mechanisms or using outdated protocols. [Recommended algorithms ](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-77r1.pdf)[ @@ -102,6 +103,7 @@ https://csrc.nist.gov/Projects/Hash-Functions [Elixir encryption, hashing, etc. Modules](https://elixir-lang.org/getting-started/erlang-libraries.html#the-crypto-module) [OWASP Top10](https://owasp.org/Top10/A02_2021-Cryptographic_Failures/) [Use TLS](https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Protection_Cheat_Sheet.html) + ### Example / Quiz **(True or False) You should build your own encryption from scratch.** diff --git a/modules/2-owasp.livemd b/modules/2-owasp.livemd index 4b31bf5..8400588 100644 --- a/modules/2-owasp.livemd +++ b/modules/2-owasp.livemd @@ -101,25 +101,29 @@ Notable CWEs included are CWE-259: Use of Hard-coded Password, CWE-327: Broken o _Please uncomment the function call that you believe is correct._ - + ```elixir result = - defmodule PasswordCompare do - def option_one(password, md5_hash) do - case :crypto.hash(:md5, password) == md5_hash do - true -> :entry_granted_op1 - false -> :entry_denied_op1 + ( + defmodule PasswordCompare do + def option_one(password, md5_hash) do + case :crypto.hash(:md5, password) == md5_hash do + true -> :entry_granted_op1 + false -> :entry_denied_op1 + end end - end - def option_two(password, bcrypt_salted_hash) do - case Bcrypt.verify_pass(password, bcrypt_salted_hash) do - true -> :entry_granted_op2 - false -> :entry_denied_op2 + def option_two(password, bcrypt_salted_hash) do + case Bcrypt.verify_pass(password, bcrypt_salted_hash) do + true -> :entry_granted_op2 + false -> :entry_denied_op2 + end end end - end + + PasswordCompare.option_two("users_password", bcrypt_salted_hash) + ) case GradingClient.check_answer(OWASP, 1, result) do :correct -> diff --git a/modules/3-ssdlc.livemd b/modules/3-ssdlc.livemd index 276c1e2..b948c47 100644 --- a/modules/3-ssdlc.livemd +++ b/modules/3-ssdlc.livemd @@ -47,10 +47,10 @@ A very easy way to prevent secrets being added to files is to access them via En _Use `System.get_env/1` on line 2._ - + ```elixir -result = super_secret_password = "p@ssw0rd" +result = super_secret_password = System.get_env("envar_secret") case GradingClient.check_answer(SDLC, 1, result) do :correct -> diff --git a/modules/5-elixir.livemd b/modules/5-elixir.livemd index a3afc69..1cb66ca 100644 --- a/modules/5-elixir.livemd +++ b/modules/5-elixir.livemd @@ -50,7 +50,7 @@ Beware of functions in applications/libraries that create atoms from input value _You should get a `true` result when you successfully fix the function._ - + ```elixir result = @@ -58,7 +58,7 @@ result = malicious_user_input = UUID.uuid4() try do - malicious_user_input |> String.to_atom() + malicious_user_input |> String.to_existing_atom() rescue e -> e end @@ -213,7 +213,7 @@ The latter will raise a `BadBooleanError` when the function returns `:ok` or `{: _Uncomment the if statement that uses the correct boolean comparison._ - + ```elixir result = @@ -234,6 +234,9 @@ result = :ok try do + if SecurityCheck.validate(user_input, password) or raise(SecurityCheck) do + :you_let_a_baddie_in + end rescue e -> e end @@ -281,9 +284,13 @@ Another approach, useful in functions that call the standard library (e.g. crypt ### Example + + + + ```elixir def encrypt_with_secret(message, wrapped_secret) do - ComeCryptoLib.encrypt(message, wrapped_secret.()) + SomeCryptoLib.encrypt(message, wrapped_secret.()) rescue e -> reraise e, prune_stacktrace(System.stacktrace()) end @@ -304,12 +311,12 @@ This prevents the table from being read by other processes, such as remote shell **We have decided that we do not want this ETS table to be read from other processes, so try making it private:** - + ```elixir result = ( - secret_table = :ets.new(:secret_table, [:public]) + secret_table = :ets.new(:secret_table, [:private]) :ets.info(secret_table)[:protection] ) diff --git a/modules/6-cookies.livemd b/modules/6-cookies.livemd index ec4f5a4..25a4bf3 100644 --- a/modules/6-cookies.livemd +++ b/modules/6-cookies.livemd @@ -181,15 +181,36 @@ In the Phoenix Framework, you would use functionality found within the [Plug lib _Fill out the `put_resp_cookie/4` function arguments with the settings outlined in the previous section, no other code changes should be necessary._ - + ```elixir result = ( cookie_name = "CHANGE_ME" + Uncomment and change(the(put_resp_cookie(call(below)))) + + conn = + Plug.Conn.put_resp_cookie( + conn, + cookie_name, + <<0::8, 42::8>>, + domain: "", + path: ..., + secure: ..., + http_only: ..., + same_site: ... + ) + + conn = + Plug.Conn.put_resp_cookie( + conn, + cookie_name, + <<0::8, 42::8>>, + domain: "" + ) cookie = - conn + conn? |> Plug.Conn.fetch_cookies() |> Plug.Conn.get_resp_cookies() |> Map.fetch!(cookie_name)