Skip to content

Commit 8d81968

Browse files
committed
Add details about each vulnerability in code comments
1 parent 1a1ea50 commit 8d81968

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

main.go

+39
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,28 @@ import (
2020
func main() {
2121
// Gosec G101: Hardcoded credentials
2222
// CWE-798: Use of Hard-coded Credentials
23+
// Vulnerability: Hard-coding credentials in source code is a security risk.
24+
// If an attacker gains access to the source code, they can easily extract the credentials.
25+
// Best practice is to store credentials securely, such as in environment variables or a secrets manager.
2326
const password = "secret123"
2427
if password == "secret123" {
2528
fmt.Println("Access granted!")
2629
}
2730

2831
// Gosec G501: Blacklisted import crypto/md5
2932
// CWE-327: Use of a Broken or Risky Cryptographic Algorithm
33+
// Vulnerability: The MD5 hash function is cryptographically broken and should not be used for security purposes.
34+
// It is vulnerable to collision attacks, where two different inputs can produce the same hash output.
35+
// Best practice is to use a secure hash function like SHA-256 or SHA-3.
3036
hash := md5.New()
3137
hash.Write([]byte("test"))
3238
fmt.Printf("%x", hash.Sum(nil))
3339

3440
// Gosec G304: File path provided as taint input
3541
// CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
42+
// Vulnerability: Using user-supplied input directly as a file path can lead to path traversal vulnerabilities.
43+
// An attacker can craft a malicious path to access files outside the intended directory.
44+
// Best practice is to validate and sanitize user input before using it as a file path.
3645
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
3746
filePath := r.URL.Query().Get("path")
3847
data, err := os.ReadFile(filePath)
@@ -45,16 +54,25 @@ func main() {
4554

4655
// Gosec G204: Subprocess launched with variable
4756
// CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
57+
// Vulnerability: Executing a command with user-supplied input can lead to command injection vulnerabilities.
58+
// An attacker can inject malicious commands to gain unauthorized access or perform destructive actions.
59+
// Best practice is to avoid using user input directly in commands and use safe alternatives like parameterized queries.
4860
userInput := "ls -l; rm -rf /"
4961
cmd := exec.Command("sh", "-c", userInput)
5062
cmd.Run()
5163

5264
// Gosec G104: Errors unhandled
65+
// Vulnerability: Ignoring errors can lead to unexpected behavior and security vulnerabilities.
66+
// Unhandled errors may result in resource leaks, inconsistent state, or exposure of sensitive information.
67+
// Best practice is to properly handle and log errors to ensure the stability and security of the application.
5368
f, _ := os.Open("file.txt")
5469
defer f.Close()
5570

5671
// Gosec G201: SQL query construction using format string
5772
// CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
73+
// Vulnerability: Constructing SQL queries by directly concatenating user input can lead to SQL injection vulnerabilities.
74+
// An attacker can manipulate the input to modify the SQL query and gain unauthorized access to the database.
75+
// Best practice is to use parameterized queries or prepared statements to separate user input from the SQL query structure.
5876
username := "admin"
5977
pass := "' OR 1=1--"
6078
query := fmt.Sprintf("SELECT * FROM users WHERE username='%s' AND password='%s'", username, pass)
@@ -63,24 +81,36 @@ func main() {
6381

6482
// Gosec G401: Use of weak cryptographic primitive
6583
// CWE-327: Use of a Broken or Risky Cryptographic Algorithm
84+
// Vulnerability: Using weak cryptographic primitives, such as DES, can compromise the security of encrypted data.
85+
// These algorithms have known vulnerabilities and are susceptible to attacks.
86+
// Best practice is to use strong, modern cryptographic algorithms like AES with appropriate key sizes.
6687
key := []byte("weak-key")
6788
block, _ := des.NewCipher(key)
6889
fmt.Printf("%x", block)
6990

7091
// Gosec G402: TLS MinVersion too low
7192
// CWE-326: Inadequate Encryption Strength
93+
// Vulnerability: Using a low TLS version, such as SSL 3.0, can expose the communication to known vulnerabilities.
94+
// Older TLS versions have weaknesses that can be exploited by attackers to compromise the security of the connection.
95+
// Best practice is to use a minimum TLS version of 1.2 or higher and disable support for older, insecure versions.
7296
config := &tls.Config{
7397
MinVersion: tls.VersionSSL30,
7498
}
7599
_, _ = tls.Dial("tcp", "example.com:443", config)
76100

77101
// Gosec G404: Use of weak random number generator
78102
// CWE-338: Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG)
103+
// Vulnerability: Using a weak random number generator, such as the default math/rand package, can lead to predictable and insecure random values.
104+
// Attackers may be able to guess or reproduce the generated random numbers, compromising the security of the system.
105+
// Best practice is to use a cryptographically secure random number generator, such as crypto/rand, for security-sensitive operations.
79106
token := rand.Int()
80107
fmt.Println("Random token:", token)
81108

82109
// Gosec G501: Blacklisted import crypto/rc4
83110
// CWE-327: Use of a Broken or Risky Cryptographic Algorithm
111+
// Vulnerability: The RC4 stream cipher is considered weak and should not be used for encryption.
112+
// It has biases and vulnerabilities that can be exploited to recover the plaintext from the ciphertext.
113+
// Best practice is to use secure encryption algorithms like AES-GCM or ChaCha20-Poly1305.
84114
cipher, _ := rc4.NewCipher([]byte("secret"))
85115
fmt.Printf("%x", cipher)
86116

@@ -92,18 +122,27 @@ func main() {
92122

93123
// Gosec G107: Potential HTTP request made with variable url
94124
// CWE-88: Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
125+
// Vulnerability: Making an HTTP request with a user-supplied URL can lead to server-side request forgery (SSRF) vulnerabilities.
126+
// An attacker can manipulate the URL to make requests to internal or external systems, potentially accessing sensitive data or performing unauthorized actions.
127+
// Best practice is to validate and sanitize the URL input, restrict the allowed domains or schemes, and use a whitelist approach if possible.
95128
url := resp.Request.URL.Query().Get("url")
96129
http.Get(url)
97130

98131
// Gosec G109: Potential Integer overflow made by strconv.Atoi result conversion to int16/32
99132
// CWE-190: Integer Overflow or Wraparound
133+
// Vulnerability: Converting a string to an integer without proper bounds checking can lead to integer overflow vulnerabilities.
134+
// If the input string represents a number that is too large for the target integer type, it can cause unexpected behavior or security issues.
135+
// Best practice is to use appropriate integer types with sufficient range and perform proper error handling and input validation.
100136
val := resp.Request.URL.Query().Get("val")
101137
num, _ := strconv.Atoi(val)
102138
var intVal int16 = int16(num)
103139
fmt.Println(intVal)
104140

105141
// Gosec G110: Potential DoS vulnerability via decompression bomb
106142
// CWE-409: Improper Handling of Highly Compressed Data (Data Amplification)
143+
// Vulnerability: Decompressing user-supplied compressed data without proper limits can lead to denial-of-service (DoS) attacks.
144+
// An attacker can craft a small compressed payload that expands to a extremely large size upon decompression, consuming excessive memory and CPU resources.
145+
// Best practice is to set appropriate size limits on the decompressed data and handle decompression errors gracefully.
107146
http.HandleFunc("/decompress", func(w http.ResponseWriter, r *http.Request) {
108147
r.Body = http.MaxBytesReader(w, r.Body, 1<<30) // 1GB
109148
gzr, _ := gzip.NewReader(r.Body)

0 commit comments

Comments
 (0)