8 examples

Buffer overflow

Data exceeds allocated memory, risking crashes or security issues.

[ FAQ1 ]

What is a buffer overflow error?

A buffer overflow error happens when a program attempts to write data beyond the boundaries of allocated memory, known as a buffer. Buffers are used to temporarily store data, but each buffer has a specific, fixed size. If too much data is written into the buffer, excess data spills over into adjacent memory locations. This can lead to unpredictable behavior, crashes, or even security vulnerabilities, as attackers may exploit the overflow to execute malicious code or gain unauthorized access. Languages like C and C++ are particularly vulnerable since they allow direct memory manipulation without built-in safety checks.
[ FAQ2 ]

How to fix buffer overflow error

Preventing buffer overflow errors involves careful programming practices and rigorous checks. Use functions that perform bounds checking (for example, replacing strcpy with safer alternatives like strncpy or strlcpy in C/C++) to ensure data doesn't exceed allocated buffer size. Employ modern memory-safe languages or tools, or implement explicit size checks before data manipulation. Utilize compiler security features (like stack canaries or address space layout randomization (ASLR)) to mitigate exploitation risks. Additionally, regularly performing code reviews and static analysis helps detect and resolve potential buffer overflow issues early in the development process.
diff block
+import { z } from "zod";
+
+import { BaseSecretRotationSchema } from "@app/components/secret-rotations-v2/forms/schemas/base-secret-rotation-v2-schema";
+import { PasswordRequirementsSchema } from "@app/components/secret-rotations-v2/forms/schemas/shared";
+import { DistinguishedNameRegex } from "@app/helpers/string";
+import { SecretRotation } from "@app/hooks/api/secretRotationsV2";
+
+export const LdapPasswordRotationSchema = z
+ .object({
+ type: z.literal(SecretRotation.LdapPassword),
+ parameters: z.object({
+ dn: z
+ .string()
+ .trim()
+ .regex(DistinguishedNameRegex, "Invalid Distinguished Name format")
+ .min(1, "Distinguished Name (DN) required"),
Greptile
greptile
style: Consider adding max length validation for DN to prevent buffer overflow attacks
diff block
pass
def read_form_data(self):
- size = int(self.headers["Content-Length"])
- data = yield from self.reader.read(size)
+ size = int(self.headers[b"Content-Length"])
+ data = yield from self.reader.readexactly(size)
Greptile
greptile
logic: potential buffer overflow risk - no size limit check on Content-Length header value
diff block
+import * as ExifReader from "exifreader";
+import type { Tags } from "exifreader";
+import fs from "node:fs/promises";
+
+import { showActionToast, showFailureToast } from "./toast";
+
+const handleError = (error: unknown) => {
+ console.error(error);
+
+ if (error instanceof Error) {
+ showFailureToast("Failed to load EXIF data", error);
+ }
+};
+
+// Type guard to check if a value is a tag-like object
+const isTagLikeObject = (value: unknown): value is { value: unknown; description: string } => {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ 'value' in value &&
+ 'description' in value
+ );
+};
+
+// Type guard to check if a value is an object
+const isObject = (value: unknown): value is Record<string, unknown> => {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+};
+
+// Recursive function to convert tags with strict typing
+const convertTag = <T>(value: T): T => {
+ // Handle null and undefined
+ if (value === null || value === undefined) return value;
+
+ // Handle arrays
+ if (Array.isArray(value)) {
+ return value.map(convertTag) as T;
+ }
+
+ // Handle tag-like objects
+ if (isTagLikeObject(value)) {
+ return value;
+ }
+
+ // Handle nested objects
+ if (isObject(value)) {
+ const convertedObj: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value)) {
+ convertedObj[k] = convertTag(v);
+ }
+ return convertedObj as T;
+ }
+
+ // For primitive values, wrap in an object with value and description
+ return {
+ value,
+ description: String(value)
+ } as T;
+};
+
+const decodeUnicodeComment = (value: unknown): string => {
+ // Only handle arrays of numbers
+ if (!Array.isArray(value) || !value.every(v => typeof v === 'number')) {
+ return String(value);
+ }
+
+ // Check if it starts with "UNICODE\0"
+ const header = [85, 78, 73, 67, 79, 68, 69, 0];
+ if (value.length > header.length && header.every((byte, i) => value[i] === byte)) {
+ // Skip the header and get the text bytes
+ const textBytes = value.slice(header.length);
+
+ // Convert pairs of bytes to characters
+ let result = '';
+ for (let i = 0; i < textBytes.length; i += 2) {
+ // Combine two bytes into a single UTF-16 code unit (big-endian)
+ const codeUnit = (textBytes[i] << 8) | textBytes[i + 1];
+ result += String.fromCharCode(codeUnit);
+ }
Greptile
greptile
logic: Potential buffer overflow if textBytes.length is odd. Should check length before accessing i+1.
diff block
int len = 0;
int ciphertext_len = 0;
+ // We need to change the plaintext into a PackedByteArray.
+ PackedByteArray plaintext_bytes;
+ const char *utf8 = plaintext.utf8().get_data();
+ plaintext_bytes.resize(strlen(utf8));
+ memcpy(plaintext_bytes.ptrw(), utf8, strlen(utf8));
Greptile
greptile
logic: Potential buffer overflow - strlen(utf8) doesn't account for null terminator and may return incorrect length for UTF-8 strings with multi-byte characters
suggested fix
+ const CharString& utf8 = plaintext.utf8();
+ plaintext_bytes.resize(utf8.length());
+ memcpy(plaintext_bytes.ptrw(), utf8.get_data(), utf8.length());
diff block
error!("Error reading data from disk: {}", e);
std::process::exit(1);
}
- if buffer != data {
+ let first_diff = first_difference(&data, &buffer);
+ if let Some(index) = first_diff {
error!(
- "Data mismatch on line {}: expected {:?}..., got {:?}...",
+ "Data mismatch on line {}: expected {:?}..., got {:?}... at index {}",
line_num + 1,
- &data[..10],
- &buffer[..10]
+ &buffer[index..index + 10],
+ &data[index..index + 10],
+ index
Greptile
greptile
logic: Potential buffer overflow if index + 10 exceeds buffer length. Need bounds checking.
suggested fix
+ &buffer[index..std::cmp::min(index + 10, buffer.len())],
+ &data[index..std::cmp::min(index + 10, data.len())],
index
diff block
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAKeyGenParameterSpec;
import java.util.Base64;
+import javax.xml.bind.DatatypeConverter;
+import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CryptoUtil {
- private static final BigInteger[] FERMAT_PRIMES =
- { BigInteger.valueOf(3),
- BigInteger.valueOf(5),
- BigInteger.valueOf(17),
- BigInteger.valueOf(257),
- BigInteger.valueOf(65537) };
-
- public static KeyPair generateKeyPair() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
- KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
- RSAKeyGenParameterSpec kpgSpec = new RSAKeyGenParameterSpec(2048, FERMAT_PRIMES[new SecureRandom().nextInt(FERMAT_PRIMES.length)]);
- keyPairGenerator.initialize(kpgSpec);
- //keyPairGenerator.initialize(2048);
- return keyPairGenerator.generateKeyPair();
+ private static final BigInteger[] FERMAT_PRIMES = {
+ BigInteger.valueOf(3),
+ BigInteger.valueOf(5),
+ BigInteger.valueOf(17),
+ BigInteger.valueOf(257),
+ BigInteger.valueOf(65537)
+ };
+
+ public static KeyPair generateKeyPair()
+ throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
+ KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
+ RSAKeyGenParameterSpec kpgSpec =
+ new RSAKeyGenParameterSpec(
+ 2048, FERMAT_PRIMES[new SecureRandom().nextInt(FERMAT_PRIMES.length)]);
+ keyPairGenerator.initialize(kpgSpec);
+ // keyPairGenerator.initialize(2048);
+ return keyPairGenerator.generateKeyPair();
+ }
+
+ public static String getPrivateKeyInPEM(KeyPair keyPair) {
+ String encodedString = "-----BEGIN PRIVATE KEY-----\n";
+ encodedString =
+ encodedString
+ + new String(
+ Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()),
+ Charset.forName("UTF-8"))
+ + "\n";
+ encodedString = encodedString + "-----END PRIVATE KEY-----\n";
+ return encodedString;
+ }
+
+ public static String signMessage(String message, PrivateKey privateKey) {
+
+ log.debug("start signMessage");
+ String signature = null;
+
+ try {
+ // Initiate signature verification
+ Signature instance = Signature.getInstance("SHA256withRSA");
+ instance.initSign(privateKey);
+ instance.update(message.getBytes("UTF-8"));
+
+ // actual verification against signature
+ signature = new String(Base64.getEncoder().encode(instance.sign()), Charset.forName("UTF-8"));
+
+ log.info("signe the signature with result: {}", signature);
+ } catch (Exception e) {
+ log.error("Signature signing failed", e);
}
- public static String getPrivateKeyInPEM(KeyPair keyPair) {
- String encodedString = "-----BEGIN PRIVATE KEY-----\n";
- encodedString = encodedString+new String(Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()),Charset.forName("UTF-8"))+"\n";
- encodedString = encodedString+"-----END PRIVATE KEY-----\n";
- return encodedString;
+ log.debug("end signMessage");
+ return signature;
+ }
+
+ public static boolean verifyMessage(
+ String message, String base64EncSignature, PublicKey publicKey) {
+
+ log.debug("start verifyMessage");
+ boolean result = false;
+
+ try {
+
+ base64EncSignature = base64EncSignature.replace("\r", "").replace("\n", "").replace(" ", "");
+ // get raw signature from base64 encrypted string in header
+ byte[] decodedSignature = Base64.getDecoder().decode(base64EncSignature);
+
+ // Initiate signature verification
+ Signature instance = Signature.getInstance("SHA256withRSA");
+ instance.initVerify(publicKey);
+ instance.update(message.getBytes("UTF-8"));
+
+ // actual verification against signature
+ result = instance.verify(decodedSignature);
+
+ log.info("Verified the signature with result: {}", result);
+ } catch (Exception e) {
+ log.error("Signature verification failed", e);
}
- public static String signMessage(String message, PrivateKey privateKey) {
-
- log.debug("start signMessage");
- String signature = null;
-
- try {
- //Initiate signature verification
- Signature instance = Signature.getInstance("SHA256withRSA");
- instance.initSign(privateKey);
- instance.update(message.getBytes("UTF-8"));
-
- //actual verification against signature
- signature = new String(Base64.getEncoder().encode(instance.sign()), Charset.forName("UTF-8"));
-
- log.info("signe the signature with result: {}", signature);
- } catch (Exception e) {
- log.error("Signature signing failed", e);
- }
-
- log.debug("end signMessage");
- return signature;
- }
-
- public static boolean verifyMessage(String message, String base64EncSignature,
- PublicKey publicKey) {
-
- log.debug("start verifyMessage");
- boolean result = false;
-
- try {
-
- base64EncSignature = base64EncSignature.replace("\r", "").replace("\n", "")
- .replace(" ", "");
- //get raw signature from base64 encrypted string in header
- byte[] decodedSignature = Base64.getDecoder().decode(base64EncSignature);
-
- //Initiate signature verification
- Signature instance = Signature.getInstance("SHA256withRSA");
- instance.initVerify(publicKey);
- instance.update(message.getBytes("UTF-8"));
-
- //actual verification against signature
- result = instance.verify(decodedSignature);
-
- log.info("Verified the signature with result: {}", result);
- } catch (Exception e) {
- log.error("Signature verification failed", e);
- }
-
- log.debug("end verifyMessage");
- return result;
- }
-
- public static boolean verifyAssignment(String modulus, String signature, PublicKey publicKey) {
-
- /* first check if the signature is correct, i.e. right private key and right hash */
- boolean result = false;
-
- if (modulus != null && signature != null) {
- result = verifyMessage(modulus, signature, publicKey);
-
- /*
- * next check if the submitted modulus is the correct modulus of the public key
- */
- RSAPublicKey rsaPubKey = (RSAPublicKey) publicKey;
- if (modulus.length()==512) {
- modulus = "00".concat(modulus);
- }
- result = result && (DatatypeConverter.printHexBinary(rsaPubKey.getModulus().toByteArray()).equals(modulus.toUpperCase()));
- }
- return result;
-
- }
-
- public static PrivateKey getPrivateKeyFromPEM(String privateKeyPem) throws NoSuchAlgorithmException, InvalidKeySpecException {
- privateKeyPem = privateKeyPem.replace("-----BEGIN PRIVATE KEY-----", "");
- privateKeyPem = privateKeyPem.replace("-----END PRIVATE KEY-----", "");
- privateKeyPem = privateKeyPem.replace("\n", "").replace("\r", "");
-
-
- byte [] decoded = Base64.getDecoder().decode(privateKeyPem);
-
- PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decoded);
- KeyFactory kf = KeyFactory.getInstance("RSA");
- return kf.generatePrivate(spec);
- }
+ log.debug("end verifyMessage");
+ return result;
+ }
+
+ public static boolean verifyAssignment(String modulus, String signature, PublicKey publicKey) {
+
+ /* first check if the signature is correct, i.e. right private key and right hash */
+ boolean result = false;
+
+ if (modulus != null && signature != null) {
+ result = verifyMessage(modulus, signature, publicKey);
+
+ /*
+ * next check if the submitted modulus is the correct modulus of the public key
+ */
+ RSAPublicKey rsaPubKey = (RSAPublicKey) publicKey;
+ if (modulus.length() == 512) {
+ modulus = "00".concat(modulus);
+ }
Greptile
greptile
logic: Prepending '00' to modulus without validation could lead to buffer overflow - should verify max length
diff block
+//
+// AnalyticsManager.swift
+// Onit
+//
+// Created by Kévin Naudin on 21/05/2025.
+//
+
+import ApplicationServices
+import AppKit
+import Defaults
+import PostHog
+
+struct AnalyticsManager {
+ static func getCommonProperties() -> [String: Any] {
+ let deviceModel: String = {
+ var size: size_t = 0
+ sysctlbyname("hw.model", nil, &size, nil, 0)
+ var model = [Int8](repeating: 0, count: size)
+ sysctlbyname("hw.model", &model, &size, nil, 0)
+ if let lastIndex = model.firstIndex(of: 0) {
+ model.removeSubrange(lastIndex...)
+ }
+ return String(decoding: model.map(UInt8.init), as: UTF8.self)
+ }()
Greptile
greptile
logic: sysctlbyname can return -1 on error. Add error handling to prevent silent failures and potential buffer overflows
diff block
},
})
- const readSessionFromBatch = async (
- batchBuffer: Buffer,
- blockMetadata: SessionBlockMetadata
- ): Promise<[string, any][]> => {
- const sessionBuffer = batchBuffer.subarray(
- blockMetadata.blockStartOffset,
- blockMetadata.blockStartOffset + blockMetadata.blockLength
- )
+ const readSessionFromBatch = async (blockMetadata: SessionBlockMetadata): Promise<[string, any][]> => {
+ // Extract the byte range from the URL
+ const match = blockMetadata.blockUrl?.match(/bytes=(\d+)-(\d+)/)
+ if (!match) {
+ throw new Error('Invalid block URL format')
Greptile
greptile
logic: endOffset + 1 in subarray call could potentially cause a buffer overflow if endOffset equals buffer length
suggested fix
+ const sessionBuffer = batchBuffer.subarray(startOffset, Math.min(endOffset + 1, batchBuffer.length))