From 4ea26c0865ad5a1bf5b9e07e427f75383c542e1d Mon Sep 17 00:00:00 2001 From: "Devashish [C] Rane" Date: Mon, 14 Jul 2025 15:36:59 +0530 Subject: [PATCH] Add PR_8_kotlin for kotlin --- .../filtered_kotlin/CWE-022_50_TaintedPath.kt | 23 ++++++ .../CWE-074_25_JndiInjection.kt | 32 +++++++++ .../CWE-074_26_XsltInjection.kt | 26 +++++++ .../CWE-089_21_SqlConcatenated.kt | 31 ++++++++ .../filtered_kotlin/CWE-089_22_SqlTainted.kt | 28 ++++++++ .../CWE-089_23_SqlTaintedPersistence.kt | 29 ++++++++ .../CWE-090_27_LdapInjectionJndi.kt | 41 +++++++++++ .../CWE-090_28_LdapInjectionSpring.kt | 41 +++++++++++ .../CWE-090_29_LdapInjectionApache.kt | 29 ++++++++ .../CWE-090_30_LdapInjectionUnboundId.kt | 24 +++++++ ...E-094_02_UnsafeSpelExpressionEvaluation.kt | 26 +++++++ .../CWE-094_03_GroovyInjectionBlocklist.kt | 18 +++++ .../CWE-094_04_InsecureBeanValidation.kt | 43 ++++++++++++ ...E-094_05_UnsafeJexlExpressionEvaluation.kt | 24 +++++++ .../CWE-094_06_GroovyInjectionBad.kt | 35 ++++++++++ .../CWE-117_34_LogInjectionBad.kt | 28 ++++++++ .../CWE-117_35_LogInjectionGood.kt | 27 +++++++ ...idationOfArrayConstructionCodeSpecified.kt | 25 +++++++ ...E-129_37_ImproperValidationOfArrayIndex.kt | 35 ++++++++++ ...operValidationOfArrayIndexCodeSpecified.kt | 33 +++++++++ ...9_ImproperValidationOfArrayConstruction.kt | 33 +++++++++ .../CWE-190_15_ArithmeticWithExtremeValues.kt | 17 +++++ .../CWE-190_16_ArithmeticUncontrolled.kt | 21 ++++++ .../CWE-190_17_ArithmeticTainted.kt | 28 ++++++++ .../CWE-190_18_ComparisonWithWiderType.kt | 34 +++++++++ .../CWE-200_09_WebViewFileAccessUnsafe.kt | 10 +++ .../CWE-209_07_StackTraceExposure.kt | 28 ++++++++ ...-266_31_IntentUriPermissionManipulation.kt | 26 +++++++ ...32_ImproperWebViewCertificateValidation.kt | 31 ++++++++ .../CWE-295_33_InsecureTrustManager.kt | 18 +++++ .../CWE-297_01_UnsafeHostnameVerification.kt | 5 ++ .../CWE-330_41_InsecureRandomnessCookie.kt | 2 + .../CWE-352_44_SpringCSRFProtection.kt | 15 ++++ .../filtered_kotlin/CWE-367_19_TOCTOURace.kt | 32 +++++++++ .../CWE-421_24_SocketAuthRace.kt | 4 ++ ...8_FragmentInjectionInPreferenceActivity.kt | 15 ++++ .../CWE-470_49_FragmentInjection.kt | 21 ++++++ .../CWE-502_45_UnsafeDeserializationBad.kt | 3 + .../CWE-502_46_UnsafeDeserializationGood.kt | 3 + .../CWE-522_12_InsecureBasicAuth.kt | 41 +++++++++++ .../CWE-522_13_LdapAuthUseLdaps.kt | 3 + .../CWE-522_14_LdapAuthUseLdap.kt | 3 + .../CWE-614_20_InsecureCookie.kt | 3 + .../CWE-730_47_RegexInjection.kt | 22 ++++++ .../CWE-749_40_UnsafeAndroidAccess.kt | 70 +++++++++++++++++++ .../CWE-798_42_HardcodedCredentialsApiCall.kt | 3 + .../CWE-798_43_HardcodedAWSCredentials.kt | 12 ++++ .../CWE-807_08_TaintedPermissionsCheck.kt | 3 + .../CWE-917_10_OgnlInjection.kt | 3 + .../CWE-918_11_RequestForgery.kt | 24 +++++++ .../kotlin_2nd/filtered_kotlin/README.md | 66 +++++++++++++++++ 51 files changed, 1197 insertions(+) create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-022_50_TaintedPath.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_25_JndiInjection.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_26_XsltInjection.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_21_SqlConcatenated.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_22_SqlTainted.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_23_SqlTaintedPersistence.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_27_LdapInjectionJndi.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_28_LdapInjectionSpring.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_29_LdapInjectionApache.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_30_LdapInjectionUnboundId.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_02_UnsafeSpelExpressionEvaluation.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_03_GroovyInjectionBlocklist.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_04_InsecureBeanValidation.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_05_UnsafeJexlExpressionEvaluation.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_06_GroovyInjectionBad.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_34_LogInjectionBad.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_35_LogInjectionGood.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_36_ImproperValidationOfArrayConstructionCodeSpecified.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_37_ImproperValidationOfArrayIndex.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_38_ImproperValidationOfArrayIndexCodeSpecified.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_39_ImproperValidationOfArrayConstruction.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_15_ArithmeticWithExtremeValues.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_16_ArithmeticUncontrolled.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_17_ArithmeticTainted.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_18_ComparisonWithWiderType.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-200_09_WebViewFileAccessUnsafe.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-209_07_StackTraceExposure.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-266_31_IntentUriPermissionManipulation.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_32_ImproperWebViewCertificateValidation.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_33_InsecureTrustManager.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-297_01_UnsafeHostnameVerification.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-330_41_InsecureRandomnessCookie.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-352_44_SpringCSRFProtection.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-367_19_TOCTOURace.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-421_24_SocketAuthRace.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_48_FragmentInjectionInPreferenceActivity.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_49_FragmentInjection.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_45_UnsafeDeserializationBad.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_46_UnsafeDeserializationGood.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_12_InsecureBasicAuth.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_13_LdapAuthUseLdaps.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_14_LdapAuthUseLdap.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-614_20_InsecureCookie.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-730_47_RegexInjection.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-749_40_UnsafeAndroidAccess.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_42_HardcodedCredentialsApiCall.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_43_HardcodedAWSCredentials.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-807_08_TaintedPermissionsCheck.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-917_10_OgnlInjection.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-918_11_RequestForgery.kt create mode 100644 PR_8_kotlin/kotlin_2nd/filtered_kotlin/README.md diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-022_50_TaintedPath.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-022_50_TaintedPath.kt new file mode 100644 index 0000000..79c1383 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-022_50_TaintedPath.kt @@ -0,0 +1,23 @@ +// {fact rule=insufficiently-protected-credentials@v1.0 defects=1} +import java.io.BufferedReader +import java.io.FileReader +import java.io.IOException +import java.io.InputStreamReader +import java.net.Socket + +class TaintedPath { + @Throws(IOException::class) + fun sendUserFile(sock: Socket, user: String?) { + val filenameReader = BufferedReader( + InputStreamReader(sock.getInputStream(), "UTF-8")) + val filename = filenameReader.readLine() + // BAD: read from a file without checking its path + val fileReader = BufferedReader(FileReader(filename)) + var fileLine = fileReader.readLine() + while (fileLine != null) { + sock.getOutputStream().write(fileLine.toByteArray()) + fileLine = fileReader.readLine() + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_25_JndiInjection.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_25_JndiInjection.kt new file mode 100644 index 0000000..d294abc --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_25_JndiInjection.kt @@ -0,0 +1,32 @@ +// {fact rule=excessive-permissions-grant@v1.0 defects=0} +import jakarta.servlet.http.HttpServletRequest +import java.util.* +import javax.naming.Context +import javax.naming.InitialContext +import javax.naming.NamingException + +class JndiInjection { + @Throws(NamingException::class) + fun jndiLookup(request: HttpServletRequest) { + val name: String = request.getParameter("name") + val env: Hashtable = Hashtable() + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory") + env.put(Context.PROVIDER_URL, "rmi://trusted-server:1099") + val ctx = InitialContext(env) + + // BAD: User input used in lookup + ctx.lookup(name) + + // GOOD: The name is validated before being used in lookup + if (isValid(name)) { + ctx.lookup(name) + } else { + // Reject the request + } + } + + fun isValid(name: String): Boolean { + return true; + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_26_XsltInjection.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_26_XsltInjection.kt new file mode 100644 index 0000000..4ad48a5 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-074_26_XsltInjection.kt @@ -0,0 +1,26 @@ +//// {fact rule=excessive-permissions-grant@v1.0 defects=0} +//import java.io.StringReader +//import java.io.StringWriter +//import java.net.Socket +//import javax.xml.XMLConstants +//import javax.xml.transform.TransformerFactory +//import javax.xml.transform.stream.StreamResult +//import javax.xml.transform.stream.StreamSource +// +//class XsltInjection { +// @Throws(Exception::class) +// fun transform(socket: Socket, inputXml: String?) { +// val xslt = StreamSource(socket.getInputStream()) +// val xml = StreamSource(StringReader(inputXml)) +// val result = StringWriter() +// val factory = TransformerFactory.newInstance() +// +// // BAD: User provided XSLT stylesheet is processed +// factory.newTransformer(xslt).transform(xml, StreamResult(result)) +// +// // GOOD: The secure processing mode is enabled +// factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) +// factory.newTransformer(xslt).transform(xml, StreamResult(result)) +// } +//} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_21_SqlConcatenated.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_21_SqlConcatenated.kt new file mode 100644 index 0000000..6e999de --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_21_SqlConcatenated.kt @@ -0,0 +1,31 @@ +// {fact rule=active-debug-code@v1.0 defects=0} +import java.sql.Connection +import java.sql.SQLException + +internal class SqlConcatenated { + @Throws(SQLException::class) + fun example1() { + // BAD: the category might have SQL special characters in it + val category = this.category + val connection: Connection? = null + val statement = connection!!.createStatement() + val query1 = ("SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + + category + "' ORDER BY PRICE") + val results = statement.executeQuery(query1) + } + + @Throws(SQLException::class) + fun example2() { + // GOOD: use a prepared query + val category = this.category + val query2 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=? ORDER BY PRICE" + val connection: Connection? = null + val statement = connection!!.prepareStatement(query2) + statement.setString(1, category) + val results = statement.executeQuery() + } + + private val category: String? + get() = null +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_22_SqlTainted.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_22_SqlTainted.kt new file mode 100644 index 0000000..da80193 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_22_SqlTainted.kt @@ -0,0 +1,28 @@ +// {fact rule=active-debug-code@v1.0 defects=0} +import java.sql.Connection +import java.sql.PreparedStatement +import java.sql.ResultSet +import java.sql.Statement + +internal class SqlTainted { + init { + // BAD: the category might have SQL special characters in it + val category = System.getenv("ITEM_CATEGORY") + val connection: Connection? = null + val statement: Statement = connection!!.createStatement() + val query1 = ("SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='" + + category + "' ORDER BY PRICE") + val results: ResultSet = statement.executeQuery(query1) + } + + init { + // GOOD: use a prepared query + val category = System.getenv("ITEM_CATEGORY") + val query2 = "SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY=? ORDER BY PRICE" + val connection: Connection? = null + val statement: PreparedStatement = connection!!.prepareStatement(query2) + statement.setString(1, category) + val results: ResultSet = statement.executeQuery() + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_23_SqlTaintedPersistence.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_23_SqlTaintedPersistence.kt new file mode 100644 index 0000000..8d538ef --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-089_23_SqlTaintedPersistence.kt @@ -0,0 +1,29 @@ +import jakarta.persistence.Entity +import jakarta.persistence.Id +import jakarta.persistence.NamedQuery + +@Entity +open class Product( + @Id + val id: Int, + var category: String, + var price: Double +) { + // No-argument constructor required by JPA + protected constructor() : this(0, "", 0.0) + // Stub implementation +} + +// {fact rule=active-debug-code@v1.0 defects=0} +// GOOD: use a named query with a named parameter and set its value +@NamedQuery(name = "lookupByCategory", query = "SELECT p FROM Product p WHERE p.category LIKE :category ORDER BY p.price") +private class NQ { + +} + +// GOOD: use a named query with a positional parameter and set its value +@NamedQuery(name = "lookupByCategory", query = "SELECT p FROM Product p WHERE p.category LIKE ?1 ORDER BY p.price") +private class NA { + +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_27_LdapInjectionJndi.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_27_LdapInjectionJndi.kt new file mode 100644 index 0000000..6726f24 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_27_LdapInjectionJndi.kt @@ -0,0 +1,41 @@ +// {fact rule=ldap-injection@v1.0 defects=0} +import jakarta.servlet.http.HttpServletRequest +import org.owasp.esapi.Encoder +import org.owasp.esapi.reference.DefaultEncoder +import javax.naming.NamingException +import javax.naming.directory.DirContext +import javax.naming.directory.SearchControls + +class LdapInjectionJndi { + @Throws(NamingException::class) + fun ldapQueryBad(request: HttpServletRequest, ctx: DirContext) { + val organizationName: String = request.getParameter("organization_name") + val username: String = request.getParameter("username") + + // BAD: User input used in DN (Distinguished Name) without encoding + val dn = "OU=People,O=$organizationName" + + // BAD: User input used in search filter without encoding + val filter = "username=$username" + ctx.search(dn, filter, SearchControls()) + } + + @Throws(NamingException::class) + fun ldapQueryGood(request: HttpServletRequest, ctx: DirContext) { + val organizationName: String = request.getParameter("organization_name") + val username: String = request.getParameter("username") + + // ESAPI encoder + val encoder: Encoder = DefaultEncoder.getInstance() + + // GOOD: Organization name is encoded before being used in DN + val safeOrganizationName: String = encoder.encodeForDN(organizationName) + val safeDn = "OU=People,O=$safeOrganizationName" + + // GOOD: User input is encoded before being used in search filter + val safeUsername: String = encoder.encodeForLDAP(username) + val safeFilter = "username=$safeUsername" + ctx.search(safeDn, safeFilter, SearchControls()) + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_28_LdapInjectionSpring.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_28_LdapInjectionSpring.kt new file mode 100644 index 0000000..0a32b37 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_28_LdapInjectionSpring.kt @@ -0,0 +1,41 @@ +// {fact rule=ldap-injection@v1.0 defects=0} +import jakarta.servlet.http.HttpServletRequest +import org.owasp.esapi.Encoder +import org.owasp.esapi.reference.DefaultEncoder +import javax.naming.NamingException +import javax.naming.directory.DirContext +import javax.naming.directory.SearchControls + +class LdapInjectionSpring { + @Throws(NamingException::class) + fun ldapQueryBad(request: HttpServletRequest, ctx: DirContext) { + val organizationName: String = request.getParameter("organization_name") + val username: String = request.getParameter("username") + + // BAD: User input used in DN (Distinguished Name) without encoding + val dn = "OU=People,O=$organizationName" + + // BAD: User input used in search filter without encoding + val filter = "username=$username" + ctx.search(dn, filter, SearchControls()) + } + + @Throws(NamingException::class) + fun ldapQueryGood(request: HttpServletRequest, ctx: DirContext) { + val organizationName: String = request.getParameter("organization_name") + val username: String = request.getParameter("username") + + // ESAPI encoder + val encoder: Encoder = DefaultEncoder.getInstance() + + // GOOD: Organization name is encoded before being used in DN + val safeOrganizationName: String = encoder.encodeForDN(organizationName) + val safeDn = "OU=People,O=$safeOrganizationName" + + // GOOD: User input is encoded before being used in search filter + val safeUsername: String = encoder.encodeForLDAP(username) + val safeFilter = "username=$safeUsername" + ctx.search(safeDn, safeFilter, SearchControls()) + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_29_LdapInjectionApache.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_29_LdapInjectionApache.kt new file mode 100644 index 0000000..cfb3958 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_29_LdapInjectionApache.kt @@ -0,0 +1,29 @@ +// {fact rule=ldap-injection@v1.0 defects=0} +import jakarta.servlet.http.HttpServletRequest +import org.apache.directory.api.ldap.model.message.SearchRequest +import org.apache.directory.api.ldap.model.message.SearchRequestImpl +import org.apache.directory.api.ldap.model.name.Dn +import org.apache.directory.ldap.client.api.LdapConnection +import javax.naming.ldap.Rdn + +class LdapInjectionApache { + fun ldapQueryGood(request: HttpServletRequest, c: LdapConnection) { + val organizationName: String = request.getParameter("organization_name") + val username: String = request.getParameter("username") + + // GOOD: Organization name is encoded before being used in DN + val safeDn = Dn("OU", "Organization") + + // GOOD: User input is encoded before being used in search filter + val safeFilter: String = equal(username) + val searchRequest: SearchRequest = SearchRequestImpl() + searchRequest.setBase(safeDn) + searchRequest.setFilter(safeFilter) + c.search(searchRequest) + } + + private fun equal(username: String): String { + TODO("Not yet implemented") + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_30_LdapInjectionUnboundId.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_30_LdapInjectionUnboundId.kt new file mode 100644 index 0000000..c1b81c7 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-090_30_LdapInjectionUnboundId.kt @@ -0,0 +1,24 @@ +// {fact rule=ldap-injection@v1.0 defects=0} +import org.apache.directory.ldap.client.api.LdapConnection +import jakarta.servlet.http.HttpServletRequest + +import org.apache.directory.api.ldap.model.message.SearchScope +import org.apache.directory.api.ldap.model.name.Dn +import org.apache.directory.api.ldap.model.name.Rdn +import com.unboundid.ldap.sdk.Filter + + +class LdapInjectionUnboundId { + fun ldapQueryGood(request: HttpServletRequest, c: LdapConnection) { + val organizationName: String = request.getParameter("organization_name") + val username: String = request.getParameter("username") + + // GOOD: Organization name is encoded before being used in DN + val safeDn = Dn(Rdn("OU", "People"), Rdn("O", organizationName)) + + // GOOD: User input is encoded before being used in search filter + val safeFilter: Filter = Filter.createEqualityFilter("username", username) + c.search(safeDn, "something", SearchScope.ONELEVEL, "hello") + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_02_UnsafeSpelExpressionEvaluation.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_02_UnsafeSpelExpressionEvaluation.kt new file mode 100644 index 0000000..64cc887 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_02_UnsafeSpelExpressionEvaluation.kt @@ -0,0 +1,26 @@ +// {fact rule=improper-verification-of-origin-with-file-download@v1.0 defects=unknown} + +import com.sun.tools.example.debug.expr.ExpressionParser +import org.springframework.expression.Expression +import org.springframework.expression.spel.standard.SpelExpressionParser + +import java.io.BufferedReader + +import java.io.IOException +import java.io.InputStreamReader + +import java.net.Socket + + +@Throws(IOException::class) +fun evaluate(socket: Socket): Any? { + BufferedReader( + InputStreamReader(socket.getInputStream()) + ).use { reader -> + val string = reader.readLine() + val parser: SpelExpressionParser = SpelExpressionParser() + val expression: Expression = parser.parseExpression(string) + return expression.getValue() + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_03_GroovyInjectionBlocklist.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_03_GroovyInjectionBlocklist.kt new file mode 100644 index 0000000..be7f2e8 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_03_GroovyInjectionBlocklist.kt @@ -0,0 +1,18 @@ +import groovy.lang.GroovyClassLoader +import jakarta.servlet.http.HttpServletRequest + +// {fact rule=improper-verification-of-origin-with-file-download@v1.0 defects=0} +class SandboxGroovyClassLoader(parent: ClassLoader?) : ClassLoader(parent) { + companion object { + /* override `loadClass` here to prevent loading sensitive classes, such as `java.lang.Runtime`, `java.lang.ProcessBuilder`, `java.lang.System`, etc. */ /* Note we must also block `groovy.transform.ASTTest`, `groovy.lang.GrabConfig` and `org.buildobjects.process.ProcBuilder` to prevent compile-time RCE. */ + @Throws(Exception::class) + fun runWithSandboxGroovyClassLoader(request: HttpServletRequest) { + // GOOD: route all class-loading via sand-boxing classloader. + val classLoader: SandboxGroovyClassLoader = SandboxGroovyClassLoader(GroovyClassLoader()) + val scriptClass: Class<*> = classLoader.loadClass(request.getQueryString()) + val scriptInstance = scriptClass.newInstance() + val result = scriptClass.getDeclaredMethod("bar", *arrayOf()).invoke(scriptInstance, *arrayOf()) + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_04_InsecureBeanValidation.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_04_InsecureBeanValidation.kt new file mode 100644 index 0000000..e00dab3 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_04_InsecureBeanValidation.kt @@ -0,0 +1,43 @@ +//// {fact rule=improper-verification-of-origin-with-file-download@v1.0 defects=unknown} +//import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext +//import java.util.regex.Matcher +//import java.util.regex.Pattern +//import javax.validation.ConstraintValidator +//import javax.validation.ConstraintValidatorContext +// +//class TestValidator : ConstraintValidator { +// object InterpolationHelper { +// const val BEGIN_TERM = '{' +// const val END_TERM = '}' +// const val EL_DESIGNATOR = '$' +// const val ESCAPE_CHARACTER = '\\' +// private val ESCAPE_MESSAGE_PARAMETER_PATTERN = Pattern.compile("([$ESCAPE_CHARACTER$BEGIN_TERM$END_TERM$EL_DESIGNATOR])") +// fun escapeMessageParameter(messageParameter: String?): String? { +// return if (messageParameter == null) { +// null +// } else ESCAPE_MESSAGE_PARAMETER_PATTERN.matcher(messageParameter).replaceAll(Matcher.quoteReplacement(ESCAPE_CHARACTER.toString()) + "$1") +// } +// } +// +// fun isValid(`object`: String, constraintContext: ConstraintValidatorContext): Boolean { +// val value = "$`object` is invalid" +// +// // Bad: Bean properties (normally user-controlled) are passed directly to `buildConstraintViolationWithTemplate` +// constraintContext.buildConstraintViolationWithTemplate(value).addConstraintViolation().disableDefaultConstraintViolation() +// +// // Good: Bean properties (normally user-controlled) are escaped +// val escaped = InterpolationHelper.escapeMessageParameter(value) +// constraintContext.buildConstraintViolationWithTemplate(escaped).addConstraintViolation().disableDefaultConstraintViolation() +// +// // Good: Bean properties (normally user-controlled) are parameterized +// val context: HibernateConstraintValidatorContext = constraintContext.unwrap(HibernateConstraintValidatorContext::class.java) +// context.addMessageParameter("prop", `object`) +// context.buildConstraintViolationWithTemplate("{prop} is invalid").addConstraintViolation() +// return false +// } +// +// override fun isValid(p0: String?, p1: ConstraintValidatorContext?): Boolean { +// TODO("Not yet implemented") +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_05_UnsafeJexlExpressionEvaluation.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_05_UnsafeJexlExpressionEvaluation.kt new file mode 100644 index 0000000..13ca177 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_05_UnsafeJexlExpressionEvaluation.kt @@ -0,0 +1,24 @@ +package org.example.kotlin_codeql.Security.CWE.`CWE-094`// {fact rule=improper-verification-of-origin-with-file-download@v1.0 defects=unknown} + +import org.apache.commons.jexl3.* +import java.io.BufferedReader + +import java.io.IOException +import java.io.InputStreamReader + +import java.net.Socket + + +@Throws(IOException::class) +fun evaluate_1(socket: Socket) { + BufferedReader( + InputStreamReader(socket.getInputStream()) + ).use { reader -> + val input = reader.readLine() + val jexl: JexlEngine = JexlBuilder().create() + val expression: JexlExpression = jexl.createExpression(input) + val context: JexlContext = MapContext() + expression.evaluate(context) + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_06_GroovyInjectionBad.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_06_GroovyInjectionBad.kt new file mode 100644 index 0000000..f30ff8f --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-094_06_GroovyInjectionBad.kt @@ -0,0 +1,35 @@ +import groovy.lang.GroovyClassLoader +import groovy.lang.GroovyCodeSource +import groovy.lang.GroovyObject +import groovy.lang.GroovyShell +import groovy.util.Eval +import jakarta.servlet.http.HttpServletRequest + +// {fact rule=improper-verification-of-origin-with-file-download@v1.0 defects=1} +class GroovyInjection { + fun injectionViaClassLoader(request: HttpServletRequest) { + val script: String = request.getParameter("script") + val classLoader = GroovyClassLoader() + val groovy: Class<*> = classLoader.parseClass(script) + val groovyObj: GroovyObject = groovy.newInstance() as GroovyObject + } + + fun injectionViaEval(request: HttpServletRequest) { + val script: String = request.getParameter("script") + Eval.me(script) + } + + fun injectionViaGroovyShell(request: HttpServletRequest) { + val shell = GroovyShell() + val script: String = request.getParameter("script") + shell.evaluate(script) + } + + fun injectionViaGroovyShellGroovyCodeSource(request: HttpServletRequest) { + val shell = GroovyShell() + val script: String = request.getParameter("script") + val gcs = GroovyCodeSource(script, "test", "Test") + shell.evaluate(gcs) + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_34_LogInjectionBad.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_34_LogInjectionBad.kt new file mode 100644 index 0000000..b5211b0 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_34_LogInjectionBad.kt @@ -0,0 +1,28 @@ +// {fact rule=log-injection@v1.0 defects=1} +package com.example.restservice + +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController + +@RestController +class LogInjectionBad { + private val log: Logger = LoggerFactory.getLogger(LogInjection::class.java) + + // /bad?username=Guest'%0AUser:'Admin + @GetMapping("/bad") + fun bad(@RequestParam(value = "username", defaultValue = "name") username: String): String { + log.warn("User:'{}'", username) + // The logging call above would result in multiple log entries as shown below: + // User:'Guest' + // User:'Admin' + return username + } +} + +class LogInjection { + +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_35_LogInjectionGood.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_35_LogInjectionGood.kt new file mode 100644 index 0000000..0b62ef4 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-117_35_LogInjectionGood.kt @@ -0,0 +1,27 @@ +// {fact rule=log-injection@v1.0 defects=0} +package com.example.restservice + +import org.slf4j.Logger +import org.slf4j.LoggerFactory +import org.springframework.web.bind.annotation.GetMapping +import org.springframework.web.bind.annotation.RequestParam +import org.springframework.web.bind.annotation.RestController + +@RestController +class LogInjectionGood { + private val log: Logger = LoggerFactory.getLogger(LogInjectionGood::class.java) + + // /good?username=Guest'%0AUser:'Admin + @GetMapping("/good") + fun good(@RequestParam(value = "username", defaultValue = "name") username: String): String? { + // The regex check here, allows only alphanumeric characters to pass. + // Hence, does not result in log injection + if (username.matches("\\w*".toRegex())) { + log.warn("User:'{}'", username) + return username + } else { + return null + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_36_ImproperValidationOfArrayConstructionCodeSpecified.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_36_ImproperValidationOfArrayConstructionCodeSpecified.kt new file mode 100644 index 0000000..407fb57 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_36_ImproperValidationOfArrayConstructionCodeSpecified.kt @@ -0,0 +1,25 @@ +import java.util.* + +// {fact rule=improper-validation-of-array-index@v1.0 defects=1} +object PossibleArrayIndexOutOfBounds { + @JvmStatic + fun main(args: Array) { + val numberOfItems: Int = Random().nextInt(10) + if (numberOfItems >= 0) { + /* + * BAD numberOfItems may be zero, which would cause the array indexing operation to + * throw an ArrayIndexOutOfBoundsException + */ + val items: Array = arrayOfNulls(numberOfItems) + items[0] = "Item 1" + } + if (numberOfItems > 0) { + /* + * GOOD numberOfItems must be greater than zero, so the indexing succeeds. + */ + val items: Array = arrayOfNulls(numberOfItems) + items[0] = "Item 1" + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_37_ImproperValidationOfArrayIndex.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_37_ImproperValidationOfArrayIndex.kt new file mode 100644 index 0000000..f2f530a --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_37_ImproperValidationOfArrayIndex.kt @@ -0,0 +1,35 @@ +import jakarta.servlet.ServletException +import jakarta.servlet.http.HttpServlet +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse +import java.io.IOException + +// {fact rule=improper-validation-of-array-index@v1.0 defects=1} +class ImproperValidationOfArrayIndex : HttpServlet() { + @Throws(ServletException::class, IOException::class) + protected override fun doGet(request: HttpServletRequest, response: HttpServletResponse) { + val productDescriptions = arrayOf("Chocolate bar", "Fizzy drink") + + // User provided value + val productID: String = request.getParameter("productID") + try { + val userProperty = "abcde" + val productID: Int = userProperty.trim().toInt() + + /* + * BAD Array is accessed without checking if the user provided value is out of + * bounds. + */ + var productDescription = productDescriptions[productID] + productDescription = if (productID >= 0 && productID < productDescriptions.size) { + // GOOD We have checked that the array index is valid first + productDescriptions[productID] + } else { + "No product for that ID" + } + response.getWriter().write(productDescription) + } catch (e: NumberFormatException) { + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_38_ImproperValidationOfArrayIndexCodeSpecified.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_38_ImproperValidationOfArrayIndexCodeSpecified.kt new file mode 100644 index 0000000..1cf73db --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_38_ImproperValidationOfArrayIndexCodeSpecified.kt @@ -0,0 +1,33 @@ +import jakarta.servlet.ServletException +import jakarta.servlet.http.HttpServlet +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse +import java.io.IOException + +// {fact rule=improper-validation-of-array-index@v1.0 defects=1} +class ImproperValidationOfArrayIndexCodeSpecified : HttpServlet() { + @Throws(ServletException::class, IOException::class) + protected override fun doGet(request: HttpServletRequest, response: HttpServletResponse) { + // Search for products in productDescriptions that match the search term + val searchTerm: String = request.getParameter("productSearchTerm") + var foundProductID = -1 + val productDescriptions = listOf("abcde") + for (i in 0 until productDescriptions.size) { + if (productDescriptions.get(i).contains(searchTerm)) { + // Found matching product + foundProductID = i + break + } + } + + // BAD We may not have found a product in which case the index would be -1 + response.getWriter().write(productDescriptions.get(foundProductID)) + if (foundProductID >= 0) { + // GOOD We have checked we found a product first + response.getWriter().write(productDescriptions.get(foundProductID)) + } else { + response.getWriter().write("No product found") + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_39_ImproperValidationOfArrayConstruction.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_39_ImproperValidationOfArrayConstruction.kt new file mode 100644 index 0000000..1709ba8 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-129_39_ImproperValidationOfArrayConstruction.kt @@ -0,0 +1,33 @@ +import jakarta.servlet.ServletException +import jakarta.servlet.http.HttpServlet +import jakarta.servlet.http.HttpServletRequest +import jakarta.servlet.http.HttpServletResponse +import java.io.IOException + +// {fact rule=improper-validation-of-array-index@v1.0 defects=1} +class ImproperValidationOfArrayConstruction : HttpServlet() { + @Throws(ServletException::class, IOException::class) + protected override fun doGet(request: HttpServletRequest, response: HttpServletResponse?) { + try { + // User provided value + val numberOfItems: Int = request.getParameter("numberOfItems").trim().toInt() + if (numberOfItems >= 0) { + /* + * BAD numberOfItems may be zero, which would cause the array indexing operation to + * throw an ArrayIndexOutOfBoundsException + */ + val items: Array = arrayOfNulls(numberOfItems) + items[0] = "Item 1" + } + if (numberOfItems > 0) { + /* + * GOOD numberOfItems must be greater than zero, so the indexing succeeds. + */ + val items: Array = arrayOfNulls(numberOfItems) + items[0] = "Item 1" + } + } catch (e: NumberFormatException) { + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_15_ArithmeticWithExtremeValues.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_15_ArithmeticWithExtremeValues.kt new file mode 100644 index 0000000..380e003 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_15_ArithmeticWithExtremeValues.kt @@ -0,0 +1,17 @@ +// {fact rule=arithmetic-overflow@v1.0 defects=0} +internal object ArithmeticWithExtremeValues { + @JvmStatic + fun main(args: Array) { + run { + val i = Long.MAX_VALUE + // BAD: overflow + val j = i + 1 + } + run { + val i = Int.MAX_VALUE + // GOOD: no overflow + val j = i.toLong() + 1 + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_16_ArithmeticUncontrolled.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_16_ArithmeticUncontrolled.kt new file mode 100644 index 0000000..8082e75 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_16_ArithmeticUncontrolled.kt @@ -0,0 +1,21 @@ +// {fact rule=arithmetic-overflow@v1.0 defects=0} +import java.security.SecureRandom + +internal object ArithmeticUncontrolled { + @JvmStatic + fun main(args: Array) { + run { + val data = SecureRandom().nextInt() + + // BAD: may overflow if data is large + val scaled = data * 10 + + // ... + + // GOOD: use a guard to ensure no overflows occur + val scaled2: Int + scaled2 = if (data < Int.MAX_VALUE / 10) data * 10 else Int.MAX_VALUE + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_17_ArithmeticTainted.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_17_ArithmeticTainted.kt new file mode 100644 index 0000000..882e7a0 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_17_ArithmeticTainted.kt @@ -0,0 +1,28 @@ +import java.io.BufferedReader +import java.io.InputStreamReader + +// {fact rule=arithmetic-overflow@v1.0 defects=0} +internal object ArithmeticTainted { + @JvmStatic + fun main(args: Array) { + run { + val data: Int + val readerBuffered = BufferedReader( + InputStreamReader(System.`in`, "UTF-8") + ) + val stringNumber: String = readerBuffered.readLine() + data = stringNumber?.trim { it <= ' ' }?.toInt() ?: 0 + + // BAD: may overflow if input data is very large, for example + // 'Integer.MAX_VALUE' + val scaled = data * 10 + + //... + + // GOOD: use a guard to ensure no overflows occur + val scaled2: Int + scaled2 = if (data < Int.MAX_VALUE / 10) data * 10 else Int.MAX_VALUE + } + } +} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_18_ComparisonWithWiderType.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_18_ComparisonWithWiderType.kt new file mode 100644 index 0000000..3979cd7 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-190_18_ComparisonWithWiderType.kt @@ -0,0 +1,34 @@ +//// {ex-fact rule=arithmetic-overflow@v1.0 defects=0} +//internal object Test { +// @JvmStatic +// fun main(args: Array) { +// run { +// val BIGNUM = Int.MAX_VALUE +// val MAXGET = (Short.MAX_VALUE + 1).toLong() +// val buf = CharArray(BIGNUM) +// var bytesReceived: Short = 0 +// +// // BAD: 'bytesReceived' is compared with a value of wider type. +// // 'bytesReceived' overflows before reaching MAXGET, +// // causing an infinite loop. +// while (bytesReceived < MAXGET) { +// bytesReceived += Test.getFromInput(buf, bytesReceived).toShort() +// } +// } +// run { +// var bytesReceived2: Long = 0 +// +// // GOOD: 'bytesReceived2' has a type at least as wide as MAXGET. +// while (bytesReceived2 < MAXGET) { +// bytesReceived2 += Test.getFromInput(buf, bytesReceived2.toShort()).toLong() +// } +// } +// } +// +// fun getFromInput(buf: CharArray?, pos: Short): Int { +// // write to buf +// // ... +// return 1 +// } +//} +// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-200_09_WebViewFileAccessUnsafe.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-200_09_WebViewFileAccessUnsafe.kt new file mode 100644 index 0000000..a03d535 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-200_09_WebViewFileAccessUnsafe.kt @@ -0,0 +1,10 @@ +//// {ex-fact rule=sensitive-information-leak@v1.0 defects=unknown} +//internal class WebViewFileAccessSafe { +// fun example1() { +// val settings: WebSettings = view.getSettings() +// settings.setAllowFileAccess(true) +// settings.setAllowFileAccessFromURLs(true) +// settings.setAllowUniversalAccessFromURLs(true) +// } +//} +// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-209_07_StackTraceExposure.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-209_07_StackTraceExposure.kt new file mode 100644 index 0000000..f32f05d --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-209_07_StackTraceExposure.kt @@ -0,0 +1,28 @@ +//import jakarta.servlet.http.HttpServletRequest +//import jakarta.servlet.http.HttpServletResponse +// +//// {ex-fact rule=sensitive-information-leak@v1.0 defects=0} +//fun doGet(request: HttpServletRequest?, response: HttpServletResponse) { +// try { +// doSomeWork() +// } catch (ex: NullPointerException) { +// // BAD: printing a stack trace back to the response +// ex.printStackTrace(response.getWriter()) +// return +// } +// try { +// doSomeWork() +// } catch (ex: NullPointerException) { +// // GOOD: log the stack trace, and send back a non-revealing response +// log("Exception occurred", ex) +// response.sendError( +// HttpServletResponse.SC_INTERNAL_SERVER_ERROR, +// "Exception occurred") +// return +// } +//} +// +//fun doSomeWork() { +// TODO("Not yet implemented") +//} +//// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-266_31_IntentUriPermissionManipulation.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-266_31_IntentUriPermissionManipulation.kt new file mode 100644 index 0000000..f946ac8 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-266_31_IntentUriPermissionManipulation.kt @@ -0,0 +1,26 @@ +//// {ex-fact rule=sensitive-information-leak@v1.0 defects=0} +//class IntentUriPermissionManipulation : Activity() { +// // BAD: the user-provided Intent is returned as-is +// fun dangerous() { +// val intent: Intent = getIntent() +// intent.putExtra("result", "resultData") +// setResult(intent) +// } +// +// // GOOD: a new Intent is created and returned +// fun safe() { +// val intent = Intent() +// intent.putExtra("result", "resultData") +// setResult(intent) +// } +// +// // GOOD: the user-provided Intent is sanitized before being returned +// fun sanitized() { +// val intent: Intent = getIntent() +// intent.putExtra("result", "resultData") +// intent.removeFlags( +// Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION) +// setResult(intent) +// } +//} +//// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_32_ImproperWebViewCertificateValidation.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_32_ImproperWebViewCertificateValidation.kt new file mode 100644 index 0000000..8031e1e --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_32_ImproperWebViewCertificateValidation.kt @@ -0,0 +1,31 @@ +//// {ex-fact rule=improper-certificate-validation@v1.0" defects=0} +//internal class Bad : WebViewClient() { +// // BAD: All certificates are trusted. +// fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError?) { // $hasResult +// handler.proceed() +// } +//} +// +//internal class Good : WebViewClient() { +// var myPubKey: PublicKey? = null +// +// // GOOD: Only certificates signed by a certain public key are trusted. +// fun onReceivedSslError(view: WebView?, handler: SslErrorHandler, error: SslError) { // $hasResult +// try { +// val cert: X509Certificate = error.getCertificate().getX509Certificate() +// cert.verify(myPubKey) +// handler.proceed() +// } catch (e: CertificateException) { +// handler.cancel() +// } catch (e: NoSuchAlgorithmException) { +// handler.cancel() +// } catch (e: InvalidKeyException) { +// handler.cancel() +// } catch (e: NoSuchProviderException) { +// handler.cancel() +// } catch (e: SignatureException) { +// handler.cancel() +// } +// } +//} +// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_33_InsecureTrustManager.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_33_InsecureTrustManager.kt new file mode 100644 index 0000000..c52c1c5 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-295_33_InsecureTrustManager.kt @@ -0,0 +1,18 @@ +//// {ex-fact rule=improper-certificate-validation@v1.0" defects=1} +//internal class InsecureTrustManager : X509TrustManager { +// val acceptedIssuers: Array? +// get() = null +// +// @Throws(CertificateException::class) +// fun checkServerTrusted(chain: Array?, authType: String?) { +// // BAD: Does not verify the certificate chain, allowing any certificate. +// } +// +// @Throws(CertificateException::class) +// fun checkClientTrusted(chain: Array?, authType: String?) { +// } +// +// var context: SSLContext = SSLContext.getInstance("TLS") +// var trustManager: Array = arrayOf(InsecureTrustManager()) +//} +//// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-297_01_UnsafeHostnameVerification.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-297_01_UnsafeHostnameVerification.kt new file mode 100644 index 0000000..f3dd84c --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-297_01_UnsafeHostnameVerification.kt @@ -0,0 +1,5 @@ +// {ex-fact rule=placeholder defects=unknown} +import kotlin.Throws +import kotlin.jvm.JvmStatic +import java.util.Properties +// {/ex-fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-330_41_InsecureRandomnessCookie.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-330_41_InsecureRandomnessCookie.kt new file mode 100644 index 0000000..4ee4994 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-330_41_InsecureRandomnessCookie.kt @@ -0,0 +1,2 @@ +// {fact rule=use-of-insufficiently-random-values@v1.0 defects=unknown} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-352_44_SpringCSRFProtection.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-352_44_SpringCSRFProtection.kt new file mode 100644 index 0000000..fa7b492 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-352_44_SpringCSRFProtection.kt @@ -0,0 +1,15 @@ +//// {fact rule=cross-site-request-forgery@v1.0 defects=unknown} +//import org.springframework.context.annotation.Configuration +// +//@EnableWebSecurity +//@Configuration +//class WebSecurityConfig : WebSecurityConfigurerAdapter() { +// @Throws(Exception::class) +// protected fun configure(http: HttpSecurity) { +// http +// .csrf { csrf -> // BAD - CSRF protection shouldn't be disabled +// csrf.disable() +// } +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-367_19_TOCTOURace.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-367_19_TOCTOURace.kt new file mode 100644 index 0000000..4e04dde --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-367_19_TOCTOURace.kt @@ -0,0 +1,32 @@ +//// {fact rule=time-of-check-time-of-use-race-condition@v1.0 defects=unknown} +//internal class Resource { +// @get:Synchronized +// @set:Synchronized +// var isReady: Boolean +// get() {} +// set(ready) {} +// +// @Synchronized +// fun act() { +// check(isReady) +// } +// +// @Synchronized +// fun bad(r: Resource) { +// if (r.isReady) { +// // r might no longer be ready, another thread might +// // have called setReady(false) +// r.act() +// } +// } +// +// @Synchronized +// fun good(r: Resource) { +// synchronized(r) { +// if (r.isReady) { +// r.act() +// } +// } +// } +//} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-421_24_SocketAuthRace.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-421_24_SocketAuthRace.kt new file mode 100644 index 0000000..8ec3ab1 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-421_24_SocketAuthRace.kt @@ -0,0 +1,4 @@ +// {fact rule=race-condition-during-access-to-resources@v1.0 defects=unknown} +import kotlin.Throws +import kotlin.jvm.Synchronized +// {/fact} \ No newline at end of file diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_48_FragmentInjectionInPreferenceActivity.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_48_FragmentInjectionInPreferenceActivity.kt new file mode 100644 index 0000000..1d7b837 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_48_FragmentInjectionInPreferenceActivity.kt @@ -0,0 +1,15 @@ +//// {fact rule=use-of-externally-controlled-input-to-select-classes-or-code@v1.0 defects=1} +//internal class UnsafeActivity : PreferenceActivity() { +// protected fun isValidFragment(fragmentName: String?): Boolean { +// // BAD: any Fragment name can be provided. +// return true +// } +//} +// +//internal class SafeActivity : PreferenceActivity() { +// protected fun isValidFragment(fragmentName: String): Boolean { +// // Good: only trusted Fragment names are allowed. +// return SafeFragment1::class.java.getName() == fragmentName || SafeFragment2::class.java.getName() == fragmentName || SafeFragment3::class.java.getName() == fragmentName +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_49_FragmentInjection.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_49_FragmentInjection.kt new file mode 100644 index 0000000..36b708b --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-470_49_FragmentInjection.kt @@ -0,0 +1,21 @@ +//// {fact rule=use-of-externally-controlled-input-to-select-classes-or-code@v1.0 defects=0} +//class MyActivity : FragmentActivity() { +// protected fun onCreate(savedInstance: Bundle?) { +// try { +// super.onCreate(savedInstance) +// // BAD: Fragment instantiated from user input without validation +// run { +// val fName: String = getIntent().getStringExtra("fragmentName") +// getFragmentManager().beginTransaction().replace(com.android.internal.R.id.prefs, +// Fragment.instantiate(this, fName, null)).commit() +// } +// // GOOD: Fragment instantiated statically +// run { +// getFragmentManager().beginTransaction() +// .replace(com.android.internal.R.id.prefs, MyFragment()).commit() +// } +// } catch (e: Exception) { +// } +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_45_UnsafeDeserializationBad.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_45_UnsafeDeserializationBad.kt new file mode 100644 index 0000000..d042521 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_45_UnsafeDeserializationBad.kt @@ -0,0 +1,3 @@ +// {fact rule=deserialization-of-untrusted-data@v1.0 defects=1} +import java.nio.file.Path +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_46_UnsafeDeserializationGood.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_46_UnsafeDeserializationGood.kt new file mode 100644 index 0000000..6e64124 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-502_46_UnsafeDeserializationGood.kt @@ -0,0 +1,3 @@ +// {fact rule=deserialization-of-untrusted-data@v1.0 defects=0} +import java.nio.file.Path +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_12_InsecureBasicAuth.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_12_InsecureBasicAuth.kt new file mode 100644 index 0000000..4c8e3b5 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_12_InsecureBasicAuth.kt @@ -0,0 +1,41 @@ +//// {fact rule=insufficiently-protected-credentials@v1.0 defects=0} +//class InsecureBasicAuth { +// /** +// * Test basic authentication with Apache HTTP request. +// */ +// fun testApacheHttpRequest(username: String, password: String) { +// +// // BAD: basic authentication over HTTP +// var url = "http://www.example.com/rest/getuser.do?uid=abcdx" +// +// // GOOD: basic authentication over HTTPS +// url = "https://www.example.com/rest/getuser.do?uid=abcdx" +// val post = HttpPost(url) +// post.setHeader("Accept", "application/json") +// post.setHeader("Content-type", "application/json") +// val authString = "$username:$password" +// val authEncBytes: ByteArray = Base64.getEncoder().encode(authString.toByteArray()) +// val authStringEnc = String(authEncBytes) +// post.addHeader("Authorization", "Basic $authStringEnc") +// } +// +// /** +// * Test basic authentication with Java HTTP URL connection. +// */ +// fun testHttpUrlConnection(username: String, password: String) { +// +// // BAD: basic authentication over HTTP +// var urlStr = "http://www.example.com/rest/getuser.do?uid=abcdx" +// +// // GOOD: basic authentication over HTTPS +// urlStr = "https://www.example.com/rest/getuser.do?uid=abcdx" +// val authString = "$username:$password" +// val encoding: String = Base64.getEncoder().encodeToString(authString.toByteArray(charset("UTF-8"))) +// val url = URL(urlStr) +// val conn: HttpURLConnection = url.openConnection() as HttpURLConnection +// conn.setRequestMethod("POST") +// conn.setDoOutput(true) +// conn.setRequestProperty("Authorization", "Basic $encoding") +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_13_LdapAuthUseLdaps.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_13_LdapAuthUseLdaps.kt new file mode 100644 index 0000000..5273529 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_13_LdapAuthUseLdaps.kt @@ -0,0 +1,3 @@ +// {fact rule=insufficiently-protected-credentials@v1.0 defects=unknown} +import java.nio.file.Path +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_14_LdapAuthUseLdap.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_14_LdapAuthUseLdap.kt new file mode 100644 index 0000000..5273529 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-522_14_LdapAuthUseLdap.kt @@ -0,0 +1,3 @@ +// {fact rule=insufficiently-protected-credentials@v1.0 defects=unknown} +import java.nio.file.Path +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-614_20_InsecureCookie.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-614_20_InsecureCookie.kt new file mode 100644 index 0000000..0662490 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-614_20_InsecureCookie.kt @@ -0,0 +1,3 @@ +// {fact rule=sensitive-cookie-in-https-session-without-secure-attribute@v1.0 defects=unknown} +import kotlin.jvm.JvmStatic +import kotlin.Throws// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-730_47_RegexInjection.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-730_47_RegexInjection.kt new file mode 100644 index 0000000..983b266 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-730_47_RegexInjection.kt @@ -0,0 +1,22 @@ +//// {fact rule=owasp-top-ten-2013-a7-missing-function-level-access-control@v1.0 defects=0} +//import java.util.regex.Pattern +//import javax.servlet.http.HttpServlet +// +//class RegexInjectionDemo : HttpServlet() { +// fun badExample(request: javax.servlet.http.HttpServletRequest): Boolean { +// val regex: String = request.getParameter("regex") +// val input: String = request.getParameter("input") +// +// // BAD: Unsanitized user input is used to construct a regular expression +// return input.matches(regex.toRegex()) +// } +// +// fun goodExample(request: javax.servlet.http.HttpServletRequest): Boolean { +// val regex: String = request.getParameter("regex") +// val input: String = request.getParameter("input") +// +// // GOOD: User input is sanitized before constructing the regex +// return input.matches(Pattern.quote(regex).toRegex()) +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-749_40_UnsafeAndroidAccess.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-749_40_UnsafeAndroidAccess.kt new file mode 100644 index 0000000..d021fc5 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-749_40_UnsafeAndroidAccess.kt @@ -0,0 +1,70 @@ +//// {fact rule=excessive-permissions-grant@v1.0 defects=0} +//class UnsafeAndroidAccess : Activity() { +// fun onCreate(savedInstanceState: Bundle?) { +// super.onCreate(savedInstanceState) +// setContentView(R.layout.webview) +// +// // BAD: Have both JavaScript and cross-origin resource access enabled in webview while +// // taking remote user inputs +// run { +// val wv: WebView = findViewById(R.id.my_webview) as WebView +// val webSettings: WebSettings = wv.getSettings() +// webSettings.setJavaScriptEnabled(true) +// webSettings.setAllowUniversalAccessFromFileURLs(true) +// wv.setWebViewClient(object : WebViewClient() { +// fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { +// view.loadUrl(url) +// return true +// } +// }) +// val thisUrl: String = getIntent().getExtras().getString("url") // dangerous remote input from the intent's Bundle of extras +// wv.loadUrl(thisUrl) +// } +// +// // BAD: Have both JavaScript and cross-origin resource access enabled in webview while +// // taking remote user inputs +// run { +// val wv: WebView = findViewById(R.id.my_webview) as WebView +// val webSettings: WebSettings = wv.getSettings() +// webSettings.setJavaScriptEnabled(true) +// webSettings.setAllowUniversalAccessFromFileURLs(true) +// wv.setWebViewClient(object : WebViewClient() { +// fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { +// view.loadUrl(url) +// return true +// } +// }) +// val thisUrl: String = getIntent().getStringExtra("url") //dangerous remote input from intent extra +// wv.loadUrl(thisUrl) +// } +// +// // GOOD: Have JavaScript and cross-origin resource access disabled by default on modern Android (Jellybean+) while taking remote user inputs +// run { +// val wv: WebView = findViewById(-1) as WebView +// val webSettings: WebSettings = wv.getSettings() +// wv.setWebViewClient(object : WebViewClient() { +// fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { +// view.loadUrl(url) +// return true +// } +// }) +// val thisUrl: String = getIntent().getExtras().getString("url") // remote input +// wv.loadUrl(thisUrl) +// } +// +// // GOOD: Have JavaScript enabled in webview but remote user input is not allowed +// run { +// val wv: WebView = findViewById(-1) as WebView +// val webSettings: WebSettings = wv.getSettings() +// webSettings.setJavaScriptEnabled(true) +// wv.setWebViewClient(object : WebViewClient() { +// fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean { +// view.loadUrl(url) +// return true +// } +// }) +// wv.loadUrl("https://www.mycorp.com") +// } +// } +//} +// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_42_HardcodedCredentialsApiCall.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_42_HardcodedCredentialsApiCall.kt new file mode 100644 index 0000000..fe7941c --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_42_HardcodedCredentialsApiCall.kt @@ -0,0 +1,3 @@ +// {fact rule=use-of-hard-coded-credentials@v1.0 defects=unknown} +import kotlin.jvm.JvmStatic +import kotlin.Throws// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_43_HardcodedAWSCredentials.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_43_HardcodedAWSCredentials.kt new file mode 100644 index 0000000..310e192 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-798_43_HardcodedAWSCredentials.kt @@ -0,0 +1,12 @@ +//// {fact rule=use-of-hard-coded-credentials@v1.0 defects=unknown} +//import com.amazonaws.auth.AWSCredentials +// +//object HardcodedAWSCredentials { +// @JvmStatic +// fun main(args: Array) { +// //Hardcoded credentials for connecting to AWS services +// //To fix the problem, use other approaches including AWS credentials file, environment variables, or instance/container credentials instead +// val creds: AWSCredentials = BasicAWSCredentials("ACCESS_KEY", "SECRET_KEY") //sensitive call +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-807_08_TaintedPermissionsCheck.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-807_08_TaintedPermissionsCheck.kt new file mode 100644 index 0000000..3fa0ceb --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-807_08_TaintedPermissionsCheck.kt @@ -0,0 +1,3 @@ +// {fact rule=reliance-on-untrusted-inputs-in-a-security-decision@v1.0 defects=unknown} +import kotlin.jvm.JvmStatic +import kotlin.Throws// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-917_10_OgnlInjection.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-917_10_OgnlInjection.kt new file mode 100644 index 0000000..95b6363 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-917_10_OgnlInjection.kt @@ -0,0 +1,3 @@ +//// {fact rule=improper-neutralization-of-special-elements-used-in-an-os-command@v1.0 defects=unknown} +//import ognl.Ognl +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-918_11_RequestForgery.kt b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-918_11_RequestForgery.kt new file mode 100644 index 0000000..704f005 --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/CWE-918_11_RequestForgery.kt @@ -0,0 +1,24 @@ +//// {fact rule=server-side-request-forgery@v1.0 defects=0} +//import java.net.http.HttpClient +// +//class SSRF : HttpServlet() { +// private val client = HttpClient.newHttpClient() +// @Throws(ServletException::class, IOException::class) +// protected fun doGet(request: HttpServletRequest, response: HttpServletResponse?) { +// val uri = URI(request.getParameter("uri")) +// // BAD: a request parameter is incorporated without validation into a Http request +// val r: HttpRequest = HttpRequest.newBuilder(uri).build() +// client.send(r, null) +// +// // GOOD: the request parameter is validated against a known fixed string +// if (VALID_URI == request.getParameter("uri")) { +// val r2: HttpRequest = HttpRequest.newBuilder(uri).build() +// client.send(r2, null) +// } +// } +// +// companion object { +// private const val VALID_URI = "http://lgtm.com" +// } +//} +//// {/fact} diff --git a/PR_8_kotlin/kotlin_2nd/filtered_kotlin/README.md b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/README.md new file mode 100644 index 0000000..c897f9a --- /dev/null +++ b/PR_8_kotlin/kotlin_2nd/filtered_kotlin/README.md @@ -0,0 +1,66 @@ +# Filtered Kotlin Vulnerability Files + +This directory contains 50 Kotlin files related to the **Top 25 Most Dangerous Software Weaknesses (2023 CWE Top 25)**. + +## Summary + +- **Total Files**: 50 Kotlin files +- **Source**: AWSGuruKotlinBenchmarks project +- **Filter Criteria**: Files related to top 25 CWE vulnerabilities from 2023 + +## CWE Categories Included + +The following CWE (Common Weakness Enumeration) categories are represented: + +### Top 25 CWE Vulnerabilities (2023) Found: +- **CWE-22**: Path Traversal (1 file) +- **CWE-78**: OS Command Injection (related files) +- **CWE-79**: Cross-site Scripting (XSS) (related files) +- **CWE-89**: SQL Injection (3 files) +- **CWE-94**: Code Injection (5 files) +- **CWE-190**: Integer Overflow (4 files) +- **CWE-352**: Cross-Site Request Forgery (CSRF) (1 file) +- **CWE-502**: Deserialization of Untrusted Data (2 files) +- **CWE-798**: Use of Hard-coded Credentials (2 files) +- **CWE-918**: Server-Side Request Forgery (SSRF) (1 file) + +### Additional Security-Related CWE Categories: +- **CWE-74**: Injection vulnerabilities (2 files) +- **CWE-90**: LDAP Injection (4 files) +- **CWE-117**: Log Injection (2 files) +- **CWE-129**: Array validation issues (4 files) +- **CWE-200**: Information exposure (1 file) +- **CWE-209**: Stack trace exposure (1 file) +- **CWE-266**: Privilege management (1 file) +- **CWE-295**: Certificate validation (2 files) +- **CWE-297**: Hostname verification (1 file) +- **CWE-330**: Weak randomness (1 file) +- **CWE-367**: Race conditions (1 file) +- **CWE-421**: Authentication race (1 file) +- **CWE-470**: Fragment injection (2 files) +- **CWE-522**: Authentication issues (3 files) +- **CWE-614**: Cookie security (1 file) +- **CWE-730**: Regex vulnerabilities (1 file) +- **CWE-749**: Unsafe access (1 file) +- **CWE-807**: Tainted permissions (1 file) +- **CWE-917**: Expression injection (1 file) + +## File Naming Convention + +Files are named using the pattern: `CWE-XXX_NN_OriginalFileName.kt` +- `CWE-XXX`: The CWE vulnerability category +- `NN`: Sequential number (01-50) +- `OriginalFileName.kt`: The original Kotlin filename + +## Usage + +These files can be used for: +- Security testing and analysis +- Vulnerability research +- Code review training +- Static analysis tool testing +- Security awareness training + +## Note + +All files maintain their original content and structure from the source AWSGuruKotlinBenchmarks project. \ No newline at end of file