This rule helps prevent Cross-Origin Resource Sharing (CORS) vulnerabilities. CORS is a mechanism that allows many resources on a web page (such as fonts, JavaScript, and so on) to be requested from another domain outside the domain from which the resource originated. It’s a useful technique for many web apps. However, if not properly implemented, it can pose a significant security risk.
An unsafe CORS policy, such as allowing any host or using wildcards in allowHost, can expose your application to attacks. This could enable an attacker to read sensitive data from your site or perform actions on behalf of your users.
To ensure safe usage of CORS, explicitly specify the trusted domains that are allowed to interact with your application. You can use methods like host("https://trusted-domain.com") in Ktor, or check the request origin against an allowlist of allowed origins in a Java Servlet. Furthermore, avoid using wildcards (*) in your CORS configurations, and instead specify the exact protocols, domains, and ports that your application needs to communicate with.
Non-Compliant Code Examples
// Non-compliant: Ktor CORS configuration with unsafe settings
funApplication.configureUnsafeCORS(){install(CORS){anyHost()// WARNING: Allows any host
// WARNING: Using wildcards in allowHost
allowHost("*")// WARNING: Overly permissive origin checking
allowOrigins{true}// Accepts any origin
}}// Non-compliant: Java Servlet
@WebServlet("/api")classUnsafeServlet:HttpServlet(){overridefundoGet(req:HttpServletRequest,res:HttpServletResponse){// WARNING: Unsafe CORS in Servlets
res.setHeader("Access-Control-Allow-Origin","*")res.addHeader("Access-Control-Allow-Origin","*")}}
Compliant Code Examples
// Compliant: Ktor examples
funApplication.configureSafeKtorCORS(){install(CORS){// Safe: Specific allowed hosts
host("https://trusted-domain.com")host("https://api.trusted-domain.com")allowCredentials=true// Optional: Configure other CORS settings
allowNonSimpleContentTypes=trueallowHeaders{headerName->headerNameinlistOf("Authorization","Content-Type")}}}// Compliant: Java Servlet examples
@WebServlet("/api")classSafeServlet:HttpServlet(){privatevalallowedOrigins=setOf("https://trusted-domain.com","https://api.trusted-domain.com")overridefundoGet(req:HttpServletRequest,res:HttpServletResponse){valorigin=req.getHeader("Origin")// Safe: Validate origin against whitelist
if(origininallowedOrigins){res.setHeader("Access-Control-Allow-Origin",origin)res.setHeader("Access-Control-Allow-Credentials","true")}else{// Optional: Default to most restrictive origin or no CORS
res.setHeader("Access-Control-Allow-Origin","https://trusted-domain.com")}}}
원활한 통합. Datadog Code Security를 경험해 보세요
Datadog Code Security
이 규칙을 사용해 Datadog Code Security로 코드를 분석하세요
규칙 사용 방법
1
2
rulesets:- kotlin-security # Rules to enforce Kotlin security.
리포지토리 루트에 위의 내용을 포함하는 static-analysis.datadog.yml을 만듭니다
무료 IDE 플러그인을 사용하거나 CI 파이프라인에 Code Security 검사를 추가합니다