packagemainimport("fmt""net/http")funcmain(){http.HandleFunc("/users",getUsers)http.ListenAndServe(":8080",nil)}funcgetUsers(whttp.ResponseWriter,r*http.Request){// Access sensitive data from the databaseusername:="admin"password:="secret"// Return the sensitive information in the HTTP responsefmt.Fprintf(w,"Username: %s, Password: %s",username,password)}
✅ compliance
packagemainimport("fmt""net/http")funcmain(){http.HandleFunc("/users",getUsers)http.ListenAndServe(":8080",nil)}funcgetUsers(whttp.ResponseWriter,r*http.Request){// Access sensitive data from the databaseusername:="admin"password:="secret"// Instead of returning sensitive information, return a generic messagefmt.Fprint(w,"Access denied")}
Insertion of Sensitive Information Into Sent Data
🐞 non-compliance
packagemainimport("fmt""log""net/http")funcmain(){http.HandleFunc("/login",login)http.ListenAndServe(":8080",nil)}funclogin(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Authenticate the userif!authenticate(username,password){errMsg:=fmt.Sprintf("Login failed for user: %s",username)log.Println(errMsg)http.Error(w,"Invalid credentials",http.StatusUnauthorized)return}// Proceed with successful login// ...// Code for handling successful login}funcauthenticate(username,passwordstring)bool{// Perform authentication logic// ...// Code for authenticating the userreturnfalse}
✅ compliance
packagemainimport("log""net/http")funcmain(){http.HandleFunc("/login",login)http.ListenAndServe(":8080",nil)}funclogin(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Authenticate the userif!authenticate(username,password){log.Println("Login failed for user:",username)http.Error(w,"Invalid credentials",http.StatusUnauthorized)return}// Proceed with successful login// ...// Code for handling successful login}funcauthenticate(username,passwordstring)bool{// Perform authentication logic// ...// Code for authenticating the userreturnfalse}
Cross-Site Request Forgery (CSRF)
🐞 non-compliance
packagemainimport("fmt""html/template""log""net/http")var(templates=template.Must(template.ParseFiles("index.html")))funcmain(){http.HandleFunc("/",indexHandler)http.HandleFunc("/transfer",transferHandler)log.Fatal(http.ListenAndServe(":8080",nil))}funcindexHandler(whttp.ResponseWriter,r*http.Request){ifr.Method==http.MethodGet{templates.ExecuteTemplate(w,"index.html",nil)}elseifr.Method==http.MethodPost{amount:=r.FormValue("amount")account:=r.FormValue("account")// Perform the money transferiftransferMoney(amount,account){fmt.Fprintln(w,"Transfer successful!")}else{fmt.Fprintln(w,"Transfer failed!")}}}functransferHandler(whttp.ResponseWriter,r*http.Request){// Process transfer request// ...}functransferMoney(amount,accountstring)bool{// Perform money transfer logic// ...returnfalse}
✅ compliance
packagemainimport("fmt""html/template""log""net/http""github.com/gorilla/csrf")var(templates=template.Must(template.ParseFiles("index.html")))funcmain(){http.HandleFunc("/",indexHandler)http.HandleFunc("/transfer",transferHandler)log.Fatal(http.ListenAndServe(":8080",csrf.Protect([]byte("32-byte-long-auth-key"))(nil)))}funcindexHandler(whttp.ResponseWriter,r*http.Request){ifr.Method==http.MethodGet{token:=csrf.Token(r)data:=struct{Tokenstring}{Token:token,}templates.ExecuteTemplate(w,"index.html",data)}elseifr.Method==http.MethodPost{iferr:=r.ParseForm();err!=nil{http.Error(w,"Bad Request",http.StatusBadRequest)return}// Validate CSRF tokeniferr:=csrf.Protect([]byte("32-byte-long-auth-key")).VerifyToken(csrf.Token(r));err!=nil{http.Error(w,"Invalid CSRF token",http.StatusForbidden)return}amount:=r.FormValue("amount")account:=r.FormValue("account")// Perform the money transferiftransferMoney(amount,account){fmt.Fprintln(w,"Transfer successful!")}else{fmt.Fprintln(w,"Transfer failed!")}}}functransferHandler(whttp.ResponseWriter,r*http.Request){// Process transfer request// ...}functransferMoney(amount,accountstring)bool{// Perform money transfer logic// ...returnfalse}
Use of Hard-coded Password
🐞 non-compliance
packagemainimport("fmt""log")funcmain(){password:="myHardcodedPassword"// Rest of the code// ...// Authenticate user with the hardcoded passwordifauthenticateUser(password){fmt.Println("Authentication successful!")}else{fmt.Println("Authentication failed!")}}funcauthenticateUser(passwordstring)bool{// Perform authentication logic// ...returnpassword=="myHardcodedPassword"}
✅ compliance
packagemainimport("fmt""log""os""syscall""golang.org/x/crypto/ssh/terminal")funcmain(){// Prompt user to enter the passwordpassword:=promptPassword("Enter your password: ")// Rest of the code// ...// Authenticate user with the entered passwordifauthenticateUser(password){fmt.Println("Authentication successful!")}else{fmt.Println("Authentication failed!")}}funcpromptPassword(promptstring)string{fmt.Print(prompt)password,_:=terminal.ReadPassword(int(syscall.Stdin))fmt.Println()returnstring(password)}funcauthenticateUser(passwordstring)bool{// Perform authentication logic// ...returnpassword=="correctPassword"}
packagemainimport("database/sql""fmt""log""net/http"_"github.com/go-sql-driver/mysql")funchandleLogin(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")db,err:=sql.Open("mysql","root:password@/mydatabase")iferr!=nil{log.Fatal(err)}deferdb.Close()query:=fmt.Sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'",username,password)rows,err:=db.Query(query)iferr!=nil{log.Fatal(err)}deferrows.Close()// Check if the login was successfulifrows.Next(){fmt.Fprintf(w,"Login successful")}else{fmt.Fprintf(w,"Login failed")}}funcmain(){http.HandleFunc("/login",handleLogin)log.Fatal(http.ListenAndServe(":8080",nil))}
✅ compliance
packagemainimport("database/sql""fmt""log""net/http"_"github.com/go-sql-driver/mysql")funchandleLogin(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")db,err:=sql.Open("mysql","root:password@/mydatabase")iferr!=nil{log.Fatal(err)}deferdb.Close()query:="SELECT * FROM users WHERE username = ? AND password = ?"rows,err:=db.Query(query,username,password)iferr!=nil{log.Fatal(err)}deferrows.Close()// Check if the login was successfulifrows.Next(){fmt.Fprintf(w,"Login successful")}else{fmt.Fprintf(w,"Login failed")}}funcmain(){http.HandleFunc("/login",handleLogin)log.Fatal(http.ListenAndServe(":8080",nil))}
packagemainimport("fmt""io/ioutil""log""net/http""os""path/filepath")funchandleFileDownload(whttp.ResponseWriter,r*http.Request){fileName:=r.URL.Query().Get("file")// Validate and sanitize the file namefileName=filepath.Clean(fileName)iffileName=="."||fileName==".."{log.Fatal("Invalid file name")}filePath:="/path/to/files/"+fileNamefile,err:=os.Open(filePath)iferr!=nil{log.Fatal(err)}deferfile.Close()fileContent,err:=ioutil.ReadAll(file)iferr!=nil{log.Fatal(err)}w.Header().Set("Content-Type","application/octet-stream")w.Header().Set("Content-Disposition",fmt.Sprintf("attachment; filename=\"%s\"",fileName))_,err=w.Write(fileContent)iferr!=nil{log.Fatal(err)}}funcmain(){http.HandleFunc("/download",handleFileDownload)log.Fatal(http.ListenAndServe(":8080",nil))}
Generation of Error Message Containing Sensitive Information
🐞 non-compliance
packagemainimport("fmt""log""net/http")funchandleLogin(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Authenticate the userifusername=="admin"&&password=="secretpassword"{// Successful loginfmt.Fprintf(w,"Welcome, admin!")}else{// Failed loginerrMsg:=fmt.Sprintf("Login failed for user: %s",username)log.Println(errMsg)http.Error(w,"Invalid username or password",http.StatusUnauthorized)}}funcmain(){http.HandleFunc("/login",handleLogin)log.Fatal(http.ListenAndServe(":8080",nil))}
✅ compliance
packagemainimport("fmt""log""net/http")funchandleLogin(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Authenticate the userifusername=="admin"&&password=="secretpassword"{// Successful loginfmt.Fprintf(w,"Welcome, admin!")}else{// Failed loginlog.Println("Login failed for user:",username)http.Error(w,"Invalid username or password",http.StatusUnauthorized)}}funcmain(){http.HandleFunc("/login",handleLogin)log.Fatal(http.ListenAndServe(":8080",nil))}
unprotected storage of credentials
🐞 non-compliance
packagemainimport("fmt""log""os")var(usernamestringpasswordstring)funcreadCredentials(){file,err:=os.Open("credentials.txt")iferr!=nil{log.Fatal(err)}deferfile.Close()fmt.Fscanf(file,"%s\n%s",&username,&password)}funcmain(){readCredentials()// Use the credentials for authentication// ...}
✅ compliance
packagemainimport("fmt""log""os""path/filepath""golang.org/x/crypto/bcrypt")var(usernamestringpassword[]byte)funcreadCredentials(){file,err:=os.Open(filepath.Join("secrets","credentials.txt"))iferr!=nil{log.Fatal(err)}deferfile.Close()fmt.Fscanf(file,"%s\n%s",&username,&password)}funcauthenticateUser(inputPassword[]byte)bool{err:=bcrypt.CompareHashAndPassword(password,inputPassword)iferr!=nil{returnfalse}returntrue}funcmain(){readCredentials()// Get user input for authentication// ...// Hash and compare passwordsinputPassword:=[]byte("password123")ifauthenticateUser(inputPassword){fmt.Println("Authentication successful!")}else{fmt.Println("Authentication failed!")}}
Trust Boundary Violation
🐞 non-compliance
packagemainimport("fmt""net/http""os")funcfetchUserData(userIDstring)([]byte,error){url:=fmt.Sprintf("https://api.example.com/users/%s",userID)response,err:=http.Get(url)iferr!=nil{returnnil,err}deferresponse.Body.Close()// Read the response bodydata:=make([]byte,response.ContentLength)_,err=response.Body.Read(data)iferr!=nil{returnnil,err}returndata,nil}funcmain(){userID:=os.Args[1]userData,err:=fetchUserData(userID)iferr!=nil{fmt.Printf("Error fetching user data: %s\n",err)return}fmt.Printf("User data: %s\n",userData)}
✅ compliance
$user_id=filter_input(INPUT_GET,'id',FILTER_VALIDATE_INT);packagemainimport("fmt""net/http""os""regexp")funcfetchUserData(userIDstring)([]byte,error){// Validate the user ID formatvalidUserID:=regexp.MustCompile(`^[a-zA-Z0-9]+$`)if!validUserID.MatchString(userID){returnnil,fmt.Errorf("Invalid user ID")}url:=fmt.Sprintf("https://api.example.com/users/%s",userID)response,err:=http.Get(url)iferr!=nil{returnnil,err}deferresponse.Body.Close()// Read the response bodydata:=make([]byte,response.ContentLength)_,err=response.Body.Read(data)iferr!=nil{returnnil,err}returndata,nil}funcmain(){userID:=os.Args[1]userData,err:=fetchUserData(userID)iferr!=nil{fmt.Printf("Error fetching user data: %s\n",err)return}fmt.Printf("User data: %s\n",userData)}
Insufficiently Protected Credentials
🐞 non-compliance
packagemainimport("fmt""net/http""os")const(apiUsername="admin"apiPassword="password")funcfetchUserData(userIDstring)([]byte,error){url:=fmt.Sprintf("https://api.example.com/users/%s",userID)request,err:=http.NewRequest(http.MethodGet,url,nil)iferr!=nil{returnnil,err}request.SetBasicAuth(apiUsername,apiPassword)client:=&http.Client{}response,err:=client.Do(request)iferr!=nil{returnnil,err}deferresponse.Body.Close()// Read the response bodydata:=make([]byte,response.ContentLength)_,err=response.Body.Read(data)iferr!=nil{returnnil,err}returndata,nil}funcmain(){userID:=os.Args[1]userData,err:=fetchUserData(userID)iferr!=nil{fmt.Printf("Error fetching user data: %s\n",err)return}fmt.Printf("User data: %s\n",userData)}
✅ compliance
packagemainimport("fmt""net/http""os")funcfetchUserData(userIDstring)([]byte,error){url:=fmt.Sprintf("https://api.example.com/users/%s",userID)request,err:=http.NewRequest(http.MethodGet,url,nil)iferr!=nil{returnnil,err}request.SetBasicAuth(getAPIUsername(),getAPIPassword())client:=&http.Client{}response,err:=client.Do(request)iferr!=nil{returnnil,err}deferresponse.Body.Close()// Read the response bodydata:=make([]byte,response.ContentLength)_,err=response.Body.Read(data)iferr!=nil{returnnil,err}returndata,nil}funcgetAPIUsername()string{// Retrieve the API username from a secure configuration or environment variablereturn"admin"}funcgetAPIPassword()string{// Retrieve the API password from a secure configuration or environment variablereturn"password"}funcmain(){userID:=os.Args[1]userData,err:=fetchUserData(userID)iferr!=nil{fmt.Printf("Error fetching user data: %s\n",err)return}fmt.Printf("User data: %s\n",userData)}
Restriction of XML External Entity Reference
🐞 non-compliance
packagemainimport("encoding/xml""fmt""io/ioutil""net/http""os")typeUserstruct{IDint`xml:"id"`Namestring`xml:"name"`}funcgetUserData(userIDstring)(*User,error){url:=fmt.Sprintf("https://api.example.com/users/%s",userID)response,err:=http.Get(url)iferr!=nil{returnnil,err}deferresponse.Body.Close()data,err:=ioutil.ReadAll(response.Body)iferr!=nil{returnnil,err}user:=&User{}err=xml.Unmarshal(data,user)iferr!=nil{returnnil,err}returnuser,nil}funcmain(){userID:=os.Args[1]user,err:=getUserData(userID)iferr!=nil{fmt.Printf("Error retrieving user data: %s\n",err)return}fmt.Printf("User ID: %d, Name: %s\n",user.ID,user.Name)}
✅ compliance
packagemainimport("encoding/xml""fmt""io/ioutil""net/http""os")typeUserstruct{IDint`xml:"id"`Namestring`xml:"name"`}funcgetUserData(userIDstring)(*User,error){url:=fmt.Sprintf("https://api.example.com/users/%s",userID)response,err:=http.Get(url)iferr!=nil{returnnil,err}deferresponse.Body.Close()decoder:=xml.NewDecoder(response.Body)decoder.Strict=true// Enable strict XML parsingdecoder.Entity=xml.HTMLEntity// Disable expansion of external entitiesuser:=&User{}err=decoder.Decode(user)iferr!=nil{returnnil,err}returnuser,nil}funcmain(){userID:=os.Args[1]user,err:=getUserData(userID)iferr!=nil{fmt.Printf("Error retrieving user data: %s\n",err)return}fmt.Printf("User ID: %d, Name: %s\n",user.ID,user.Name)}
Vulnerable and Outdated Components
🐞 non-compliance
packagemainimport("fmt""github.com/vulnerable/library")funcmain(){data:="Sensitive information"encryptedData:=library.OldEncryption(data)// Using a vulnerable and outdated encryption functionfmt.Println("Encrypted Data:",encryptedData)}
✅ compliance
packagemainimport("fmt""github.com/secure/library")funcmain(){data:="Sensitive information"encryptedData:=library.NewEncryption(data)// Using a secure and updated encryption functionfmt.Println("Encrypted Data:",encryptedData)}
Improper Validation of Certificate with Host Mismatch
🐞 non-compliance
packagemainimport("crypto/tls""fmt""net/http")funcmain(){tr:=&http.Transport{TLSClientConfig:&tls.Config{InsecureSkipVerify:true,// Disables certificate validation},}client:=&http.Client{Transport:tr}resp,err:=client.Get("https://example.com")iferr!=nil{fmt.Println("Error:",err)return}deferresp.Body.Close()// Process the response// ...}
✅ compliance
packagemainimport("crypto/tls""fmt""net/http")funcmain(){tr:=&http.Transport{TLSClientConfig:&tls.Config{InsecureSkipVerify:false,// Enables certificate validation},}client:=&http.Client{Transport:tr}resp,err:=client.Get("https://example.com")iferr!=nil{fmt.Println("Error:",err)return}deferresp.Body.Close()// Process the response// ...}
Improper Authentication
🐞 non-compliance
packagemainimport("fmt""net/http")funcmain(){http.HandleFunc("/login",loginHandler)http.HandleFunc("/dashboard",dashboardHandler)http.ListenAndServe(":8080",nil)}funcloginHandler(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Perform authenticationifusername=="admin"&&password=="password"{// Successful authentication// ...fmt.Fprintf(w,"Login successful!")}else{// Failed authentication// ...fmt.Fprintf(w,"Login failed!")}}funcdashboardHandler(whttp.ResponseWriter,r*http.Request){// Check if the user is authenticatedifisAuthenticated(r){// Show dashboard// ...fmt.Fprintf(w,"Welcome to the dashboard!")}else{// Redirect to login pagehttp.Redirect(w,r,"/login",http.StatusFound)}}funcisAuthenticated(r*http.Request)bool{// Check if the user is authenticated// ...returnfalse}
✅ compliance
packagemainimport("fmt""golang.org/x/crypto/bcrypt""net/http")funcmain(){http.HandleFunc("/login",loginHandler)http.HandleFunc("/dashboard",dashboardHandler)http.ListenAndServe(":8080",nil)}funcloginHandler(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Retrieve the stored hashed password for the given usernamehashedPassword,_:=getHashedPassword(username)// Compare the provided password with the hashed passworderr:=bcrypt.CompareHashAndPassword([]byte(hashedPassword),[]byte(password))iferr==nil{// Successful authentication// ...fmt.Fprintf(w,"Login successful!")}else{// Failed authentication// ...fmt.Fprintf(w,"Login failed!")}}funcdashboardHandler(whttp.ResponseWriter,r*http.Request){// Check if the user is authenticatedifisAuthenticated(r){// Show dashboard// ...fmt.Fprintf(w,"Welcome to the dashboard!")}else{// Redirect to login pagehttp.Redirect(w,r,"/login",http.StatusFound)}}funcisAuthenticated(r*http.Request)bool{// Check if the user is authenticated// ...returnfalse}funcgetHashedPassword(usernamestring)(string,error){// Retrieve the hashed password from the storage for the given username// ...return"",nil}
Session Fixation
🐞 non-compliance
packagemainimport("fmt""net/http")varsessionIDstringfuncmain(){http.HandleFunc("/login",loginHandler)http.HandleFunc("/dashboard",dashboardHandler)http.ListenAndServe(":8080",nil)}funcloginHandler(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")// Perform authenticationifusername=="admin"{// Successful authenticationsessionID="123456"// Fixed session IDhttp.SetCookie(w,&http.Cookie{Name:"sessionID",Value:sessionID})fmt.Fprintf(w,"Login successful!")}else{// Failed authenticationfmt.Fprintf(w,"Login failed!")}}funcdashboardHandler(whttp.ResponseWriter,r*http.Request){// Check if the user has a valid sessionifr.Cookie!=nil&&r.Cookie["sessionID"]!=nil&&r.Cookie["sessionID"].Value==sessionID{// Show dashboardfmt.Fprintf(w,"Welcome to the dashboard!")}else{// Redirect to login pagehttp.Redirect(w,r,"/login",http.StatusFound)}}
✅ compliance
packagemainimport("fmt""net/http")funcmain(){http.HandleFunc("/login",loginHandler)http.HandleFunc("/dashboard",dashboardHandler)http.ListenAndServe(":8080",nil)}funcloginHandler(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")// Perform authenticationifusername=="admin"{// Generate a new session IDsessionID:=generateSessionID()// Set the session ID as a cookie valuehttp.SetCookie(w,&http.Cookie{Name:"sessionID",Value:sessionID})// Redirect to the dashboardhttp.Redirect(w,r,"/dashboard",http.StatusFound)}else{// Failed authenticationfmt.Fprintf(w,"Login failed!")}}funcdashboardHandler(whttp.ResponseWriter,r*http.Request){// Check if the user has a valid sessionsessionIDCookie,err:=r.Cookie("sessionID")iferr==nil&&isValidSessionID(sessionIDCookie.Value){// Show dashboardfmt.Fprintf(w,"Welcome to the dashboard!")}else{// Redirect to login pagehttp.Redirect(w,r,"/login",http.StatusFound)}}funcgenerateSessionID()string{// Generate a new session ID// ...return"generated-session-id"}funcisValidSessionID(sessionIDstring)bool{// Check if the session ID is valid// ...returntrue}
Inclusion of Functionality from Untrusted Control
🐞 non-compliance
packagemainimport("fmt""net/http""os/exec")funcmain(){http.HandleFunc("/execute",executeHandler)http.ListenAndServe(":8080",nil)}funcexecuteHandler(whttp.ResponseWriter,r*http.Request){command:=r.FormValue("command")// Execute the command received from the useroutput,err:=exec.Command(command).CombinedOutput()iferr!=nil{fmt.Fprintf(w,"Error executing command: %v",err)return}fmt.Fprintf(w,"Command output:\n%s",output)}
✅ compliance
packagemainimport("fmt""net/http""os/exec""strings")funcmain(){http.HandleFunc("/execute",executeHandler)http.ListenAndServe(":8080",nil)}funcexecuteHandler(whttp.ResponseWriter,r*http.Request){command:=r.FormValue("command")// Validate and sanitize the command inputif!isValidCommand(command){fmt.Fprintf(w,"Invalid command")return}// Execute the validated commandoutput,err:=exec.Command(command).CombinedOutput()iferr!=nil{fmt.Fprintf(w,"Error executing command: %v",err)return}fmt.Fprintf(w,"Command output:\n%s",output)}funcisValidCommand(commandstring)bool{// Validate the command input against a whitelist of allowed commandsallowedCommands:=[]string{"ls","echo","pwd"}// Example whitelistfor_,allowedCmd:=rangeallowedCommands{ifcommand==allowedCmd{returntrue}}returnfalse}
Download of Code Without Integrity Check
🐞 non-compliance
packagemainimport("fmt""io/ioutil""net/http""os")funcmain(){url:="http://example.com/malicious-code.zip"filePath:="/path/to/save/malicious-code.zip"// Download the file from the specified URLresponse,err:=http.Get(url)iferr!=nil{fmt.Println("Error downloading file:",err)return}deferresponse.Body.Close()// Read the contents of the response bodydata,err:=ioutil.ReadAll(response.Body)iferr!=nil{fmt.Println("Error reading response:",err)return}// Save the downloaded fileerr=ioutil.WriteFile(filePath,data,0644)iferr!=nil{fmt.Println("Error saving file:",err)return}fmt.Println("File downloaded successfully!")}
✅ compliance
packagemainimport("fmt""io/ioutil""net/http""os")funcmain(){url:="http://example.com/malicious-code.zip"filePath:="/path/to/save/malicious-code.zip"// Download the file from the specified URLresponse,err:=http.Get(url)iferr!=nil{fmt.Println("Error downloading file:",err)return}deferresponse.Body.Close()// Read the contents of the response bodydata,err:=ioutil.ReadAll(response.Body)iferr!=nil{fmt.Println("Error reading response:",err)return}// Perform an integrity check on the downloaded fileif!isFileIntegrityValid(data){fmt.Println("File integrity check failed!")return}// Save the downloaded fileerr=ioutil.WriteFile(filePath,data,0644)iferr!=nil{fmt.Println("Error saving file:",err)return}fmt.Println("File downloaded and saved successfully!")}funcisFileIntegrityValid(data[]byte)bool{// Implement an integrity check algorithm (e.g., cryptographic hash)// to validate the integrity of the downloaded file// and return true if the integrity check passes, or false otherwise// Example using SHA256 hashexpectedHash:="..."actualHash:=calculateHash(data)returnexpectedHash==actualHash}funccalculateHash(data[]byte)string{// Calculate the hash of the data using a suitable cryptographic hash function// and return the hash value as a string// Example using SHA256 hash// ...return"..."}
packagemainimport("encoding/json""fmt""log")typeUserstruct{IDintUsernamestringEmailstring}funcmain(){data:=`{"ID": 1, "Username": "john", "Email": "[email protected]"}`// Perform input validation and sanitizationif!isValidJSON(data){log.Fatal("Invalid JSON data")}varuserUsererr:=json.Unmarshal([]byte(data),&user)iferr!=nil{log.Fatal("Error deserializing user:",err)}// Perform additional validation on the deserialized user objectif!isValidUser(user){log.Fatal("Invalid user data")}fmt.Println("User:",user)}funcisValidJSON(datastring)bool{// Implement validation logic to ensure the input data is valid JSON// and return true if valid, or false otherwise// Example: use json.Valid function from the encoding/json packagereturnjson.Valid([]byte(data))}funcisValidUser(userUser)bool{// Implement additional validation logic on the deserialized user object// to ensure it meets the application's requirements// and return true if valid, or false otherwise// Example: check if the username and email meet certain criteriaiflen(user.Username)<3||len(user.Email)==0{returnfalse}returntrue}
Insufficient Logging
🐞 non-compliance
packagemainimport("fmt""log""net/http""os")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){// Process the request// ...// Log the request detailslog.Println("Request received:",r.Method,r.URL.Path)// Perform some sensitive operationperformSensitiveOperation()// Log the completion of the requestlog.Println("Request processed successfully")}funcperformSensitiveOperation(){// Perform some sensitive operation// ...// Log the sensitive operationlog.Println("Sensitive operation performed")}
✅ compliance
packagemainimport("fmt""net/http""os"log"github.com/sirupsen/logrus")funcmain(){// Initialize the loggerinitLogger()http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funcinitLogger(){// Set the desired log output, format, and levellog.SetOutput(os.Stdout)log.SetFormatter(&log.JSONFormatter{})log.SetLevel(log.InfoLevel)}funchandleRequest(whttp.ResponseWriter,r*http.Request){// Process the request// ...// Log the request detailslog.WithFields(log.Fields{"method":r.Method,"path":r.URL.Path,}).Info("Request received")// Perform some sensitive operationperformSensitiveOperation()// Log the completion of the requestlog.Info("Request processed successfully")}funcperformSensitiveOperation(){// Perform some sensitive operation// ...// Log the sensitive operationlog.Warn("Sensitive operation performed")}
Improper Output Neutralization for Logs
🐞 non-compliance
packagemainimport("fmt""log""net/http")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")// Log the usernamelog.Println("User logged in:",username)// Process the request// ...}
✅ compliance
packagemainimport("fmt""log""net/http""strings")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")// Sanitize the usernamesanitizedUsername:=sanitizeString(username)// Log the sanitized usernamelog.Printf("User logged in: %s",sanitizedUsername)// Process the request// ...}funcsanitizeString(sstring)string{// Replace special characters that could affect log outputs=strings.ReplaceAll(s,"\n","\\n")s=strings.ReplaceAll(s,"\r","\\r")s=strings.ReplaceAll(s,"\t","\\t")returns}
Omission of Security-relevant Information
🐞 non-compliance
packagemainimport("fmt""log""net/http")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Log the user login eventlog.Printf("User logged in: %s",username)// Process the request// ...}
✅ compliance
packagemainimport("fmt""log""net/http")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Log the user login event with all relevant informationlog.Printf("User logged in - Username: %s, Password: %s",username,password)// Process the request// ...}
Sensitive Information into Log File
🐞 non-compliance
packagemainimport("fmt""log""net/http""os")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Log the sensitive informationlogFile,err:=os.OpenFile("app.log",os.O_CREATE|os.O_WRONLY|os.O_APPEND,0644)iferr!=nil{log.Fatal(err)}deferlogFile.Close()logger:=log.New(logFile,"",log.LstdFlags)logger.Printf("Sensitive information - Username: %s, Password: %s",username,password)// Process the request// ...}
✅ compliance
packagemainimport("fmt""log""net/http")funcmain(){http.HandleFunc("/",handleRequest)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleRequest(whttp.ResponseWriter,r*http.Request){username:=r.FormValue("username")password:=r.FormValue("password")// Process the request// Log a message without sensitive informationlog.Printf("Received request - Username: %s",username)// Perform authenticationif!authenticate(username,password){log.Printf("Authentication failed for user: %s",username)http.Error(w,"Authentication failed",http.StatusUnauthorized)return}// Continue with the request// ...}funcauthenticate(username,passwordstring)bool{// Perform authentication logic// ...}
Server-Side Request Forgery (SSRF)
🐞 non-compliance
packagemainimport("fmt""io/ioutil""log""net/http")funcmain(){http.HandleFunc("/fetch",handleFetch)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleFetch(whttp.ResponseWriter,r*http.Request){url:=r.FormValue("url")// Make a request to the provided URLresponse,err:=http.Get(url)iferr!=nil{log.Fatal(err)}deferresponse.Body.Close()// Read the response bodybody,err:=ioutil.ReadAll(response.Body)iferr!=nil{log.Fatal(err)}fmt.Fprintf(w,"Response Body: %s",body)}
✅ compliance
packagemainimport("fmt""io/ioutil""log""net/http""net/url")funcmain(){http.HandleFunc("/fetch",handleFetch)log.Fatal(http.ListenAndServe(":8080",nil))}funchandleFetch(whttp.ResponseWriter,r*http.Request){rawURL:=r.FormValue("url")// Parse the URL to ensure it is valid and safeparsedURL,err:=url.ParseRequestURI(rawURL)iferr!=nil{http.Error(w,"Invalid URL",http.StatusBadRequest)return}// Ensure that the URL points to a permitted domainallowedDomains:=[]string{"example.com","trusteddomain.com"}if!isDomainAllowed(parsedURL.Host,allowedDomains){http.Error(w,"Access to the specified domain is not allowed",http.StatusForbidden)return}// Make a request to the provided URLresponse,err:=http.Get(parsedURL.String())iferr!=nil{log.Fatal(err)}deferresponse.Body.Close()// Read the response bodybody,err:=ioutil.ReadAll(response.Body)iferr!=nil{log.Fatal(err)}fmt.Fprintf(w,"Response Body: %s",body)}funcisDomainAllowed(domainstring,allowedDomains[]string)bool{for_,allowedDomain:=rangeallowedDomains{ifdomain==allowedDomain{returntrue}}returnfalse}