The Wayback Machine - https://web.archive.org/web/20241001191659/https://www.geeksforgeeks.org/security-issues-in-c-language/
Open In App

Security issues in C language

Last Updated : 05 Dec, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

C is a very powerful and popular programming language. It was first developed in the 1970s. C language is used in programming Network drivers, Interpreters, and Compilers, etc.
Even though the C language is widely used in different systems still it has many security flaws associated with it. This article focuses on discussing security vulnerabilities in the C language. Mainly these security issues are related to vulnerable library functions, No bound checking for array and Pointers.

Vulnerable Library Functions:
CWE Codes: CWE – 242 , CWE – 120, CWE-77

1. Buffer And Memory Related:

a. gets(): This function is a part of the standard input-output library of the C language. It does not have any check for buffer size and malicious input can easily cause a buffer overflow.
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
 
// Driver code
int main()
{
    char buf[24];
    printf("Please enter your name and press <Enter>\n");
    gets(buf);
    printf("%s", buf);
    return 0;
}


Warning:

prog.c: In function ‘main’: 
prog.c:10:1: warning: implicit declaration of function ‘gets’ 
[-Wimplicit-function-declaration] 
gets(buf); 
^ 
/tmp/ccmwzcCQ.o: In function `main’: 
69c380139e12adbab30e0550af51f5a9.c:(.text+0x2e): warning: the `gets’ 
function is dangerous and should not be used. 

Output:

Input: 
GeeksforGeeks
Output: 
Please enter your name and press 
GeeksforGeeks 

Explanation:
In the above code, the attacker can give large chunk of data as input, and the gets() function will try to store all that data into the buffer without considering the buffer size which will eventually cause a buffer overflow situation that can further cause arbitrary code execution, information leak.

Mitigation:
To solve this issue with the gets() function. Programmers can use fgets() function. It limits the input length based on the buffer size.
Below is the C program to implement the above approach- 

C




// C program to implement
// the above approach
#include <stdio.h>
#define MAX 15
 
// Driver code
int main()
{
    char buf[MAX];
    fgets(buf, MAX, stdin);
    printf("%s", buf);
    return 0;
}


Output:

Input: GeeksforGeeks
Output: GeeksforGeeks 

Explanation:
In the above code, fgets() function is taking buffer size ‘MAX’ as an argument and it will only write data that can be safely stored into the buffer of that size without overflowing it.

b. strcpy(): This built-in function also doesn’t check for the buffer length and can overwrite memory locations based on the malicious input.If the buffer size of dest string is more than src string, then copy the src string to dest string with terminating NULL character. But if dest buffer is less than src then it will copy the content without terminating NULL character. The strings may not overlap, and the destination string must be large enough to receive the copy.
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>
 
// Driver code
int main()
{
    char str1[2];
    char str2[] = "GeeksforGeeks";
    strcpy(str1, str2);
    printf("Copied string is: %s\n", str1);
    return 0;
}


Output:

Input: 
GeeksforGeeks
Output: 
Copied string is: GeeksforGeeks 

Explanation:
In the above code, strcpy() function is trying to copy the string available on str2[] to str1[] which does not have enough space in a buffer allocated to handle that which will eventually result in a buffer overflow in the application.

Mitigation:
Use of strncpy() function instead of strcpy(). strncpy() limits the length of input based on the buffer size available.
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 24
 
// Driver code
int main()
{
    // 24 is the buffer size
    char str1[BUFFER_SIZE];
    char str2[] = "GeeksforGeeks";
 
    // Limits number of characters
    // to be copied
    strncpy(str1, str2, BUFFER_SIZE);
    printf("Copied string is: %s\n", str1);
    return 0;
}


Output:

Input: 
GeeksforGeeks
Output: 
Copied string is: GeeksforGeeks 

Explanation:
In the above code, strncpy() function is taking BUFFER_SIZE as an argument and it will only write data that can be safely stored into the str1[ ] without overflowing the buffer. Using strcpy() function to copy a large character array into a smaller one is dangerous, but if the string will fit, then it will not be worth the risk. If the destination string is not large enough to store the source string then the behavior of strcpy() is unspecified or undefined.

Note:
Other library functions with same type of vulnerability- calloc, malloc, realloc, strcat, memcpy.

2. Command execution Vulnerabilities:
If the attacker can control the command text or arguments to an external function call, then he can run arbitrary codes very easily.
Below is the C program to demonstrate the above concept- 

C




// C program to implement
// the above approach
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
// Driver code
int main()
{
    char str[40];
    fgets(str, 39, stdin);
    system(str);
    printf("%s", str);
}


Runtime Errors:

sh: 1: GeeksforGeeks: not found

Output:

Input: 
GeeksforGeeks
Output: 
GeeksforGeeks

Explanation:
In the above code, if the str is controlled by the attacker then he can execute any command to the system and can put the entire system at risk. Observed CVEs are CVE-1999-0067, CVE-2019-12921.

Mitigation:

  • Ensure that all external commands called from the program are statically created.
  • Use library calls rather than external processes to recreate the desired functionality.

Note:
Other library functions with the same type of vulnerability: execl, execle, popen. 

3. Format String Vulnerabilities:
Format specifiers like %d, %s if used in an improper way within the code than it may give the edge to the attacker for gaining access for arbitrary code execution, information leak and can also completely control the application. If successful, it returns the total number of characters written excluding null-character appended in the string, in case of failure a negative number is returned. 
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
 
// Driver code
int main()
{
    char str[5];
    sprintf(str, "%s",
            "GGGGGGGGGGGGGG");
    printf("%s", str);
}


Runtime Error:

Abort signal from abort(3) (SIGABRT) 

Explanation:
In this above code, the sprintf function with format specifier %s may cause a buffer overflow because the output size is 15 which is greater than the size of buffer received that is of size 5 only. 
Besides this, the str[ ] can also be controlled by a external agent and cause all the above mentioned vulnerabilities (CWE – 13 ). Observed CVEs are CVE-2001-0717, CVE-2002-1788, CVE-2006-2480 etc.

Mitigation:

  • Choose a language not have such flaws.
  • Ensure that all format string functions are passed a static string that cannot be controlled by the user.
  • Use functions that do not support the %n operator in format strings.

Note:
Other library functions with the same type of vulnerability: fprintf, printf, sprintf, snprintf.

Concept of Pointer:
The pointer concept causes multiple security issues with the C programming language.

1. NULL Pointer Dereference: CWE CODE: CWE-476. If a program dereference a pointer that is expected to be valid but turns out as NULL then it causes program crash, exit. Mitigation to this is to do a check for the NULL pointer before performing any operation. Observed CVEs are CVE-2005-3274, CVE-2005-1912, CVE-2004-0079 etc.
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
 
// Driver code
int main()
{
    int val = 1;
    int* p = NULL;
    *p = val;
    printf("%d", *p);
    return 0;
}


Runtime Error:

Segmentation Fault (SIGSEGV)

Explanation:
In this code, *p is a NULL pointer which means it does not point to a memory location and trying to dereference it results in unexpected behavior in the program or segmentation fault.

Mitigation:
Below is the C program to demonstrate the mitigation strategy for the above problem-

C




// C program to implement
// the above concept
#include <stdio.h>
 
// Driver code
int main()
{
    int val = 1;
    int* p = NULL;
    if (p == NULL) {
        printf("Pointer is NULL");
    }
    else {
        *p = val;
        printf("%d", *p);
    }
    return 0;
}


Output:

Pointer is NULL 

Explanation:
In this code, the first check is performed for a NULL pointer, before doing any operation on a pointer. Here is the if statement checks for the NULL condition and if it is found to be true then no further operation is getting executed.

2. Use after Free(Commonly referred to as Dangling pointer): CWE CODE: CWE-416. If a referencing memory is freed and then there is any attempt made to free that again, then it cause this situation. It can cause a program crash, information leak, and data corruption. Observed CVEs are CVE-2010-4168, CVE-2010-2941, CVE-2010-2547 etc.
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
int* fun()
{
    int y = 10;
    return &y;
}
 
// Driver code
int main()
{
    int* p = fun();
    printf("%d", *p);
    return 0;
}


Output: 

Segmentation Fault (SIGSEGV)

Explanation:
In the above code, the main() function the  *p contains the return value of the fun(). With the call of fun() the control moves to the context of the int *fun(), the fun() returns the address of the ‘y’ variable but in the context of main() ‘y’ is no longer available after the program flow returned. Therefore, it can be said that the *p is a dangling pointer as it points to the de-allocated memory.

Mitigation:
After freeing pointers set them to NULL. Below is the C program to demonstrate the above concept- 

C




// C program to implement
// the above approach
#include <stdio.h>
#include <stdlib.h>
 
// Driver code
int main()
{
    int n = 5;
    int* ptr;
    ptr = (int*)malloc(n * sizeof(int));
 
    // Memory has been successfully allocated
    printf("Memory successfully allocated using malloc.\n");
 
    // Free the memory
    free(ptr);
    printf("Malloc Memory successfully freed.\n");
 
    // freed pointer set to NULL value
    ptr = NULL;
 
    return 0;
}


Output:

Memory successfully allocated using malloc. 
Malloc Memory successfully freed. 

Explanation:
In this above code, after free(ptr) operation the ptr pointer value is set to NULL and it will mitigate the chances of a dangling pointer.

No bound Checking for Array:

1. Out of Bounds Write: CWE CODE: CWE-787 In this, the software writes the data before or after the intended buffer. It may cause execution of unauthorized codes, Crash and restart. Observed CVEs are CVE-2020-0022, CVE-2009-0269, CVE-2009-1532 etc.
Below is the C program to demonstrate the above concept-

C




// Program to demonstrate
// accessing array out of bounds
#include <stdio.h>
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    printf("arr [0] is %d\n", arr[0]);
    printf("arr[10] is %d\n", arr[10]);
 
    // allocation memory to out of bound
    // element
    arr[10] = 11;
    printf("arr[10] is %d\n", arr[10]);
    return 0;
}


Runtime Error:

Segmentation Fault (SIGSEGV)

Explanation:
In this above code, array has valid indexes 0, 1, 2, 3, and 4 but there is an attempt to write the value on the arr[10]. As the C compiler will not check for the array bound it will write that data after the intended buffer. But when there is an attempt to print the value at index 10, it will show an error.

Mitigation:

  • Always make sure the buffer is large enough.
  • Functions used to accept input should have a buffer limit implementation.

Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
int arr[5];
 
// Driver code
int main()
{
    int size = sizeof(arr) / sizeof(arr[0]);
 
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr;[i]);
    }
 
    // Print elements of array
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}


Output: 

Input: 1 2 3 4 5 6 7 8 9 10
Output: 1 2 3 4 5 

Explanation:
In the above code, the sizeof operator is being used to determine the size of the array so that one can get the valid range of the index. sizeof(arr) will give the entire size of the array and sizeof(arr[0]) will give the size of one element so using the divide operation one can easily find the number of elements in the array followed by the range of the index.

2. Out of Bounds Read: CWE CODE: CWE-125. In this, the software reads the data before or after the intended buffer. Attackers may use this to read sensitive information from other memory locations or may cause crashes.Observed CVEs are CVE-2014-0160, CVE-2009-2523, CVE-2004-0184 etc.
Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
int getValueFromArray(int* arr,
                      int size,
                      int index)
{
    int value = -1;
 
    // only maximum limit is there
    if (index < size) {
        value = arr[index];
    }
    return value;
}
 
// Driver code
int main()
{
    int arrtest[] = { 1, 2, 3, 4, 5 };
    int j = getValueFromArray(arrtest, 5, -1);
    printf("%d", j);
    return 0;
}


Output:

0

Explanation:
In this above code, the if statement within the function only checking the index value is less than the size of the array or not. The attacker may give a negative value as an index even that is not valid still the read operation will be executed which will eventually cause the reading of unintended data.

Mitigation:

  • Input validation.
  • Ensure to validate correct calculations for length of an argument, buffer size, etc.

Below is the C program to demonstrate the above concept-

C




// C program to implement
// the above approach
#include <stdio.h>
int getValueFromArray(int* arr,
                      int size,
                      int index)
{
    int value = -1;
 
    // only maximum limit and minimum
    // limit is there
    if (index >= 0 && index < size) {
        value = arr[index];
    }
    return value;
}
 
// Driver code
int main()
{
    int arrtest[] = { 1, 2, 3, 4, 5 };
    int j = getValueFromArray(arrtest, 5, -1);
    printf("%d", j);
    return 0;
}


Output: 

-1

Explanation:
In this code, both maximum and minimum index range is checked in the if statement. If the attacker tries to give invalid indexes then the read operation will not be performed.



Similar Reads

Difference Between C Language and LISP Language
C Language: C is the procedural Programming language. It was designed to be compiled using a compiler. The Language has small and fixed number of keywords like if/else, for, while,.. etc. We can use more than one assignment that may be used in one statement in this language. Functions are also used here, it can return values that can be ignored, wh
2 min read
fgets() and gets() in C language
For reading a string value with spaces, we can use either gets() or fgets() in C programming language. Here, we will see what is the difference between gets() and fgets(). fgets() The fgets() reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character
3 min read
isxdigit() function in C Language
isxdigit() function in C programming language checks that whether the given character is hexadecimal or not. isxdigit() function is defined in ctype.h header file. Hexadecimal equivalent of Decimal Numbers: Hexadecimal: 0 1 2 3 4 5 6 7 8 9 A B C D E F Decimal: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Syntax: char isxdigit( char x); Examples: Input : A
2 min read
isupper() function in C Language
isupper() function in C programming checks whether the given character is upper case or not. isupper() function is defined in ctype.h header file. Syntax : int isupper ( int x ); Examples: Input: A Output: Entered character is uppercase character Input: a Output: Entered character is not uppercase character Input: 1 Output: Entered character is not
2 min read
isalnum() function in C Language
isalnum() function in C programming language checks whether the given character is alphanumeric or not. isalnum() function defined in ctype.h header file. Alphanumeric: A character that is either a letter or a number. Syntax: int isalnum(int x); Examples: Input : 1 Output : Entered character is alphanumeric Input : A Output : Entered character is a
2 min read
trunc() , truncf() , truncl() in C language
All three functions are used to remove digits after decimal point and return the modified decimal number. trunc() : Truncates a double value after the decimal point and gives the integer part as the result. The return value and the arguments are of the type double. Syntax : double trunc(double x); Parameters: x :It takes a double value as an input
4 min read
How to clear console in C language?
It is one of the basic need a program may required i.e clear the console during execution time. Need of a clear console screen : A console screen must be cleared once its stated objectives have been completed. A user also needs a clear screen for new data. Like any other language, C offers a variety of ways to clear the console screen. The clear sc
7 min read
Assigning multiple characters in an int in C language
Consider the following C program. #include <stdio.h> int main(void) { int a = 'd'; printf("%d\n", a); /*OUTPUT - 100 (ASCII Code for character d)*/ int b = 'dd'; printf("%d", b); /*OUTPUT - 25700 (Explanation in detail given below)*/ return 0; } Output : 100 25700 We can easily guess that the output for 'd' is 100 as 100 i
1 min read
Difference between Java and C language
Here are some of the differences between Java and C language. C is much faster than Java Java is slower than C due to overhead. C Java C was developed by Dennis M. Ritchie between 1969 and 1973.Java was developed by James Gosling in 1995.C is a Procedural Programming Language.Java is Object-Oriented language.C is more procedure-oriented.Java is mor
3 min read
Similarities and Differences between Ruby and C language
Similarities between Ruby and C There are many similarities between C and Ruby, and some of them are: Like C, in Ruby alsoâ€Ķ A programmer is able to program procedurally if they like to do. But still, behind the scenes, it will be object-oriented.Both the languages have the same operators, for example, compound assignment and bitwise operators. But
3 min read
Introduction to the C99 Programming Language : Part I
Introduction: C99 is a standardized version of the C programming language that was published in 1999 by the International Organization for Standardization (ISO). It introduced a number of new features and improvements over the previous C89 standard, including support for variable-length arrays, flexible array members, complex numbers, and new keywo
8 min read
Introduction to the C99 Programming Language : Part II
In this article, we are going to discover some more interesting additions to C89 which gave us C99 standard: Variable Argument Lists: C99 brings out a small changes to the preprocessor. Macros can accept a variable number of arguments. These Macros are indicated by ellipsis (...) in their declaration. These Variable Arguments are represented by the
4 min read
Introduction to the C99 Programming Language : Part III
Kindly read Introduction to the C99 Programming Language (Part I) and Introduction to the C99 Programming Language (Part II) before reading this article. Addition of Library Functions: C99 provides some Additional Library functions listed below. Library Function Usage complex.h complex.h supports complex arithmetic fenv.h fenv.h gives access to flo
3 min read
Features of C Programming Language
C is a procedural programming language. It was initially developed by Dennis Ritchie in the year 1972. It was mainly developed as a system programming language to write an operating system. The main features of C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for sys
3 min read
Draw a smiley face using Graphics in C language
Prerequisite: graphics.h, How to include graphics.h in CodeBlocks? The task is to write a C program to draw a smiley face using graphics in C.To run the program we have the include the below header file: #include <graphic.h> Approach: We will create a Smiley Face with the help below functions: fillellipse(int x, int y, int x_radius, int y_rad
2 min read
Shopping Cart Project Using C Language
Online Shopping applications are one of the favorite applications out of all online applications. It is a very much used application in everyone's life. So, Let's try to create a Shopping cart using C language which can perform basic tasks for us. The functionality of the Shopping Cart Although online Shopping has many functionalities we can't incl
11 min read
Test Cases For Signup Page Using C Language
Prerequisite: Structure in C In this article, we are going to check on how to check test cases for the signup page using C language. The signup page is where we enter data to create our account on any of the websites or applications. A test case is a document that contains various sets of data, conditions to be performed, and the expected result fo
6 min read
C Programming Language Standard
Introduction:The C programming language has several standard versions, with the most commonly used ones being C89/C90, C99, C11, and C18. C89/C90 (ANSI C or ISO C) was the first standardized version of the language, released in 1989 and 1990, respectively. This standard introduced many of the features that are still used in modern C programming, in
6 min read
A C Programming Language Puzzle
Give a = 12 and b = 36 write a C function/macro that returns 3612 without using arithmetic, strings and predefined functions. We strongly recommend you to minimize your browser and try this yourself first. Below is one solution that uses String Token-Pasting Operator (##) of C macros. For example, the expression "a##b" prints concatenation of 'a' a
1 min read
Signals in C language
Prerequisite : Fork system call, Wait system call A signal is a software generated interrupt that is sent to a process by the OS because of when user press ctrl-c or another process tell something to this process. There are fix set of signals that can be sent to a process. signal are identified by integers. Signal number have symbolic names. For ex
5 min read
Difference between %d and %i format specifier in C language
A format specifier is a special character or sequence of characters used to define the type of data to be printed on the screen or the type of data to be scanned from standard input. A format specifier begins with a '%' character followed by the sequence of characters for different types of data. In short, it tells us which type of data to store an
3 min read
lvalue and rvalue in C language
lvalue:- lvalue simply means an object that has an identifiable location in memory (i.e. having an address). In any assignment statement "lvalue" must have the capability to store the data.lvalue cannot be a function, expression (like a+b) or a constant (like 3 , 4 , etc.). L-value: "l-value" refers to memory location which identifies an object. l-
4 min read
Difference between while(1) and while(0) in C language
Prerequisite: while loop in C/C++ In most computer programming languages, a while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition. The boolean condition is either true or false. while(1) It is an infinite loop which will run till a break statement is issued explicitly. Interestingly not
3 min read
kbhit in C language
kbhit() functionality is basically stand for the Keyboard Hit. This function is deals with keyboard pressing kbhit() is present in conio.h and used to determine if a key has been pressed or not. To use kbhit function in your program you should include the header file "conio.h". If a key has been pressed then it returns a non zero value otherwise re
2 min read
How to use POSIX semaphores in C language
Semaphores are very useful in process synchronization and multithreading. But how to use one in real life, for example say in C Language? Well, we have the POSIX semaphore library in Linux systems. Let's learn how to use it. The basic code of a semaphore is simple as presented here. But this code cannot be written directly, as the functions require
2 min read
Benefits of C language over other programming languages
C is a middle-level programming language developed by Dennis Ritchie during the early 1970s while working at AT&T Bell Labs in the USA. The objective of its development was in the context of the re-design of the UNIX operating system to enable it to be used on multiple computers. Earlier the language B was now used for improving the UNIX system
3 min read
Difference Between Matlab and C Language
Matlab and C are both powerful programming languages but they serve different purposes and have distinct features. In this article, we will learn the fundamental differences between Matlab and the C language. MATLABMATLAB stands for Matrix Laboratory and is a high-level programming language primarily used for numerical computing such as matrix mani
3 min read
Interesting Facts About C Language
C Programming language is a general purpose, case-sensitive, procedural programming language. It is one of the first and few high-level languages that is still popular among the coding community. It was developed by Dennis Ritchie and was first released in 1972. C programming language has a rich history and unique characteristics making it a topic
3 min read
Kahn’s Algorithm in C Language
In this post, we will see the implementation of Kahn's Algorithm in C language. What is Kahn's Algorithm?The Kahn's Algorithm is a classic algorithm used to the perform the topological sorting on the Directed Acyclic Graph (DAG). It produces a linear ordering of the vertices such that for every directed edge u→v vertex u comes before v. This algori
5 min read
Tarjan’s Algorithm in C Language
In this post, we will see the implementation of Tarjan's Algorithm in C language. What is Tarjan's Algorithm?Tarjan's Algorithm is a classic algorithm used for finding strongly connected components (SCCs) in a directed graph. An SCC is a maximal subgraph where every vertex is reachable from every other vertex in the subgraph. This algorithm is wide
5 min read
Article Tags :