// Noncompliant code - exposing sensitive information in error logdefprocessUserInput(input:String):Unit={// Process user input// ...// Log error with sensitive informationvalerrorMessage=s"Error processing user input: $input"Logger.error(errorMessage)}
✅ compliance
// Compliant code - avoiding exposure of sensitive information in error logdefprocessUserInput(input:String):Unit={// Process user input// ...// Log error without sensitive informationLogger.error("Error processing user input")}
Insertion of Sensitive Information Into Sent Data
🐞 non-compliance
// Noncompliant code - inserting sensitive information into sent datadefsendUserData(userId:String):Unit={// Retrieve user datavaluserData=retrieveUserData(userId)// Insert sensitive information into sent datavalsentData=s"User data: $userData"sendRequest(sentData)}defretrieveUserData(userId:String):String={// Retrieve user data from the database// ...// Return the user data as a string}defsendRequest(data:String):Unit={// Send the data to a remote server// ...}
✅ compliance
// Compliant code - avoiding insertion of sensitive information into sent datadefsendUserData(userId:String):Unit={// Retrieve user datavaluserData=retrieveUserData(userId)// Send the user data without inserting sensitive informationsendRequest(userData)}defretrieveUserData(userId:String):String={// Retrieve user data from the database// ...// Return the user data as a string}defsendRequest(data:String):Unit={// Send the data to a remote server// ...}
Cross-Site Request Forgery (CSRF)
🐞 non-compliance
// Noncompliant code - lack of CSRF protectiondeftransferFunds(request:Request):Response={valsourceAccount=request.getParameter("sourceAccount")valdestinationAccount=request.getParameter("destinationAccount")valamount=request.getParameter("amount")// Perform fund transfer logic// ...// Return response// ...}
✅ compliance
// Compliant code - CSRF protection using tokensdeftransferFunds(request:Request):Response={valsourceAccount=request.getParameter("sourceAccount")valdestinationAccount=request.getParameter("destinationAccount")valamount=request.getParameter("amount")// Verify CSRF tokenvalcsrfToken=request.getParameter("csrfToken")if(!validateCsrfToken(csrfToken)){// CSRF token validation failed, handle the error or return an appropriate response// ...}// Perform fund transfer logic// ...// Return response// ...}defvalidateCsrfToken(csrfToken:String):Boolean={// Validate the CSRF token against a stored value or session token// Return true if the token is valid, false otherwise// ...}
// Compliant code - use of secure password storagedefauthenticate(username:String,password:String):Boolean={// Retrieve the stored password hash for the user from a secure database or password storage mechanismvalstoredPasswordHash=getStoredPasswordHash(username)// Compare the entered password with the stored password hash using a secure password hashing algorithmvalisPasswordValid=verifyPassword(password,storedPasswordHash)isPasswordValid}defgetStoredPasswordHash(username:String):String={// Retrieve the stored password hash for the user from a secure database or password storage mechanism// ...}defverifyPassword(password:String,storedPasswordHash:String):Boolean={// Use a secure password hashing algorithm (e.g., bcrypt, Argon2, scrypt) to verify the password// Compare the password hash derived from the entered password with the stored password hash// Return true if the password is valid, false otherwise// ...}
importscala.util.Random// Noncompliant code - uses Random.nextInt without sufficient entropydefgenerateOTP():String={valotp=Random.nextInt(9999).toStringotp}
✅ compliance
importjava.security.SecureRandomimportscala.util.Random// Compliant code - uses SecureRandom for generating OTP with sufficient entropydefgenerateOTP():String={valsecureRandom=newSecureRandom()valotp=secureRandom.nextInt(10000).toStringotp}
XSS
🐞 non-compliance
importscala.xml.NodeSeq// Noncompliant code - vulnerable to XSSdefdisplayMessage(message:String):NodeSeq={<div>{message}</div>}
✅ compliance
importscala.xml.{NodeSeq,Text}// Compliant code - properly escapes the message to prevent XSSdefdisplayMessage(message:String):NodeSeq={<div>{Text(message)}</div>}
SQL Injection
🐞 non-compliance
importjava.sql.{Connection,DriverManager,ResultSet}// Noncompliant code - vulnerable to SQL injectiondefgetUser(userId:String):Option[String]={valquery=s"SELECT name FROM users WHERE id = $userId"varconnection:Connection=nullvarresult:Option[String]=Nonetry{connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","username","password")valstatement=connection.createStatement()valresultSet=statement.executeQuery(query)if(resultSet.next()){result=Some(resultSet.getString("name"))}}catch{casee:Exception=>e.printStackTrace()}finally{if(connection!=null){connection.close()}}result}
✅ compliance
importjava.sql.{Connection,DriverManager,PreparedStatement,ResultSet}// Compliant code - uses parameterized queries to prevent SQL injectiondefgetUser(userId:String):Option[String]={valquery="SELECT name FROM users WHERE id = ?"varconnection:Connection=nullvarresult:Option[String]=Nonetry{connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","username","password")valstatement=connection.prepareStatement(query)statement.setString(1,userId)valresultSet=statement.executeQuery()if(resultSet.next()){result=Some(resultSet.getString("name"))}}catch{casee:Exception=>e.printStackTrace()}finally{if(connection!=null){connection.close()}}result}
External Control of File Name or Path
🐞 non-compliance
importjava.io.File// Noncompliant code - vulnerable to external control of file name or pathdefreadFile(fileName:String):String={valfile=newFile(fileName)valcontent=scala.io.Source.fromFile(file).mkStringcontent}
✅ compliance
importjava.io.File// Compliant code - validates and sanitizes the file namedefreadFile(fileName:String):Option[String]={if(!fileName.contains("..")&&fileName.matches("[a-zA-Z0-9]+\\.txt")){valfile=newFile(fileName)valcontent=scala.io.Source.fromFile(file).mkStringSome(content)}else{None}}
Generation of Error Message Containing Sensitive Information
🐞 non-compliance
// Noncompliant code - error message containing sensitive informationdefdivide(a:Int,b:Int):Int={if(b!=0){a/b}else{thrownewArithmeticException("Division by zero error. Numerator: "+a+", Denominator: "+b)}}
✅ compliance
// Compliant code - generic error message without sensitive informationdefdivide(a:Int,b:Int):Int={if(b!=0){a/b}else{thrownewArithmeticException("Division by zero error.")}}
unprotected storage of credentials
🐞 non-compliance
// Noncompliant code - unprotected storage of credentialsvalusername="admin"valpassword="secretpassword"
✅ compliance
// Compliant code - secure storage of credentialsvalusername=readSecureValue("username")valpassword=readSecureValue("password")defreadSecureValue(key:String):String={// Implement a secure mechanism to retrieve the value of the given key// Examples: reading from an encrypted configuration file, retrieving from a secure key vault, etc.// This implementation depends on the specific security requirements and infrastructure of the application.// The focus is on securely retrieving the credentials, ensuring they are not stored directly in the code.// The exact implementation details are beyond the scope of this example.// Ideally, secrets management tools or libraries should be used for secure credential storage.// This ensures that credentials are not hardcoded in the code and are accessed securely at runtime.// Additionally, access controls and encryption should be implemented to protect the stored credentials.// For simplicity, this example assumes a custom readSecureValue() function that securely retrieves the value.// The actual implementation should use established and tested secure practices.// This example is meant to illustrate the concept of securely storing and retrieving credentials.// It is recommended to use a robust secrets management solution in real-world scenarios.// This code snippet should be adapted to meet the specific security requirements of the application.// Placeholder implementationif(key=="username"){// Retrieve the username value securely"admin"}elseif(key=="password"){// Retrieve the password value securely"secretpassword"}else{// Handle other keys as needed""}}
Trust Boundary Violation
🐞 non-compliance
// Noncompliant code - trust boundary violationvaluserRole=getUserRoleFromRequest(request)valisAdmin=checkUserRole(userRole)defgetUserRoleFromRequest(request:Request):String={// Extract the user role from the request parameter without proper validation// This code assumes the user role is directly provided in the request// without any sanitization or validation checksrequest.getParameter("role")}defcheckUserRole(userRole:String):Boolean={// Perform a check to determine if the user has administrative privileges// In this noncompliant code, the check is solely based on the value of the user role// without any additional validation or verificationuserRole.toLowerCase()=="admin"}
✅ compliance
// Compliant code - proper validation of user rolevaluserRole=getUserRoleFromRequest(request)valisAdmin=checkUserRole(userRole)defgetUserRoleFromRequest(request:Request):String={// Extract the user role from the request parameter and perform proper validation// Validate and sanitize the user-provided input to prevent trust boundary violationsvalrawUserRole=request.getParameter("role")validateUserRole(rawUserRole)}defvalidateUserRole(userRole:String):String={// Perform proper validation and sanitization of the user role// This could include checks such as ensuring the user role is within an allowed set of values,// validating against a predefined list of roles, or using a dedicated role validation library.// The exact validation logic depends on the specific requirements and design of the application.// This example assumes a simple validation for demonstration purposes.if(userRole.toLowerCase()=="admin"||userRole.toLowerCase()=="user"){userRole.toLowerCase()}else{// Handle invalid user roles as needed, such as assigning a default role or throwing an exception"guest"}}defcheckUserRole(userRole:String):Boolean={// Perform a check to determine if the user has administrative privileges// The user role has been properly validated before reaching this pointuserRole=="admin"}
// Compliant code - protected credentialsvalusername=readUsernameFromConfig()valpassword=readPasswordFromConfig()valconnection=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",username,password)defreadUsernameFromConfig():String={// Read the username from a secure configuration file or environment variable// This ensures that the credentials are not directly hardcoded in the source code// and are kept separate from the code repository// The specific method for retrieving the username will depend on the application's configuration mechanism// such as reading from a properties file, using a secure vault, or fetching from environment variables// This example assumes reading from a properties file for demonstration purposesvalproperties=newProperties()properties.load(newFileInputStream("config.properties"))properties.getProperty("db.username")}defreadPasswordFromConfig():String={// Read the password from a secure configuration file or environment variable// Similar to the username, the password should be stored separately from the source codevalproperties=newProperties()properties.load(newFileInputStream("config.properties"))properties.getProperty("db.password")}
Restriction of XML External Entity Reference
🐞 non-compliance
// Noncompliant code - unrestricted XML entity referenceimportscala.xml.XMLvalxml=XML.loadString("""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>&xxe;</root>
""")// Process the XML data
✅ compliance
// Compliant code - restricted XML entity referenceimportscala.xml.{Elem,XML}importjavax.xml.XMLConstantsimportjavax.xml.parsers.DocumentBuilderFactory// Set up secure XML parsingvalfactory=DocumentBuilderFactory.newInstance()factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true)factory.setExpandEntityReferences(false)valbuilder=factory.newDocumentBuilder()valxml=XML.withSAXParser(builder).loadString("""
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<root>&xxe;</root>
""")// Process the XML data
Vulnerable and Outdated Components
🐞 non-compliance
// Noncompliant code - using outdated library versionimportorg.apache.commons.codec.digest.DigestUtilsvalpassword="password123"valhashedPassword=DigestUtils.sha1Hex(password)
✅ compliance
// Compliant code - using secure and up-to-date library versionimportjava.security.MessageDigestvalpassword="password123"valsha256=MessageDigest.getInstance("SHA-256")valhashedPassword=sha256.digest(password.getBytes).map("%02x".format(_)).mkString
Improper Validation of Certificate with Host Mismatch
// Noncompliant code - session fixation vulnerabilityimportjavax.servlet.http.{HttpServletRequest,HttpServletResponse}deflogin(request:HttpServletRequest,response:HttpServletResponse):Unit={valsessionId=request.getParameter("sessionid")// Perform login logic// ...valnewSessionId=generateNewSessionId()request.getSession(true).setAttribute("sessionid",newSessionId)response.sendRedirect("/dashboard")}defgenerateNewSessionId():String={// Generate new session ID logic goes here// ..."newSessionId"// Dummy session ID for demonstration purposes}
✅ compliance
// Compliant code - protected against session fixationimportjavax.servlet.http.{HttpServletRequest,HttpServletResponse}importjava.util.UUIDdeflogin(request:HttpServletRequest,response:HttpServletResponse):Unit={valnewSessionId=generateNewSessionId()request.changeSessionId()// Invalidate existing session IDrequest.getSession(true).setAttribute("sessionid",newSessionId)response.sendRedirect("/dashboard")}defgenerateNewSessionId():String={UUID.randomUUID().toString// Generate a new session ID using a secure method}
Inclusion of Functionality from Untrusted Control
🐞 non-compliance
// Noncompliant code - inclusion of functionality from untrusted controldefprocessTemplate(templateName:String):String={valtemplate=loadTemplate(templateName)template.render()}defloadTemplate(templateName:String):Template={// Load template file from untrusted source// ...Template.fromFile(templateName)// Unsafe inclusion of template}
✅ compliance
// Compliant code - protected against inclusion of functionality from untrusted controldefprocessTemplate(templateName:String):String={valtemplate=loadTemplate(templateName)template.render()}defloadTemplate(templateName:String):Template={if(isValidTemplateName(templateName)){// Load template from trusted source// ...Template.fromFile(templateName)// Safe inclusion of template}else{thrownewIllegalArgumentException("Invalid template name")}}defisValidTemplateName(templateName:String):Boolean={// Implement validation logic for template name// ...// Return true if the template name is valid, false otherwise}
importscala.sys.process._defdownloadAndExecute(url:String,checksum:String):Unit={valcommand=s"curl $url | bash"valdownloadedCode=command.!!if(verifyIntegrity(downloadedCode,checksum)){// Execute the downloaded code// ...}else{thrownewSecurityException("Code integrity check failed")}}defverifyIntegrity(code:String,checksum:String):Boolean={// Perform integrity check by comparing the code's checksum with the expected checksum// ...// Return true if the code's integrity is valid, false otherwise}
# Compliant codeimportjava.io.{ByteArrayInputStream,ObjectInputStream}importjava.util.Base64defdeserializeObject(data:Array[Byte]):Any={valstream=newByteArrayInputStream(data)valobjectInputStream=newObjectInputStream(stream)// Perform input validation and sanitize the data// Example: Validate that the data is from a trusted source or has a specific formatvalobj=objectInputStream.readObject()objectInputStream.close()obj}
# Compliant coderequire'logger'logger=Logger.new('application.log')deftransfer_funds(sender,recipient,amount)ifsender.balance>=amountsender.balance-=amountrecipient.balance+=amountlogger.info("Funds transferred: $#{amount} from #{sender.name} to #{recipient.name}")elselogger.warn("Insufficient funds for transfer: $#{amount} from #{sender.name} to #{recipient.name}")endend
Improper Output Neutralization for Logs
🐞 non-compliance
# Noncompliant codelogger=Logger.new('application.log')deflog_user_activity(user_id,activity)logger.info("User #{user_id} performed activity: #{activity}")end
✅ compliance
# Compliant codelogger=Logger.new('application.log')deflog_user_activity(user_id,activity)sanitized_user_id=sanitize_output(user_id)sanitized_activity=sanitize_output(activity)logger.info("User #{sanitized_user_id} performed activity: #{sanitized_activity}")enddefsanitize_output(input)# Implement output neutralization logic here# For example, remove or escape special characters that could be used for log injectionsanitized_input=input.gsub(/[<>]/,'')# Return the sanitized inputsanitized_inputend
require'open-uri'# Noncompliant codedeffetch_url(url)data=open(url).read# Process the fetched dataend
✅ compliance
require'open-uri'require'uri'# Compliant codedeffetch_url(url)parsed_url=URI.parse(url)ifparsed_url.host=='trusted-domain.com'data=open(url).read# Process the fetched dataelse# Handle the case of an untrusted or restricted domainputs'Access to the specified domain is not allowed.'endend