├── 00.java ├── 00.Vulnerability │ ├── Vulnerability1.java │ ├── Vulnerability10.java │ ├── Vulnerability11.java │ ├── Vulnerability12.java │ ├── Vulnerability13.java │ ├── Vulnerability14.java │ ├── Vulnerability15.java │ ├── Vulnerability16.java │ ├── Vulnerability17.java │ ├── Vulnerability18.java │ ├── Vulnerability19.java │ ├── Vulnerability2.java │ ├── Vulnerability20.java │ ├── Vulnerability21.java │ ├── Vulnerability22.java │ ├── Vulnerability23.java │ ├── Vulnerability24.java │ ├── Vulnerability25.java │ ├── Vulnerability26.java │ ├── Vulnerability27.java │ ├── Vulnerability28.java │ ├── Vulnerability29.java │ ├── Vulnerability3.java │ ├── Vulnerability30.java │ ├── Vulnerability31.java │ ├── Vulnerability32.java │ ├── Vulnerability33.java │ ├── Vulnerability4.java │ ├── Vulnerability5.java │ ├── Vulnerability6.java │ ├── Vulnerability7.java │ ├── Vulnerability8.java │ └── Vulnerability9.java └── 01.Security_Hotspot │ ├── Security01.java │ ├── Security02.java │ ├── Security03.java │ ├── Security04.java │ ├── Security05.java │ ├── Security06.java │ ├── Security07.java │ ├── Security08.java │ ├── Security09.java │ ├── Security10.java │ ├── Security11.java │ ├── Security12.java │ ├── Security13.java │ ├── Security14.java │ ├── Security15.java │ ├── Security16.java │ ├── Security17.java │ ├── Security18.java │ ├── Security19.java │ ├── Security20.java │ ├── Security21.java │ ├── Security22.java │ ├── Security23.java │ ├── Security24.java │ ├── Security25.java │ ├── Security26.java │ ├── Security27.java │ ├── Security28.java │ ├── Security29.java │ ├── Security30.java │ ├── Security31.java │ ├── Security32.java │ ├── Security33.java │ ├── Security34.java │ ├── Security35.java │ ├── Security36.java │ └── Security37.java ├── 01.python ├── Security_Hotspot │ ├── Security01.py │ ├── Security02.py │ ├── Security03.py │ ├── Security04.py │ ├── Security05.py │ ├── Security06.py │ ├── Security07.py │ ├── Security08.py │ ├── Security09.py │ ├── Security10.py │ ├── Security11.py │ ├── Security12.py │ ├── Security13.py │ ├── Security14.py │ ├── Security15.py │ ├── Security16.py │ ├── Security17.py │ ├── Security18.py │ ├── Security19.py │ ├── Security20.py │ ├── Security21.py │ ├── Security22.py │ ├── Security23.py │ ├── Security24.py │ ├── Security25.py │ ├── Security26.py │ ├── Security27.py │ ├── Security28.py │ ├── Security29.py │ ├── Security30.py │ ├── Security31.py │ ├── Security32.py │ ├── Security33.py │ ├── Security34.py │ ├── Security35.py │ ├── Security36.py │ ├── Security37.py │ ├── Security38.py │ ├── Security39.py │ ├── Security40.py │ ├── Security41.py │ ├── Security42.py │ └── Security43.py ├── Vulnerability │ ├── Vulnerability1.py │ ├── Vulnerability10.py │ ├── Vulnerability11.py │ ├── Vulnerability12.py │ ├── Vulnerability13.py │ ├── Vulnerability14.py │ ├── Vulnerability15.py │ ├── Vulnerability16.py │ ├── Vulnerability2.py │ ├── Vulnerability3.py │ ├── Vulnerability4.py │ ├── Vulnerability5.py │ ├── Vulnerability6.py │ ├── Vulnerability7.py │ ├── Vulnerability8.py │ └── Vulnerability9.py ├── python.py ├── vulnerabilities.py └── vulnerabilities_sonar_16.py └── 02.docker └── dockerfile.txt /00.java/00.Vulnerability/Vulnerability1.java: -------------------------------------------------------------------------------- 1 | ###### «ActiveMQConnectionFactory» не должен быть уязвим для десериализации вредоносного кода. 2 | 3 | Уязвимость 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/выпуск: 30 мин. 9 | 10 | ActiveMQ может отправлять/получать сообщения объекта JMS (с именем ObjectMessage в контексте ActiveMQ) в соответствии со спецификацией JMS. Внутри ActiveMQ использует механизм сериализации Java для маршалинга/демаршалинга полезной нагрузки сообщения. Десериализация на основе данных, предоставленных пользователем, может привести к атакам с удаленным выполнением кода, при которых структура сериализованных данных изменяется для изменения поведения десериализуемого объекта. 11 | 12 | Чтобы ограничить риск стать жертвой такой атаки, ActiveMQ 5.12.2+ заставляет разработчиков явно вносить в белый список пакеты, которыми можно обмениваться с помощью ObjectMessages. 13 | Пример несовместимого кода 14 | 15 | 16 | ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); 17 | factory.setTrustAllPackages(true); // Noncompliant 18 | 19 | ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); 20 | // no call to factory.setTrustedPackages(...); 21 | 22 | Compliant Solution 23 | 24 | ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("tcp://localhost:61616"); 25 | factory.setTrustedPackages(Arrays.asList("org.mypackage1", "org.mypackage2")); 26 | 27 | See 28 | 29 | OWASP Top 10 2021 Category A8 - Software and Data Integrity Failures 30 | OWASP Top 10 2017 Category A8 - Insecure Deserialization 31 | MITRE, CWE-502 - Deserialization of Untrusted Data 32 | ActiveMQ ObjectMessage Security Advisory 33 | CVE-2015-5254 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability10.java: -------------------------------------------------------------------------------- 1 | Server certificates should be verified during SSL/TLS connections 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. 11 | 12 | The certificate chain validation includes these steps: 13 | 14 | The certificate is issued by its parent Certificate Authority or the root CA trusted by the system. 15 | Each CA is allowed to issue certificates. 16 | Each certificate in the chain is not expired. 17 | 18 | This rule raises an issue when an implementation of X509TrustManager is not controlling the validity of the certificate (ie: no exception is raised). Empty implementations of the X509TrustManager interface are often created to disable certificate validation. The correct solution is to provide an appropriate trust store. 19 | Noncompliant Code Example 20 | 21 | class TrustAllManager implements X509TrustManager { 22 | 23 | @Override 24 | public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Noncompliant, nothing means trust any client 25 | } 26 | 27 | @Override 28 | public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // Noncompliant, this method never throws exception, it means trust any server 29 | LOG.log(Level.SEVERE, ERROR_MESSAGE); 30 | } 31 | 32 | @Override 33 | public X509Certificate[] getAcceptedIssuers() { 34 | return null; 35 | } 36 | } 37 | 38 | See 39 | 40 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 41 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 42 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 43 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 44 | MITRE, CWE-295 - Improper Certificate Validation 45 | CERT, MSC61-J. - Do not use insecure or weak cryptographic algorithms 46 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability12.java: -------------------------------------------------------------------------------- 1 | Passwords should not be stored in plain-text or with a fast hashing algorithm 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 30min 9 | 10 | A user password should never be stored in clear-text, instead a hash should be produced from it using a secure algorithm: 11 | 12 | not vulnerable to brute force attacks. 13 | not vulnerable to collision attacks (see rule s4790). 14 | and a salt should be added to the password to lower the risk of rainbow table attacks (see rule s2053). 15 | 16 | This rule raises an issue when a password is stored in clear-text or with a hash algorithm vulnerable to bruce force attacks. These algorithms, like md5 or SHA-family functions are fast to compute the hash and therefore brute force attacks are possible (it’s easier to exhaust the entire space of all possible passwords) especially with hardware like GPU, FPGA or ASIC. Modern password hashing algorithms such as bcrypt, PBKDF2 or argon2 are recommended. 17 | Noncompliant Code Example 18 | 19 | @Autowired 20 | public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception { 21 | auth.jdbcAuthentication() 22 | .dataSource(dataSource) 23 | .usersByUsernameQuery("SELECT * FROM users WHERE username = ?") 24 | .passwordEncoder(new StandardPasswordEncoder()); // Noncompliant 25 | 26 | // OR 27 | auth.jdbcAuthentication() 28 | .dataSource(dataSource) 29 | .usersByUsernameQuery("SELECT * FROM users WHERE username = ?"); // Noncompliant; default uses plain-text 30 | 31 | // OR 32 | auth.userDetailsService(...); // Noncompliant; default uses plain-text 33 | // OR 34 | auth.userDetailsService(...).passwordEncoder(new StandardPasswordEncoder()); // Noncompliant 35 | } 36 | 37 | Compliant Solution 38 | 39 | @Autowired 40 | public void configureGlobal(AuthenticationManagerBuilder auth, DataSource dataSource) throws Exception { 41 | auth.jdbcAuthentication() 42 | .dataSource(dataSource) 43 | .usersByUsernameQuery("Select * from users where username=?") 44 | .passwordEncoder(new BCryptPasswordEncoder()); 45 | 46 | // or 47 | auth.userDetailsService(null).passwordEncoder(new BCryptPasswordEncoder()); 48 | } 49 | 50 | See 51 | 52 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 53 | OWASP Top 10 2021 Category A4 - Insecure Design 54 | OWASP CheatSheet - Password Storage Cheat Sheet 55 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 56 | MITRE, CWE-256 - Plaintext Storage of a Password 57 | MITRE, CWE-916 - Use of Password Hash With Insufficient Computational Effort 58 | SANS Top 25 - Porous Defenses 59 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability13.java: -------------------------------------------------------------------------------- 1 | OpenSAML2 should be configured to prevent authentication bypass 2 | 3 | Vulnerability 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | In 2018, Duo Security found a new vulnerability class that affects SAML-based single sign-on (SSO) systems and this led to the following vulnerabilities being disclosed: CVE-2017-11427, CVE-2017-11428, CVE-2017-11429, CVE-2017-11430, CVE-2018-0489, CVE-2018-7340. 11 | 12 | From a specially crafted file, an attacker having already access to the SAML system with his own account can bypass the authentication mechanism and be authenticated as another user. 13 | 14 | This is due to the fact that SAML protocol rely on XML format and how the underlying XML parser interprets XML comments. 15 | 16 | If an attacker manage to change the field identifying the authenticated user with XML comments, he can exploit the vulnerability. 17 | 18 | Here is an example of a potential payload: 19 | 20 | 21 | [...] 22 | 23 | admin@domain.com.evil.com 24 | 25 | [...] 26 | 27 | 28 | The attacker will manage to generate a valid content with the account "admin@domain.com.evil.com". He will modify it with XML comments to finally be authenticated as "admin@domain.com". To prevent this vulnerability on application using Spring Security SAML relying on OpenSAML2, XML comments should be ignored thanks to the property ignoreComments set to true. 29 | Noncompliant Code Example 30 | 31 | import org.opensaml.xml.parse.BasicParserPool; 32 | import org.opensaml.xml.parse.ParserPool; 33 | import org.opensaml.xml.parse.StaticBasicParserPool; 34 | 35 | public ParserPool parserPool() { 36 | StaticBasicParserPool staticBasicParserPool = new StaticBasicParserPool(); 37 | staticBasicParserPool.setIgnoreComments(false); // Noncompliant: comments are not ignored during parsing opening the door to exploit the vulnerability 38 | return staticBasicParserPool; 39 | } 40 | 41 | public ParserPool parserPool() { 42 | BasicParserPool basicParserPool = new BasicParserPool(); 43 | basicParserPool.setIgnoreComments(false); // Noncompliant 44 | return basicParserPool; 45 | } 46 | 47 | Compliant Solution 48 | 49 | public ParserPool parserPool() { 50 | return new StaticBasicParserPool(); // Compliant: "ignoreComments" is set to "true" in StaticBasicParserPool constructor 51 | } 52 | 53 | public ParserPool parserPool() { 54 | return new BasicParserPool(); // Compliant: "ignoreComments" is set to "true" in BasicParserPool constructor 55 | } 56 | 57 | See 58 | 59 | OWASP Top 10 2021 Category A6 - Vulnerable and Outdated Components 60 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 61 | OWASP Top 10 2017 Category A2 - Broken Authentication 62 | OWASP Top 10 2017 Category A9 - Using Components with Known Vulnerabilities 63 | Duo Finds SAML Vulnerabilities Affecting Multiple Implementations 64 | Spring Security SAML and this week’s SAML Vulnerability 65 | Spring Security SAML: Issue #228 66 | 67 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability14.java: -------------------------------------------------------------------------------- 1 | Mobile database encryption keys should not be disclosed 2 | 3 | Vulnerability 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | Storing data locally is a common task for mobile applications. There are many convenient solutions that allow storing data persistently, for example SQLiteDatabase and Realm. These systems can be initialized with a secret key in order to store the data encrypted. 11 | 12 | The encryption key is meant to stay secret and should not be hard-coded in the application as it would mean that: 13 | 14 | All user would use the same encryption key. 15 | The encryption key would be known by anyone who as access to the source code or the application binary code. 16 | Data stored encrypted in the database would not be protected. 17 | 18 | There are different approaches how the key can be provided to encrypt and decrypt the database. One of the most convinient way to is to rely on EncryptedSharedPreferences to store encryption keys. It can also be provided dynamically by the user of the application or fetched from a remote server. 19 | Noncompliant Code Example 20 | 21 | SQLCipher 22 | 23 | String key = "gb09ym9ydoolp3w886d0tciczj6ve9kszqd65u7d126040gwy86xqimjpuuc788g"; 24 | SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("test.db", key, null); // Noncompliant 25 | 26 | Realm 27 | 28 | String key = "gb09ym9ydoolp3w886d0tciczj6ve9kszqd65u7d126040gwy86xqimjpuuc788g"; 29 | RealmConfiguration config = new RealmConfiguration.Builder(); 30 | .encryptionKey(key.toByteArray()) // Noncompliant 31 | .build(); 32 | Realm realm = Realm.getInstance(config); 33 | 34 | Compliant Solution 35 | 36 | SQLCipher 37 | 38 | SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase("test.db", getKey(), null); 39 | 40 | Realm 41 | 42 | RealmConfiguration config = new RealmConfiguration.Builder() 43 | .encryptionKey(getKey()) 44 | .build(); 45 | Realm realm = Realm.getInstance(config); 46 | 47 | See 48 | 49 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 50 | OWASP Top 10 2021 Category A4 - Insecure Design 51 | Mobile AppSec Verification Standard - Data Storage and Privacy Requirements 52 | OWASP Mobile Top 10 2016 Category M2 - Insecure Data Storage 53 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 54 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 55 | MITRE, CWE-311 - Missing Encryption of Sensitive Data 56 | MITRE, CWE-321 - Use of Hard-coded Cryptographic Key 57 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability15.java: -------------------------------------------------------------------------------- 1 | Members of Spring components should be injected 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | Spring @Component, @Controller, @Service, and @Repository classes are singletons by default, meaning only one instance of the class is ever instantiated in the application. Typically such a class might have a few static members, such as a logger, but all non-static members should be managed by Spring. That is, they should have one of these annotations: @Resource, @Inject, @Autowired or @Value. 11 | 12 | Having non-injected members in one of these classes could indicate an attempt to manage state. Because they are singletons, such an attempt is almost guaranteed to eventually expose data from User1’s session to User2. 13 | 14 | This rule raises an issue when a singleton @Component, @Controller, @Service, or @Repository, not annotated with @ConfigurationProperties, has non-static members that are not annotated with one of: 15 | 16 | org.springframework.beans.factory.annotation.Autowired 17 | org.springframework.beans.factory.annotation.Value 18 | javax.annotation.Inject 19 | javax.annotation.Resource 20 | 21 | Noncompliant Code Example 22 | 23 | @Controller 24 | public class HelloWorld { 25 | 26 | private String name = null; 27 | 28 | @RequestMapping("/greet", method = GET) 29 | public String greet(String greetee) { 30 | 31 | if (greetee != null) { 32 | this.name = greetee; 33 | } 34 | 35 | return "Hello " + this.name; // if greetee is null, you see the previous user's data 36 | } 37 | } 38 | 39 | See 40 | 41 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 42 | 43 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability16.java: -------------------------------------------------------------------------------- 1 | LDAP connections should be authenticated 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | An LDAP client authenticates to an LDAP server with a "bind request" which provides, among other, a simple authentication method. 11 | 12 | Simple authentication in LDAP can be used with three different mechanisms: 13 | 14 | Anonymous Authentication Mechanism by performing a bind request with a username and password value of zero length. 15 | Unauthenticated Authentication Mechanism by performing a bind request with a password value of zero length. 16 | Name/Password Authentication Mechanism by performing a bind request with a password value of non-zero length. 17 | 18 | Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password, their use is therefore strongly discouraged. 19 | Noncompliant Code Example 20 | 21 | This rule raises an issue when an LDAP connection is created with Context.SECURITY_AUTHENTICATION set to "none". 22 | 23 | // Set up the environment for creating the initial context 24 | Hashtable env = new Hashtable(); 25 | env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 26 | env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); 27 | 28 | // Use anonymous authentication 29 | env.put(Context.SECURITY_AUTHENTICATION, "none"); // Noncompliant 30 | 31 | // Create the initial context 32 | DirContext ctx = new InitialDirContext(env); 33 | 34 | Compliant Solution 35 | 36 | // Set up the environment for creating the initial context 37 | Hashtable env = new Hashtable(); 38 | env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); 39 | env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); 40 | 41 | // Use simple authentication 42 | env.put(Context.SECURITY_AUTHENTICATION, "simple"); 43 | env.put(Context.SECURITY_PRINCIPAL, "cn=S. User, ou=NewHires, o=JNDITutorial"); 44 | env.put(Context.SECURITY_CREDENTIALS, getLDAPPassword()); 45 | 46 | // Create the initial context 47 | DirContext ctx = new InitialDirContext(env); 48 | 49 | See 50 | 51 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 52 | OWASP Top 10 2017 Category A2 - Broken Authentication 53 | MITRE, CWE-521 - Weak Password Requirements 54 | ldapwiki.com- Simple Authentication 55 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability17.java: -------------------------------------------------------------------------------- 1 | JWT should be signed and verified with strong cipher algorithms 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 30min 9 | 10 | If a JSON Web Token (JWT) is not signed with a strong cipher algorithm (or not signed at all) an attacker can forge it and impersonate user identities. 11 | 12 | Don’t use none algorithm to sign or verify the validity of a token. 13 | Don’t use a token without verifying its signature before. 14 | 15 | Noncompliant Code Example 16 | 17 | Using jwtk/Java JWT library (to verify a signed token (containing a JWS) don’t use the parse method as it doesn’t throw an exception if an unsigned token is provided): 18 | 19 | // Signing: 20 | io.jsonwebtoken.Jwts.builder() // Noncompliant, token is not signed. 21 | .setSubject(USER_LOGIN) 22 | .compact(); 23 | // Verifying: 24 | io.jsonwebtoken.Jwts.parser().setSigningKey(SECRET_KEY).parse(token).getBody(); // Noncompliant 25 | 26 | Using auth0/Java JWT library: 27 | 28 | // Signing: 29 | com.auth0.jwt.JWT.create() 30 | .withSubject(SUBJECT) 31 | .sign(Algorithm.none()); // Noncompliant, use only strong cipher algorithms when signing this JWT. 32 | // Verifying: 33 | JWTVerifier nonCompliantVerifier = com.auth0.jwt.JWT.require(Algorithm.none()) // Noncompliant 34 | .withSubject(LOGIN) 35 | .build(); 36 | 37 | Compliant Solution 38 | 39 | Using Java JWT library (to verify a signed token (containing a JWS) use the parseClaimsJws method that will throw an exception if an unsigned token is provided): 40 | 41 | // Signing: 42 | Jwts.builder() // Compliant 43 | .setSubject(USER_LOGIN) 44 | .signWith(SignatureAlgorithm.HS256, SECRET_KEY) 45 | .compact(); 46 | // Verifying: 47 | Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token).getBody(); // Compliant 48 | 49 | Using auth0/Java JWT library. I 50 | 51 | // Signing: 52 | JWT.create() 53 | .withSubject(SUBJECT) 54 | .sign(Algorithm.HMAC256(SECRET_KEY)); // Compliant 55 | // Verifying: 56 | JWTVerifier nonCompliantVerifier = JWT.require(Algorithm.HMAC256(SECRET_KEY)) // Compliant 57 | .withSubject(LOGIN) 58 | .build(); 59 | 60 | See 61 | 62 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 63 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 64 | MITRE, CWE-347 - Improper Verification of Cryptographic Signature 65 | 66 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability18.java: -------------------------------------------------------------------------------- 1 | Insecure temporary file creation methods should not be used 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | Using File.createTempFile as the first step in creating a temporary directory causes a race condition and is inherently unreliable and insecure. Instead, Files.createTempDirectory (Java 7+) should be used. 11 | 12 | This rule raises an issue when the following steps are taken in immediate sequence: 13 | 14 | call to File.createTempFile 15 | delete resulting file 16 | call mkdir on the File object 17 | 18 | Note that this rule is automatically disabled when the project’s sonar.java.source is lower than 7. 19 | Noncompliant Code Example 20 | 21 | File tempDir; 22 | tempDir = File.createTempFile("", "."); 23 | tempDir.delete(); 24 | tempDir.mkdir(); // Noncompliant 25 | 26 | Compliant Solution 27 | 28 | Path tempPath = Files.createTempDirectory(""); 29 | File tempDir = tempPath.toFile(); 30 | 31 | See 32 | 33 | OWASP Top 10 2021 Category A1 - Broken Access Control 34 | OWASP Top 10 2017 Category A9 - Using Components with Known Vulnerabilities 35 | MITRE, CWE-377 - Insecure Temporary File 36 | MITRE, CWE-379 - Creation of Temporary File in Directory with Incorrect Permissions 37 | OWASP, Insecure Temporary File 38 | 39 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability19.java: -------------------------------------------------------------------------------- 1 | Hashes should include an unpredictable salt 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 30min 9 | 10 | In cryptography, a "salt" is an extra piece of data which is included when hashing a password. This makes rainbow-table attacks more difficult. Using a cryptographic hash function without an unpredictable salt increases the likelihood that an attacker could successfully find the hash value in databases of precomputed hashes (called rainbow-tables). 11 | 12 | This rule raises an issue when a hashing function which has been specifically designed for hashing passwords, such as PBKDF2, is used with a non-random, reused or too short salt value. It does not raise an issue on base hashing algorithms such as sha1 or md5 as they should not be used to hash passwords. 13 | Recommended Secure Coding Practices 14 | 15 | Use hashing functions generating their own secure salt or generate a secure random value of at least 16 bytes. 16 | The salt should be unique by user password. 17 | 18 | Noncompliant Code Example 19 | 20 | Below, the hashed password use a predictable salt: 21 | 22 | byte[] salt = "notrandom".getBytes(); 23 | 24 | PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, 10000); // Noncompliant, predictable salt 25 | PBEKeySpec spec = new PBEKeySpec(chars, salt, 10000, 256); // Noncompliant, predictable salt 26 | 27 | Compliant Solution 28 | 29 | Use java.security.SecureRandom to generate an unpredictable salt: 30 | 31 | SecureRandom random = new SecureRandom(); 32 | byte[] salt = new byte[16]; 33 | random.nextBytes(salt); 34 | 35 | PBEParameterSpec cipherSpec = new PBEParameterSpec(salt, 10000); // Compliant 36 | PBEKeySpec spec = new PBEKeySpec(chars, salt, 10000, 256); // Compliant 37 | 38 | See 39 | 40 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 41 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 42 | MITRE, CWE-759 - Use of a One-Way Hash without a Salt 43 | MITRE, CWE-760 - Use of a One-Way Hash with a Predictable Salt 44 | SANS Top 25 - Porous Defenses 45 | 46 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability2.java: -------------------------------------------------------------------------------- 1 | ###### Шаблоны URL-адресов «HttpSecurity» должны быть правильно упорядочены. 2 | 3 | Уязвимость 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянная/проблема: 10 мин. 9 | 10 | Шаблоны URL-адресов, настроенные в методе HttpSecurity.authorizeRequests(), рассматриваются в том порядке, в котором они были объявлены. Легко допустить ошибку и объявить менее строгую конфигурацию перед более строгой. Поэтому необходимо пересмотреть порядок объявлений «antMatchers». /** должен быть последним, если он объявлен. 11 | 12 | Это правило вызывает проблему, когда: 13 | 14 | Шаблону предшествует другой, который заканчивается на ** и имеет то же начало. Например: /page*-admin/db/** стоит после /page*-admin/** 15 | Шаблону без подстановочных знаков предшествует другой соответствующий шаблон. Например: /page-index/db идет после /page*/**. 16 | 17 | Пример несовместимого кода 18 | 19 | protected void configure(HttpSecurity http) throws Exception { 20 | http.authorizeRequests() 21 | .antMatchers("/resources/**", "/signup", "/about").permitAll() // Compliant 22 | .antMatchers("/admin/**").hasRole("ADMIN") 23 | .antMatchers("/admin/login").permitAll() // Noncompliant; the pattern "/admin/login" should appear before "/admin/**" 24 | .antMatchers("/**", "/home").permitAll() 25 | .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") // Noncompliant; the pattern "/db/**" should occurs before "/**" 26 | .and().formLogin().loginPage("/login").permitAll().and().logout().permitAll(); 27 | } 28 | 29 | Compliant Solution 30 | 31 | protected void configure(HttpSecurity http) throws Exception { 32 | http.authorizeRequests() 33 | .antMatchers("/resources/**", "/signup", "/about").permitAll() // Compliant 34 | .antMatchers("/admin/login").permitAll() 35 | .antMatchers("/admin/**").hasRole("ADMIN") // Compliant 36 | .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')") 37 | .antMatchers("/**", "/home").permitAll() // Compliant; "/**" is the last one 38 | .and().formLogin().loginPage("/login").permitAll().and().logout().permitAll(); 39 | } 40 | 41 | See 42 | 43 | OWASP Top 10 2021 Category A1 - Broken Access Control 44 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 45 | 46 | 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability20.java: -------------------------------------------------------------------------------- 1 | Exceptions should not be thrown from servlet methods 2 | 3 | Vulnerability 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 20min 9 | 10 | Even though the signatures for methods in a servlet include throws IOException, ServletException, it’s a bad idea to let such exceptions be thrown. Failure to catch exceptions in a servlet could leave a system in a vulnerable state, possibly resulting in denial-of-service attacks, or the exposure of sensitive information because when a servlet throws an exception, the servlet container typically sends debugging information back to the user. And that information could be very valuable to an attacker. 11 | 12 | This rule checks all exceptions in methods named "do*" are explicitly handled in servlet classes. 13 | Noncompliant Code Example 14 | 15 | public void doGet(HttpServletRequest request, HttpServletResponse response) 16 | throws IOException, ServletException { 17 | String ip = request.getRemoteAddr(); 18 | InetAddress addr = InetAddress.getByName(ip); // Noncompliant; getByName(String) throws UnknownHostException 19 | //... 20 | } 21 | 22 | Compliant Solution 23 | 24 | public void doGet(HttpServletRequest request, HttpServletResponse response) 25 | throws IOException, ServletException { 26 | try { 27 | String ip = request.getRemoteAddr(); 28 | InetAddress addr = InetAddress.getByName(ip); 29 | //... 30 | } 31 | catch (UnknownHostException uhex) { 32 | //... 33 | } 34 | } 35 | 36 | See 37 | 38 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 39 | MITRE, CWE-600 - Uncaught Exception in Servlet 40 | CERT, ERR01-J. - Do not allow exceptions to expose sensitive information 41 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability21.java: -------------------------------------------------------------------------------- 1 | Encryption algorithms should be used with secure mode and padding scheme 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 20min 9 | 10 | Encryption algorithms should use secure modes and padding schemes where appropriate to guarantee data confidentiality and integrity. 11 | 12 | For block cipher encryption algorithms (like AES): 13 | The ECB (Electronic Codebook) cipher mode doesn’t provide serious message confidentiality: under a given key any given plaintext block always gets encrypted to the same ciphertext block. This mode should never be used. 14 | The CBC (Cipher Block Chaining) mode by itself provides only data confidentiality. This cipher mode is also vulnerable to padding oracle attacks when used with padding. Using CBC along with Message Authentication Code can provide data integrity and should prevent such attacks. In practice the implementation has many pitfalls and it’s recommended to avoid CBC with padding completely. 15 | The GCM (Galois Counter Mode) mode which works internally with zero/no padding scheme, is recommended, as it is designed to provide both data authenticity (integrity) and confidentiality. Other similar modes are CCM, CWC, EAX, IAPM and OCB. 16 | For RSA encryption algorithm, the recommended padding scheme is OAEP. 17 | 18 | Noncompliant Code Example 19 | 20 | Cipher.getInstance("AES"); // Noncompliant: by default ECB mode is chosen 21 | Cipher.getInstance("AES/ECB/NoPadding"); // Noncompliant: ECB doesn't provide serious message confidentiality 22 | 23 | Cipher.getInstance("AES/CBC/PKCS5Padding"); // Noncompliant: Vulnerable to Padding Oracle attacks 24 | 25 | Cipher.getInstance("RSA/None/NoPadding"); // Noncompliant: RSA without OAEP padding scheme is not recommended 26 | 27 | Compliant Solution 28 | 29 | Cipher.getInstance("AES/GCM/NoPadding"); 30 | 31 | Cipher.getInstance("RSA/None/OAEPWITHSHA-256ANDMGF1PADDING"); 32 | // or the ECB mode can be used for RSA when "None" is not available with the security provider used - in that case, ECB will be treated as "None" for RSA. 33 | Cipher.getInstance("RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"); 34 | 35 | See 36 | 37 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 38 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 39 | Mobile AppSec Verification Standard - Cryptography Requirements 40 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 41 | MITRE, CWE-327 - Use of a Broken or Risky Cryptographic Algorithm 42 | CERT, MSC61-J. - Do not use insecure or weak cryptographic algorithms 43 | SANS Top 25 - Porous Defenses 44 | 45 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability22.java: -------------------------------------------------------------------------------- 1 | Cryptographic keys should be robust 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 2min 9 | 10 | Most of cryptographic systems require a sufficient key size to be robust against brute-force attacks. 11 | 12 | NIST recommendations will be checked for these use-cases: 13 | 14 | Digital Signature Generation and Verification: 15 | 16 | p ≥ 2048 AND q ≥ 224 for DSA (p is key length and q the modulus length) 17 | n ≥ 2048 for RSA (n is the key length) 18 | 19 | Key Agreement: 20 | 21 | p ≥ 2048 AND q ≥ 224 for DH and MQV 22 | n ≥ 224 for ECDH and ECMQV (Examples: secp192r1 is a non-compliant curve (n < 224) but secp224k1 is compliant (n >= 224)) 23 | 24 | Symmetric keys: 25 | 26 | key length ≥ 128 bits 27 | 28 | This rule will not raise issues for ciphers that are considered weak (no matter the key size) like DES, Blowfish. 29 | Noncompliant Code Example 30 | 31 | KeyPairGenerator keyPairGen1 = KeyPairGenerator.getInstance("RSA"); 32 | keyPairGen1.initialize(1024); // Noncompliant 33 | 34 | KeyPairGenerator keyPairGen5 = KeyPairGenerator.getInstance("EC"); 35 | ECGenParameterSpec ecSpec1 = new ECGenParameterSpec("secp112r1"); // Noncompliant 36 | keyPairGen5.initialize(ecSpec1); 37 | 38 | KeyGenerator keyGen1 = KeyGenerator.getInstance("AES"); 39 | keyGen1.init(64); // Noncompliant 40 | 41 | Compliant Solution 42 | 43 | KeyPairGenerator keyPairGen6 = KeyPairGenerator.getInstance("RSA"); 44 | keyPairGen6.initialize(2048); // Compliant 45 | 46 | KeyPairGenerator keyPairGen5 = KeyPairGenerator.getInstance("EC"); 47 | ECGenParameterSpec ecSpec10 = new ECGenParameterSpec("secp256r1"); // compliant 48 | keyPairGen5.initialize(ecSpec10); 49 | 50 | KeyGenerator keyGen2 = KeyGenerator.getInstance("AES"); 51 | keyGen2.init(128); // Compliant 52 | 53 | See 54 | 55 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 56 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 57 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 58 | Mobile AppSec Verification Standard - Cryptography Requirements 59 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 60 | NIST 800-131A - Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Lengths 61 | MITRE, CWE-326 - Inadequate Encryption Strength 62 | 63 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability24.java: -------------------------------------------------------------------------------- 1 | Counter Mode initialization vectors should not be reused 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | When encrypting data with Counter (CTR) derived block cipher modes of operation, it is essential not to reuse the same initialization vector (IV) with a given key, such IV is called a "nonce" (number used only once). Galois/Counter (GCM) and Counter with Cipher Block Chaining-Message Authentication Code (CCM) are both CTR-based modes of operation. 11 | 12 | An attacker, who has knowledge of one plaintext (original content) and ciphertext (encrypted content) pair, is able to retrieve the corresponding plaintext of any other ciphertext generated with the same IV and key. It also drastically decreases the key recovery computational complexity by downgrading it to a simpler polynomial root-finding problem. 13 | 14 | When using GCM, NIST recommends a 96 bit length nonce using a 'Deterministic' approach or at least 96 bits using a 'Random Bit Generator (RBG)'. The 'Deterministic' construction involves a counter, which increments per encryption process. The 'RBG' construction, as the name suggests, generates the nonce using a random bit generator. Collision probabilities (nonce-key pair reuse) using the 'RBG-based' approach require a shorter key rotation period, 2^32 maximum invocations per key. 15 | Noncompliant Code Example 16 | 17 | public void encrypt(byte[] key, byte[] ptxt) { 18 | byte[] bytesIV = "7cVgr5cbdCZV".getBytes("UTF-8"); // The initialization vector is a static value 19 | 20 | GCMParameterSpec gcmSpec = new GCMParameterSpec(128, nonce); // The initialization vector is configured here 21 | SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); 22 | 23 | Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 24 | cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); // Noncompliant 25 | } 26 | 27 | Compliant Solution 28 | 29 | public void encrypt(byte[] key, byte[] ptxt) { 30 | SecureRandom random = new SecureRandom(); 31 | byte[] bytesIV = new byte[12]; 32 | random.nextBytes(bytesIV); // Random 96 bit IV 33 | 34 | GCMParameterSpec gcmSpec = new GCMParameterSpec(128, nonce); 35 | SecretKeySpec keySpec = new SecretKeySpec(key, "AES"); 36 | 37 | Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); 38 | cipher.init(Cipher.ENCRYPT_MODE, keySpec, iv); 39 | } 40 | 41 | See 42 | 43 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 44 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 45 | Mobile AppSec Verification Standard - Cryptography Requirements 46 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 47 | MITRE, CWE-323 - Reusing a Nonce, Key Pair in Encryption 48 | NIST, SP-800-38A - Recommendation for Block Cipher Modes of Operation 49 | NIST, SP-800-38C - Recommendation for Block Cipher Modes of Operation: The CCM Mode for Authentication and Confidentiality 50 | NIST, SP-800-38D - Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC 51 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability25.java: -------------------------------------------------------------------------------- 1 | Classes should not be loaded dynamically 2 | 3 | Vulnerability 4 | Critical 5 | Deprecated 6 | 7 | Available SinceDec 19, 2023 8 | SonarQube (Java) 9 | Constant/issue: 45min 10 | 11 | Dynamically loaded classes could contain malicious code executed by a static class initializer. I.E. you wouldn’t even have to instantiate or explicitly invoke methods on such classes to be vulnerable to an attack. 12 | 13 | This rule raises an issue for each use of dynamic class loading. 14 | Noncompliant Code Example 15 | 16 | String className = System.getProperty("messageClassName"); 17 | Class clazz = Class.forName(className); // Noncompliant 18 | 19 | See 20 | 21 | OWASP Top 10 2017 Category A1 - Injection 22 | MITRE, CWE-470 - Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') 23 | 24 | Deprecated 25 | 26 | This rule is deprecated; use S6173 instead. -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability26.java: -------------------------------------------------------------------------------- 1 | Cipher Block Chaining IVs should be unpredictable 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | When encrypting data with the Cipher Block Chaining (CBC) mode an Initialization Vector (IV) is used to randomize the encryption, ie under a given key the same plaintext doesn’t always produce the same ciphertext. The IV doesn’t need to be secret but should be unpredictable to avoid "Chosen-Plaintext Attack". 11 | 12 | To generate Initialization Vectors, NIST recommends to use a secure random number generator. 13 | Noncompliant Code Example 14 | 15 | public void encrypt(String key, String plainText) throws GeneralSecurityException { 16 | byte[] bytesIV = "7cVgr5cbdCZVw5WY".getBytes(StandardCharsets.UTF_8); // secondary 17 | 18 | GCMParameterSpec iv = new GCMParameterSpec(128,bytesIV); // secondary 19 | SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); 20 | 21 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 22 | cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); // Noncompliant 23 | } 24 | 25 | Compliant Solution 26 | 27 | public void encrypt(String key, String plainText) throws GeneralSecurityException { 28 | SecureRandom random = new SecureRandom(); 29 | byte[] bytesIV = new byte[16]; 30 | random.nextBytes(bytesIV); // Random initialization vector 31 | 32 | GCMParameterSpec iv = new GCMParameterSpec(128, bytesIV); 33 | SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES"); 34 | 35 | Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 36 | cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); 37 | } 38 | 39 | See 40 | 41 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 42 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 43 | Mobile AppSec Verification Standard - Cryptography Requirements 44 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 45 | MITRE, CWE-329 - Not Using an Unpredictable IV with CBC Mode 46 | NIST, SP-800-38A - Recommendation for Block Cipher Modes of Operation 47 | Derived from FindSecBugs rule STATIC_IV 48 | 49 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability27.java: -------------------------------------------------------------------------------- 1 | Cipher algorithms should be robust 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | Strong cipher algorithms are cryptographic systems resistant to cryptanalysis, they are not vulnerable to well-known attacks like brute force attacks for example. 11 | 12 | A general recommendation is to only use cipher algorithms intensively tested and promoted by the cryptographic community. 13 | 14 | More specifically for block cipher, it’s not recommended to use algorithm with a block size inferior than 128 bits. 15 | Noncompliant Code Example 16 | 17 | import javax.crypto.Cipher; 18 | import java.security.NoSuchAlgorithmException; 19 | import javax.crypto.NoSuchPaddingException; 20 | 21 | public class test { 22 | 23 | public static void main(String[] args) { 24 | try 25 | { 26 | Cipher c1 = Cipher.getInstance("DES"); // Noncompliant: DES works with 56-bit keys allow attacks via exhaustive search 27 | Cipher c7 = Cipher.getInstance("DESede"); // Noncompliant: Triple DES is vulnerable to meet-in-the-middle attack 28 | Cipher c13 = Cipher.getInstance("RC2"); // Noncompliant: RC2 is vulnerable to a related-key attack 29 | Cipher c19 = Cipher.getInstance("RC4"); // Noncompliant: vulnerable to several attacks (see https://en.wikipedia.org/wiki/RC4#Security) 30 | Cipher c25 = Cipher.getInstance("Blowfish"); // Noncompliant: Blowfish use a 64-bit block size makes it vulnerable to birthday attacks 31 | 32 | NullCipher nc = new NullCipher(); // Noncompliant: the NullCipher class provides an "identity cipher" one that does not transform or encrypt the plaintext in any way. 33 | } 34 | catch(NoSuchAlgorithmException|NoSuchPaddingException e) 35 | { 36 | } 37 | } 38 | } 39 | 40 | Compliant Solution 41 | 42 | import javax.crypto.Cipher; 43 | import java.security.NoSuchAlgorithmException; 44 | import javax.crypto.NoSuchPaddingException; 45 | 46 | public class test { 47 | 48 | public static void main(String[] args) { 49 | try 50 | { 51 | Cipher c31 = Cipher.getInstance("AES/GCM/NoPadding"); // Compliant 52 | } 53 | catch(NoSuchAlgorithmException|NoSuchPaddingException e) 54 | { 55 | } 56 | } 57 | } 58 | 59 | See 60 | 61 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 62 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 63 | Mobile AppSec Verification Standard - Cryptography Requirements 64 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 65 | MITRE, CWE-327 - Use of a Broken or Risky Cryptographic Algorithm 66 | CERT, MSC61-J. - Do not use insecure or weak cryptographic algorithms 67 | SANS Top 25 - Porous Defenses 68 | 69 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability28.java: -------------------------------------------------------------------------------- 1 | Basic authentication should not be used 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 2h 9 | 10 | Basic authentication’s only means of obfuscation is Base64 encoding. Since Base64 encoding is easily recognized and reversed, it offers only the thinnest veil of protection to your users, and should not be used. 11 | Noncompliant Code Example 12 | 13 | // Using HttpPost from Apache HttpClient 14 | String encoding = Base64Encoder.encode ("login:passwd"); 15 | org.apache.http.client.methods.HttpPost httppost = new HttpPost(url); 16 | httppost.setHeader("Authorization", "Basic " + encoding); // Noncompliant 17 | 18 | or 19 | 20 | // Using HttpURLConnection 21 | String encoding = Base64.getEncoder().encodeToString(("login:passwd").getBytes(‌"UTF‌​-8"​)); 22 | HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 23 | conn.setRequestMethod("POST"); 24 | conn.setDoOutput(true); 25 | conn.setRequestProperty("Authorization", "Basic " + encoding); // Noncompliant 26 | 27 | See 28 | 29 | OWASP Top 10 2021 Category A4 - Insecure Design 30 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 31 | OWASP Web Service Security Cheat Sheet 32 | MITRE, CWE-522 - Insufficiently Protected Credentials 33 | SANS Top 25 - Porous Defenses 34 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability3.java: -------------------------------------------------------------------------------- 1 | ###### Подписи XML должны быть надежно проверены. 2 | 3 | Уязвимость 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/выпуск: 15 мин. 9 | 10 | Проверка подписи XML осуществляется путем анализа сторонних данных, которым нельзя доверять до тех пор, пока они не будут фактически проверены. 11 | 12 | Как и любой другой процесс анализа, неограниченная проверка сторонних XML-подписей может привести к уязвимостям безопасности. В этом случае угрозы варьируются от отказа в обслуживании до нарушения конфиденциальности. 13 | 14 | По умолчанию API цифровой подписи Java XML не применяет ограничений на проверку подписи XML, если только приложение не запускается с менеджером безопасности. 15 | Чтобы защитить приложение от этих уязвимостей, установите для атрибута org.jcp.xml.dsig.secureValidation значение true с помощью метода javax.xml.crypto.dsig.dom.DOMValidateContext.setProperty. 16 | Этот атрибут гарантирует, что код применяет следующие ограничения: 17 | 18 | Запрещает использование преобразований XSLT. 19 | Ограничивает количество элементов SignedInfo или Manifest Reference до 30 или меньше. 20 | Ограничивает количество эталонных преобразований до 5 или меньше. 21 | Запрещает использование подписей, связанных с MD5, или алгоритмов MAC. 22 | Гарантирует уникальность идентификаторов ссылок, что помогает предотвратить атаки с использованием упаковки подписи. 23 | Запрещает ссылочные URI типа http, https или file. 24 | Не позволяет элементу RetrivalMethod ссылаться на другой элемент RetrivalMethod. 25 | Запрещает ключи RSA или DSA длиной менее 1024 бит. 26 | 27 | Пример несовместимого кода 28 | 29 | NodeList signatureElement = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); 30 | 31 | XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 32 | DOMValidateContext valContext = new DOMValidateContext(new KeyValueKeySelector(), signatureElement.item(0)); // Noncompliant 33 | XMLSignature signature = fac.unmarshalXMLSignature(valContext); 34 | 35 | boolean signatureValidity = signature.validate(valContext); 36 | 37 | Compliant Solution 38 | 39 | In order to benefit from this secure validation mode, set the DOMValidateContext’s org.jcp.xml.dsig.secureValidation property to TRUE. 40 | 41 | NodeList signatureElement = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); 42 | 43 | XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); 44 | DOMValidateContext valContext = new DOMValidateContext(new KeyValueKeySelector(), signatureElement.item(0)); 45 | valContext.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.TRUE); 46 | XMLSignature signature = fac.unmarshalXMLSignature(valContext); 47 | 48 | boolean signatureValidity = signature.validate(valContext); 49 | 50 | See 51 | 52 | Oracle Java Documentation - XML Digital Signature API Overview and Tutorial 53 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 54 | MITRE, CWE-347 - Improper Verification of Cryptographic Signature 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability30.java: -------------------------------------------------------------------------------- 1 | A secure password should be used when connecting to a database 2 | 3 | Vulnerability 4 | Blocker 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 45min 9 | 10 | When relying on the password authentication mode for the database connection, a secure password should be chosen. 11 | 12 | This rule raises an issue when an empty password is used. 13 | Noncompliant Code Example 14 | 15 | Connection conn = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "login", ""); 16 | 17 | Compliant Solution 18 | 19 | String password = System.getProperty("database.password"); 20 | Connection conn = DriverManager.getConnection("jdbc:derby:memory:myDB;create=true", "login", password); 21 | 22 | See 23 | 24 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 25 | OWASP Top 10 2017 Category A2 - Broken Authentication 26 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 27 | MITRE, CWE-521 - Weak Password Requirements 28 | 29 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability31.java: -------------------------------------------------------------------------------- 1 | A new session should be created during user authentication 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | Session fixation attacks occur when an attacker can force a legitimate user to use a session ID that he knows. To avoid fixation attacks, it’s a good practice to generate a new session each time a user authenticates and delete/invalidate the existing session (the one possibly known by the attacker). 11 | Noncompliant Code Example 12 | 13 | In a Spring Security’s context, session fixation protection is enabled by default but can be disabled with sessionFixation().none() method: 14 | 15 | @Override 16 | protected void configure(HttpSecurity http) throws Exception { 17 | http.sessionManagement() 18 | .sessionFixation().none(); // Noncompliant: the existing session will continue 19 | } 20 | 21 | Compliant Solution 22 | 23 | In a Spring Security’s context, session fixation protection can be enabled as follows: 24 | 25 | @Override 26 | protected void configure(HttpSecurity http) throws Exception { 27 | http.sessionManagement() 28 | .sessionFixation().newSession(); // Compliant: a new session is created without any of the attributes from the old session being copied over 29 | 30 | // or 31 | 32 | http.sessionManagement() 33 | .sessionFixation().migrateSession(); // Compliant: a new session is created, the old one is invalidated and the attributes from the old session are copied over. 34 | } 35 | 36 | See 37 | 38 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 39 | OWASP Top 10 2017 Category A2 - Broken Authentication 40 | OWASP Sesssion Fixation 41 | MITRE, CWE-384 - Session Fixation 42 | 43 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability32.java: -------------------------------------------------------------------------------- 1 | "SecureRandom" seeds should not be predictable 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 2min 9 | 10 | The java.security.SecureRandom class provides a strong random number generator (RNG) appropriate for cryptography. However, seeding it with a constant or another predictable value will weaken it significantly. In general, it is much safer to rely on the seed provided by the SecureRandom implementation. 11 | 12 | This rule raises an issue when SecureRandom.setSeed() or SecureRandom(byte[]) are called with a seed that is either one of: 13 | 14 | a constant 15 | the system time 16 | 17 | Noncompliant Code Example 18 | 19 | SecureRandom sr = new SecureRandom(); 20 | sr.setSeed(123456L); // Noncompliant 21 | int v = sr.next(32); 22 | 23 | sr = new SecureRandom("abcdefghijklmnop".getBytes("us-ascii")); // Noncompliant 24 | v = sr.next(32); 25 | 26 | Compliant Solution 27 | 28 | SecureRandom sr = new SecureRandom(); 29 | int v = sr.next(32); 30 | 31 | See 32 | 33 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 34 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 35 | MITRE, CWE-330 - Use of Insufficiently Random Values 36 | MITRE, CWE-332 - Insufficient Entropy in PRNG 37 | MITRE, CWE-336 - Same Seed in Pseudo-Random Number Generator (PRNG) 38 | MITRE, CWE-337 - Predictable Seed in Pseudo-Random Number Generator (PRNG) 39 | CERT, MSC63J. - Ensure that SecureRandom is properly seeded 40 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability33.java: -------------------------------------------------------------------------------- 1 | "HttpServletRequest.getRequestedSessionId()" should not be used 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | According to the Oracle Java API, the HttpServletRequest.getRequestedSessionId() method: 11 | 12 | Returns the session ID specified by the client. This may not be the same as the ID of the current valid session for this request. If the client did not specify a session ID, this method returns null. 13 | 14 | The session ID it returns is either transmitted in a cookie or a URL parameter so by definition, nothing prevents the end-user from manually updating the value of this session ID in the HTTP request. 15 | 16 | Here is an example of a updated HTTP header: 17 | 18 | GET /pageSomeWhere HTTP/1.1 19 | Host: webSite.com 20 | User-Agent: Mozilla/5.0 21 | Cookie: JSESSIONID=Hacked_Session_Value'''"> 22 | 23 | Due to the ability of the end-user to manually change the value, the session ID in the request should only be used by a servlet container (E.G. Tomcat or Jetty) to see if the value matches the ID of an an existing session. If it does not, the user should be considered unauthenticated. Moreover, this session ID should never be logged as is but using a one-way hash to prevent hijacking of active sessions. 24 | Noncompliant Code Example 25 | 26 | if(isActiveSession(request.getRequestedSessionId()) ){ 27 | ... 28 | } 29 | 30 | See 31 | 32 | OWASP Top 10 2021 Category A4 - Insecure Design 33 | OWASP Top 10 2017 Category A2 - Broken Authentication 34 | MITRE, CWE-807 - Reliance on Untrusted Inputs in a Security Decision 35 | SANS Top 25 - Porous Defenses 36 | 37 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability6.java: -------------------------------------------------------------------------------- 1 | ###### Анализаторы XML не должны быть уязвимы для атак типа «отказ в обслуживании». 2 | 3 | Уязвимость 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/выпуск: 15 мин. 9 | 10 | Атака XML-бомба/миллиард смеха — это вредоносный XML-документ, содержащий один и тот же большой объект, повторяемый снова и снова. Если не установлено никаких ограничений, таких как ограничение на количество расширений сущностей, процессор XML может потреблять много памяти и времени во время анализа таких документов, что приводит к отказу в обслуживании. 11 | Пример несовместимого кода 12 | 13 | Для фабрик DocumentBuilder, SAXParser и Schema и Transformer JAPX: 14 | 15 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 16 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant 17 | 18 | SAXParserFactory factory = SAXParserFactory.newInstance(); 19 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant 20 | 21 | SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 22 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant 23 | 24 | TransformerFactory factory = javax.xml.transform.TransformerFactory.newInstance(); 25 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant 26 | 27 | For Dom4j library: 28 | 29 | SAXReader xmlReader = new SAXReader(); 30 | xmlReader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant 31 | 32 | For Jdom2 library: 33 | 34 | SAXBuilder builder = new SAXBuilder(); 35 | builder.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, false); // Noncompliant 36 | 37 | Compliant Solution 38 | 39 | For DocumentBuilder, SAXParser and Schema and Transformer JAPX factories: 40 | 41 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 42 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 43 | 44 | SAXParserFactory factory = SAXParserFactory.newInstance(); 45 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 46 | 47 | SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 48 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 49 | 50 | TransformerFactory factory = javax.xml.transform.TransformerFactory.newInstance(); 51 | factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 52 | 53 | For Dom4j library: 54 | 55 | SAXReader xmlReader = new SAXReader(); 56 | xmlReader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 57 | 58 | For Jdom2 library: 59 | 60 | SAXBuilder builder = new SAXBuilder(); 61 | builder.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); 62 | 63 | See 64 | 65 | Oracle Java Documentation - XML External Entity Injection Attack 66 | OWASP Top 10 2017 Category A4 - XML External Entities (XXE) 67 | OWASP XXE Prevention Cheat Sheet 68 | MITRE, CWE-776 - Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion') 69 | 70 | 71 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability7.java: -------------------------------------------------------------------------------- 1 | ###### Анализаторы XML не должны допускать включение произвольных файлов. 2 | 3 | Уязвимость 4 | Блокатор 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/выпуск: 15 мин. 9 | 10 | Стандарт XML позволяет включать файлы XML с помощью элемента xinclude. 11 | 12 | Процессоры XML заменят элемент xinclude содержимым файла, расположенного по URI, определенному в атрибуте href, возможно, из внешнего хранилища, такого как файловая система или сеть, что может привести, если не установлены ограничения, к произвольному файлу. раскрытие информации или уязвимости подделки запросов на стороне сервера (SSRF). 13 | Пример несовместимого кода 14 | 15 | For DocumentBuilder, SAXParser, XMLInput, Transformer and Schema JAPX factories: 16 | 17 | factory.setXIncludeAware(true); // Noncompliant 18 | // or 19 | factory.setFeature("http://apache.org/xml/features/xinclude", true); // Noncompliant 20 | 21 | For Dom4j library: 22 | 23 | SAXReader xmlReader = new SAXReader(); 24 | xmlReader.setFeature("http://apache.org/xml/features/xinclude", true); // Noncompliant 25 | 26 | For Jdom2 library: 27 | 28 | SAXBuilder builder = new SAXBuilder(); 29 | builder.setFeature("http://apache.org/xml/features/xinclude", true); // Noncompliant 30 | 31 | Compliant Solution 32 | 33 | Xinclude is disabled by default and can be explicitely disabled like below. 34 | 35 | For DocumentBuilder, SAXParser, XMLInput, Transformer and Schema JAPX factories: 36 | 37 | factory.setXIncludeAware(false); 38 | // or 39 | factory.setFeature("http://apache.org/xml/features/xinclude", false); 40 | 41 | For Dom4j library: 42 | 43 | SAXReader xmlReader = new SAXReader(); 44 | xmlReader.setFeature("http://apache.org/xml/features/xinclude", false); 45 | 46 | For Jdom2 library: 47 | 48 | SAXBuilder builder = new SAXBuilder(); 49 | builder.setFeature("http://apache.org/xml/features/xinclude", false); 50 | 51 | Exceptions 52 | 53 | This rule does not raise issues when Xinclude is enabled with a custom EntityResolver: 54 | 55 | For DocumentBuilderFactory: 56 | 57 | DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 58 | factory.setXIncludeAware(true); 59 | // ... 60 | DocumentBuilder builder = factory.newDocumentBuilder(); 61 | builder.setEntityResolver((publicId, systemId) -> new MySafeEntityResolver(publicId, systemId)); 62 | 63 | For SAXBuilder: 64 | 65 | SAXBuilder builder = new SAXBuilder(); 66 | builder.setFeature("http://apache.org/xml/features/xinclude", true); 67 | builder.setEntityResolver((publicId, systemId) -> new MySafeEntityResolver(publicId, systemId)); 68 | 69 | For SAXReader: 70 | 71 | SAXReader xmlReader = new SAXReader(); 72 | xmlReader.setFeature("http://apache.org/xml/features/xinclude", true); 73 | xmlReader.setEntityResolver((publicId, systemId) -> new MySafeEntityResolver(publicId, systemId)); 74 | 75 | For XMLInputFactory: 76 | 77 | XMLInputFactory factory = XMLInputFactory.newInstance(); 78 | factory.setProperty("http://apache.org/xml/features/xinclude", true); 79 | factory.setXMLResolver(new MySafeEntityResolver()); 80 | 81 | See 82 | 83 | Oracle Java Documentation - XML External Entity Injection Attack 84 | OWASP Top 10 2017 Category A4 - XML External Entities (XXE) 85 | OWASP XXE Prevention Cheat Sheet 86 | MITRE, CWE-611 - Information Exposure Through XML External Entity Reference 87 | MITRE, CWE-827 - Improper Control of Document Type Definition 88 | -------------------------------------------------------------------------------- /00.java/00.Vulnerability/Vulnerability8.java: -------------------------------------------------------------------------------- 1 | ###### Не следует использовать слабые протоколы SSL/TLS. 2 | 3 | Уязвимость 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/проблема: 2 мин. 9 | 10 | Это правило создает проблему, когда используется или разрешена небезопасная версия протокола TLS (т. е. протокол, отличный от «TLSv1.2», «TLSv1.3», «DTLSv1.2» или «DTLSv1.3»). 11 | 12 | Рекомендуется установить TLS 1.2 в качестве минимальной версии протокола и запретить более старые версии, такие как TLS 1.0. Невыполнение этого требования может открыть возможности для атак на понижение версии: злоумышленник, способный перехватить соединение, может изменить запрошенную версию протокола и понизить ее до менее безопасной версии. 13 | 14 | В большинстве случаев использование конфигурации системы по умолчанию не соответствует требованиям. Действительно, приложение может быть развернуто в широком спектре систем с разными конфигурациями. Хотя использование системного значения по умолчанию может быть безопасным в современных современных системах, в старых системах это может быть не так. Поэтому рекомендуется в каждом случае явно устанавливать безопасную конфигурацию. 15 | Пример несовместимого кода 16 | 17 | javax.net.ssl.SSLContext library: 18 | 19 | context = SSLContext.getInstance("TLSv1.1"); // Noncompliant 20 | 21 | okhttp library: 22 | 23 | ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) 24 | .tlsVersions(TlsVersion.TLS_1_1) // Noncompliant 25 | .build(); 26 | 27 | Compliant Solution 28 | 29 | javax.net.ssl.SSLContext library: 30 | 31 | context = SSLContext.getInstance("TLSv1.2"); // Compliant 32 | 33 | okhttp library: 34 | 35 | ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) 36 | .tlsVersions(TlsVersion.TLS_1_2) // Compliant 37 | .build(); 38 | 39 | See 40 | 41 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 42 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 43 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 44 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 45 | MITRE, CWE-327 - Inadequate Encryption Strength 46 | MITRE, CWE-326 - Use of a Broken or Risky Cryptographic Algorithm 47 | SANS Top 25 - Porous Defenses 48 | Diagnosing TLS, SSL, and HTTPS 49 | SSL and TLS Deployment Best Practices - Use secure protocols 50 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security01.java: -------------------------------------------------------------------------------- 1 | ###### Java: S5324 2 | Доступ к внешнему хранилищу Android важен с точки зрения безопасности 3 | 4 | Точка доступа безопасности 5 | Критический 6 | 7 | Доступно с 19 декабря 2023 г. 8 | СонарКьюб (Java) 9 | 10 | Локальное хранение данных — обычная задача для мобильных приложений. К таким данным относятся, помимо прочего, файлы. Одним из удобных способов хранения файлов является использование внешнего хранилища файлов, которое обычно предлагает больший объем дискового пространства по сравнению с внутренним хранилищем. 11 | 12 | Файлы, созданные во внешнем хранилище, доступны для чтения и записи глобально. Таким образом, вредоносное приложение, имеющее разрешения WRITE_EXTERNAL_STORAGE или READ_EXTERNAL_STORAGE, может попытаться прочитать конфиденциальную информацию из файлов, которые другие приложения сохранили во внешнем хранилище. 13 | 14 | Внешнее хранилище также может быть удалено пользователем (например, если оно основано на SD-карте), что сделает файлы недоступными для приложения. 15 | 16 | ###### Спросите себя, есть ли 17 | 18 | Ваше приложение использует внешнее хранилище для: 19 | 20 | хранить файлы, содержащие конфиденциальные данные. 21 | хранить файлы, которые не предназначены для совместного использования с другими приложениями. 22 | хранить файлы, которые имеют решающее значение для работы приложения. 23 | 24 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 25 | Пример конфиденциального кода 26 | 27 | import android.content.Context; 28 | 29 | public class AccessExternalFiles { 30 | 31 | public void accessFiles(Context context) { 32 | context.getExternalFilesDir(null); // Sensitive 33 | } 34 | } 35 | 36 | ###### Рекомендуемые методы безопасного кодирования 37 | 38 | По возможности используйте внутреннюю память, поскольку система запрещает другим приложениям доступ к этому местоположению. 39 | Используйте внешнее хранилище только в том случае, если вам необходимо поделиться неконфиденциальными файлами с другими приложениями. 40 | Если вашему приложению приходится использовать внешнее хранилище для хранения конфиденциальных данных, убедитесь, что оно шифрует файлы с помощью EncryptedFile. 41 | Данные, поступающие из внешнего хранилища, всегда следует считать недоверенными и подлежат проверке. 42 | Поскольку некоторые внешние хранилища можно удалить, никогда не храните на них файлы, которые имеют решающее значение для удобства использования вашего приложения. 43 | 44 | Соответствующее решение 45 | 46 | import android.content.Context; 47 | 48 | public class AccessExternalFiles { 49 | 50 | public void accessFiles(Context context) { 51 | context.getFilesDir(); 52 | } 53 | } 54 | 55 | See 56 | 57 | OWASP Top 10 2021 Category A4 - Insecure Design 58 | Android Security tips on external file storage 59 | Mobile AppSec Verification Standard - Data Storage and Privacy Requirements 60 | OWASP Mobile Top 10 2016 Category M2 - Insecure Data Storage 61 | MITRE, CWE-312 - Cleartext Storage of Sensitive Information 62 | SANS Top 25 - Risky Resource Management 63 | SANS Top 25 - Porous Defenses 64 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security02.java: -------------------------------------------------------------------------------- 1 | ###### Разрешение как безопасных, так и небезопасных методов HTTP важно с точки зрения безопасности. 2 | 3 | Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/проблема: 5 минут 9 | 10 | Метод HTTP безопасен, если используется для выполнения операции только для чтения, например получения информации. Напротив, небезопасный метод HTTP используется для изменения состояния приложения, например, для обновления профиля пользователя в веб-приложении. 11 | 12 | Распространенными безопасными методами HTTP являются GET, HEAD или OPTIONS. 13 | 14 | Распространенными небезопасными методами HTTP являются POST, PUT и DELETE. 15 | 16 | Разрешение как безопасным, так и небезопасным методам HTTP выполнять определенную операцию в веб-приложении может повлиять на его безопасность, например, защита CSRF в большинстве случаев защищает только операции, выполняемые небезопасными методами HTTP. 17 | 18 | ###### Спросите себя, есть ли 19 | 20 | Методы HTTP вообще не определены для маршрута/контроллера приложения. 21 | Безопасные методы HTTP определяются и используются для маршрута/контроллера, который может изменять состояние приложения. 22 | 23 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 24 | Пример конфиденциального кода 25 | 26 | @RequestMapping("/delete_user") // Sensitive: by default all HTTP methods are allowed 27 | public String delete1(String username) { 28 | // state of the application will be changed here 29 | } 30 | 31 | @RequestMapping(path = "/delete_user", method = {RequestMethod.GET, RequestMethod.POST}) // Sensitive: both safe and unsafe methods are allowed 32 | String delete2(@RequestParam("id") String id) { 33 | // state of the application will be changed here 34 | } 35 | 36 | 37 | 38 | ###### Рекомендуемые методы безопасного кодирования 39 | 40 | Для всех маршрутов/контроллеров приложения авторизованные методы HTTP должны быть явно определены, а безопасные методы HTTP должны использоваться только для выполнения операций только для чтения. 41 | Соответствующее решение 42 | 43 | @RequestMapping("/delete_user", method = RequestMethod.POST) // Compliant 44 | public String delete1(String username) { 45 | // state of the application will be changed here 46 | } 47 | 48 | @RequestMapping(path = "/delete_user", method = RequestMethod.POST) // Compliant 49 | String delete2(@RequestParam("id") String id) { 50 | // state of the application will be changed here 51 | } 52 | 53 | See 54 | 55 | OWASP Top 10 2021 Category A1 - Broken Access Control 56 | OWASP Top 10 2021 Category A4 - Insecure Design 57 | OWASP Top 10 2017 Category A5 - Broken Access Control 58 | MITRE, CWE-352 - Cross-Site Request Forgery (CSRF) 59 | OWASP: Cross-Site Request Forgery 60 | SANS Top 25 - Insecure Interaction Between Components 61 | Spring Security Official Documentation: Use proper HTTP verbs (CSRF protection) 62 | 63 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security03.java: -------------------------------------------------------------------------------- 1 | ###### Разрешение десериализации объектов LDAP важно для безопасности. 2 | 3 | Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/проблема: 2 мин. 9 | 10 | JNDI поддерживает десериализацию объектов из каталогов LDAP, что может привести к удаленному выполнению кода. 11 | 12 | Это правило вызывает проблему, когда поисковый запрос LDAP выполняется с элементами управления SearchControls, настроенными на разрешение десериализации. 13 | 14 | 15 | ###### Спросите себя, есть ли 16 | 17 | Приложение подключается к недоверенному каталогу LDAP. 18 | Объекты, управляемые пользователем, могут храниться в каталоге LDAP. 19 | 20 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 21 | Пример конфиденциального кода 22 | 23 | DirContext ctx = new InitialDirContext(); 24 | // ... 25 | ctx.search(query, filter, 26 | new SearchControls(scope, countLimit, timeLimit, attributes, 27 | true, // Noncompliant; allows deserialization 28 | deref)); 29 | 30 | 31 | 32 | 33 | 34 | ###### Рекомендуемые методы безопасного кодирования 35 | 36 | Рекомендуется отключить десериализацию объектов LDAP. 37 | 38 | 39 | Compliant Solution 40 | 41 | DirContext ctx = new InitialDirContext(); 42 | // ... 43 | ctx.search(query, filter, 44 | new SearchControls(scope, countLimit, timeLimit, attributes, 45 | false, // Compliant 46 | deref)); 47 | 48 | See 49 | 50 | OWASP Top 10 2021 Category A8 - Software and Data Integrity Failures 51 | MITRE, CWE-502 - Deserialization of Untrusted Data 52 | OWASP Top 10 2017 Category A8 - Insecure Deserialization 53 | BlackHat presentation 54 | Derived from FindSecBugs rule LDAP_ENTRY_POISONING 55 | 56 | 57 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security04.java: -------------------------------------------------------------------------------- 1 | ###### Разрешение запросов с чрезмерной длиной содержимого важно для безопасности. 2 | 3 | Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/проблема: 5 минут 9 | 10 | Отклонение запросов со значительной длиной контента — хорошая практика для контроля интенсивности сетевого трафика и, следовательно, потребления ресурсов, чтобы предотвратить DoS-атаки. 11 | 12 | Спросите себя, есть ли 13 | 14 | ограничения размера не определены для различных ресурсов веб-приложения. 15 | веб-приложение не защищено функциями ограничения скорости. 16 | инфраструктура веб-приложений имеет ограниченные ресурсы. 17 | 18 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 19 | Пример конфиденциального кода 20 | 21 | With default limit value of 8388608 (8MB). 22 | 23 | A 100 MB file is allowed to be uploaded: 24 | 25 | @Bean(name = "multipartResolver") 26 | public CommonsMultipartResolver multipartResolver() { 27 | CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); 28 | multipartResolver.setMaxUploadSize(104857600); // Sensitive (100MB) 29 | return multipartResolver; 30 | } 31 | 32 | @Bean(name = "multipartResolver") 33 | public CommonsMultipartResolver multipartResolver() { 34 | CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(); // Sensitive, by default if maxUploadSize property is not defined, there is no limit and thus it's insecure 35 | return multipartResolver; 36 | } 37 | 38 | @Bean 39 | public MultipartConfigElement multipartConfigElement() { 40 | MultipartConfigFactory factory = new MultipartConfigFactory(); // Sensitive, no limit by default 41 | return factory.createMultipartConfig(); 42 | } 43 | 44 | 45 | 46 | ###### Рекомендуемые методы безопасного кодирования 47 | 48 | Для большинства функций приложения рекомендуется ограничить размер запросов следующими значениями: 49 | меньше или равно 8 МБ для загрузки файлов. 50 | меньше или равно 2 МБ для других запросов. 51 | 52 | Рекомендуется настроить правило, указав предельные значения, соответствующие веб-приложению. 53 | Соответствующее решение 54 | 55 | 56 | File upload size is limited to 8 MB: 57 | 58 | @Bean(name = "multipartResolver") 59 | public CommonsMultipartResolver multipartResolver() { 60 | multipartResolver.setMaxUploadSize(8388608); // Compliant (8 MB) 61 | return multipartResolver; 62 | } 63 | 64 | See 65 | 66 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 67 | Owasp Cheat Sheet - Owasp Denial of Service Cheat Sheet 68 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 69 | MITRE, CWE-770 - Allocation of Resources Without Limits or Throttling 70 | MITRE, CWE-400 - Uncontrolled Resource Consumption 71 | 72 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security06.java: -------------------------------------------------------------------------------- 1 | ###### Разрешение неаутентифицированным пользователям использовать ключи в Android KeyStore важно с точки зрения безопасности. 2 | 3 | Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКьюб (Java) 8 | Постоянно/проблема: 5 минут 9 | 10 | Android KeyStore — это безопасный контейнер для хранения материалов ключей, в частности он предотвращает извлечение материалов ключей, т. е. когда процесс приложения скомпрометирован, злоумышленник не может извлечь ключи, но все равно может их использовать. Можно включить функцию безопасности Android, аутентификацию пользователя, чтобы ограничить использование ключей только аутентифицированными пользователями. Экран блокировки необходимо разблокировать с помощью определенных учетных данных (шаблон/PIN-код/пароль, биометрические данные). 11 | 12 | 13 | ###### спроси себя, есть ли 14 | 15 | Приложение требует запретить использование ключей в случае компрометации процесса приложения. 16 | Ключевой материал используется в контексте высокочувствительного приложения, такого как мобильное приложение для электронного банкинга. 17 | 18 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 19 | Пример несовместимого кода 20 | 21 | Any user can use the key: 22 | 23 | KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); 24 | 25 | KeyGenParameterSpec builder = new KeyGenParameterSpec.Builder("test_secret_key_noncompliant", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) // Noncompliant 26 | .setBlockModes(KeyProperties.BLOCK_MODE_GCM) 27 | .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) 28 | .build(); 29 | 30 | keyGenerator.init(builder); 31 | 32 | 33 | 34 | ######## Рекомендуемые методы безопасного кодирования 35 | 36 | Рекомендуется включить аутентификацию пользователя (установив для setUserAuthenticationRequired значение true во время генерации ключа), чтобы использовать ключи в течение ограниченного периода времени (путем установки соответствующих значений для setUserAuthenticationValidityDurationSeconds), после чего пользователь должен повторно пройти аутентификацию. 37 | Соответствующее решение 38 | 39 | Использование ключа ограничено аутентифицированными пользователями (в течение периода времени, определенного в 60 секунд): 40 | 41 | KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); 42 | 43 | KeyGenParameterSpec builder = new KeyGenParameterSpec.Builder("test_secret_key", KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) 44 | .setBlockModes(KeyProperties.BLOCK_MODE_GCM) 45 | .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) 46 | .setUserAuthenticationRequired(true) 47 | .setUserAuthenticationParameters (60, KeyProperties.AUTH_DEVICE_CREDENTIAL) 48 | .build(); 49 | 50 | keyGenerator.init(builder) 51 | 52 | See 53 | 54 | OWASP Top 10 2021 Category A4 - Insecure Design 55 | developer.android.com - Android keystore system 56 | developer.android.com - Require user authentication for key use 57 | Mobile AppSec Verification Standard - Authentication and Session Management Requirements 58 | OWASP Mobile Top 10 2016 Category M4 - Insecure Authentication 59 | MITRE, CWE-522 - Insufficiently Protected Credentials 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security09.java: -------------------------------------------------------------------------------- 1 | ###### Creating cookies without the "HttpOnly" flag is security-sensitive 2 | 3 | Security Hotspot 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | When a cookie is configured with the HttpOnly attribute set to true, the browser guaranties that no client-side script will be able to read it. In most cases, when a cookie is created, the default value of HttpOnly is false and it’s up to the developer to decide whether or not the content of the cookie can be read by the client-side script. As a majority of Cross-Site Scripting (XSS) attacks target the theft of session-cookies, the HttpOnly attribute can help to reduce their impact as it won’t be possible to exploit the XSS vulnerability to steal session-cookies. 11 | 12 | 13 | ###### Ask Yourself Whether 14 | 15 | the cookie is sensitive, used to authenticate the user, for instance a session-cookie 16 | the HttpOnly attribute offer an additional protection (not the case for an XSRF-TOKEN cookie / CSRF token for example) 17 | 18 | There is a risk if you answered yes to any of those questions. 19 | Sensitive Code Example 20 | 21 | If you create a security-sensitive cookie in your JAVA code: 22 | 23 | Cookie c = new Cookie(COOKIENAME, sensitivedata); 24 | c.setHttpOnly(false); // Sensitive: this sensitive cookie is created with the httponly flag set to false and so it can be stolen easily in case of XSS vulnerability 25 | 26 | By default the HttpOnly flag is set to false: 27 | 28 | Cookie c = new Cookie(COOKIENAME, sensitivedata); // Sensitive: this sensitive cookie is created with the httponly flag not defined (by default set to false) and so it can be stolen easily in case of XSS vulnerability 29 | 30 | 31 | 32 | 33 | ######## Recommended Secure Coding Practices 34 | 35 | By default the HttpOnly flag should be set to true for most of the cookies and it’s mandatory for session / sensitive-security cookies. 36 | 37 | Compliant Solution 38 | 39 | Cookie c = new Cookie(COOKIENAME, sensitivedata); 40 | c.setHttpOnly(true); // Compliant: this sensitive cookie is protected against theft (HttpOnly=true) 41 | 42 | See 43 | 44 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 45 | OWASP HttpOnly 46 | OWASP Top 10 2017 Category A7 - Cross-Site Scripting (XSS) 47 | MITRE, CWE-1004 - Sensitive Cookie Without 'HttpOnly' Flag 48 | SANS Top 25 - Insecure Interaction Between Components 49 | Derived from FindSecBugs rule HTTPONLY_COOKIE 50 | 51 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security10.java: -------------------------------------------------------------------------------- 1 | ###### CCreating cookies without the "secure" flag is security-sensitive 2 | 3 | Security Hotspot 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | When a cookie is protected with the secure attribute set to true it will not be send by the browser over an unencrypted HTTP request and thus cannot be observed by an unauthorized person during a man-in-the-middle attack. 11 | 12 | 13 | ###### Ask Yourself Whether 14 | 15 | the cookie is for instance a session-cookie not designed to be sent over non-HTTPS communication. 16 | it’s not sure that the website contains mixed content or not (ie HTTPS everywhere or not) 17 | 18 | There is a risk if you answered yes to any of those questions. 19 | Sensitive Code Example 20 | 21 | If you create a security-sensitive cookie in your JAVA code: 22 | 23 | Cookie c = new Cookie(COOKIENAME, sensitivedata); 24 | c.setSecure(false); // Sensitive: a security-ensitive cookie is created with the secure flag set to false 25 | 26 | By default the secure flag is set to false: 27 | 28 | Cookie c = new Cookie(COOKIENAME, sensitivedata); // Sensitive: a security-sensitive cookie is created with the secure flag not defined (by default set to false) 29 | 30 | 31 | 32 | 33 | ######## Recommended Secure Coding Practices 34 | 35 | It is recommended to use HTTPs everywhere so setting the secure flag to true should be the default behaviour when creating cookies. 36 | Set the secure flag to true for session-cookies. 37 | 38 | Compliant Solution 39 | 40 | Cookie c = new Cookie(COOKIENAME, sensitivedata); 41 | c.setSecure(true); // Compliant: the sensitive cookie will not be send during an unencrypted HTTP request thanks to the secure flag set to true 42 | 43 | See 44 | 45 | OWASP Top 10 2021 Category A4 - Insecure Design 46 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 47 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 48 | MITRE, CWE-311 - Missing Encryption of Sensitive Data 49 | MITRE, CWE-315 - Cleartext Storage of Sensitive Information in a Cookie 50 | MITRE, CWE-614 - Sensitive Cookie in HTTPS Session Without 'Secure' Attribute 51 | SANS Top 25 - Porous Defenses 52 | 53 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security11.java: -------------------------------------------------------------------------------- 1 | ###### Delivering code in production with debug features activated is security-sensitive 2 | 3 | Security Hotspot 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 1min 9 | 10 | Delivering code in production with debug features activated is security-sensitive. It has led in the past to the following vulnerabilities: 11 | 12 | CVE-2018-1999007 13 | CVE-2015-5306 14 | CVE-2013-2006 15 | 16 | An application’s debug features enable developers to find bugs more easily and thus facilitate also the work of attackers. It often gives access to detailed information on both the system running the application and users. 17 | 18 | 19 | ###### Ask Yourself Whether 20 | 21 | the code or configuration enabling the application debug features is deployed on production servers or distributed to end users. 22 | the application runs by default with debug features activated. 23 | 24 | There is a risk if you answered yes to any of those questions. 25 | Sensitive Code Example 26 | 27 | Throwable.printStackTrace(...) prints a Throwable and its stack trace to System.Err (by default) which is not easily parseable and can expose sensitive information: 28 | 29 | try { 30 | /* ... */ 31 | } catch(Exception e) { 32 | e.printStackTrace(); // Sensitive 33 | } 34 | 35 | EnableWebSecurity annotation for SpringFramework with debug to true enables debugging support: 36 | 37 | import org.springframework.context.annotation.Configuration; 38 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 39 | 40 | @Configuration 41 | @EnableWebSecurity(debug = true) // Sensitive 42 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 43 | // ... 44 | } 45 | 46 | WebView.setWebContentsDebuggingEnabled(true) for Android enables debugging support: 47 | 48 | import android.webkit.WebView; 49 | 50 | WebView.setWebContentsDebuggingEnabled(true); // Sensitive 51 | WebView.getFactory().getStatics().setWebContentsDebuggingEnabled(true); // Sensitive 52 | 53 | 54 | 55 | 56 | ######## Recommended Secure Coding Practices 57 | 58 | Do not enable debug features on production servers or applications distributed to end users. 59 | Compliant Solution 60 | 61 | Loggers should be used (instead of printStackTrace) to print throwables: 62 | 63 | try { 64 | /* ... */ 65 | } catch(Exception e) { 66 | LOGGER.log("context", e); 67 | } 68 | 69 | EnableWebSecurity annotation for SpringFramework with debug to false disables debugging support: 70 | 71 | import org.springframework.context.annotation.Configuration; 72 | import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 73 | 74 | @Configuration 75 | @EnableWebSecurity(debug = false) 76 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 77 | // ... 78 | } 79 | 80 | WebView.setWebContentsDebuggingEnabled(false) for Android disables debugging support: 81 | 82 | import android.webkit.WebView; 83 | 84 | WebView.setWebContentsDebuggingEnabled(false); 85 | WebView.getFactory().getStatics().setWebContentsDebuggingEnabled(false); 86 | 87 | See 88 | 89 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 90 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 91 | MITRE, CWE-489 - Active Debug Code 92 | MITRE, CWE-215 - Information Exposure Through Debug Information 93 | ie in HTTPS Session Without 'Secure' Attribute 94 | SANS Top 25 - Porous Defenses 95 | 96 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security12.java: -------------------------------------------------------------------------------- 1 | ###### Disabling auto-escaping in template engines is security-sensitive 2 | 3 | Security Hotspot 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | To reduce the risk of cross-site scripting attacks, templating systems, such as Twig, Django, Smarty, Groovy's template engine, allow configuration of automatic variable escaping before rendering templates. When escape occurs, characters that make sense to the browser (eg: ) will be transformed/replaced with escaped/sanitized values (eg: & lt;a& gt; ). 11 | 12 | Auto-escaping is not a magic feature to annihilate all cross-site scripting attacks, it depends on the strategy applied and the context, for example a "html auto-escaping" strategy (which only transforms html characters into html entities) will not be relevant when variables are used in a html attribute because ':' character is not escaped and thus an attack as below is possible: 13 | 14 | link // myLink = javascript:alert(document.cookie) 15 | link // JS injection (XSS attack) 16 | 17 | 18 | ###### Ask Yourself Whether 19 | 20 | Templates are used to render web content and 21 | dynamic variables in templates come from untrusted locations or are user-controlled inputs 22 | there is no local mechanism in place to sanitize or validate the inputs. 23 | 24 | There is a risk if you answered yes to any of those questions. 25 | Sensitive Code Example 26 | 27 | With JMustache by samskivert: 28 | 29 | Mustache.compiler().escapeHTML(false).compile(template).execute(context); // Sensitive 30 | Mustache.compiler().withEscaper(Escapers.NONE).compile(template).execute(context); // Sensitive 31 | 32 | With Freemarker: 33 | 34 | freemarker.template.Configuration configuration = new freemarker.template.Configuration(); 35 | configuration.setAutoEscapingPolicy(DISABLE_AUTO_ESCAPING_POLICY); // Sensitive 36 | 37 | 38 | 39 | ######## Recommended Secure Coding Practices 40 | 41 | Enable auto-escaping by default and continue to review the use of inputs in order to be sure that the chosen auto-escaping strategy is the right one. 42 | Compliant Solution 43 | 44 | With JMustache by samskivert: 45 | 46 | Mustache.compiler().compile(template).execute(context); // Compliant, auto-escaping is enabled by default 47 | Mustache.compiler().escapeHTML(true).compile(template).execute(context); // Compliant 48 | 49 | With Freemarker. See "setAutoEscapingPolicy" documentation for more details. 50 | 51 | freemarker.template.Configuration configuration = new freemarker.template.Configuration(); 52 | configuration.setAutoEscapingPolicy(ENABLE_IF_DEFAULT_AUTO_ESCAPING_POLICY); // Compliant 53 | 54 | See 55 | 56 | OWASP Top 10 2021 Category A3 - Injection 57 | OWASP Cheat Sheet - XSS Prevention Cheat Sheet 58 | OWASP Top 10 2017 Category A7 - Cross-Site Scripting (XSS) 59 | MITRE, CWE-79 - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') 60 | 61 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security13.java: -------------------------------------------------------------------------------- 1 | ###### Disabling CSRF protections is security-sensitive 2 | 3 | Security Hotspot 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | A cross-site request forgery (CSRF) attack occurs when a trusted user of a web application can be forced, by an attacker, to perform sensitive actions that he didn’t intend, such as updating his profile or sending a message, more generally anything that can change the state of the application. 11 | 12 | The attacker can trick the user/victim to click on a link, corresponding to the privileged action, or to visit a malicious web site that embeds a hidden web request and as web browsers automatically include cookies, the actions can be authenticated and sensitive. 13 | 14 | 15 | ###### Ask Yourself Whether 16 | 17 | The web application uses cookies to authenticate users. 18 | There exist sensitive operations in the web application that can be performed when the user is authenticated. 19 | The state / resources of the web application can be modified by doing HTTP POST or HTTP DELETE requests for example. 20 | 21 | There is a risk if you answered yes to any of those questions. 22 | Sensitive Code Example 23 | 24 | Spring Security provides by default a protection against CSRF attacks which can be disabled: 25 | 26 | @EnableWebSecurity 27 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 28 | 29 | @Override 30 | protected void configure(HttpSecurity http) throws Exception { 31 | http.csrf().disable(); // Sensitive: csrf protection is entirely disabled 32 | // or 33 | http.csrf().ignoringAntMatchers("/route/"); // Sensitive: csrf protection is disabled for specific routes 34 | } 35 | } 36 | 37 | 38 | 39 | 40 | ######## Recommended Secure Coding Practices 41 | 42 | Protection against CSRF attacks is strongly recommended: 43 | to be activated by default for all unsafe HTTP methods. 44 | implemented, for example, with an unguessable CSRF token 45 | Of course all sensitive operations should not be performed with safe HTTP methods like GET which are designed to be used only for information retrieval. 46 | 47 | Compliant Solution 48 | 49 | Spring Security CSRF protection is enabled by default, do not disable it: 50 | 51 | @EnableWebSecurity 52 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 53 | 54 | @Override 55 | protected void configure(HttpSecurity http) throws Exception { 56 | // http.csrf().disable(); // Compliant 57 | } 58 | } 59 | 60 | See 61 | 62 | OWASP Top 10 2021 Category A1 - Broken Access Control 63 | MITRE, CWE-352 - Cross-Site Request Forgery (CSRF) 64 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 65 | OWASP: Cross-Site Request Forgery 66 | SANS Top 25 - Insecure Interaction Between Components 67 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security14.java: -------------------------------------------------------------------------------- 1 | ###### Disclosing fingerprints from web application technologies is security-sensitive 2 | 3 | Security Hotspot 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | Disclosing technology fingerprints allows an attacker to gather information about the technologies used to develop the web application and to perform relevant security assessments more quickly (like the identification of known vulnerable components). 11 | 12 | 13 | ###### Ask Yourself Whether 14 | 15 | The x-powered-by HTTP header or similar is used by the application. 16 | Technologies used by the application are confidential and should not be easily guessed. 17 | 18 | There is a risk if you answered yes to any of these questions. 19 | Sensitive Code Example 20 | 21 | public ResponseEntity testResponseEntity() { 22 | HttpHeaders responseHeaders = new HttpHeaders(); 23 | responseHeaders.set("x-powered-by", "myproduct"); // Sensitive 24 | 25 | return new ResponseEntity("foo", responseHeaders, HttpStatus.CREATED); 26 | } 27 | 28 | 29 | 30 | 31 | 32 | 33 | ######## Recommended Secure Coding Practices 34 | 35 | It’s recommended to not disclose technologies used on a website, with x-powered-by HTTP header for example. 36 | 37 | In addition, it’s better to completely disable this HTTP header rather than setting it a random value. 38 | Compliant Solution 39 | 40 | Don’t use x-powered-by or Server HTTP header or any other means disclosing fingerprints of the application. 41 | See 42 | 43 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 44 | OWASP Testing Guide - OTG-INFO-008 - Fingerprint Web Application Framework 45 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 46 | MITRE, CWE-200 - Information Exposure 47 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security15.java: -------------------------------------------------------------------------------- 1 | ###### Enabling file access for WebViews is security-sensitive 2 | 3 | Security Hotspot 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | WebViews can be used to display web content as part of a mobile application. A browser engine is used to render and display the content. Like a web application a mobile application that uses WebViews can be vulnerable to Cross-Site Scripting if untrusted code is rendered. 11 | 12 | If malicious JavaScript code in a WebView is executed this can leak the contents of sensitive files when access to local files is enabled. 13 | 14 | 15 | ###### Ask Yourself Whether 16 | 17 | No local files have to be accessed by the Webview. 18 | The WebView contains untrusted data that could cause harm when rendered. 19 | 20 | There is a risk if you answered yes to any of those questions. 21 | Sensitive Code Example 22 | 23 | import android.webkit.WebView; 24 | 25 | WebView webView = (WebView) findViewById(R.id.webview); 26 | webView.getSettings().setAllowFileAccess(true); // Sensitive 27 | webView.getSettings().setAllowContentAccess(true); // Sensitive 28 | 29 | 30 | 31 | ######## Recommended Secure Coding Practices 32 | 33 | It’s recommended to disable access to local files for WebViews unless it is necessary. In the case of a successful attack through a Cross-Site Scripting vulnerability the attackers attack surface decreases drastically if no files can be read out. 34 | Compliant Solution 35 | 36 | import android.webkit.WebView; 37 | 38 | WebView webView = (WebView) findViewById(R.id.webview); 39 | webView.getSettings().setAllowFileAccess(false); 40 | webView.getSettings().setAllowContentAccess(false); 41 | 42 | See 43 | 44 | OWASP Top 10 2021 Category A3 - Injection 45 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 46 | OWASP Top 10 2017 Category A7 - Cross-Site Scripting (XSS) 47 | MITRE, CWE-79 - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') 48 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security16.java: -------------------------------------------------------------------------------- 1 | ###### Enabling JavaScript support for WebViews is security-sensitive 2 | 3 | Security Hotspot 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | WebViews can be used to display web content as part of a mobile application. A browser engine is used to render and display the content. Like a web application a mobile application that uses WebViews can be vulnerable to Cross-Site Scripting if untrusted code is rendered. In the context of a WebView JavaScript code can exfiltrate local files that might be sensitive or even worse, access exposed functions of the application that can result in more severe vulnerabilities such as code injection. Thus JavaScript support should not be enabled for WebViews unless it is absolutely necessary and the authenticity of the web resources can be guaranteed. 11 | 12 | ###### Ask Yourself Whether 13 | 14 | The WebWiew only renders static web content that does not require JavaScript code to be executed. 15 | The WebView contains untrusted data that could cause harm when rendered. 16 | 17 | There is a risk if you answered yes to any of those questions. 18 | Sensitive Code Example 19 | 20 | import android.webkit.WebView; 21 | 22 | WebView webView = (WebView) findViewById(R.id.webview); 23 | webView.getSettings().setJavaScriptEnabled(true); // Sensitive 24 | 25 | 26 | 27 | ######## Recommended Secure Coding Practices 28 | 29 | It’s recommended to disable JavaScript support for WebViews unless it is necessary to execute JavaScript code. Only trusted pages should be rendered. 30 | Compliant Solution 31 | 32 | import android.webkit.WebView; 33 | 34 | WebView webView = (WebView) findViewById(R.id.webview); 35 | webView.getSettings().setJavaScriptEnabled(false); 36 | 37 | See 38 | 39 | OWASP Top 10 2021 Category A3 - Injection 40 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 41 | OWASP Top 10 2017 Category A7 - Cross-Site Scripting (XSS) 42 | MITRE, CWE-79 - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') 43 | 44 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security19.java: -------------------------------------------------------------------------------- 1 | ###### Hard-coded passwords are security-sensitive 2 | 3 | Security Hotspot 4 | Blocker 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 30min 9 | 10 | Because it is easy to extract strings from an application source code or binary, passwords should not be hard-coded. This is particularly true for applications that are distributed or that are open-source. 11 | 12 | In the past, it has led to the following vulnerabilities: 13 | 14 | CVE-2019-13466 15 | CVE-2018-15389 16 | 17 | Passwords should be stored outside of the code in a configuration file, a database, or a password management service. 18 | 19 | This rule flags instances of hard-coded passwords used in database and LDAP connections. It looks for hard-coded passwords in connection strings, and for variable names that match any of the patterns from the provided list. 20 | 21 | ###### Ask Yourself Whether 22 | 23 | The password allows access to a sensitive component like a database, a file storage, an API, or a service. 24 | The password is used in production environments. 25 | Application re-distribution is required before updating the password. 26 | 27 | There would be a risk if you answered yes to any of those questions. 28 | Sensitive Code Example 29 | 30 | String username = "steve"; 31 | String password = "blue"; 32 | Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + 33 | "user=" + uname + "&password=" + password); // Sensitive 34 | 35 | 36 | 37 | 38 | 39 | 40 | ######## Recommended Secure Coding Practices 41 | 42 | Store the credentials in a configuration file that is not pushed to the code repository. 43 | Store the credentials in a database. 44 | Use your cloud provider’s service for managing secrets. 45 | If a password has been disclosed through the source code: change it. 46 | 47 | Compliant Solution 48 | 49 | String username = getEncryptedUser(); 50 | String password = getEncryptedPassword(); 51 | Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" + 52 | "user=" + uname + "&password=" + password); 53 | 54 | See 55 | 56 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 57 | OWASP Top 10 2017 Category A2 - Broken Authentication 58 | MITRE, CWE-798 - Use of Hard-coded Credentials 59 | MITRE, CWE-259 - Use of Hard-coded Password 60 | CERT, MSC03-J. - Never hard code sensitive information 61 | Derived from FindSecBugs rule Hard Coded Password 62 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security23.java: -------------------------------------------------------------------------------- 1 | ###### Searching OS commands in PATH is security-sensitive 2 | 3 | Security Hotspot 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | When executing an OS command and unless you specify the full path to the executable, then the locations in your application’s PATH environment variable will be searched for the executable. That search could leave an opening for an attacker if one of the elements in PATH is a directory under his control. 11 | 12 | ###### Ask Yourself Whether 13 | 14 | The directories in the PATH environment variable may be defined by not trusted entities. 15 | 16 | There is a risk if you answered yes to this question. 17 | Sensitive Code Example 18 | 19 | The full path of the command is not specified and thus the executable will be searched in all directories listed in the PATH environment variable: 20 | 21 | Runtime.getRuntime().exec("make"); // Sensitive 22 | Runtime.getRuntime().exec(new String[]{"make"}); // Sensitive 23 | 24 | ProcessBuilder builder = new ProcessBuilder("make"); // Sensitive 25 | builder.command("make"); // Sensitive 26 | 27 | 28 | 29 | 30 | 31 | 32 | ######## Recommended Secure Coding Practices 33 | 34 | Fully qualified/absolute path should be used to specify the OS command to execute. 35 | Compliant Solution 36 | 37 | The command is defined by its full path: 38 | 39 | Runtime.getRuntime().exec("/usr/bin/make"); // Compliant 40 | Runtime.getRuntime().exec(new String[]{"~/bin/make"}); // Compliant 41 | 42 | ProcessBuilder builder = new ProcessBuilder("./bin/make"); // Compliant 43 | builder.command("../bin/make"); // Compliant 44 | builder.command(Arrays.asList("..\bin\make", "-j8")); // Compliant 45 | 46 | builder = new ProcessBuilder(Arrays.asList(".\make")); // Compliant 47 | builder.command(Arrays.asList("C:\bin\make", "-j8")); // Compliant 48 | builder.command(Arrays.asList("\\SERVER\bin\make")); // Compliant 49 | 50 | See 51 | 52 | OWASP Top 10 2021 Category A8 - Software and Data Integrity Failures 53 | OWASP Top 10 2017 Category A1 - Injection 54 | MITRE, CWE-426 - Untrusted Search Path 55 | MITRE, CWE-427 - Uncontrolled Search Path Element 56 | 57 | 58 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security24.java: -------------------------------------------------------------------------------- 1 | ###### Setting JavaBean properties is security-sensitive 2 | 3 | Security Hotspot 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | Setting JavaBean properties is security sensitive. Doing it with untrusted values has led in the past to the following vulnerability: 11 | 12 | CVE-2014-0114 13 | 14 | JavaBeans can have their properties or nested properties set by population functions. An attacker can leverage this feature to push into the JavaBean malicious data that can compromise the software integrity. A typical attack will try to manipulate the ClassLoader and finally execute malicious code. 15 | 16 | This rule raises an issue when: 17 | 18 | BeanUtils.populate(…​) or BeanUtilsBean.populate(…​) from Apache Commons BeanUtils are called 19 | BeanUtils.setProperty(…​) or BeanUtilsBean.setProperty(…​) from Apache Commons BeanUtils are called 20 | org.springframework.beans.BeanWrapper.setPropertyValue(…​) or org.springframework.beans.BeanWrapper.setPropertyValues(…​) from Spring is called 21 | 22 | 23 | 24 | ###### Ask Yourself Whether 25 | 26 | the new property values might have been tampered with or provided by an untrusted source. 27 | sensitive properties can be modified, for example: class.classLoader 28 | 29 | There is a risk if you answered yes to any of those questions. 30 | Sensitive Code Example 31 | 32 | Company bean = new Company(); 33 | HashMap map = new HashMap(); 34 | Enumeration names = request.getParameterNames(); 35 | while (names.hasMoreElements()) { 36 | String name = (String) names.nextElement(); 37 | map.put(name, request.getParameterValues(name)); 38 | } 39 | BeanUtils.populate(bean, map); // Sensitive: "map" is populated with data coming from user input, here "request.getParameterNames()" 40 | 41 | 42 | 43 | 44 | 45 | ######## Recommended Secure Coding Practices 46 | 47 | Sanitize all values used as JavaBean properties. 48 | 49 | Don’t set any sensitive properties. Keep full control over which properties are set. If the property names are provided by an unstrusted source, filter them with a whitelist. 50 | See 51 | 52 | OWASP Top 10 2021 Category A3 - Injection 53 | OWASP Top 10 2021 Category A8 - Software and Data Integrity Failures 54 | OWASP Top 10 2017 Category A1 - Injection 55 | MITRE, CWE-915 - Improperly Controlled Modification of Dynamically-Determined Object Attributes 56 | CERT, MSC61-J. - Do not use insecure or weak cryptographic algorithms 57 | Derived from FindSecBugs rule BEAN_PROPERTY_INJECTION 58 | 59 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security26.java: -------------------------------------------------------------------------------- 1 | ###### Using biometric authentication without a cryptographic solution is security-sensitive 2 | 3 | Security Hotspot 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 5min 9 | 10 | Android comes with Android KeyStore, a secure container for storing key materials. It’s possible to define certain keys to be unlocked when users authenticate using biometric credentials. This way, even if the application process is compromised, the attacker cannot access keys, as presence of the authorized user is required. 11 | 12 | These keys can be used, to encrypt, sign or create a message authentication code (MAC) as proof that the authentication result has not been tampered with. This protection defeats the scenario where an attacker with physical access to the device would try to hook into the application process and call the onAuthenticationSucceeded method directly. Therefore he would be unable to extract the sensitive data or to perform the critical operations protected by the biometric authentication. 13 | 14 | 15 | ###### Ask Yourself Whether 16 | 17 | The application contains: 18 | 19 | Cryptographic keys / sensitive information that need to be protected using biometric authentication. 20 | 21 | There is a risk if you answered yes to this question. 22 | Noncompliant Code Example 23 | 24 | A CryptoObject is not used during authentication: 25 | 26 | // ... 27 | BiometricPrompt biometricPrompt = new BiometricPrompt(activity, executor, callback); 28 | // ... 29 | biometricPrompt.authenticate(promptInfo); // Noncompliant 30 | 31 | 32 | 33 | 34 | 35 | ######## Recommended Secure Coding Practices 36 | 37 | It’s recommended to tie the biometric authentication to a cryptographic operation by using a CryptoObject during authentication. 38 | Compliant Solution 39 | 40 | A CryptoObject is used during authentication: 41 | 42 | // ... 43 | BiometricPrompt biometricPrompt = new BiometricPrompt(activity, executor, callback); 44 | // ... 45 | biometricPrompt.authenticate(promptInfo, new BiometricPrompt.CryptoObject(cipher)); // Compliant 46 | 47 | See 48 | 49 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 50 | developer.android.com - Use a cryptographic solution that depends on authentication 51 | OWASP Mobile Top 10 Category M4 - Insecure Authentication 52 | OWASP MASVS - Authentication and Session Management Requirements 53 | MITRE, CWE-287 - Improper Authentication 54 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security28.java: -------------------------------------------------------------------------------- 1 | ###### Using hardcoded IP addresses is security-sensitive 2 | 3 | Security Hotspot 4 | Minor 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 30min 9 | 10 | Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities: 11 | 12 | CVE-2006-5901 13 | CVE-2005-3725 14 | 15 | Today’s services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery, and deployment: 16 | 17 | The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file. 18 | It misleads to use the same address in every environment (dev, sys, qa, prod). 19 | 20 | Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service, try to get access to the system, or try to spoof the IP address to bypass security checks. Such attacks can always be possible, but in the case of a hardcoded IP address solving the issue will take more time, which will increase an attack’s impact. 21 | Exceptions 22 | 23 | No issue is reported for the following cases because they are not considered sensitive: 24 | 25 | Loopback addresses 127.0.0.0/8 in CIDR notation (from 127.0.0.0 to 127.255.255.255) 26 | Broadcast address 255.255.255.255 27 | Non-routable address 0.0.0.0 28 | Strings of the form 2.5.. as they often match Object Identifiers (OID) 29 | Addresses in the ranges 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, reserved for documentation purposes by RFC 5737 30 | Addresses in the range 2001:db8::/32, reserved for documentation purposes by RFC 3849 31 | 32 | 33 | ###### Ask Yourself Whether 34 | 35 | The disclosed IP address is sensitive, e.g.: 36 | 37 | Can give information to an attacker about the network topology. 38 | It’s a personal (assigned to an identifiable person) IP address. 39 | 40 | There is a risk if you answered yes to any of these questions. 41 | Sensitive Code Example 42 | 43 | String ip = "192.168.12.42"; // Sensitive 44 | Socket socket = new Socket(ip, 6667); 45 | 46 | 47 | ######## Recommended Secure Coding Practices 48 | 49 | Don’t hard-code the IP address in the source code, instead make it configurable with environment variables, configuration files, or a similar approach. Alternatively, if confidentially is not required a domain name can be used since it allows to change the destination quickly without having to rebuild the software. 50 | Compliant Solution 51 | 52 | String ip = System.getenv("IP_ADDRESS"); // Compliant 53 | Socket socket = new Socket(ip, 6667); 54 | 55 | See 56 | 57 | OWASP Top 10 2021 Category A1 - Broken Access Control 58 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 59 | CERT, MSC03-J. - Never hard code sensitive information 60 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security29.java: -------------------------------------------------------------------------------- 1 | ###### Using long-term access keys is security-sensitive 2 | 3 | Security Hotspot 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 1h 9 | 10 | In AWS, long-term access keys will be valid until you manually revoke them. This makes them highly sensitive as any exposure can have serious consequences and should be used with care. 11 | 12 | This rule will trigger when encountering an instantiation of com.amazonaws.auth.BasicAWSCredentials. 13 | 14 | ###### Ask Yourself Whether 15 | 16 | The access key is used directly in an application or AWS CLI script running on an Amazon EC2 instance. 17 | Cross-account access is needed. 18 | The access keys need to be embedded within a mobile application. 19 | Existing identity providers (SAML 2.0, on-premises identity store) already exists. 20 | 21 | For more information, see Use IAM roles instead of long-term access keys. 22 | 23 | There is a risk if you answered yes to any of those questions. 24 | Sensitive Code Example 25 | 26 | import com.amazonaws.auth.AWSCredentials; 27 | import com.amazonaws.auth.BasicAWSCredentials; 28 | // ... 29 | 30 | AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, secretAccessKey); 31 | 32 | 33 | 34 | ######## Recommended Secure Coding Practices 35 | 36 | Consider using IAM roles or other features of the AWS Security Token Service that provide temporary credentials, limiting the risks. 37 | Compliant Solution 38 | 39 | Example for AWS STS (see Getting Temporary Credentials with AWS STS). 40 | 41 | BasicSessionCredentials sessionCredentials = new BasicSessionCredentials( 42 | session_creds.getAccessKeyId(), 43 | session_creds.getSecretAccessKey(), 44 | session_creds.getSessionToken()); 45 | 46 | See 47 | 48 | Best practices for managing AWS access keys 49 | Managing access keys for IAM users 50 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security30.java: -------------------------------------------------------------------------------- 1 | ###### Using non-standard cryptographic algorithms is security-sensitive 2 | 3 | Security Hotspot 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 1d 9 | 10 | The use of a non-standard algorithm is dangerous because a determined attacker may be able to break the algorithm and compromise whatever data has been protected. Standard algorithms like SHA-256, SHA-384, SHA-512, …​ should be used instead. 11 | 12 | This rule tracks creation of java.security.MessageDigest subclasses. 13 | 14 | 15 | ###### Sensitive Code Example 16 | 17 | public class MyCryptographicAlgorithm extends MessageDigest { 18 | ... 19 | } 20 | 21 | 22 | 23 | ######## Recommended Secure Coding Practices 24 | 25 | Use a standard algorithm instead of creating a custom one. 26 | 27 | Compliant Solution 28 | 29 | MessageDigest digest = MessageDigest.getInstance("SHA-256"); 30 | 31 | See 32 | 33 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 34 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 35 | MITRE, CWE-327 - Use of a Broken or Risky Cryptographic Algorithm 36 | SANS Top 25 - Porous Defenses 37 | Derived from FindSecBugs rule MessageDigest is Custom 38 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security31.java: -------------------------------------------------------------------------------- 1 | ###### Using pseudorandom number generators (PRNGs) is security-sensitive 2 | 3 | Security Hotspot 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | Using pseudorandom number generators (PRNGs) is security-sensitive. For example, it has led in the past to the following vulnerabilities: 11 | 12 | CVE-2013-6386 13 | CVE-2006-3419 14 | CVE-2008-4102 15 | 16 | When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. 17 | 18 | As the java.util.Random class relies on a pseudorandom number generator, this class and relating java.lang.Math.random() method should not be used for security-critical applications or for protecting sensitive data. In such context, the java.security.SecureRandom class which relies on a cryptographically strong random number generator (RNG) should be used in place. 19 | 20 | 21 | ###### Ask Yourself Whether 22 | 23 | the code using the generated value requires it to be unpredictable. It is the case for all encryption mechanisms or when a secret value, such as a password, is hashed. 24 | the function you use generates a value which can be predicted (pseudo-random). 25 | the generated value is used multiple times. 26 | an attacker can access the generated value. 27 | 28 | There is a risk if you answered yes to any of those questions. 29 | Sensitive Code Example 30 | 31 | Random random = new Random(); // Sensitive use of Random 32 | byte bytes[] = new byte[20]; 33 | random.nextBytes(bytes); // Check if bytes is used for hashing, encryption, etc... 34 | 35 | 36 | 37 | 38 | ######## Recommended Secure Coding Practices 39 | 40 | Use a cryptographically strong random number generator (RNG) like "java.security.SecureRandom" in place of this PRNG. 41 | Use the generated random values only once. 42 | You should not expose the generated random value. If you have to store it, make sure that the database or file is secure. 43 | 44 | Compliant Solution 45 | 46 | SecureRandom random = new SecureRandom(); // Compliant for security-sensitive use cases 47 | byte bytes[] = new byte[20]; 48 | random.nextBytes(bytes); 49 | 50 | See 51 | 52 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 53 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 54 | Mobile AppSec Verification Standard - Cryptography Requirements 55 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 56 | MITRE, CWE-338 - Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG) 57 | MITRE, CWE-330 - Use of Insufficiently Random Values 58 | MITRE, CWE-326 - Inadequate Encryption Strength 59 | MITRE, CWE-1241 - Use of Predictable Algorithm in Random Number Generator 60 | CERT, MSC02-J. - Generate strong random numbers 61 | CERT, MSC30-C. - Do not use the rand() function for generating pseudorandom numbers 62 | CERT, MSC50-CPP. - Do not use std::rand() for generating pseudorandom numbers 63 | Derived from FindSecBugs rule Predictable Pseudo Random Number Generator 64 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security35.java: -------------------------------------------------------------------------------- 1 | ###### Using unencrypted files in mobile applications is security-sensitive 2 | 3 | Security Hotspot 4 | Major 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 10min 9 | 10 | Storing files locally is a common task for mobile applications. Files that are stored unencrypted can be read out and modified by an attacker with physical access to the device. Access to sensitive data can be harmful for the user of the application, for example when the device gets stolen. 11 | 12 | 13 | ###### Ask Yourself Whether 14 | 15 | The file contains sensitive data that could cause harm when leaked. 16 | 17 | There is a risk if you answered yes to any of those questions. 18 | Sensitive Code Example 19 | 20 | Files.write(path, content); // Sensitive 21 | 22 | FileOutputStream out = new FileOutputStream(file); // Sensitive 23 | 24 | FileWriter fw = new FileWriter("outfilename", false); // Sensitive 25 | 26 | 27 | 28 | 29 | ######## Recommended Secure Coding Practices 30 | 31 | It’s recommended to password-encrypt local files that contain sensitive information. The class EncryptedFile can be used to easily encrypt files. 32 | Compliant Solution 33 | 34 | String masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC); 35 | 36 | File file = new File(context.getFilesDir(), "secret_data"); 37 | EncryptedFile encryptedFile = EncryptedFile.Builder( 38 | file, 39 | context, 40 | masterKeyAlias, 41 | EncryptedFile.FileEncryptionScheme.AES256_GCM_HKDF_4KB 42 | ).build(); 43 | 44 | // write to the encrypted file 45 | FileOutputStream encryptedOutputStream = encryptedFile.openFileOutput(); 46 | 47 | See 48 | 49 | OWASP Top 10 2021 Category A4 - Insecure Design 50 | Mobile AppSec Verification Standard - Data Storage and Privacy Requirements 51 | OWASP Mobile Top 10 2016 Category M2 - Insecure Data Storage 52 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 53 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 54 | MITRE, CWE-311 - Missing Encryption of Sensitive Data 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security36.java: -------------------------------------------------------------------------------- 1 | ###### Using unsafe Jackson deserialization configuration is security-sensitive 2 | 3 | Security Hotspot 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | Constant/issue: 15min 9 | 10 | Using unsafe Jackson deserialization configuration is security-sensitive. It has led in the past to the following vulnerabilities: 11 | 12 | CVE-2017-4995 13 | CVE-2018-19362 14 | 15 | When Jackson is configured to allow Polymorphic Type Handling (aka PTH), formerly known as Polymorphic Deserialization, "deserialization gadgets" may allow an attacker to perform remote code execution. 16 | 17 | This rule raises an issue when: 18 | 19 | enableDefaultTyping() is called on an instance of com.fasterxml.jackson.databind.ObjectMapper or org.codehaus.jackson.map.ObjectMapper. 20 | or when the annotation @JsonTypeInfo is set at class, interface or field levels and configured with use = JsonTypeInfo.Id.CLASS or use = Id.MINIMAL_CLASS. 21 | 22 | 23 | ###### Ask Yourself Whether 24 | 25 | You configured the Jackson deserializer as mentioned above. 26 | The serialized data might come from an untrusted source. 27 | 28 | There is a risk if you answered yes to any of those questions. 29 | Sensitive Code Example 30 | 31 | ObjectMapper mapper = new ObjectMapper(); 32 | mapper.enableDefaultTyping(); // Sensitive 33 | 34 | @JsonTypeInfo(use = Id.CLASS) // Sensitive 35 | abstract class PhoneNumber { 36 | } 37 | 38 | 39 | 40 | 41 | 42 | ######## Recommended Secure Coding Practices 43 | 44 | Use the latest patch versions of jackson-databind blocking the already discovered "deserialization gadgets". 45 | Avoid using the default typing configuration: ObjectMapper.enableDefaultTyping(). 46 | If possible, use @JsonTypeInfo(use = Id.NAME) instead of @JsonTypeInfo(use = Id.CLASS) or @JsonTypeInfo(use = Id. MINIMAL_CLASS) and so rely on @JsonTypeName and @JsonSubTypes. 47 | 48 | See 49 | 50 | OWASP Top 10 2021 Category A8 - Software and Data Integrity Failures 51 | OWASP Top 10 2017 Category A8 - Insecure Deserialization 52 | OWASP - Deserialization of untrusted data 53 | MITRE, CWE-502 - Deserialization of Untrusted Data 54 | On Jackson CVEs: Don’t Panic 55 | CVE-2017-1509 56 | CVE-2017-7525 57 | Derived from FindSecBugs rule JACKSON_UNSAFE_DESERIALIZATION 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /00.java/01.Security_Hotspot/Security37.java: -------------------------------------------------------------------------------- 1 | ###### Using weak hashing algorithms is security-sensitive 2 | 3 | Security Hotspot 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Java) 8 | 9 | Cryptographic hash algorithms such as MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (which uses SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 and SHA-1 are no longer considered secure, because it is possible to have collisions (little computational effort is enough to find two or more different inputs that produce the same hash). 10 | 11 | 12 | ###### Ask Yourself Whether 13 | 14 | The hashed value is used in a security context like: 15 | 16 | User-password storage. 17 | Security token generation (used to confirm e-mail when registering on a website, reset password, etc …​). 18 | To compute some message integrity. 19 | 20 | There is a risk if you answered yes to any of those questions. 21 | Sensitive Code Example 22 | 23 | MessageDigest md1 = MessageDigest.getInstance("SHA"); // Sensitive: SHA is not a standard name, for most security providers it's an alias of SHA-1 24 | MessageDigest md2 = MessageDigest.getInstance("SHA1"); // Sensitive 25 | 26 | 27 | 28 | 29 | 30 | 31 | ######## Recommended Secure Coding Practices 32 | 33 | Safer alternatives, such as SHA-256, SHA-512, SHA-3 are recommended, and for password hashing, it’s even better to use algorithms that do not compute too "quickly", like bcrypt, scrypt, argon2 or pbkdf2 because it slows down brute force attacks. 34 | Compliant Solution 35 | 36 | MessageDigest md1 = MessageDigest.getInstance("SHA-512"); // Compliant 37 | 38 | See 39 | 40 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 41 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 42 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 43 | Mobile AppSec Verification Standard - Cryptography Requirements 44 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 45 | MITRE, CWE-1240 - Use of a Risky Cryptographic Primitive 46 | SANS Top 25 - Porous Defenses 47 | 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security01.py: -------------------------------------------------------------------------------- 1 | '''Метод HTTP безопасен, если используется для выполнения операции только для чтения, например получения информации. Напротив, небезопасный метод HTTP используется для изменения состояния приложения, например, для обновления профиля пользователя в веб-приложении. 2 | 3 | Распространенными безопасными методами HTTP являются GET, HEAD или OPTIONS. 4 | 5 | Распространенными небезопасными методами HTTP являются POST, PUT и DELETE. 6 | 7 | Разрешение как безопасным, так и небезопасным методам HTTP выполнять определенную операцию в веб-приложении может повлиять на его безопасность, например, защита CSRF в большинстве случаев защищает только операции, выполняемые небезопасными методами HTTP. 8 | 9 | Спросите себя, есть ли 10 | 11 | Методы HTTP вообще не определены для маршрута/контроллера приложения. 12 | Безопасные методы HTTP определяются и используются для маршрута/контроллера, который может изменять состояние приложения. 13 | 14 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 15 | 16 | For Django:''' 17 | 18 | # No method restriction 19 | def view(request): # Sensitive 20 | return HttpResponse("...") 21 | 22 | @require_http_methods(["GET", "POST"]) # Sensitive 23 | def view(request): 24 | return HttpResponse("...") 25 | 26 | For Flask: 27 | 28 | @methods.route('/sensitive', methods=['GET', 'POST']) # Sensitive 29 | def view(): 30 | return Response("...", 200) 31 | 32 | 33 | 34 | ### Рекомендуемые методы безопасного кодирования 35 | 36 | '''Для всех маршрутов/контроллеров приложения авторизованные методы HTTP должны быть явно определены, а безопасные методы HTTP должны использоваться только для выполнения операций только для чтения. 37 | 38 | 39 | For Django:''' 40 | 41 | @require_http_methods(["POST"]) 42 | def view(request): 43 | return HttpResponse("...") 44 | 45 | @require_POST 46 | def view(request): 47 | return HttpResponse("...") 48 | 49 | @require_GET 50 | def view(request): 51 | return HttpResponse("...") 52 | 53 | @require_safe 54 | def view(request): 55 | return HttpResponse("...") 56 | 57 | For Flask: 58 | 59 | @methods.route('/compliant1') 60 | def view(): 61 | return Response("...", 200) 62 | 63 | @methods.route('/compliant2', methods=['GET']) 64 | def view(): 65 | return Response("...", 200) 66 | 67 | '''See 68 | 69 | OWASP Top 10 2021 Category A1 - Broken Access Control 70 | OWASP Top 10 2021 Category A4 - Insecure Design 71 | OWASP Top 10 2017 Category A5 - Broken Access Control 72 | MITRE, CWE-352 - Cross-Site Request Forgery (CSRF) 73 | OWASP: Cross-Site Request Forgery 74 | SANS Top 25 - Insecure Interaction Between Components 75 | Django - Allowed HTTP Methods 76 | Flask - HTTP Methods''' 77 | 78 | 79 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security04.py: -------------------------------------------------------------------------------- 1 | ###### Разрешение неограниченной исходящей связи очень важно для безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/выпуск: 1 час 9 | 10 | Разрешение неограниченной исходящей связи может привести к утечке данных. 11 | 12 | Ограничительная группа безопасности — это дополнительный уровень защиты, который может предотвратить злоупотребление или эксплуатацию ресурса. Например, это усложняет кражу данных в случае успешно использованной уязвимости. 13 | 14 | Принимая решение о том, следует ли ограничить исходящие соединения, учтите, что ограничение соединений приведет к дополнительным работам по администрированию и обслуживанию. 15 | 16 | 17 | ###### Спросите себя, есть ли 18 | 19 | Ресурс имеет доступ к конфиденциальным данным. 20 | Ресурс является частью частной сети. 21 | 22 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 23 | Пример конфиденциального кода 24 | 25 | For aws_cdk.aws_ec2.SecurityGroup:''' 26 | 27 | from aws_cdk import ( 28 | aws_ec2 as ec2 29 | ) 30 | 31 | ec2.SecurityGroup( # Sensitive; allow_all_outbound is enabled by default 32 | self, 33 | "example", 34 | vpc=vpc 35 | ) 36 | 37 | 38 | ### Рекомендуемые методы безопасного кодирования 39 | 40 | # Рекомендуется ограничить исходящие соединения набором доверенных пунктов назначения. 41 | # Соответствующее решение 42 | 43 | For aws_cdk.aws_ec2.SecurityGroup: 44 | 45 | from aws_cdk import ( 46 | aws_ec2 as ec2 47 | ) 48 | 49 | sg = ec2.SecurityGroup( 50 | self, 51 | "example", 52 | vpc=vpc, 53 | allow_all_outbound=False 54 | ) 55 | 56 | sg.add_egress_rule( 57 | peer=ec2.Peer.ipv4("203.0.113.127/32"), 58 | connection=ec2.Port.tcp(443) 59 | ) 60 | 61 | '''See 62 | 63 | OWASP Top 10 2021 Category A1 - Broken Access Control 64 | AWS Documentation - Control traffic to resources using security groups 65 | MITRE, CWE-284 - Improper Access Control 66 | OWASP Top 10 2017 Category A5 - Broken Access Control''' 67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security06.py: -------------------------------------------------------------------------------- 1 | ###### Создание файлов cookie без флага «HttpOnly» является чувствительным к безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянная/проблема: 10 мин. 9 | 10 | Если файл cookie настроен с атрибутом HttpOnly, установленным в значение true, браузер гарантирует, что ни один клиентский сценарий не сможет его прочитать. В большинстве случаев при создании файла cookie значение HttpOnly по умолчанию равно false, и разработчик должен решить, может ли содержимое файла cookie быть прочитано клиентским сценарием. Поскольку большинство атак с использованием межсайтового скриптинга (XSS) направлены на кражу файлов cookie сеанса, атрибут HttpOnly может помочь уменьшить их воздействие, поскольку будет невозможно использовать уязвимость XSS для кражи файлов cookie сеанса. 11 | 12 | ###### Спросите себя, есть ли 13 | 14 | файл cookie чувствителен и используется для аутентификации пользователя, например сеансовый файл cookie 15 | Атрибут HttpOnly обеспечивает дополнительную защиту (например, это не касается файла cookie XSRF-TOKEN/токена CSRF) 16 | 17 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 18 | Пример конфиденциального кода 19 | 20 | Flask:''' 21 | 22 | from flask import Response 23 | 24 | @app.route('/') 25 | def index(): 26 | response = Response() 27 | response.set_cookie('key', 'value') # Sensitive 28 | return response 29 | 30 | 31 | 32 | ### Рекомендуемые методы безопасного кодирования 33 | 34 | '''По умолчанию флаг HttpOnly должен быть установлен в значение true для большинства файлов cookie и является обязательным для файлов cookie сеанса или конфиденциальной безопасности. 35 | 36 | Соответствующее решение 37 | 38 | Flask:''' 39 | 40 | from flask import Response 41 | 42 | @app.route('/') 43 | def index(): 44 | response = Response() 45 | response.set_cookie('key', 'value', httponly=True) # Compliant 46 | return response 47 | 48 | '''See 49 | 50 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 51 | OWASP HttpOnly 52 | OWASP Top 10 2017 Category A7 - Cross-Site Scripting (XSS) 53 | MITRE, CWE-1004 - Sensitive Cookie Without 'HttpOnly' Flag 54 | SANS Top 25 - Insecure Interaction Between Components 55 | Derived from FindSecBugs rule HTTPONLY_COOKIE 56 | ''' -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security07.py: -------------------------------------------------------------------------------- 1 | ###### Создание файлов cookie без флага «безопасно» является чувствительным к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | Если файл cookie защищен атрибутом Secure, для которого установлено значение true, он не будет отправлен браузером по незашифрованному HTTP-запросу и, следовательно, не сможет быть обнаружен посторонним лицом во время атаки «человек посередине». 11 | 12 | ###### Спросите себя, есть ли 13 | 14 | например, файл cookie представляет собой сеансовый файл cookie, не предназначенный для отправки по каналу связи, отличному от HTTPS. 15 | не уверен, содержит ли сайт смешанный контент или нет (т.е. везде HTTPS или нет) 16 | 17 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 18 | Пример конфиденциального кода 19 | 20 | Flask 21 | ''' 22 | from flask import Response 23 | 24 | @app.route('/') 25 | def index(): 26 | response = Response() 27 | response.set_cookie('key', 'value') # Sensitive 28 | return response 29 | 30 | 31 | ### Рекомендуемые методы безопасного кодирования 32 | ''' 33 | Рекомендуется везде использовать HTTP, поэтому установка флага безопасности в значение true должна быть поведением по умолчанию при создании файлов cookie. 34 | Установите для флага безопасности значение true для файлов cookie сеанса. 35 | 36 | Соответствующее решение 37 | 38 | Flask''' 39 | 40 | from flask import Response 41 | 42 | @app.route('/') 43 | def index(): 44 | response = Response() 45 | response.set_cookie('key', 'value', secure=True) # Compliant 46 | return response 47 | 48 | '''See 49 | 50 | OWASP Top 10 2021 Category A4 - Insecure Design 51 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 52 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 53 | MITRE, CWE-311 - Missing Encryption of Sensitive Data 54 | MITRE, CWE-315 - Cleartext Storage of Sensitive Information in a Cookie 55 | MITRE, CWE-614 - Sensitive Cookie in HTTPS Session Without 'Secure' Attribute 56 | SANS Top 25 - Porous Defenses 57 | ''' 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security08.py: -------------------------------------------------------------------------------- 1 | ###### Создание общедоступных API чувствительно к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Блокатор 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | Публичный API, который может быть запрошен любыми аутентифицированными или неаутентифицированными пользователями, может привести к несанкционированным действиям и раскрытию информации. 11 | 12 | ###### Спросите себя, есть ли 13 | 14 | Публичный API: 15 | 16 | раскрывает конфиденциальные данные, такие как личная информация. 17 | может использоваться для выполнения чувствительных операций. 18 | 19 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 20 | Пример конфиденциального кода 21 | 22 | For aws_cdk.aws_apigateway.Resource: 23 | ''' 24 | from aws_cdk import ( 25 | aws_apigateway as apigateway 26 | ) 27 | 28 | resource = api.root.add_resource("example") 29 | resource.add_method( 30 | "GET", 31 | authorization_type=apigateway.AuthorizationType.NONE # Sensitive 32 | ) 33 | 34 | # For aws_cdk.aws_apigatewayv2.CfnRoute: 35 | 36 | from aws_cdk import ( 37 | aws_apigatewayv2 as apigateway 38 | ) 39 | 40 | apigateway.CfnRoute( 41 | self, 42 | "no-auth", 43 | api_id=api.ref, 44 | route_key="GET /test", 45 | authorization_type="NONE" # Sensitive 46 | ) 47 | 48 | 49 | ### RРекомендуемые методы безопасного кодирования 50 | 51 | # Рекомендуется ограничить доступ к API авторизованным лицам, за исключением случаев, когда API предлагает неконфиденциальную услугу, предназначенную для публичного использования. 52 | # Соответствующее решение 53 | # 54 | # For aws_cdk.aws_apigateway.Resource: 55 | 56 | from aws_cdk import ( 57 | aws_apigateway as apigateway 58 | ) 59 | 60 | opts = apigateway.MethodOptions( 61 | authorization_type=apigateway.AuthorizationType.IAM 62 | ) 63 | resource = api.root.add_resource( 64 | "example", 65 | default_method_options=opts 66 | ) 67 | resource.add_method( 68 | "POST", 69 | authorization_type=apigateway.AuthorizationType.IAM 70 | ) 71 | resource.add_method( # authorization_type is inherited from the Resource's configured default_method_options 72 | "POST" 73 | ) 74 | 75 | # For aws_cdk.aws_apigatewayv2.CfnRoute: 76 | 77 | from aws_cdk import ( 78 | aws_apigatewayv2 as apigateway 79 | ) 80 | 81 | apigateway.CfnRoute( 82 | self, 83 | "auth", 84 | api_id=api.ref, 85 | route_key="GET /test", 86 | authorization_type="AWS_IAM" 87 | ) 88 | 89 | '''See 90 | 91 | OWASP Top 10 2021 Category A1 - Broken Access Control 92 | AWS Documentation - Controlling and managing access to a REST API in API Gateway 93 | MITRE, CWE-284 - Improper Access Control 94 | OWASP Top 10 2017 Category A5 - Broken Access Control''' 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security09.py: -------------------------------------------------------------------------------- 1 | ###### Доставка кода в производство с активированными функциями отладки важна для безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 1 минута 9 | 10 | Доставка кода в рабочую среду с активированными функциями отладки важна с точки зрения безопасности. В прошлом это приводило к следующим уязвимостям: 11 | 12 | CVE-2018-1999007 13 | CVE-2015-5306 14 | CVE-2013-2006 15 | 16 | Функции отладки приложения позволяют разработчикам легче находить ошибки и, таким образом, облегчают работу злоумышленников. Часто это дает доступ к подробной информации как о системе, на которой работает приложение, так и о пользователях. 17 | 18 | ###### Спросите себя, есть ли 19 | 20 | Код или конфигурация, обеспечивающие функции отладки приложения, развертываются на рабочих серверах или распространяются среди конечных пользователей. 21 | Приложение запускается по умолчанию с активированными функциями отладки. 22 | 23 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 24 | Пример конфиденциального кода 25 | ''' 26 | from django.conf import settings 27 | 28 | settings.configure(DEBUG=True) # Sensitive when set to True 29 | settings.configure(DEBUG_PROPAGATE_EXCEPTIONS=True) # Sensitive when set to True 30 | 31 | def custom_config(config): 32 | settings.configure(default_settings=config, DEBUG=True) # Sensitive 33 | 34 | # Django’s "settings.py" or "global_settings.py" configuration file: 35 | 36 | # NOTE: The following code raises issues only if the file is named "settings.py" or "global_settings.py". This is the default 37 | # name of Django configuration file 38 | 39 | DEBUG = True # Sensitive 40 | DEBUG_PROPAGATE_EXCEPTIONS = True # Sensitive 41 | 42 | ### Рекомендуемые методы безопасного кодирования 43 | 44 | '''Не включайте функции отладки на рабочих серверах или в приложениях, распространяемых конечным пользователям. 45 | Видеть 46 | 47 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 48 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 49 | MITRE, CWE-489 - Active Debug Code 50 | MITRE, CWE-215 - Information Exposure Through Debug Information''' 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security10.py: -------------------------------------------------------------------------------- 1 | ###### Отключение автоматического экранирования в механизмах шаблонов является чувствительным к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | Чтобы снизить риск атак с использованием межсайтовых сценариев, системы шаблонов, такие как Twig, Django, Smarty, механизм шаблонов Groovy, позволяют настраивать автоматическое экранирование переменных перед отрисовкой шаблонов. При возникновении escape-символов, которые имеют смысл для браузера (например: ), будут преобразованы/заменены экранированными/обработанными значениями (например: <a& gt; ). 11 | 12 | Автоматическое экранирование не является волшебной функцией, способной уничтожить все атаки с использованием межсайтовых сценариев. Это зависит от применяемой стратегии и контекста. Например, стратегия «автоматического экранирования HTML» (которая только преобразует символы HTML в объекты HTML) не будет работать. актуально, когда переменные используются в атрибуте html, поскольку символ «:» не экранируется и, следовательно, возможна атака, как показано ниже: 13 | 14 | link // myLink = javascript:alert(document.cookie) 15 | link // JS injection (XSS attack) 16 | 17 | 18 | ###### Спросите себя, есть ли 19 | 20 | Шаблоны используются для отображения веб-контента и динамические переменные в шаблонах поступают из ненадежных мест или являются входными данными, контролируемыми пользователем. 21 | не существует локального механизма для очистки или проверки входных данных. 22 | 23 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 24 | Пример конфиденциального кода 25 | ''' 26 | from jinja2 import Environment 27 | 28 | env = Environment() # Sensitive: New Jinja2 Environment has autoescape set to false 29 | env = Environment(autoescape=False) # Sensitive: 30 | 31 | ### Рекомендуемые методы безопасного кодирования 32 | 33 | '''Включите автоматическое экранирование по умолчанию и продолжайте проверять использование входных данных, чтобы убедиться, что выбранная стратегия автоматического экранирования является правильной. 34 | Соответствующее решение 35 | ''' 36 | from jinja2 import Environment 37 | env = Environment(autoescape=True) # Compliant 38 | 39 | '''See 40 | 41 | OWASP Top 10 2021 Category A3 - Injection 42 | OWASP Cheat Sheet - XSS Prevention Cheat Sheet 43 | OWASP Top 10 2017 Category A7 - Cross-Site Scripting (XSS) 44 | MITRE, CWE-79 - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') 45 | ''' 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security12.py: -------------------------------------------------------------------------------- 1 | ###### Отключение шифрования корзин S3 на стороне сервера важно для безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | 9 | Шифрование на стороне сервера (SSE) шифрует объект (не метаданные) при его записи на диск (где находится корзина S3) и расшифровывает его при чтении с диска. Это не меняет способ доступа к объектам: пока у пользователя есть необходимые разрешения, объекты извлекаются так, как если бы они были незашифрованными. Таким образом, SSE помогает только в случае кражи дисков, неправильной утилизации дисков и других атак на саму инфраструктуру AWS. 10 | 11 | Существует три варианта SSE: 12 | 13 | Шифрование на стороне сервера с помощью ключей, управляемых Amazon S3 (SSE-S3) 14 | AWS самостоятельно управляет ключами шифрования и самим шифрованием (с помощью AES-256). 15 | Шифрование на стороне сервера с помощью главных ключей клиента (CMK), хранящихся в службе управления ключами AWS (SSE-KMS). 16 | AWS управляет шифрованием (AES-256) объектов и ключами шифрования, предоставляемыми сервисом AWS KMS. 17 | Шифрование на стороне сервера с помощью ключей, предоставленных клиентом (SSE-C) 18 | AWS управляет только шифрованием (AES-256) объектов с помощью ключей шифрования, предоставленных клиентом. AWS не хранит ключи шифрования клиента. 19 | 20 | 21 | ###### Спросите себя, есть ли 22 | 23 | В корзине S3 хранится конфиденциальная информация. 24 | Инфраструктура должна соответствовать некоторым правилам, таким как HIPAA или PCI DSS, и другим стандартам. 25 | 26 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 27 | Пример конфиденциального кода 28 | 29 | Шифрование на стороне сервера не используется:''' 30 | 31 | bucket = s3.Bucket(self,"bucket", 32 | encryption=s3.BucketEncryption.UNENCRYPTED # Sensitive 33 | ) 34 | 35 | # Значением шифрования по умолчанию является KMS, если установлен ключ шифрования. В противном случае, если оба параметра отсутствуют, сегмент не зашифрован. 36 | 37 | 38 | 39 | ### Рекомендуемые методы безопасного кодирования 40 | 41 | '''Рекомендуется использовать SSE. Выбор подходящей опции зависит от уровня контроля, необходимого для управления ключами шифрования. 42 | Соответствующее решение 43 | 44 | Server-side encryption with Amazon S3-Managed Keys is used: 45 | ''' 46 | bucket = s3.Bucket(self,"bucket", 47 | encryption=s3.BucketEncryption.S3_MANAGED 48 | ) 49 | 50 | # Alternatively with a KMS key managed by the user. 51 | 52 | bucket = s3.Bucket(self,"bucket", 53 | encryptionKey=access_key 54 | ) 55 | 56 | '''See 57 | 58 | OWASP Top 10 2021 Category A4 - Insecure Design 59 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 60 | MITRE, CWE-311 - Missing Encryption of Sensitive Data 61 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 62 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 63 | AWS documentation - Protecting data using server-side encryption 64 | AWS CDK version 2 - BucketEncryption''' 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security13.py: -------------------------------------------------------------------------------- 1 | ###### Отключение управления версиями корзин S3 важно для безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | Корзины S3 могут иметь версии. Когда корзина S3 не версионирована, это означает, что новая версия объекта перезаписывает существующую версию в корзине S3. 11 | 12 | Это может привести к непреднамеренной или намеренной потере информации. 13 | 14 | ###### Спросите себя, есть ли 15 | 16 | В сегменте хранится информация, требующая высокой доступности. 17 | 18 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 19 | Пример конфиденциального кода''' 20 | 21 | bucket = s3.Bucket(self, "bucket", 22 | versioned=False # Sensitive 23 | ) 24 | 25 | '''Значение по умолчанию для параметра versioned — False, поэтому отсутствие этого параметра также является чувствительным. 26 | 27 | ### Рекомендуемые методы безопасного кодирования 28 | 29 | Рекомендуется включить управление версиями S3 и, таким образом, иметь возможность извлекать и восстанавливать различные версии объекта. 30 | Соответствующее решение''' 31 | 32 | bucket = s3.Bucket(self, "bucket", 33 | versioned=True 34 | ) 35 | 36 | '''See 37 | 38 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 39 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 40 | AWS documentation - Using versioning in S3 buckets 41 | AWS CDK version 2 - Using versioning in S3 buckets''' 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security14.py: -------------------------------------------------------------------------------- 1 | ###### Динамически исполняемый код чувствителен к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Критический 5 | Устарело 6 | 7 | Доступно с 19 декабря 2023 г. 8 | СонарКуб (Python) 9 | Постоянно/выпуск: 30 мин. 10 | 11 | Динамическое выполнение кода чувствительно к безопасности. В прошлом это приводило к следующим уязвимостям: 12 | 13 | CVE-2017-9807 14 | CVE-2017-9802 15 | 16 | Некоторые API позволяют выполнять динамический код, предоставляя его в виде строк во время выполнения. Эти API могут быть полезны в некоторых очень специфических случаях использования метапрограммирования. Однако в большинстве случаев их использование не одобряется, поскольку они также увеличивают риск злонамеренного внедрения кода. Такие атаки могут запускаться либо на сервере, либо на клиенте (пример: XSS-атака) и оказывать огромное влияние на безопасность приложения. 17 | 18 | Это правило помечает для проверки каждый случай выполнения такого динамического кода. Это правило не обнаруживает внедрения кода. Он лишь подчеркивает использование API, которые следует использовать экономно и очень осторожно. 19 | ###### Спросите себя, есть ли 20 | 21 | исполняемый код может быть получен из ненадежного источника и не был очищен. 22 | вам действительно нужно запускать код динамически. 23 | 24 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 25 | Пример конфиденциального кода''' 26 | 27 | import os 28 | 29 | value = input() 30 | command = 'os.system("%s")' % value 31 | 32 | def evaluate(command, file, mode): 33 | eval(command) # Sensitive. 34 | 35 | eval(command) # Sensitive. Dynamic code 36 | 37 | def execute(code, file, mode): 38 | exec(code) # Sensitive. 39 | exec(compile(code, file, mode)) # Sensitive. 40 | 41 | exec(command) # Sensitive. 42 | 43 | 44 | ### Рекомендуемые методы безопасного кодирования 45 | 46 | '''Что касается выполнения неизвестного кода, лучшее решение — не запускать код, предоставленный ненадежным источником. Если вам действительно это нужно, запустите код в изолированной среде. Используйте тюрьмы, брандмауэры и любые средства, которые предоставляет ваша операционная система и язык программирования (пример: менеджеры безопасности в Java, iframe и политика одного и того же происхождения для javascript в веб-браузере). 47 | 48 | Не пытайтесь создать черный список опасного кода. Таким образом невозможно охватить все атаки. 49 | 50 | По возможности избегайте использования API динамического кода. Жестко закодированный код всегда безопаснее. 51 | 52 | See 53 | 54 | OWASP Top 10 2021 Category A3 - Injection 55 | OWASP Top 10 2017 Category A1 - Injection 56 | MITRE, CWE-95 - Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection') 57 | ''' -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security17.py: -------------------------------------------------------------------------------- 1 | ###### Форматирование SQL-запросов чувствительно к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/выпуск: 20 мин. 9 | 10 | Форматированные SQL-запросы могут быть сложны в обслуживании и отладке, а также могут увеличить риск внедрения SQL-кода при объединении в запрос ненадежных значений. Однако это правило не обнаруживает SQL-инъекции (в отличие от правила S3649), его цель — только выделить сложные/форматированные запросы. 11 | 12 | 13 | ###### Спросите себя, есть ли 14 | 15 | Некоторые части запроса берутся из ненадежных значений (например, вводимых пользователем данных). 16 | Запрос повторяется/дублируется в других частях кода. 17 | Приложение должно поддерживать разные типы реляционных баз данных. 18 | 19 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 20 | Пример конфиденциального кода''' 21 | 22 | from django.db import models 23 | from django.db import connection 24 | from django.db import connections 25 | from django.db.models.expressions import RawSQL 26 | 27 | value = input() 28 | 29 | 30 | class MyUser(models.Model): 31 | name = models.CharField(max_length=200) 32 | 33 | 34 | def query_my_user(request, params, value): 35 | with connection.cursor() as cursor: 36 | cursor.execute("{0}".format(value)) # Sensitive 37 | 38 | # https://docs.djangoproject.com/en/2.1/ref/models/expressions/#raw-sql-expressions 39 | 40 | RawSQL("select col from %s where mycol = %s and othercol = " + value, ("test",)) # Sensitive 41 | 42 | # https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra 43 | 44 | MyUser.objects.extra( 45 | select={ 46 | 'mycol': "select col from sometable here mycol = %s and othercol = " + value}, # Sensitive 47 | select_params=(someparam,), 48 | }, 49 | ) 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | ### Рекомендуемые методы безопасного кодирования 58 | 59 | '''Используйте параметризованные запросы, подготовленные операторы или хранимые процедуры и привязывайте переменные к параметрам запроса SQL. 60 | Рассмотрите возможность использования фреймворков ORM, если вам необходим абстрактный уровень для доступа к данным. 61 | 62 | Соответствующее решение''' 63 | 64 | cursor = connection.cursor(prepared=True) 65 | sql_insert_query = """ select col from sometable here mycol = %s and othercol = %s """ 66 | 67 | select_tuple = (1, value) 68 | 69 | cursor.execute(sql_insert_query, select_tuple) # Compliant, the query is parameterized 70 | connection.commit() 71 | 72 | '''See 73 | 74 | OWASP Top 10 2021 Category A3 - Injection 75 | OWASP Top 10 2017 Category A1 - Injection 76 | MITRE, CWE-20 - Improper Input Validation 77 | MITRE, CWE-89 - Improper Neutralization of Special Elements used in an SQL Command 78 | SANS Top 25 - Insecure Interaction Between Components 79 | Derived from FindSecBugs rules Potential SQL/JPQL Injection (JPA), Potential SQL/JDOQL Injection (JDO), Potential SQL/HQL Injection (Hibernate)''' 80 | 81 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security19.py: -------------------------------------------------------------------------------- 1 | ###### Жестко закодированные учетные данные чувствительны к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Блокатор 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/выпуск: 30 мин. 9 | 10 | Поскольку строки из исходного или двоичного кода приложения легко извлечь, учетные данные не следует жестко запрограммировать. Это особенно верно для приложений, которые распространяются или имеют открытый исходный код. 11 | 12 | В прошлом это приводило к следующим уязвимостям: 13 | 14 | CVE-2019-13466 15 | CVE-2018-15389 16 | 17 | Учетные данные должны храниться вне кода в файле конфигурации, базе данных или службе управления секретами. 18 | 19 | Это правило помечает экземпляры жестко запрограммированных учетных данных, используемых в соединениях с базой данных и LDAP. Он ищет жестко запрограммированные учетные данные в строках подключения, а также имена переменных, соответствующие любому из шаблонов из предоставленного списка. 20 | 21 | Рекомендуется настроить конфигурацию этого правила, добавив дополнительные учетные слова, такие как «oauthToken», «secret»,…​ 22 | 23 | 24 | ###### Спросите себя, есть ли 25 | 26 | Учетные данные позволяют получить доступ к конфиденциальному компоненту, такому как база данных, хранилище файлов, API или служба. 27 | Учетные данные используются в производственных средах. 28 | Перед обновлением учетных данных требуется перераспределение приложения. 29 | 30 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 31 | Пример конфиденциального кода''' 32 | 33 | username = 'admin' 34 | password = 'admin' # Sensitive 35 | usernamePassword = 'user=admin&password=admin' # Sensitive 36 | 37 | 38 | 39 | 40 | 41 | ### Рекомендуемые методы безопасного кодирования 42 | ''' 43 | Сохраните учетные данные в файле конфигурации, который не будет отправлен в репозиторий кода. 44 | Сохраните учетные данные в базе данных. 45 | Используйте службу своего облачного провайдера для управления секретами. 46 | Если пароль был раскрыт через исходный код: измените его. 47 | 48 | Соответствующее решение''' 49 | 50 | import os 51 | 52 | username = os.getenv("username") # Compliant 53 | password = os.getenv("password") # Compliant 54 | usernamePassword = 'user=%s&password=%s' % (username, password) # Compliant{code} 55 | 56 | '''See 57 | 58 | 59 | Топ-10 OWASP 2021 г., Категория A7 — Сбои идентификации и аутентификации 60 | Топ-10 OWASP 2017 г., категория A2 — нарушенная аутентификация 61 | MITRE, CWE-798 — Использование жестко закодированных учетных данных 62 | MITRE, CWE-259 — Использование жестко запрограммированного пароля 63 | SANS Top 25 — пористая защита 64 | Получено из правила FindSecBugs. Жестко закодированный пароль. 65 | 66 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 67 | OWASP Top 10 2017 Category A2 - Broken Authentication 68 | MITRE, CWE-798 - Use of Hard-coded Credentials 69 | MITRE, CWE-259 - Use of Hard-coded Password 70 | SANS Top 25 - Porous Defenses 71 | Derived from FindSecBugs rule Hard Coded Password''' 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security21.py: -------------------------------------------------------------------------------- 1 | ###### Политики, разрешающие публичный доступ к ресурсам, чувствительны к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Блокатор 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | Ресурсные политики, предоставляющие доступ всем пользователям, могут привести к утечке информации. 11 | 12 | ###### Спросите себя, есть ли 13 | 14 | Ресурс AWS хранит или обрабатывает конфиденциальные данные. 15 | Ресурс AWS спроектирован как частный. 16 | 17 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 18 | Пример конфиденциального кода 19 | 20 | This policy allows all users, including anonymous ones, to access an S3 bucket:''' 21 | 22 | from aws_cdk.aws_iam import PolicyStatement, AnyPrincipal, Effect 23 | from aws_cdk.aws_s3 import Bucket 24 | 25 | bucket = Bucket(self, "ExampleBucket") 26 | 27 | bucket.add_to_resource_policy(PolicyStatement( 28 | effect=Effect.ALLOW, 29 | actions=["s3:*"], 30 | resources=[bucket.arn_for_objects("*")], 31 | principals=[AnyPrincipal()] # Sensitive 32 | )) 33 | 34 | ### Рекомендуемые методы безопасного кодирования 35 | 36 | '''Рекомендуется реализовать принцип наименьших привилегий, то есть предоставлять необходимые разрешения только пользователям для выполнения их необходимых задач. В контексте политик на основе ресурсов составьте список участников, которым необходим доступ, и предоставьте им только необходимые привилегии. 37 | Соответствующее решение 38 | 39 | Эта политика позволяет только авторизованным пользователям:''' 40 | 41 | 42 | from aws_cdk.aws_iam import PolicyStatement, AccountRootPrincipal, Effect 43 | from aws_cdk.aws_s3 import Bucket 44 | 45 | bucket = Bucket(self, "ExampleBucket") 46 | 47 | bucket.add_to_resource_policy(PolicyStatement( 48 | effect=Effect.ALLOW, 49 | actions=["s3:*"], 50 | resources=[bucket.arn_for_objects("*")], 51 | principals=[AccountRootPrincipal()] 52 | )) 53 | 54 | '''See 55 | 56 | OWASP Top 10 2021 Category A1 - Broken Access Control 57 | AWS Documentation - Grant least privilege 58 | MITRE, CWE-732 - Incorrect Permission Assignment for Critical Resource 59 | MITRE, CWE-284 - Improper Access Control 60 | OWASP Top 10 2017 Category A5 - Broken Access Control''' 61 | 62 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security22.py: -------------------------------------------------------------------------------- 1 | ###### питон: S6304 2 | '''Политики, предоставляющие доступ ко всем ресурсам учетной записи, чувствительны к безопасности. 3 | 4 | Точка доступа безопасности 5 | Блокатор 6 | 7 | Доступно с 19 декабря 2023 г. 8 | СонарКуб (Python) 9 | Постоянно/проблема: 5 минут 10 | 11 | Политика, которая разрешает удостоверениям доступ ко всем ресурсам в учетной записи AWS, может нарушать принцип минимальных привилегий. Предположим, что у удостоверения есть разрешение на доступ ко всем ресурсам, хотя ему требуется доступ только к некоторым неконфиденциальным ресурсам. В этом случае произойдет несанкционированный доступ и раскрытие конфиденциальной информации. 12 | Исключения 13 | 14 | Не следует вызывать ключевые политики (при использовании действий AWS KMS). 15 | Не следует поднимать вопросы о политиках, не использующих какие-либо ресурсы (тогда и только тогда, когда все действия в политике никогда не требуют ресурсов). 16 | 17 | 18 | ###### Спросите себя, есть ли 19 | 20 | В учетной записи AWS имеется несколько ресурсов с разными уровнями чувствительности. 21 | 22 | Риск существует, если вы ответили утвердительно на этот вопрос. 23 | Пример несовместимого кода 24 | 25 | Подстановочный знак «*» указан в качестве ресурса для этого PolicyStatement. Это предоставляет разрешение на обновление для всех политик учетной записи:''' 26 | 27 | from aws_cdk.aws_iam import Effect, PolicyDocument, PolicyStatement 28 | 29 | PolicyDocument( 30 | statements=[ 31 | PolicyStatement( 32 | effect=Effect.ALLOW, 33 | actions="iam:CreatePolicyVersion", 34 | resources=["*"] # Sensitive 35 | ) 36 | ] 37 | ) 38 | 39 | 40 | 41 | ### Рекомендуемые методы безопасного кодирования 42 | 43 | '''Рекомендуется применять принцип наименьших привилегий, то есть предоставлять доступ только к необходимым ресурсам. Хорошей практикой для достижения этой цели является организация или маркировка ресурсов в зависимости от уровня конфиденциальности данных, которые они хранят или обрабатывают. Таким образом, управление безопасным контролем доступа менее подвержено ошибкам. 44 | Соответствующее решение 45 | 46 | Ограничьте разрешение на обновление соответствующим подмножеством политик:''' 47 | 48 | from aws_cdk import Aws 49 | from aws_cdk.aws_iam import Effect, PolicyDocument, PolicyStatement 50 | 51 | PolicyDocument( 52 | statements=[ 53 | PolicyStatement( 54 | effect=Effect.ALLOW, 55 | actions="iam:CreatePolicyVersion", 56 | resources=[f"arn:aws:iam::{Aws.ACCOUNT_ID}:policy/team1/*"] 57 | ) 58 | ] 59 | ) 60 | 61 | '''See 62 | 63 | OWASP Top 10 2021 Category A1 - Broken Access Control 64 | AWS Documentation - Grant least privilege 65 | MITRE, CWE-732 - Incorrect Permission Assignment for Critical Resource 66 | MITRE, CWE-284 - Improper Access Control 67 | OWASP Top 10 2017 Category A5 - Broken Access Control''' 68 | 69 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security23.py: -------------------------------------------------------------------------------- 1 | ###### Политики, предоставляющие все привилегии, чувствительны к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Блокатор 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | Политика, предоставляющая все разрешения, может указывать на неправильный контроль доступа, который нарушает принцип наименьших привилегий. Предположим, удостоверению предоставлены полные разрешения на доступ к ресурсу, хотя для правильной работы ему требуется только разрешение на чтение. В этом случае может произойти непреднамеренная перезапись ресурсов, что приведет к потере информации. 11 | 12 | 13 | ###### Спросите себя, есть ли 14 | 15 | Идентификаторы, получившие все разрешения: 16 | 17 | для выполнения намеченной функции требуется только часть этих разрешений. 18 | отслеживали активность, показавшую, что фактически используется только часть этих разрешений. 19 | 20 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 21 | Пример конфиденциального кода 22 | 23 | Политика, управляемая клиентом, которая предоставляет все разрешения с помощью подстановочного знака (*) в свойстве Action:''' 24 | 25 | from aws_cdk.aws_iam import PolicyStatement, Effect 26 | 27 | PolicyStatement( 28 | effect=Effect.ALLOW, 29 | actions=["*"], # Sensitive 30 | resources=["arn:aws:iam:::user/*"] 31 | ) 32 | 33 | 34 | 35 | ### Рекомендуемые методы безопасного кодирования 36 | 37 | '''Рекомендуется применять принцип наименьших привилегий, то есть предоставлять удостоверениям только необходимые разрешения. Хорошей практикой является начать с самого минимального набора разрешений и со временем совершенствовать политику. Чтобы исправить чрезмерно разрешительные политики, уже развернутые в рабочей среде, можно было бы проанализировать отслеживаемую активность, чтобы сократить набор разрешений до тех, которые используются наиболее часто. 38 | Соответствующее решение 39 | 40 | Политика, управляемая клиентом, которая предоставляет только необходимые разрешения:''' 41 | 42 | from aws_cdk.aws_iam import PolicyStatement, Effect 43 | 44 | PolicyStatement( 45 | effect=Effect.ALLOW, 46 | actions=["iam:GetAccountSummary"], 47 | resources=["arn:aws:iam:::user/*"] 48 | ) 49 | 50 | '''See 51 | 52 | OWASP Top 10 2021 Category A1 - Broken Access Control 53 | AWS Documentation - Grant least privilege 54 | Google Cloud Documentation - Understanding roles 55 | MITRE, CWE-732 - Incorrect Permission Assignment for Critical Resource 56 | MITRE, CWE-284 - Improper Access Control 57 | OWASP Top 10 2017 Category A5 - Broken Access Control 58 | ''' 59 | 60 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security24.py: -------------------------------------------------------------------------------- 1 | ###### Чтение стандартного ввода чувствительно к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Критический 5 | Устарело 6 | 7 | Доступно с 19 декабря 2023 г. 8 | СонарКуб (Python) 9 | 10 | Чтение стандартного ввода чувствительно к безопасности. В прошлом это приводило к следующим уязвимостям: 11 | 12 | CVE-2005-2337 13 | CVE-2017-11449 14 | 15 | Злоумышленники обычно создают входные данные, позволяющие им использовать уязвимости программного обеспечения. Таким образом, любые данные, считанные со стандартного ввода (stdin), могут быть опасными и должны быть проверены. 16 | 17 | Это правило помечает код, считывающий со стандартного ввода. 18 | Устарело 19 | 20 | Это правило устарело и со временем будет удалено. 21 | 22 | 23 | ###### Спросите себя, есть ли 24 | 25 | данные, считанные со стандартного ввода, не очищаются перед использованием. 26 | 27 | Вы находитесь в группе риска, если ответили утвердительно на этот вопрос. 28 | Пример конфиденциального кода 29 | 30 | Python 2 and Python 3''' 31 | 32 | import sys 33 | from sys import stdin, __stdin__ 34 | 35 | # Any reference to sys.stdin or sys.__stdin__ without a method call is Sensitive 36 | sys.stdin # Sensitive 37 | 38 | for line in sys.stdin: # Sensitive 39 | print(line) 40 | 41 | it = iter(sys.stdin) # Sensitive 42 | line = next(it) 43 | 44 | # Calling the following methods on stdin or __stdin__ is sensitive 45 | sys.stdin.read() # Sensitive 46 | sys.stdin.readline() # Sensitive 47 | sys.stdin.readlines() # Sensitive 48 | 49 | # Calling other methods on stdin or __stdin__ does not require a review, thus it is not Sensitive 50 | sys.stdin.seekable() # Ok 51 | # ... 52 | 53 | # Python 2 only 54 | 55 | raw_input('What is your password?') # Sensitive 56 | 57 | # Python 3 only 58 | 59 | input('What is your password?') # Sensitive 60 | 61 | # Function fileinput.input and class fileinput.FileInput read the standard input when the list of files is empty. 62 | 63 | for line in fileinput.input(): # Sensitive 64 | print(line) 65 | 66 | for line in fileinput.FileInput(): # Sensitive 67 | print(line) 68 | 69 | for line in fileinput.input(['setup.py']): # Ok 70 | print(line) 71 | 72 | for line in fileinput.FileInput(['setup.py']): # Ok 73 | print(line) 74 | 75 | 76 | 77 | 78 | ### Рекомендуемые методы безопасного кодирования 79 | 80 | '''Очистите все данные, считанные со стандартного ввода, перед их использованием. 81 | Видеть 82 | 83 | MITRE, CWE-20 — неправильная проверка ввода''' 84 | 85 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security26.py: -------------------------------------------------------------------------------- 1 | ###### Установка свободных прав доступа к файлам POSIX важна для безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/проблема: 5 минут 9 | 10 | В Unix класс «другие» относится ко всем пользователям, кроме владельца файла и членов группы, назначенной этому файлу. 11 | 12 | Предоставление разрешений этой группе может привести к непреднамеренному доступу к файлам. 13 | 14 | 15 | ###### Спросите себя, есть ли 16 | 17 | Приложение предназначено для работы в многопользовательской среде. 18 | Соответствующие файлы и каталоги могут содержать конфиденциальную информацию. 19 | 20 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 21 | Пример конфиденциального кода 22 | 23 | For os.umask:''' 24 | 25 | os.umask(0) # Sensitive 26 | 27 | # For os.chmod, os.lchmod, and os.fchmod: 28 | 29 | os.chmod("/tmp/fs", stat.S_IRWXO) # Sensitive 30 | os.lchmod("/tmp/fs", stat.S_IRWXO) # Sensitive 31 | os.fchmod(fd, stat.S_IRWXO) # Sensitive 32 | 33 | 34 | 35 | 36 | 37 | 38 | ### Рекомендуемые методы безопасного кодирования 39 | ''' 40 | Файлам и каталогам следует назначать максимально строгие разрешения. 41 | Соответствующее решение 42 | For os.umask:''' 43 | 44 | os.umask(0o777) 45 | 46 | # For os.chmod, os.lchmod, and os.fchmod: 47 | 48 | os.chmod("/tmp/fs", stat.S_IRWXU) 49 | os.lchmod("/tmp/fs", stat.S_IRWXU) 50 | os.fchmod(fd, stat.S_IRWXU) 51 | ''' 52 | See 53 | 54 | OWASP Top 10 2021 Category A1 - Broken Access Control 55 | OWASP Top 10 2021 Category A4 - Insecure Design 56 | OWASP Top 10 2017 Category A5 - Broken Access Control 57 | OWASP File Permission 58 | MITRE, CWE-732 - Incorrect Permission Assignment for Critical Resource 59 | MITRE, CWE-266 - Incorrect Privilege Assignment 60 | SANS Top 25 - Porous Defenses''' 61 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security27.py: -------------------------------------------------------------------------------- 1 | ###### Процессы сигнализации чувствительны к безопасности 2 | ''' 3 | Точка доступа безопасности 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | 9 | Процессы сигнализации или группы процессов могут серьезно повлиять на стабильность этого приложения или других приложений в той же системе. 10 | 11 | Случайная установка неправильного PID или сигнала или разрешение ненадежным источникам присваивать произвольные значения этим параметрам может привести к отказу в обслуживании. 12 | 13 | Кроме того, система обрабатывает сигнал по-разному, если PID назначения меньше или равен 0. Такое другое поведение может повлиять на несколько процессов с одинаковым (E)UID одновременно, если вызов останется неконтролируемым. 14 | 15 | 16 | ###### Спросите себя, есть ли 17 | 18 | Параметры pid и sig не являются доверенными (они поступают из внешнего источника). 19 | Эта функция активируется лицами, не являющимися администраторами. 20 | Обработчики сигналов целевых процессов останавливают важные функции. 21 | 22 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 23 | Пример конфиденциального кода''' 24 | 25 | import os 26 | 27 | @app.route("/kill-pid/") 28 | def send_signal(pid): 29 | os.kill(pid, 9) # Sensitive 30 | 31 | @app.route("/kill-pgid/") 32 | def send_signal(pgid): 33 | os.killpg(pgid, 9) # Sensitive 34 | 35 | 36 | 37 | ### Рекомендуемые методы безопасного кодирования 38 | ''' 39 | Для приложений с отслеживанием состояния и управлением пользователями убедитесь, что этот код запускают только администраторы. 40 | Прежде чем использовать их, убедитесь, что параметры pid и sig верны. 41 | Убедитесь, что процесс отправки сигналов выполняется с как можно меньшим количеством привилегий ОС. 42 | Изолируйте процесс в системе на основе его (E)UID. 43 | Убедитесь, что сигнал не прерывает какие-либо важные функции при перехвате обработчиками сигнала цели. 44 | 45 | Соответствующее решение 46 | ''' 47 | import os 48 | 49 | @app.route("/kill-pid/") 50 | def send_signal(pid): 51 | # Validate the untrusted PID, 52 | # With a pre-approved list or authorization checks 53 | if is_valid_pid(pid): 54 | os.kill(pid, 9) 55 | 56 | @app.route("/kill-pgid/") 57 | def send_signal(pgid): 58 | # Validate the untrusted PGID, 59 | # With a pre-approved list or authorization checks 60 | if is_valid_pgid(pgid): 61 | os.kill(pgid, 9) 62 | ''' 63 | See 64 | 65 | MITRE, CWE-283 - Unverified Ownership 66 | kill(1) — Linux manual page 67 | kill(2) — Linux manual page 68 | ''' 69 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security29.py: -------------------------------------------------------------------------------- 1 | ###### Использование аргументов командной строки важно для безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Критический 5 | Устарело 6 | 7 | Доступно с 19 декабря 2023 г. 8 | СонарКуб (Python) 9 | 10 | Использование аргументов командной строки важно с точки зрения безопасности. В прошлом это приводило к следующим уязвимостям: 11 | 12 | CVE-2018-7281 13 | CVE-2018-12326 14 | CVE-2011-3198 15 | 16 | Аргументы командной строки могут быть опасными, как и любой другой пользовательский ввод. Их никогда не следует использовать без предварительной проверки и дезинфекции. 17 | 18 | Помните также, что любой пользователь может получить список процессов, запущенных в системе, что делает предоставленные им аргументы видимыми. Таким образом, передачу конфиденциальной информации через аргументы командной строки следует считать небезопасной. 19 | 20 | Это правило вызывает проблему при каждой ссылке на sys.argv, вызове optparse.OptionParser() или вызове argparse.ArgumentParser(). Целью является проведение проверок кода безопасности. 21 | Устарело 22 | 23 | Это правило устарело и со временем будет удалено. 24 | 25 | 26 | ###### Спросите себя, есть ли 27 | 28 | любые аргументы командной строки используются без предварительной очистки. 29 | ваше приложение принимает конфиденциальную информацию через аргументы командной строки. 30 | 31 | Если вы ответили утвердительно хотя бы на один из этих вопросов, вы находитесь в группе риска. 32 | 33 | 34 | 35 | 36 | ### рекомендуемые методы безопасного кодирования 37 | 38 | Очистите все аргументы командной строки перед их использованием. 39 | 40 | Любой пользователь или приложение может составить список запущенных процессов и увидеть аргументы командной строки, с которыми они были запущены. Существуют более безопасные способы предоставления конфиденциальной информации приложению, чем раскрытие ее в командной строке. Обычно их записывают на стандартный ввод процесса или указывают путь к файлу, содержащему информацию. 41 | Видеть 42 | 43 | Топ-10 OWASP 2017 г. Категория A1 – Инъекции 44 | MITRE, CWE-88 — внедрение или модификация аргументов 45 | MITRE, CWE-214 — раскрытие информации через технологическую среду 46 | SANS Top 25 — небезопасное взаимодействие между компонентами''' 47 | 48 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security30.py: -------------------------------------------------------------------------------- 1 | ###### Использование жестко закодированных IP-адресов чувствительно к безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Незначительный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянно/выпуск: 30 мин. 9 | 10 | Жесткое кодирование IP-адресов чувствительно к безопасности. В прошлом это приводило к следующим уязвимостям: 11 | 12 | CVE-2006-5901 13 | CVE-2005-3725 14 | 15 | Сегодняшние сервисы имеют постоянно меняющуюся архитектуру из-за потребностей в масштабировании и резервировании. Ошибочно думать, что у службы всегда будет один и тот же IP-адрес. Когда он изменится, жестко закодированный IP-адрес также придется изменить. Это окажет влияние на разработку, доставку и развертывание продукта: 16 | 17 | Каждый раз, когда это происходит, разработчикам придется быстро исправлять ситуацию, вместо того чтобы заставлять рабочую группу изменять файл конфигурации. 18 | Использование одного и того же адреса в каждой среде (dev, sys, qa, prod) вводит в заблуждение. 19 | 20 | И последнее, но не менее важное: это влияет на безопасность приложений. Злоумышленники могут декомпилировать код и тем самым обнаружить потенциально конфиденциальный адрес. Они могут выполнить атаку типа «отказ в обслуживании» на службу, попытаться получить доступ к системе или попытаться подделать IP-адрес, чтобы обойти проверки безопасности. Такие атаки всегда возможны, но в случае жестко закодированного IP-адреса решение проблемы займет больше времени, что увеличит воздействие атаки. 21 | Исключения 22 | 23 | В следующих случаях о проблемах не сообщается, поскольку они не считаются конфиденциальными: 24 | 25 | Адреса обратной связи 127.0.0.0/8 в нотации CIDR (от 127.0.0.0 до 127.255.255.255) 26 | Широковещательный адрес 255.255.255.255 27 | Немаршрутизируемый адрес 0.0.0.0 28 | Строки вида 2.5.<номер>.<номер>, поскольку они часто соответствуют идентификаторам объектов (OID). 29 | Адреса в диапазонах 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, зарезервированы для целей документации согласно RFC 5737. 30 | Адреса в диапазоне 2001:db8::/32, зарезервированы для целей документации в RFC 3849. 31 | 32 | 33 | ###### спроси себя, есть ли 34 | 35 | Раскрытый IP-адрес является конфиденциальным, например: 36 | 37 | Может предоставить злоумышленнику информацию о топологии сети. 38 | Это личный (присвоенный определенному лицу) IP-адрес. 39 | 40 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 41 | Пример конфиденциального кода 42 | ''' 43 | ip = '192.168.12.42' 44 | sock = socket.socket() 45 | sock.bind((ip, 9090)) 46 | 47 | 48 | ### Рекомендуемые методы безопасного кодирования 49 | ''' 50 | Не жестко кодируйте IP-адрес в исходном коде, а сделайте его настраиваемым с помощью переменных среды, файлов конфигурации или аналогичного подхода. В качестве альтернативы, если конфиденциальность не требуется, можно использовать доменное имя, поскольку оно позволяет быстро изменить место назначения без необходимости пересборки программного обеспечения. 51 | Соответствующее решение 52 | 53 | ip = config.get(section, ipAddress) 54 | sock = socket.socket() 55 | sock.bind((ip, 9090)) 56 | 57 | See 58 | 59 | OWASP Top 10 2021 Category A1 - Broken Access Control 60 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure''' 61 | 62 | 63 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security31.py: -------------------------------------------------------------------------------- 1 | ###### Использование нестандартных криптографических алгоритмов является чувствительным к безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянная/выпуск: 1д 9 | 10 | Использование нестандартного алгоритма опасно, поскольку решительный злоумышленник может взломать алгоритм и поставить под угрозу любые защищенные данные. Вместо этого следует использовать стандартные алгоритмы, такие как Argon2PasswordHasher, BCryptPasswordHasher и т. д. 11 | 12 | Это правило отслеживает создание подклассов BasePasswordHasher для приложений Django. 13 | ''' 14 | 15 | ###### сSensitive Code Example 16 | 17 | class CustomPasswordHasher(BasePasswordHasher): # Sensitive 18 | # ... 19 | 20 | 21 | 22 | 23 | ### Рекомендуемые методы безопасного кодирования 24 | 25 | '''Используйте стандартный алгоритм вместо создания собственного. 26 | 27 | Видеть 28 | 29 | Топ-10 OWASP 2021 г., категория A2 — криптографические сбои 30 | Топ-10 OWASP 2017 г., категория A3 — раскрытие конфиденциальных данных 31 | MITRE, CWE-327 — Использование сломанного или рискованного криптографического алгоритма 32 | SANS Top 25 — пористая защита 33 | ''' 34 | 35 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security32.py: -------------------------------------------------------------------------------- 1 | ###### Использование генераторов псевдослучайных чисел (PRNG) чувствительно к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянная/проблема: 10 мин. 9 | 10 | Использование генераторов псевдослучайных чисел (PRNG) чувствительно к безопасности. Например, в прошлом это приводило к следующим уязвимостям: 11 | 12 | CVE-2013-6386 13 | CVE-2006-3419 14 | CVE-2008-4102 15 | 16 | Когда программное обеспечение генерирует предсказуемые значения в контексте, требующем непредсказуемости, злоумышленник может угадать следующее значение, которое будет сгенерировано, и использовать это предположение, чтобы выдать себя за другого пользователя или получить доступ к конфиденциальной информации. 17 | 18 | 19 | 20 | ###### Спросите себя, есть ли 21 | 22 | код, использующий сгенерированное значение, требует, чтобы оно было непредсказуемым. Это относится ко всем механизмам шифрования или к хешированию секретного значения, например пароля. 23 | используемая вами функция генерирует значение, которое можно предсказать (псевдослучайное). 24 | сгенерированное значение используется несколько раз. 25 | злоумышленник может получить доступ к сгенерированному значению. 26 | 27 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 28 | Пример конфиденциального кода''' 29 | 30 | import random 31 | 32 | random.getrandbits(1) # Sensitive 33 | random.randint(0,9) # Sensitive 34 | random.random() # Sensitive 35 | 36 | # the following functions are sadly used to generate salt by selecting characters in a string ex: "abcdefghijk"... 37 | random.sample(['a', 'b'], 1) # Sensitive 38 | random.choice(['a', 'b']) # Sensitive 39 | random.choices(['a', 'b']) # Sensitive 40 | 41 | 42 | 43 | ### Рекомендуемые методы безопасного кодирования 44 | ''' 45 | Используйте только генераторы случайных чисел, рекомендованные OWASP или любой другой доверенной организацией. 46 | Используйте сгенерированные случайные значения только один раз. 47 | Вы не должны раскрывать сгенерированное случайное значение. Если вам необходимо сохранить его, убедитесь, что база данных или файл защищены. 48 | 49 | Видеть 50 | 51 | Топ-10 OWASP 2021 г., категория A2 — криптографические сбои 52 | Топ-10 OWASP 2017 г., категория A3 — раскрытие конфиденциальных данных 53 | Стандарт проверки Mobile AppSec — требования к криптографии 54 | Топ-10 OWASP Mobile 2016 г., категория M5 – Недостаточная криптография 55 | MITRE, CWE-338 — Использование криптографически слабого генератора псевдослучайных чисел (PRNG) 56 | MITRE, CWE-330 — Использование недостаточно случайных значений 57 | MITRE, CWE-326 — недостаточная надежность шифрования 58 | MITRE, CWE-1241 — Использование предсказуемого алгоритма в генераторе случайных чисел 59 | Получено на основе правила FindSecBugs. Генератор предсказуемых псевдослучайных чисел.''' 60 | 61 | 62 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security33.py: -------------------------------------------------------------------------------- 1 | ###### Использование общедоступных для записи каталогов чувствительно к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | 9 | В операционных системах есть глобальные каталоги, к которым любой пользователь имеет доступ на запись. Эти папки в основном используются как области временного хранения, такие как /tmp в системах на базе Linux. Приложение, манипулирующее файлами из этих папок, подвергается гонке за именами файлов: злонамеренный пользователь может попытаться создать файл с предсказуемым именем раньше, чем это сделает приложение. Успешная атака может привести к доступу, изменению, повреждению или удалению других файлов. Этот риск еще выше, если приложение работает с повышенными разрешениями. 10 | 11 | В прошлом это приводило к следующим уязвимостям: 12 | 13 | CVE-2012-2451 14 | CVE-2015-1838 15 | 16 | Это правило вызывает проблему всякий раз, когда оно обнаруживает жестко закодированный путь к общедоступному для записи каталогу, например /tmp (см. примеры ниже). Он также обнаруживает доступ к переменным среды, которые указывают на общедоступные для записи каталоги, например, TMP и TMPDIR. 17 | 18 | /tmp 19 | /var/tmp 20 | /usr/tmp 21 | /dev/shm 22 | /dev/mqueue 23 | /run/lock 24 | /var/run/lock 25 | /Library/Caches 26 | /Users/Shared 27 | /private/tmp 28 | /private/var/tmp 29 | \Windows\Temp 30 | \Temp 31 | \TMP 32 | 33 | 34 | 35 | 36 | ###### Спросите себя, есть ли 37 | 38 | Файлы считываются или записываются в общедоступную папку. 39 | Приложение создает файлы с предсказуемыми именами в общедоступной папке. 40 | 41 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 42 | Пример конфиденциального кода''' 43 | 44 | file = open("/tmp/temporary_file","w+") # Sensitive 45 | 46 | tmp_dir = os.environ.get('TMPDIR') # Sensitive 47 | file = open(tmp_dir+"/temporary_file","w+") 48 | 49 | 50 | 51 | ### Рекомендуемые методы безопасного кодирования 52 | ''' 53 | Используйте выделенную подпапку со строго контролируемыми разрешениями. 54 | Используйте безопасные API для создания временных файлов. Такой API обеспечит: 55 | Сгенерированное имя файла непредсказуемо 56 | Файл доступен для чтения и записи только создавшему идентификатор пользователя. 57 | Дескриптор файла не наследуется дочерними процессами. 58 | Файл будет уничтожен, как только он будет закрыт. 59 | 60 | Соответствующее решение''' 61 | 62 | import tempfile 63 | 64 | file = tempfile.TemporaryFile(dir="/tmp/my_subdirectory", mode='"w+") # Compliant 65 | 66 | '''See 67 | 68 | OWASP Top 10 2021 Category A1 - Broken Access Control 69 | OWASP Top 10 2017 Category A5 - Broken Access Control 70 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 71 | MITRE, CWE-377 - Insecure Temporary File 72 | MITRE, CWE-379 - Creation of Temporary File in Directory with Incorrect Permissions 73 | OWASP, Insecure Temporary File 74 | Python tempfile module''' 75 | 76 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security36.py: -------------------------------------------------------------------------------- 1 | ###### Использование незашифрованных томов EBS чувствительно к безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | 9 | Amazon Elastic Block Store (EBS) — это сервис блочного хранилища для Amazon Elastic Compute Cloud (EC2). Тома EBS можно зашифровать, обеспечивая безопасность как хранящихся, так и передаваемых данных между экземпляром и подключенным к нему хранилищем EBS. В случае, если злоумышленники получают физический доступ к носителю данных, они не смогут получить доступ к данным. Шифрование можно включить для определенных томов или для всех новых томов и снимков. Тома, созданные из снимков, наследуют свою конфигурацию шифрования. Том, созданный из зашифрованного снимка, также будет зашифрован по умолчанию. 10 | 11 | ###### Спросите себя, есть ли 12 | 13 | Диск содержит конфиденциальные данные, утечка которых может причинить вред. 14 | К службе хранения данных в зашифрованном виде предъявляются требования соответствия. 15 | 16 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 17 | Пример конфиденциального кода 18 | 19 | For aws_cdk.aws_ec2.Volume:''' 20 | 21 | from aws_cdk.aws_ec2 import Volume 22 | 23 | class EBSVolumeStack(Stack): 24 | 25 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 26 | super().__init__(scope, construct_id, **kwargs) 27 | Volume(self, 28 | "unencrypted-explicit", 29 | availability_zone="eu-west-1a", 30 | size=Size.gibibytes(1), 31 | encrypted=False # Sensitive 32 | ) 33 | 34 | from aws_cdk.aws_ec2 import Volume 35 | 36 | class EBSVolumeStack(Stack): 37 | 38 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 39 | super().__init__(scope, construct_id, **kwargs) 40 | Volume(self, 41 | "unencrypted-implicit", 42 | availability_zone="eu-west-1a", 43 | size=Size.gibibytes(1) 44 | ) # Sensitive as encryption is disabled by default 45 | 46 | 47 | 48 | 49 | ### Рекомендуемые методы безопасного кодирования 50 | 51 | '''Рекомендуется шифровать тома EBS, содержащие конфиденциальную информацию. Шифрование и дешифрование прозрачно выполняются EC2, поэтому дальнейшие изменения приложения не требуются. Вместо включения шифрования для каждого тома также можно включить глобальное шифрование для определенного региона. Хотя создание томов из зашифрованных снимков приведет к их шифрованию, явное включение этого параметра безопасности предотвратит любое неожиданное понижение уровня безопасности в будущем. 52 | Соответствующее решение 53 | 54 | 55 | For aws_cdk.aws_ec2.Volume:''' 56 | 57 | from aws_cdk.aws_ec2 import Volume 58 | 59 | class EBSVolumeStack(Stack): 60 | 61 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 62 | super().__init__(scope, construct_id, **kwargs) 63 | Volume(self, 64 | "encrypted-explicit", 65 | availability_zone="eu-west-1a", 66 | size=Size.gibibytes(1), 67 | encrypted=True 68 | ) 69 | 70 | '''See 71 | 72 | OWASP Top 10 2021 Category A4 - Insecure Design 73 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 74 | Amazon EBS encryption 75 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 76 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 77 | MITRE, CWE-311 - Missing Encryption of Sensitive Data''' 78 | 79 | 80 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security37.py: -------------------------------------------------------------------------------- 1 | ###### Использование незашифрованных файловых систем EFS важно для безопасности. 2 | 3 | '''Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянная/проблема: 10 мин. 9 | 10 | Amazon Elastic File System (EFS) — это бессерверная файловая система, не требующая выделения ресурсов или управления хранилищем. Сохраненные файлы могут быть автоматически зашифрованы службой. В случае, если злоумышленники получают физический доступ к носителю данных или иным образом сливают сообщение, они не могут получить доступ к данным. 11 | 12 | ###### Спросите себя, есть ли 13 | 14 | Файловая система содержит конфиденциальные данные, утечка которых может причинить вред. 15 | К службе хранения данных в зашифрованном виде предъявляются требования соответствия. 16 | 17 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 18 | Пример конфиденциального кода 19 | 20 | For aws_cdk.aws_efs.FileSystem and aws_cdk.aws_efs.CfnFileSystem:''' 21 | 22 | from aws_cdk import ( 23 | aws_efs as efs 24 | ) 25 | 26 | efs.FileSystem( 27 | self, 28 | "example", 29 | encrypted=False # Sensitive 30 | ) 31 | 32 | ### Рекомендуемые методы безопасного кодирования 33 | ''' 34 | Рекомендуется шифровать файловые системы EFS, содержащие конфиденциальную информацию. Шифрование и дешифрование прозрачно выполняются EFS, поэтому дальнейшие изменения приложения не требуются. 35 | Соответствующее решение 36 | 37 | 38 | For aws_cdk.aws_efs.FileSystem and aws_cdk.aws_efs.CfnFileSystem:''' 39 | 40 | from aws_cdk import ( 41 | aws_efs as efs 42 | ) 43 | 44 | efs.FileSystem( 45 | self, 46 | "example", 47 | encrypted=True 48 | ) 49 | 50 | '''See 51 | 52 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 53 | OWASP Top 10 2021 Category A4 - Insecure Design 54 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 55 | AWS Documentation - Data encryption in Amazon EFS 56 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 57 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 58 | MITRE, CWE-311 - Missing Encryption of Sensitive Data''' 59 | 60 | 61 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security40.py: -------------------------------------------------------------------------------- 1 | ###### питон: S6319 2 | '''Использование незашифрованных экземпляров блокнотов SageMaker важно для безопасности. 3 | 4 | Точка доступа безопасности 5 | Главный 6 | 7 | Доступно с 19 декабря 2023 г. 8 | СонарКуб (Python) 9 | Постоянная/проблема: 10 мин. 10 | 11 | Amazon SageMaker — это управляемый сервис машинного обучения в размещенной рабочей среде. Для обучения моделей машинного обучения экземпляры SageMaker могут обрабатывать потенциально конфиденциальные данные, например личную информацию, которую не следует хранить в незашифрованном виде. В случае физического доступа злоумышленников к носителю данных они не смогут расшифровать зашифрованные данные. 12 | 13 | 14 | 15 | ###### Спросите себя, есть ли 16 | 17 | Экземпляр содержит конфиденциальные данные, утечка которых может причинить вред. 18 | К службе хранения данных в зашифрованном виде предъявляются требования соответствия. 19 | 20 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 21 | Пример конфиденциального кода 22 | 23 | For aws_cdk.aws_sagemaker.CfnNotebookInstance:''' 24 | 25 | from aws_cdk import ( 26 | aws_sagemaker as sagemaker 27 | ) 28 | 29 | class CfnSagemakerStack(Stack): 30 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 31 | super().__init__(scope, construct_id, **kwargs) 32 | 33 | sagemaker.CfnNotebookInstance( 34 | self, "Sensitive", 35 | instance_type="instanceType", 36 | role_arn="roleArn" 37 | ) # Sensitive, no KMS key is set by default; thus, encryption is disabled 38 | 39 | 40 | 41 | 42 | ### Рекомендуемые методы безопасного кодирования 43 | 44 | '''Рекомендуется шифровать экземпляры блокнотов SageMaker, содержащие конфиденциальную информацию. Шифрование и дешифрование выполняются SageMaker прозрачно, поэтому никаких дополнительных изменений в приложении не требуется. 45 | Соответствующее решение 46 | For aws_cdk.aws_sagemaker.CfnNotebookInstance:''' 47 | 48 | from aws_cdk import ( 49 | aws_sagemaker as sagemaker, 50 | aws_kms as kms 51 | ) 52 | 53 | class CfnSagemakerStack(Stack): 54 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 55 | super().__init__(scope, construct_id, **kwargs) 56 | 57 | my_key = kms.Key(self, "Key") 58 | sagemaker.CfnNotebookInstance( 59 | self, "Compliant", 60 | instance_type="instanceType", 61 | role_arn="roleArn", 62 | kms_key_id=my_key.key_id 63 | ) 64 | ''' 65 | See 66 | 67 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 68 | OWASP Top 10 2021 Category A4 - Insecure Design 69 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 70 | Protect Data at Rest Using Encryption 71 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 72 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 73 | MITRE, CWE-311 - Missing Encryption of Sensitive Data''' 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security42.py: -------------------------------------------------------------------------------- 1 | ###### Использование незашифрованных очередей SQS важно для безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Главный 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | Постоянная/проблема: 10 мин. 9 | 10 | Amazon Simple Queue Service (SQS) — это управляемая служба очередей сообщений для связи между приложениями (A2A). Amazon SQS может хранить сообщения в зашифрованном виде сразу после их получения. В случае, если злоумышленники получают физический доступ к носителю данных или иным образом сливают сообщение из файловой системы, например, через уязвимость в службе, они не смогут получить доступ к данным. 11 | 12 | ###### Спросите себя, есть ли 13 | 14 | Очередь содержит конфиденциальные данные, утечка которых может причинить вред. 15 | К службе хранения данных в зашифрованном виде предъявляются требования соответствия. 16 | 17 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 18 | Пример конфиденциального кода 19 | 20 | For aws_cdk.aws_sqs.Queue:''' 21 | 22 | from aws_cdk import ( 23 | aws_sqs as sqs 24 | ) 25 | 26 | class QueueStack(Stack): 27 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 28 | super().__init__(scope, construct_id, **kwargs) 29 | sqs.Queue( # Sensitive, unencrypted by default 30 | self, 31 | "example" 32 | ) 33 | 34 | # For aws_cdk.aws_sqs.CfnQueue: 35 | 36 | from aws_cdk import ( 37 | aws_sqs as sqs 38 | ) 39 | 40 | class CfnQueueStack(Stack): 41 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 42 | super().__init__(scope, construct_id, **kwargs) 43 | sqs.CfnQueue( # Sensitive, unencrypted by default 44 | self, 45 | "example" 46 | ) 47 | 48 | 49 | 50 | ### Рекомендуемые методы безопасного кодирования 51 | ''' 52 | Рекомендуется шифровать очереди SQS, содержащие конфиденциальную информацию. Шифрование и дешифрование прозрачно выполняются SQS, поэтому дальнейшие изменения приложения не требуются. 53 | Соответствующее решение 54 | 55 | For aws_cdk.aws_sqs.Queue:''' 56 | 57 | from aws_cdk import ( 58 | aws_sqs as sqs 59 | ) 60 | 61 | class QueueStack(Stack): 62 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 63 | super().__init__(scope, construct_id, **kwargs) 64 | sqs.Queue( 65 | self, 66 | "example", 67 | encryption=sqs.QueueEncryption.KMS_MANAGED 68 | ) 69 | 70 | # For aws_cdk.aws_sqs.CfnQueue: 71 | 72 | from aws_cdk import ( 73 | aws_sqs as sqs 74 | ) 75 | 76 | class CfnQueueStack(Stack): 77 | def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: 78 | super().__init__(scope, construct_id, **kwargs) 79 | my_key = kms.Key(self, "key") 80 | sqs.CfnQueue( 81 | self, 82 | "example", 83 | kms_master_key_id=my_key.key_id 84 | ) 85 | ''' 86 | See 87 | 88 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 89 | OWASP Top 10 2021 Category A4 - Insecure Design 90 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 91 | AWS Documentation - Encryption at rest 92 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 93 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 94 | MITRE, CWE-311 - Missing Encryption of Sensitive Data''' 95 | 96 | 97 | 98 | 99 | -------------------------------------------------------------------------------- /01.python/Security_Hotspot/Security43.py: -------------------------------------------------------------------------------- 1 | ###### Использование слабых алгоритмов хеширования чувствительно к безопасности. 2 | ''' 3 | Точка доступа безопасности 4 | Критический 5 | 6 | Доступно с 19 декабря 2023 г. 7 | СонарКуб (Python) 8 | 9 | Криптографические алгоритмы хеширования, такие как MD2, MD4, MD5, MD6, HAVAL-128, HMAC-MD5, DSA (использующий SHA-1), RIPEMD, RIPEMD-128, RIPEMD-160, HMACRIPEMD160 и SHA-1, больше не считаются безопасными. , потому что возможны коллизии (достаточно небольших вычислительных усилий, чтобы найти два или более разных входных данных, которые создают один и тот же хэш). 10 | 11 | ###### Спросите себя, есть ли 12 | 13 | Хэшированное значение используется в контексте безопасности, например: 14 | 15 | Хранилище паролей пользователя. 16 | Генерация токена безопасности (используется для подтверждения электронной почты при регистрации на сайте, сброса пароля и т. д.). 17 | Чтобы вычислить некоторую целостность сообщения. 18 | 19 | Существует риск, если вы ответили утвердительно на любой из этих вопросов. 20 | Пример конфиденциального кода 21 | ''' 22 | import hashlib 23 | m = hashlib.md5() # Sensitive 24 | 25 | import hashlib 26 | m = hashlib.sha1() # Sensitive 27 | 28 | import md5 # Sensitive and deprecated since Python 2.5; use the hashlib module instead. 29 | m = md5.new() 30 | 31 | import sha # Sensitive and deprecated since Python 2.5; use the hashlib module instead. 32 | m = sha.new() 33 | 34 | 35 | 36 | ### Рекомендуемые методы безопасного кодирования 37 | ''' 38 | Рекомендуется использовать более безопасные альтернативы, такие как SHA-256, SHA-512, SHA-3, а для хеширования паролей даже лучше использовать алгоритмы, которые не вычисляются слишком «быстро», например bcrypt, scrypt, argon2 или pbkdf2, поскольку они замедляют работу. отражать атаки грубой силы. 39 | Соответствующее решение''' 40 | 41 | import hashlib 42 | m = hashlib.sha512() # Compliant 43 | ''' 44 | See 45 | 46 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 47 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 48 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 49 | Mobile AppSec Verification Standard - Cryptography Requirements 50 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 51 | MITRE, CWE-1240 - Use of a Risky Cryptographic Primitive 52 | SANS Top 25 - Porous Defenses''' 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability1.py: -------------------------------------------------------------------------------- 1 | '''A secure password should be used when connecting to a database 2 | 3 | Vulnerability 4 | Blocker 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 45min 9 | 10 | When relying on the password authentication mode for the database connection, a secure password should be chosen. 11 | 12 | This rule raises an issue when an empty password is used. 13 | Noncompliant Code Example 14 | 15 | Flask-SQLAlchemy''' 16 | 17 | def configure_app(app): 18 | app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://user:@domain.com" # Noncompliant 19 | 20 | ### Django 21 | # settings.py 22 | 23 | DATABASES = { 24 | 'postgresql_db': { 25 | 'ENGINE': 'django.db.backends.postgresql', 26 | 'NAME': 'quickdb', 27 | 'USER': 'sonarsource', 28 | 'PASSWORD': '', # Noncompliant 29 | 'HOST': 'localhost', 30 | 'PORT': '5432' 31 | } 32 | } 33 | 34 | # mysql/mysql-connector-python 35 | 36 | from mysql.connector import connection 37 | connection.MySQLConnection(host='localhost', user='sonarsource', password='') # Noncompliant 38 | 39 | ### Compliant Solution 40 | # Flask-SQLAlchemy 41 | 42 | def configure_app(app, pwd): 43 | app.config['SQLALCHEMY_DATABASE_URI'] = f"postgresql://user:{pwd}@domain.com" # Compliant 44 | 45 | ### Django 46 | # settings.py 47 | import os 48 | 49 | DATABASES = { 50 | 'postgresql_db': { 51 | 'ENGINE': 'django.db.backends.postgresql', 52 | 'NAME': 'quickdb', 53 | 'USER': 'sonarsource', 54 | 'PASSWORD': os.getenv('DB_PASSWORD'), # Compliant 55 | 'HOST': 'localhost', 56 | 'PORT': '5432' 57 | } 58 | } 59 | 60 | # mysql/mysql-connector-python 61 | 62 | from mysql.connector import connection 63 | import os 64 | 65 | db_password = os.getenv('DB_PASSWORD') 66 | connection.MySQLConnection(host='localhost', user='sonarsource', password=db_password) # Compliant 67 | 68 | '''See 69 | 70 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 71 | OWASP Top 10 2017 Category A2 - Broken Authentication 72 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 73 | MITRE, CWE-521 - Weak Password Requirements''' 74 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability10.py: -------------------------------------------------------------------------------- 1 | '''Insecure temporary file creation methods should not be used 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 10min 9 | 10 | Creating temporary files using insecure methods exposes the application to race conditions on filenames: a malicious user can try to create a file with a predictable name before the application does. A successful attack can result in other files being accessed, modified, corrupted or deleted. This risk is even higher if the application run with elevated permissions. 11 | 12 | In the past, it has led to the following vulnerabilities: 13 | 14 | CVE-2014-1858 15 | CVE-2014-1932 16 | 17 | Noncompliant Code Example''' 18 | 19 | import tempfile 20 | 21 | filename = tempfile.mktemp() # Noncompliant 22 | tmp_file = open(filename, "w+") 23 | 24 | # Compliant Solution 25 | 26 | import tempfile 27 | 28 | tmp_file1 = tempfile.NamedTemporaryFile(delete=False) # Compliant; Easy replacement to tempfile.mktemp() 29 | tmp_file2 = tempfile.NamedTemporaryFile() # Compliant; Created file will be automatically deleted 30 | 31 | '''See 32 | 33 | OWASP Top 10 2021 Category A1 - Broken Access Control 34 | OWASP Top 10 2017 Category A9 - Using Components with Known Vulnerabilities 35 | MITRE, CWE-377 - Insecure Temporary File 36 | MITRE, CWE-379 - Creation of Temporary File in Directory with Incorrect Permissions 37 | OWASP, Insecure Temporary File 38 | Python tempfile module 39 | Python 2.7 os module''' 40 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability11.py: -------------------------------------------------------------------------------- 1 | '''python:S5659 2 | JWT should be signed and verified 3 | 4 | Vulnerability 5 | Critical 6 | 7 | Available SinceDec 19, 2023 8 | SonarQube (Python) 9 | Constant/issue: 30min 10 | 11 | If a JSON Web Token (JWT) is not signed with a strong cipher algorithm (or not signed at all) an attacker can forge it and impersonate user identities. 12 | 13 | Don’t use none algorithm to sign or verify the validity of a token. 14 | Don’t use a token without verifying its signature before. 15 | 16 | Noncompliant Code Example 17 | 18 | For pyjwt module:''' 19 | 20 | jwt.decode(token, verify = False) # Noncompliant 21 | jwt.decode(token, key, options={"verify_signature": False}) # Noncompliant 22 | 23 | # For python_jwt module: 24 | 25 | jwt.process_jwt(token) # Noncompliant 26 | 27 | ### Compliant Solution 28 | # For pyjwt module: 29 | 30 | jwt.decode(token, key, algo) 31 | 32 | # For python_jwt module: 33 | 34 | jwt.process_jwt(token) # Compliant because followed by verify_jwt() 35 | jwt.verify_jwt(token, key, algo) 36 | 37 | '''See 38 | 39 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 40 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 41 | MITRE, CWE-347 - Improper Verification of Cryptographic Signature''' 42 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability12.py: -------------------------------------------------------------------------------- 1 | '''LDAP connections should be authenticated 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 15min 9 | 10 | An LDAP client authenticates to an LDAP server with a "bind request" which provides, among other, a simple authentication method. 11 | 12 | Simple authentication in LDAP can be used with three different mechanisms: 13 | 14 | Anonymous Authentication Mechanism by performing a bind request with a username and password value of zero length. 15 | Unauthenticated Authentication Mechanism by performing a bind request with a password value of zero length. 16 | Name/Password Authentication Mechanism by performing a bind request with a password value of non-zero length. 17 | 18 | Anonymous binds and unauthenticated binds allow access to information in the LDAP directory without providing a password, their use is therefore strongly discouraged. 19 | Noncompliant Code Example''' 20 | 21 | import ldap 22 | 23 | def init_ldap(): 24 | connect = ldap.initialize('ldap://example:1389') 25 | 26 | connect.simple_bind('cn=root') # Noncompliant 27 | connect.simple_bind_s('cn=root') # Noncompliant 28 | connect.bind_s('cn=root', None) # Noncompliant 29 | connect.bind('cn=root', None) # Noncompliant 30 | 31 | # Compliant Solution 32 | 33 | import ldap 34 | import os 35 | 36 | def init_ldap(): 37 | connect = ldap.initialize('ldap://example:1389') 38 | 39 | connect.simple_bind('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant 40 | connect.simple_bind_s('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant 41 | connect.bind_s('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant 42 | connect.bind('cn=root', os.environ.get('LDAP_PASSWORD')) # Compliant 43 | 44 | '''See 45 | 46 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 47 | OWASP Top 10 2017 Category A2 - Broken Authentication 48 | MITRE, CWE-521 - Weak Password Requirements 49 | ldapwiki.com- Simple Authentication''' 50 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability13.py: -------------------------------------------------------------------------------- 1 | '''Server certificates should be verified during SSL/TLS connections 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 5min 9 | 10 | Validation of X.509 certificates is essential to create secure SSL/TLS sessions not vulnerable to man-in-the-middle attacks. 11 | 12 | The certificate chain validation includes these steps: 13 | 14 | The certificate is issued by its parent Certificate Authority or the root CA trusted by the system. 15 | Each CA is allowed to issue certificates. 16 | Each certificate in the chain is not expired. 17 | 18 | It’s not recommended to reinvent the wheel by implementing custom certificate chain validation. 19 | 20 | TLS libraries provide built-in certificate validation functions that should be used. 21 | Noncompliant Code Example 22 | 23 | psf/requests library:''' 24 | 25 | import requests 26 | 27 | requests.request('GET', 'https://example.domain', verify=False) # Noncompliant 28 | requests.get('https://example.domain', verify=False) # Noncompliant 29 | 30 | # Python ssl standard library: 31 | 32 | import ssl 33 | 34 | ctx1 = ssl._create_unverified_context() # Noncompliant: by default certificate validation is not done 35 | ctx2 = ssl._create_stdlib_context() # Noncompliant: by default certificate validation is not done 36 | 37 | ctx3 = ssl.create_default_context() 38 | ctx3.verify_mode = ssl.CERT_NONE # Noncompliant 39 | 40 | # pyca/pyopenssl library: 41 | 42 | from OpenSSL import SSL 43 | 44 | ctx1 = SSL.Context(SSL.TLSv1_2_METHOD) # Noncompliant: by default certificate validation is not done 45 | 46 | ctx2 = SSL.Context(SSL.TLSv1_2_METHOD) 47 | ctx2.set_verify(SSL.VERIFY_NONE, verify_callback) # Noncompliant 48 | 49 | # Compliant Solution 50 | # psf/requests library: 51 | 52 | import requests 53 | 54 | requests.request('GET', 'https://example.domain', verify=True) 55 | requests.request('GET', 'https://example.domain', verify='/path/to/CAbundle') 56 | requests.get(url='https://example.domain') # by default certificate validation is enabled 57 | 58 | # Python ssl standard library: 59 | 60 | import ssl 61 | 62 | ctx = ssl.create_default_context() 63 | ctx.verify_mode = ssl.CERT_REQUIRED 64 | 65 | ctx = ssl._create_default_https_context() # by default certificate validation is enabled 66 | 67 | # pyca/pyopenssl library: 68 | 69 | from OpenSSL import SSL 70 | 71 | ctx = SSL.Context(SSL.TLSv1_2_METHOD) 72 | ctx.set_verify(SSL.VERIFY_PEER, verify_callback) # Compliant 73 | ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verify_callback) # Compliant 74 | ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT | SSL.VERIFY_CLIENT_ONCE, verify_callback) # Compliant 75 | 76 | '''See 77 | 78 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 79 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 80 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 81 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 82 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 83 | Mobile AppSec Verification Standard - Network Communication Requirements 84 | OWASP Mobile Top 10 2016 Category M3 - Insecure Communication 85 | MITRE, CWE-295 - Improper Certificate Validation''' 86 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability14.py: -------------------------------------------------------------------------------- 1 | '''Server hostnames should be verified during SSL/TLS connections 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 5min 9 | 10 | To establish a SSL/TLS connection not vulnerable to man-in-the-middle attacks, it’s essential to make sure the server presents the right certificate. 11 | 12 | The certificate’s hostname-specific data should match the server hostname. 13 | 14 | It’s not recommended to re-invent the wheel by implementing custom hostname verification. 15 | 16 | TLS/SSL libraries provide built-in hostname verification functions that should be used. 17 | Noncompliant Code Example 18 | 19 | Python ssl standard library:''' 20 | 21 | import ssl 22 | 23 | ctx = ssl._create_unverified_context() # Noncompliant: by default hostname verification is not done 24 | ctx = ssl._create_stdlib_context() # Noncompliant: by default hostname verification is not done 25 | 26 | ctx = ssl.create_default_context() 27 | ctx.check_hostname = False # Noncompliant 28 | 29 | ctx = ssl._create_default_https_context() 30 | ctx.check_hostname = False # Noncompliant 31 | 32 | # Compliant Solution 33 | # Python ssl standard library: 34 | 35 | import ssl 36 | 37 | ctx = ssl._create_unverified_context() 38 | ctx.check_hostname = True # Compliant 39 | 40 | ctx = ssl._create_stdlib_context() 41 | ctx.check_hostname = True # Compliant 42 | 43 | ctx = ssl.create_default_context() # Compliant: by default hostname verification is enabled 44 | ctx = ssl._create_default_https_context() # Compliant: by default hostname verification is enabled 45 | 46 | '''See 47 | 48 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 49 | OWASP Top 10 2021 Category A5 - Security Misconfiguration 50 | OWASP Top 10 2021 Category A7 - Identification and Authentication Failures 51 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 52 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 53 | Mobile AppSec Verification Standard - Network Communication Requirements 54 | OWASP Mobile Top 10 2016 Category M3 - Insecure Communication 55 | MITRE, CWE-297 - Improper Validation of Certificate with Host Mismatch''' 56 | -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability5.py: -------------------------------------------------------------------------------- 1 | '''Cipher Block Chaining IVs should be unpredictable 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 15min 9 | 10 | When encrypting data with the Cipher Block Chaining (CBC) mode an Initialization Vector (IV) is used to randomize the encryption, ie under a given key the same plaintext doesn’t always produce the same ciphertext. The IV doesn’t need to be secret but should be unpredictable to avoid "Chosen-Plaintext Attack". 11 | 12 | To generate Initialization Vectors, NIST recommends to use a secure random number generator. 13 | Noncompliant Code Example 14 | 15 | For PyCryptodome module:''' 16 | 17 | from Crypto.Cipher import AES 18 | from Crypto.Random import get_random_bytes 19 | from Crypto.Util.Padding import pad, unpad 20 | 21 | static_vector = b'x' * AES.block_size 22 | cipher = AES.new(key, AES.MODE_CBC, static_vector) 23 | cipher.encrypt(pad(data, AES.block_size)) # Noncompliant 24 | 25 | # For cryptography module: 26 | 27 | from os import urandom 28 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 29 | 30 | static_vector = b'x' * 16 31 | cipher = Cipher(algorithms.AES(key), modes.CBC(static_vector)) 32 | cipher.encryptor() # Noncompliant 33 | 34 | # Compliant Solution 35 | # For PyCryptodome module: 36 | 37 | from Crypto.Cipher import AES 38 | from Crypto.Random import get_random_bytes 39 | from Crypto.Util.Padding import pad, unpad 40 | 41 | random_vector = get_random_bytes(AES.block_size) 42 | cipher = AES.new(key, AES.MODE_CBC, random_vector) 43 | cipher.encrypt(pad(data, AES.block_size)) 44 | 45 | # For cryptography module: 46 | 47 | from os import urandom 48 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes 49 | 50 | random_vector = urandom(16) 51 | cipher = Cipher(algorithms.AES(key), modes.CBC(random_vector)) 52 | cipher.encryptor() 53 | 54 | '''See 55 | 56 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 57 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 58 | Mobile AppSec Verification Standard - Cryptography Requirements 59 | OWASP Mobile Top 10 2016 Category M5 - Insufficient Cryptography 60 | MITRE, CWE-329 - Not Using an Unpredictable IV with CBC Mode 61 | NIST, SP-800-38A - Recommendation for Block Cipher Modes of Operation 62 | ''' -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability6.py: -------------------------------------------------------------------------------- 1 | '''python:S4426 2 | Cryptographic key generation should be based on strong parameters 3 | 4 | Vulnerability 5 | Critical 6 | 7 | Available SinceDec 19, 2023 8 | SonarQube (Python) 9 | Constant/issue: 2min 10 | 11 | When generating cryptographic keys (or key pairs), it is important to use strong parameters. Key length, for instance, should provide enough entropy against brute-force attacks. 12 | 13 | For RSA and DSA algorithms key size should be at least 2048 bits long 14 | For ECC (elliptic curve cryptography) algorithms key size should be at least 224 bits long 15 | For RSA public key exponent should be at least 65537. 16 | 17 | This rule raises an issue when a RSA, DSA or ECC key-pair generator is initialized using weak parameters. 18 | 19 | It supports the following libraries: 20 | 21 | cryptography 22 | PyCrypto 23 | Cryptodome 24 | 25 | Noncompliant Code Example''' 26 | 27 | from cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa 28 | 29 | dsa.generate_private_key(key_size=1024, backend=backend) # Noncompliant 30 | rsa.generate_private_key(public_exponent=999, key_size=2048, backend=backend) # Noncompliant 31 | ec.generate_private_key(curve=ec.SECT163R2, backend=backend) # Noncompliant 32 | 33 | # Compliant Solution 34 | 35 | from cryptography.hazmat.primitives.asymmetric import rsa, ec, dsa 36 | 37 | dsa.generate_private_key(key_size=2048, backend=backend) # Compliant 38 | rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=backend) # Compliant 39 | ec.generate_private_key(curve=ec.SECT409R1, backend=backend) # Compliant 40 | 41 | '''See 42 | 43 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 44 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 45 | OWASP Top 10 2017 Category A6 - Security Misconfiguration 46 | ANSSI RGSv2 - Référentiel Général de Sécurité version 2 47 | NIST FIPS 186-4 - Digital Signature Standard (DSS) 48 | MITRE, CWE-326 - Inadequate Encryption Strength 49 | ''' -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability8.py: -------------------------------------------------------------------------------- 1 | '''Hashes should include an unpredictable salt 2 | 3 | Vulnerability 4 | Critical 5 | 6 | Available SinceDec 19, 2023 7 | SonarQube (Python) 8 | Constant/issue: 30min 9 | 10 | In cryptography, a "salt" is an extra piece of data which is included when hashing a password. This makes rainbow-table attacks more difficult. Using a cryptographic hash function without an unpredictable salt increases the likelihood that an attacker could successfully find the hash value in databases of precomputed hashes (called rainbow-tables). 11 | 12 | This rule raises an issue when a hashing function which has been specifically designed for hashing passwords, such as PBKDF2, is used with a non-random, reused or too short salt value. It does not raise an issue on base hashing algorithms such as sha1 or md5 as they should not be used to hash passwords. 13 | Recommended Secure Coding Practices 14 | 15 | Use hashing functions generating their own secure salt or generate a secure random value of at least 16 bytes. 16 | The salt should be unique by user password. 17 | 18 | Noncompliant Code Example 19 | 20 | hashlib''' 21 | 22 | import crypt 23 | from hashlib import pbkdf2_hmac 24 | 25 | hash = pbkdf2_hmac('sha256', password, b'D8VxSmTZt2E2YV454mkqAY5e', 100000) # Noncompliant: salt is hardcoded 26 | 27 | crypt 28 | 29 | hash = crypt.crypt(password) # Noncompliant: salt is not provided 30 | 31 | ### Compliant Solution 32 | # hashlib 33 | 34 | import crypt 35 | from hashlib import pbkdf2_hmac 36 | 37 | salt = os.urandom(32) 38 | hash = pbkdf2_hmac('sha256', password, salt, 100000) # Compliant 39 | 40 | crypt 41 | 42 | salt = crypt.mksalt(crypt.METHOD_SHA256) 43 | hash = crypt.crypt(password, salt) # Compliant 44 | 45 | '''See 46 | 47 | OWASP Top 10 2021 Category A2 - Cryptographic Failures 48 | OWASP Top 10 2017 Category A3 - Sensitive Data Exposure 49 | MITRE, CWE-759 - Use of a One-Way Hash without a Salt 50 | MITRE, CWE-760 - Use of a One-Way Hash with a Predictable Salt 51 | SANS Top 25 - Porous Defenses 52 | ''' -------------------------------------------------------------------------------- /01.python/Vulnerability/Vulnerability9.py: -------------------------------------------------------------------------------- 1 | '''HTML autoescape mechanism should not be globally disabled 2 | 3 | Vulnerability 4 | Blocker 5 | Deprecated 6 | 7 | Available SinceDec 19, 2023 8 | SonarQube (Python) 9 | Constant/issue: 5min 10 | 11 | Template engines have an HTML autoescape mechanism that protects web applications against most common cross-site-scripting (XSS) vulnerabilities. 12 | 13 | By default, it automatically replaces HTML special characters in any template variables. This secure by design configuration should not be globally disabled. 14 | 15 | Escaping HTML from template variables prevents switching into any execution context, like