Semgrep go rules¶
go_sql_rule-concat-sqli¶
Summary:
Improper neutralization of special elements used in an SQL command ('SQL Injection')
Severity: High
CWE: CWE-89
Description:
SQL Injection vulnerability detected from dynamic query construction using
fmt.Sprintf(), string concatenation, or strings.Builder with db.Exec(),
db.Query(), or db.QueryRow(). User input can manipulate SQL logic, leading to
unauthorized data access, data modification, or in severe cases, command execution.
Remediation:
Consider using parameterized queries with ? placeholders to safely pass user input:
db.Query("SELECT * FROM users WHERE userName = ?", userName). For dynamic table or
column names that cannot be parameterized, use an allowlist approach with a map of
valid values (e.g., map user input "recent" to "created_at DESC"). Never directly
concatenate user input into SQL strings. For comprehensive guidance, see: SQL_Injection_Prevention_Cheat_Sheet.html
OWASP:
- A1:2017-Injection
- A03:2021-Injection
go_subproc_rule-subproc¶
Summary:
Improper neutralization of special elements used in an OS command ('OS Command Injection')
Severity: High
CWE: CWE-78
Description:
OS command injection detected in exec.Command(), exec.CommandContext(),
syscall.ForkExec(), or syscall.StartProcess(). User-controlled input passed
to these functions can allow attackers to execute arbitrary system commands,
leading to full system compromise. User input should never be used in constructing
commands or arguments, including filenames from user uploads or downloads.
Remediation:
Consider using a hardcoded set of commands and arguments instead of accepting user input. If filenames must be passed, recommended to use a hash or unique identifier rather than user-supplied filenames. Strongly recommended to use native Go libraries that implement the same functionality instead of executing OS commands, as this eliminates command injection risk entirely. If user input is unavoidable, implement strict validation using an allowlist of permitted values.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
go_unsafe_rule-unsafe¶
Summary:
Use of inherently dangerous function (unsafe package)
Severity: High
CWE: CWE-242
Description:
Use of unsafe package functions (unsafe.Alignof(), unsafe.Offsetof(),
unsafe.Sizeof(), unsafe.Pointer()) bypasses Go's type safety guarantees and
enables direct memory manipulation. This can lead to buffer overflows, use-after-free
vulnerabilities, memory leaks, and arbitrary code execution.
Remediation:
Consider removing all calls to the unsafe package unless absolutely required for
performance-critical operations or interfacing with C code. Recommended to use Go's
built-in type-safe alternatives and standard library functions instead. If unsafe
operations are truly necessary, isolate them in well-documented, thoroughly reviewed
functions with clear contracts and extensive testing. Review each usage to ensure
it's genuinely required and cannot be replaced with safe alternatives.
OWASP:
- A9:2017-Using Components with Known Vulnerabilities
- A06:2021-Vulnerable and Outdated Components
go_blocklist_rule-blocklist-des¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application imports crypto/des which provides the Data Encryption Standard
(DES) algorithm. DES uses a 56-bit key size and has been cryptographically broken
through exhaustive key search attacks since the late 1990s. DES was officially
withdrawn as a standard by NIST (FIPS 46-3) in 2005 and should not be used in any
modern application. Using des.NewCipher() or des.NewTripleDESCipher() exposes
encrypted data to practical brute-force attacks.
Remediation:
Consider migrating to authenticated encryption algorithms that provide both
confidentiality and integrity. The recommended approach is to use
chacha20poly1305.NewX() from the golang.org/x/crypto/chacha20poly1305
package, which offers faster performance, larger nonce sizes (192 bits), and
better resistance to nonce misuse compared to alternatives. For applications
requiring AES compatibility, cipher.NewGCM() with a 32-byte key provides
AES-256-GCM, though it requires careful nonce management as reusing a nonce
with the same key causes catastrophic security failures. When using AES-GCM,
ensure nonces are generated with io.ReadFull(rand.Reader, nonce) and keys
are rotated after 2^32 operations. Complete implementation examples are
available at https://pkg.go.dev/golang.org/x/crypto/chacha20poly1305#NewX
and https://pkg.go.dev/crypto/cipher#NewGCM for both encryption schemes.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_blocklist_rule-blocklist-md5¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application imports crypto/md5 which provides the MD5 hash algorithm. MD5
has been cryptographically broken since 2004 with practical collision attacks
demonstrated by Wang et al., allowing attackers to create two different inputs
that produce identical hash outputs. Using md5.New() or md5.Sum() for any
security-critical purpose such as digital signatures, integrity verification, or
certificate validation creates serious vulnerabilities. MD5 should not be used
in any context where collision resistance is required.
Remediation:
Consider using modern hash algorithms from the BLAKE2 or SHA-3 families for
general-purpose cryptographic hashing. For file integrity or non-password data,
recommended to use blake2b.New512() from golang.org/x/crypto/blake2b, which
provides better security and performance than older SHA-2 algorithms. For
password hashing specifically, consider using argon2.IDKey() from
golang.org/x/crypto/argon2 or bcrypt.GenerateFromPassword() from
golang.org/x/crypto/bcrypt, as these are memory-hard functions designed to
resist brute-force attacks. When implementing Argon2id, recommended parameters
are memory=64MB, iterations=3, and parallelism=2 for a balanced security-
performance trade-off. Always use subtle.ConstantTimeCompare() when comparing
password hashes to prevent timing attacks. See
https://pkg.go.dev/golang.org/x/crypto/blake2b and OWASP's Password Storage
Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_blocklist_rule-blocklist-rc4¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application imports crypto/rc4 which provides the RC4 stream cipher
algorithm. RC4 has multiple cryptographic weaknesses including biases in its
keystream that enable practical attacks, particularly in protocols like WEP and
early TLS versions. The algorithm was prohibited for use in TLS by RFC 7465 in
2015 due to these vulnerabilities. Using rc4.NewCipher() exposes encrypted data
to statistical attacks that can recover plaintext, especially when large amounts
of data are encrypted with the same key.
Remediation:
Consider replacing RC4 with modern authenticated encryption algorithms that
provide both confidentiality and integrity protection. The recommended approach
is to use chacha20poly1305.NewX() from golang.org/x/crypto/chacha20poly1305,
which offers superior performance on most platforms and uses 192-bit nonces that
greatly reduce the risk of nonce reuse. For environments requiring AES
compatibility, cipher.NewGCM() with a 32-byte key provides AES-256-GCM, though
this requires strict nonce management since reusing a nonce even once with the
same key completely breaks the security. When migrating from RC4, ensure proper
key generation using io.ReadFull(rand.Reader, key) and never reuse nonces
across encryption operations. Complete migration examples are available at
https://pkg.go.dev/golang.org/x/crypto/chacha20poly1305#NewX and
https://pkg.go.dev/crypto/cipher#NewGCM for both recommended alternatives.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_blocklist_rule-blocklist-sha1¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application imports crypto/sha1 which provides the SHA-1 hash algorithm.
SHA-1 has been cryptographically broken with practical collision attacks publicly
demonstrated by Google and CWI Amsterdam in 2017 (SHAttered attack), allowing
creation of two different inputs producing the same hash output. Using sha1.New()
or sha1.Sum() for any security purpose such as digital signatures, certificate
validation, or integrity checks is dangerous. SHA-1 was deprecated by NIST in 2011
and should be replaced in all cryptographic applications.
Remediation:
Consider migrating to collision-resistant hash algorithms from the SHA-3 or
BLAKE2 families. For general-purpose cryptographic hashing of files or data
integrity, recommended to use blake2b.New512() from
golang.org/x/crypto/blake2b, which offers both better security margins and
superior performance compared to SHA-2. For digital signatures, SHA-256 from the
standard library crypto/sha256 package provides adequate security, though
BLAKE2 is preferred for new implementations. For password hashing specifically,
consider using argon2.IDKey() from golang.org/x/crypto/argon2 or
bcrypt.GenerateFromPassword() from golang.org/x/crypto/bcrypt, as these
memory-hard key derivation functions resist GPU-based brute-force attacks. When
implementing Argon2id, recommended parameters are memory=64MB, iterations=3, and
parallelism=2. Always use subtle.ConstantTimeCompare() when verifying password
hashes to prevent timing side-channels. See
https://pkg.go.dev/golang.org/x/crypto/blake2b and OWASP's Password Storage
Cheat Sheet at
https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_crypto_rule-badtlssettings¶
Summary:
Use of a broken or risky cryptographic algorithm
Severity: Medium
CWE: CWE-327
Description:
The application configures tls.Config or tls.CipherSuite with
cryptographically weak cipher suites that do not appear in Go's recommended
list of secure ciphers. Weak cipher suites are vulnerable to various attacks
including those that compromise confidentiality or allow downgrade attacks to
weaker protocols. Modern cipher suites must support Perfect Forward Secrecy
(PFS) to ensure that past encrypted transmissions cannot be decrypted even if
the TLS certificate is compromised. Without PFS, compromise of a server's
private key would allow attackers to decrypt all previously captured traffic.
Remediation:
Consider upgrading all TLS connections to use TLS 1.3 by setting
MinVersion: tls.VersionTLS13 in your tls.Config. When using TLS 1.3, Go
automatically selects the most secure cipher suite during the handshake, and
all TLS 1.3 cipher suites inherently support Perfect Forward Secrecy. If you
must support TLS 1.0-1.2 for legacy clients, explicitly configure the
CipherSuites field to include only PFS-enabled ciphers:
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, and
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305. Set MinVersion: tls.VersionTLS12
at minimum to disable deprecated TLS 1.0 and 1.1. For more information on
cipher suites in Go, see https://go.dev/blog/tls-cipher-suites
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_crypto_rule-insecure-ignore-host-key¶
Summary:
Key exchange without entity authentication
Severity: Medium
CWE: CWE-322
Description:
The application uses ssh.InsecureIgnoreHostKey() from the
golang.org/x/crypto/ssh package, which disables SSH host key verification.
Host key verification is a critical security mechanism that authenticates the
SSH server's identity and prevents man-in-the-middle attacks. When host keys
are ignored, clients cannot validate that they are connecting to the intended
server, allowing attackers to intercept the connection and capture credentials
or inject malicious commands. This is equivalent to ignoring certificate
validation in HTTPS connections and completely undermines the security
guarantees of SSH.
Remediation:
Consider using the golang.org/x/crypto/ssh/knownhosts package for the
HostKeyCallback property in your ssh.ClientConfig. The knownhosts.New()
function parses OpenSSH's standard known_hosts file format and provides a
callback that validates server host keys against trusted entries. This
approach maintains compatibility with standard SSH tooling and provides the
same security guarantees as OpenSSH clients. When connecting to servers for
the first time, use knownhosts.New() combined with proper host key
verification through an out-of-band channel rather than blindly accepting
unknown keys. For automated systems, pre-populate the known_hosts file with
verified host keys during deployment. More details available at
https://pkg.go.dev/golang.org/x/crypto/ssh/knownhosts
OWASP:
- A2:2017-Broken Authentication
- A07:2021-Identification and Authentication Failures
go_crypto_rule-tlsversion¶
Summary:
Use of deprecated TLS version
Severity: Medium
CWE: CWE-310
Description:
The application configures tls.Config with MinVersion set to
tls.VersionTLS10 or tls.VersionTLS11, or sets MaxVersion without
specifying a minimum version. TLS 1.0 and 1.1 were formally deprecated by
the IETF in RFC 8996 (March 2021) due to numerous cryptographic weaknesses
including vulnerabilities to BEAST, CRIME, and POODLE attacks. Major
browsers and security standards like PCI DSS have prohibited these versions
since 2020. Using deprecated TLS versions exposes encrypted connections to
downgrade attacks and allows adversaries to exploit known protocol-level
vulnerabilities, potentially leading to unauthorized access to sensitive
data transmitted over the connection.
Remediation:
Consider configuring all tls.Config instances with
MinVersion: tls.VersionTLS13 to enforce TLS 1.3, which provides the
strongest security guarantees and automatically selects secure cipher
suites with Perfect Forward Secrecy. TLS 1.3 also improves performance by
reducing handshake round trips. If you must support legacy clients that
don't support TLS 1.3, set MinVersion: tls.VersionTLS12 as an absolute
minimum, as TLS 1.2 is currently the oldest acceptable version. Avoid
setting MaxVersion unless you have a specific compatibility requirement,
as this prevents upgrading to newer, more secure protocol versions. When
using TLS 1.2, ensure you also configure secure cipher suites that support
Perfect Forward Secrecy. For more information, see
https://go.dev/blog/tls-cipher-suites
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_crypto_rule-weakkeystrength¶
Summary:
Inadequate encryption strength
Severity: Medium
CWE: CWE-326
Description:
The application calls rsa.GenerateKey() from the crypto/rsa package with
a key size smaller than 2048 bits. NIST deprecated 1024-bit RSA keys for
digital signatures in December 2010, and security standards like PCI DSS
require minimum 2048-bit keys. While 1024-bit keys have not yet been publicly
factored, continued advances in computing power and cryptanalytic techniques
make factorization increasingly feasible. Successful factorization of an RSA
private key allows attackers to forge signatures, decrypt encrypted data, and
completely compromise systems relying on that key pair for authentication or
confidentiality.
Remediation:
Consider generating RSA keys with a minimum size of 2048 bits by passing 2048
or larger as the second parameter to rsa.GenerateKey(). For new
applications with high security requirements, use 3072-bit or 4096-bit keys
for longer-term security, though note that larger keys increase computational
overhead for signing and verification operations. Alternatively, consider
migrating to elliptic curve cryptography using the crypto/ecdsa package
with P-256 or P-384 curves, which provide equivalent security to 3072-bit and
7680-bit RSA keys respectively while requiring significantly smaller key
sizes and faster operations. When generating keys, always use crypto/rand
as the random source, never math/rand.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_crypto_rule-weakrandsource¶
Summary:
Use of cryptographically weak Pseudo-Random Number Generator (PRNG)
Severity: Medium
CWE: CWE-338
Description:
The application uses the math/rand package to generate random numbers in a
context where crypto/rand is not also imported. The math/rand package
implements a deterministic pseudo-random number generator (PRNG) that is not
cryptographically secure. Random values generated by math/rand are
predictable if an attacker can observe or guess the seed value, and the
package explicitly documents that it should not be used for security-sensitive
applications. Using math/rand for session tokens, cryptographic keys,
password reset tokens, or any security-critical identifiers can allow
attackers to predict future values and compromise authentication or
authorization mechanisms.
Remediation:
Consider replacing all imports of math/rand with crypto/rand for any
security-sensitive random number generation. The crypto/rand package
provides cryptographically secure random numbers by reading from the
operating system's secure random source (e.g., /dev/urandom on Unix
systems). Use crypto/rand.Read() to fill byte slices with random data, or
crypto/rand.Int() for random integers within a specific range. Note that
crypto/rand has a different API than math/rand and requires explicit
error handling since it can fail if the system's entropy source is
unavailable. It is acceptable to use math/rand for non-security purposes
like statistical simulations or game logic, but in those cases ensure the
code clearly documents why cryptographic randomness is not required.
OWASP:
- A3:2017-Sensitive Data Exposure
- A02:2021-Cryptographic Failures
go_file-permissions_rule-fileperm¶
Summary:
Incorrect permission assignment for critical resource
Severity: Medium
CWE: CWE-732
Description:
File permissions set using os.Chmod(), os.OpenFile(), or os.WriteFile() are
overly permissive (greater than 0640). This allows unauthorized users or processes
to read, modify, or execute sensitive files, potentially leading to information
disclosure, data tampering, or privilege escalation.
Remediation:
Consider using restrictive file permissions that limit access to only the application
user when possible: 0400 for read-only access, 0200 for write-only access, or
0600 for read/write access. Recommended to avoid permissions like 0777 or 0666
that grant access to all users. If group or world access is required, carefully
evaluate the security implications and use the minimum necessary permissions such as
0640 (owner read/write, group read) or 0440 (owner and group read-only).
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_file-permissions_rule-mkdir¶
Summary:
Incorrect permission assignment for critical resource
Severity: Medium
CWE: CWE-732
Description:
Overly permissive directory permissions detected in os.Mkdir() or os.MkdirAll()
calls. Setting permissions higher than 0750 allows unauthorized users to access,
modify, or delete directory contents. This can lead to information disclosure,
privilege escalation, or data tampering by local attackers.
Remediation:
Consider restricting directory permissions to limit access. Use 0700 (octal) for
owner-only read/write/execute access when the application user is the sole accessor.
Use 0750 to grant the owner full access while allowing group members read and execute
permissions. Recommended approach: err := os.Mkdir("directory", 0700) or
err := os.MkdirAll("path/to/directory", 0700). For more details on permission
values, see: File-system_permissions
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_filesystem_rule-decompression-bomb¶
Summary:
Improper handling of highly compressed data
Severity: Medium
CWE: CWE-409
Description:
The application uses decompression functions like gzip.NewReader(),
zlib.NewReader(), bzip2.NewReader(), flate.NewReader(), lzw.NewReader(),
tar.NewReader(), or zip.NewReader() from the standard library without imposing
limits on the decompressed output size. This creates vulnerability to decompression
bomb attacks where maliciously crafted compressed files expand to extremely large
sizes, potentially causing the process to exhaust memory or fill disk storage,
resulting in Denial of Service (DoS).
Remediation:
Consider wrapping decompression readers with io.LimitReader() to impose a
maximum limit on the decompressed output size before copying or processing the
data. The limit should be based on your application's expected maximum file size
requirements. For example, if processing user-uploaded compressed logs that should
never exceed 10MB uncompressed, set the limit accordingly. The rule detects
unprotected uses of io.Copy() and io.CopyBuffer() with decompression readers
from packages like compress/gzip, compress/zlib, compress/bzip2,
compress/flate, compress/lzw, and archive/tar or archive/zip. Recommended
to validate both the compressed and uncompressed sizes, and consider implementing
additional safeguards such as timeouts for decompression operations to prevent
resource exhaustion attacks.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
go_filesystem_rule-fileread¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Medium
CWE: CWE-22
Description:
The application constructs file paths dynamically and passes them to file I/O
functions like os.Open(), os.OpenFile(), os.ReadFile(), or
ioutil.ReadFile(). When path information originates from user-controlled sources
such as HTTP request parameters (http.Request.FormValue(), http.Request.URL),
environment variables (os.Getenv()), or string concatenation with untrusted data,
this creates path traversal vulnerabilities (CWE-22). Attackers can exploit this by
injecting sequences like ../ to access files outside the intended directory,
potentially reading sensitive configuration files, credentials, or other users' data.
Remediation:
Consider implementing a defense-in-depth approach to prevent path traversal
attacks. Recommended to avoid using user input in file paths entirely by mapping
user-supplied filenames to randomly generated identifiers stored in a database.
When user input must be incorporated, use filepath.Base() to extract only the
filename component without directory information, then join it with a hardcoded
base directory using filepath.Join(). Always validate the resolved path starts
with your intended base directory using strings.HasPrefix() after calling
filepath.Clean() to normalize the path. The rule detects taint flows from
sources like http.Request fields, os.Getenv(), and string operations to
file I/O sinks, and recognizes sanitization through filepath.Clean() combined
with prefix validation. For additional security, consider using chroot jails or
containerization to limit filesystem access at the OS level.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_filesystem_rule-httprootdir¶
Summary:
Files or directories accessible to external parties
Severity: Medium
CWE: CWE-552
Description:
The application uses http.Dir("/") to create a file server handler that mounts
the root directory of the filesystem. When combined with http.FileServer() and
served via HTTP, this configuration exposes the entire filesystem to any client
that can reach the HTTP endpoint. Attackers can potentially access any file the
HTTP server process has permission to read, including sensitive system files like
/etc/passwd, /etc/shadow, application configuration files containing credentials,
private keys, or database connection strings.
Remediation:
Consider restricting http.Dir() to only serve files from a specific application
directory that contains only public assets intended for web serving, such as
/var/www/html/public or /app/static. Recommended to create a dedicated
directory structure that isolates public web content from application code,
configuration files, and sensitive data. When using http.FileServer() with
http.Dir(), ensure the path points to a restricted subdirectory and not system
directories. Additionally, consider implementing authentication and authorization
middleware before the file server handler to control access to static files.
For production deployments, recommended to use a reverse proxy like nginx or a
CDN to serve static files instead of serving them directly from your Go
application, which provides better performance and security isolation.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_filesystem_rule-poorwritepermissions¶
Summary:
Incorrect default permissions
Severity: Medium
CWE: CWE-276
Description:
The application uses ioutil.WriteFile() with file permission modes greater than
0600 (octal), granting excessive permissions to the created files. When permissions
exceed 0600, the file becomes readable or writable by group members or other users
on the system beyond the file owner. This violates the principle of least privilege
and can expose sensitive data to unauthorized local users, particularly in shared
hosting environments or multi-tenant systems where different applications run under
different user accounts on the same server.
Remediation:
Consider using restrictive file permissions that limit access to only the file
owner when writing files with os.WriteFile() or ioutil.WriteFile(). Recommended
permission values are 0400 (read-only), 0200 (write-only), or 0600 (read-write)
for files that should only be accessed by the application user. For files that must
be shared with a specific group, use 0640 (owner read-write, group read-only) rather
than world-readable permissions. The rule detects permission modes greater than
0o600 in octal notation passed to ioutil.WriteFile(). When storing sensitive data
such as credentials, private keys, session tokens, or API keys, always use 0600 or
more restrictive permissions. For configuration files, consider 0640 if they need
group access, but never use world-readable modes like 0644 or 0666 for sensitive
content.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_filesystem_rule-tempfiles¶
Summary:
Creation of temporary file with insecure permissions
Severity: Medium
CWE: CWE-378
Description:
The application creates files in shared system temporary directories (/tmp or
/var/tmp) using predictable paths with os.WriteFile(), ioutil.WriteFile(),
os.OpenFile() with os.O_CREATE, or os.Create() instead of using
os.CreateTemp(). This creates a time-of-check-time-of-use (TOCTOU) race condition
vulnerability where an attacker with local access can predict the file path and
create a symbolic link at that location before the application writes to it. This
can lead to arbitrary file overwrites with the application's privileges, potentially
escalating to privilege escalation or denial of service attacks.
Remediation:
Consider using os.CreateTemp() which creates temporary files with unpredictable
names and secure permissions (0600) that are only accessible to the file owner.
Recommended to create temporary files in an application-specific directory rather
than shared system directories like /tmp or /var/tmp. For example, create a
directory under /opt/appdir/temp with restrictive permissions (0700) owned by
the application user, then pass this path as the first argument to os.CreateTemp().
The function automatically generates unique filenames using cryptographically random
suffixes, eliminating TOCTOU race conditions. Remember to defer os.Remove() after
creating the file to ensure cleanup. The rule detects hardcoded paths matching
/tmp/ or /var/tmp/ patterns passed to file creation functions. For additional
security in containerized environments, consider mounting temporary directories on
separate filesystems with noexec and nosuid flags.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_filesystem_rule-ziparchive¶
Summary:
Improper limitation of a pathname to a restricted directory ('Path Traversal')
Severity: Medium
CWE: CWE-22
Description:
The application extracts archive files using zip.OpenReader() or tar.OpenReader()
and passes file paths from the archive to filepath.Join() without proper validation.
This creates a "Zip Slip" vulnerability where maliciously crafted archives can include
file entries with path traversal sequences like ../../etc/passwd that, when extracted,
write files outside the intended destination directory. Attackers can exploit this to
overwrite critical system files, application configuration, or executable code,
potentially leading to remote code execution or privilege escalation. The vulnerability
is particularly dangerous because archive file names are completely attacker-controlled
and filepath.Join() alone does not prevent directory traversal.
Remediation:
Consider implementing multiple layers of validation when extracting archive files.
Recommended to use filepath.Clean() to normalize paths from the archive, then
join with your base directory using filepath.Join(), and finally validate the
resolved path starts with your intended base directory using strings.HasPrefix().
Additionally, use filepath.Base() to extract only the filename without directory
components if you don't need to preserve directory structure. The rule recognizes
this sanitization pattern when filepath.Clean() or path.Clean() is combined with
prefix validation. Beyond path validation, consider limiting the uncompressed size
of files to prevent decompression bombs, validating file count limits, and using
file.Mode().IsRegular() to skip symbolic links which could point to arbitrary
system files. For maximum security, recommended to generate random filenames instead
of using archive-provided names, and extract to an application-specific directory
with restricted permissions rather than system directories.
OWASP:
- A5:2017-Broken Access Control
- A01:2021-Broken Access Control
go_injection_rule-ssrf¶
Summary:
Server Side Request Forgery (SSRF)
Severity: Medium
CWE: CWE-918
Description:
This rule detected user-controlled input from HTTP request parameters,
environment variables, or standard input flowing to Go HTTP client functions
including http.Get(), http.Post(), http.Head(), http.PostForm(),
http.NewRequest(), http.NewRequestWithContext(), and third-party libraries
like ftp.Dial(), ldap.DialURL(), smtp.Dial(), and
retryablehttp.NewRequest(). The taint analysis tracks untrusted data sources
through decoders and unmarshalers to network request sinks. When user input
controls URLs or connection parameters without validation, Server-Side Request
Forgery (SSRF) vulnerabilities arise that allow attackers to force the server
to access internal resources, cloud metadata endpoints (169.254.169.254), or
arbitrary systems, potentially exposing sensitive APIs, performing network
reconnaissance, or bypassing firewall rules and network segmentation.
Remediation:
Consider implementing a strict URL allowlist that validates user input
against approved domains using Go's url.Parse() to extract and validate the
scheme, host, and port components before making requests. Restrict allowed
protocols to http:// and https:// only, explicitly rejecting dangerous
schemes. Implement DNS rebinding protection by creating a custom
http.Transport with a DialContext function that resolves hostnames using
net.LookupIP() and blocks connections to private IP ranges (127.0.0.0/8,
10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16) and cloud metadata addresses
(169.254.169.254) by checking if resolved IPs are private, loopback,
multicast, or unspecified using methods like ip.IsPrivate() and
ip.IsLoopback(). Configure HTTP clients with custom transports that enforce
these restrictions at the network layer. Disable or strictly validate HTTP
redirects using http.Client.CheckRedirect to prevent redirect-based SSRF
bypasses. Network-level defenses can include running the application with
restricted user privileges or in isolated network segments with iptables or
firewall rules. Consider routing all outbound requests through a monitored
egress proxy. Use a server-side mapping approach where user input provides
keys that map to pre-configured safe URLs. For more information see OWASP: Server_Side_Request_Forgery
OWASP:
- A1:2017-Injection
- A10:2021-Server-Side Request Forgery
go_injection_rule-template-injection¶
Summary:
Improper neutralization of input during web page generation ('Cross-site Scripting')
Severity: Medium
CWE: CWE-79
Description:
Template injection vulnerability detected in template.HTML(), template.JS(),
template.URL(), or template.HTMLAttr() with non-constant input. These functions
bypass Go's automatic HTML escaping, allowing user input to be treated as markup or
script code. This can lead to Cross-Site Scripting (XSS) attacks where attackers
inject malicious JavaScript that executes in victims' browsers.
Remediation:
Consider avoiding template.HTML(), template.JS(), template.URL(), and
template.HTMLAttr() with user-controlled input entirely. If these types must be
used, recommended to only pass hardcoded constant strings that are defined at
compile time. Go's html/template package automatically escapes values, so normal
template rendering without these bypass functions provides safe output. If dynamic
content is required, validate and sanitize user input using strict allowlists.
OWASP:
- A1:2017-Injection
- A03:2021-Injection
go_leak_rule-pprof-endpoint¶
Summary:
Active debug code (pprof enabled)
Severity: Medium
CWE: CWE-489
Description:
Profiling endpoint /debug/pprof exposed via net/http/pprof import. This endpoint
does not require authentication and can be accessed by anonymous users, potentially
leaking sensitive application internals, memory contents, goroutine information, and
performance data. This should not be enabled in production environments.
Remediation:
Consider removing the net/http/pprof import from production code to completely
disable the profiling endpoint. If profiling is needed in production for debugging,
recommended to implement authentication and authorization checks before allowing
access to the /debug/pprof endpoints. Alternatively, consider serving pprof on
a separate internal port that is not exposed externally and is only accessible
from trusted networks.
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
go_memory_rule-integer-overflow¶
Summary:
Integer overflow or wraparound
Severity: Medium
CWE: CWE-190
Description:
Integer overflow detected when converting strconv.Atoi() return value to smaller types
(int32 or int16). Go's int type is architecture-dependent (32-bit or 64-bit), but
converting to fixed-size types without validation can cause overflow. This may lead to
unexpected application behavior such as incorrect calculations, logic errors, or security
vulnerabilities.
Remediation:
Consider validating the value returned from strconv.Atoi() before performing
type conversion to smaller integer types. Check that the value fits within the
target type's range by comparing against math.MaxInt16 or math.MaxInt32
constants. If the value exceeds the maximum (or is below the minimum), handle
the error appropriately rather than silently truncating. For more information,
see: math
OWASP:
- A1:2017-Injection
- A03:2021-Injection
go_http_rule-http-serve¶
Summary:
Allocation of resources without limits or throttling
Severity: Low
CWE: CWE-770
Description:
HTTP server created using http.ListenAndServe(), http.ListenAndServeTLS(),
http.Serve(), http.ServeTLS(), or http.Server{} without timeout configuration
is vulnerable to resource consumption attacks. An adversary may open thousands of
connections without completing requests or terminating connections, potentially causing
denial of service by exhausting server resources.
Remediation:
Consider avoiding the default http.ListenAndServe() and http.Serve() functions
in production environments as they cannot have timeouts configured. Recommended to
create a custom http.Server with explicit timeout values: ReadHeaderTimeout
(time to read request headers), ReadTimeout (total time to read request including
body), WriteTimeout (time before timing out response writes), and IdleTimeout
(wait time for next request with keep-alives). For additional protection, consider
using http.TimeoutHandler to set per-request timeouts at the handler level.
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
go_network_rule-bind-to-all-interfaces¶
Summary:
Binding to an unrestricted IP address
Severity: Low
CWE: CWE-1327
Description:
Service binding to all network interfaces detected. Using net.Listen() or tls.Listen()
with address "0.0.0.0" or "[::]" binds to all available network interfaces, potentially
exposing the service to unintended or unsecured networks. This can create security risks
if the service should only be accessible on specific interfaces.
Remediation:
Consider specifying a specific network interface IP address instead of binding
to all interfaces. Recommended approaches include retrieving the IP address from
an environment variable (e.g., os.Getenv("BIND_ADDRESS")), reading from a
configuration file, or programmatically determining the primary interface's IP
address. This ensures the service only listens on intended, secured network
interfaces.
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration
go_memory_rule-memoryaliasing¶
Summary:
Incorrect access of indexable resource ('Range Error')
Severity: Info
CWE: CWE-118
Description:
Memory aliasing detected in for ... range loop. The iteration variable is reused for each
loop iteration, always pointing to the same memory location. Taking the address of this
variable (&var) causes all references to point to the final iteration value, leading to
unexpected behavior when addresses are stored, passed to functions, or used in goroutines.
Remediation:
Consider fixing this issue using one of three approaches: (1) avoid taking the
address of the iteration variable entirely, (2) reassign the iteration variable
to a new local variable inside the loop (e.g., tmp := iterVar), or (3) use
the indexed address from the original collection (e.g., &collection[idx]).
Each approach ensures unique memory addresses for each iteration. For more
information, see: spec
OWASP:
- A6:2017-Security Misconfiguration
- A05:2021-Security Misconfiguration