Blog | G5 Cyber Security

Safe String Functions in Code

TL;DR

String functions are powerful but can cause problems if used carelessly (especially with user input). This guide shows how to use them safely, preventing crashes and security issues.

1. Understand the Risks

Common string function risks include:

2. Choosing Safer Alternatives

Many languages offer safer string functions than older, potentially dangerous ones.

3. Using `strncpy` Correctly (C/C++)

While better than strcpy, strncpy still requires care.

  1. Always specify the buffer size: This prevents writing past the end of your string.
    char dest[20];
    const char *src = "This is a long string";
    sncpy(dest, src, sizeof(dest) - 1); // Leave space for null terminator
  2. Null-terminate the destination: strncpy doesn’t automatically add a null terminator if it copies fewer characters than the buffer size. You *must* do this manually.
    dest[sizeof(dest) - 1] = ' ';

4. Avoiding Format String Vulnerabilities

Never use user input directly in the format string of functions like printf or fprintf.

  1. Use placeholders: Pass user input as arguments to the function.
    char *user_input = "Some text";
    printf("User input: %s", user_input); // Correct
    // printf(user_input); // WRONG! Vulnerable to format string attacks

5. Input Validation and Sanitisation

Before using any user-provided string, validate and sanitise it.

6. Example: Safe String Concatenation in C

Demonstrates a safer approach to string concatenation.

#include 
#include 

int main() {
  char base[50] = "Initial text: ";
  char addition[20] = "Added content";
  size_t base_len = strlen(base);
  size_t addition_len = strlen(addition);

  if (base_len + addition_len < sizeof(base)) {
    strcat(base, addition); // Safe because we checked the length
    printf("%sn", base);
  } else {
    printf("String concatenation would overflow buffer.n");
  }

  return 0;
}

7. cyber security Considerations

Always treat user input as potentially malicious. Proper string handling is a crucial part of preventing injection attacks and other cyber security vulnerabilities.

Exit mobile version