DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • DataWeave: Play With Dates (Part 1)
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  • How to Convert XLS to XLSX in Java
  • Cosmos DB Disaster Recovery: Multi-Region Write Pitfalls and How to Evade Them
  1. DZone
  2. Software Design and Architecture
  3. Security
  4. Strategies in C to Avoid Common Buffer Overflow Errors

Strategies in C to Avoid Common Buffer Overflow Errors

How can you avoid common buffer overflow errors in C? Check out this strategy to prevent future vulnerabilities and ensure better security.

By 
Thiago Nascimento user avatar
Thiago Nascimento
DZone Core CORE ·
Jul. 06, 20 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
12.7K Views

Join the DZone community and get the full member experience.

Join For Free

Many are the variables to be considered in order to describe the relevance of a topic as cybercrimes. All of them represent a justification for employing efforts toward the development of a programming code each more secure. In this context, a very representative example is the costs related to crimes exploiting failures in insecure codes. Anderson et al. (2013) presented a synthetic vision of the financial damage caused by those criminal actions. According to the authors, the costs generated by cyber tax frauds summed a total of 125,000 millions of dollars only in the year 2011.

Although a huge number of vulnerabilities have already been identified, many other ones are found every year. Some of the most common ones are related to the manipulation of variables storing data of type String and Integer. In general, hackers and other types of attackers take advantage of unappropriated memory allocations or of errors during the operations involving those data types. A very typical exploited error is known as buffer overflow. Mitigation strategies to avoid this kind of threat requires a sharp domain of the programming language used for developing the code. Besides, a strong understanding of the computer hierarchy of memory and the way data are represented on them may help programmers to develop software more secure and less error-prone. Hereafter, the aforementioned vulnerabilities will be discussed more deeply and the accordingly mitigation strategies will also be described in more detail.

Common Buffer Overflow Vulnerabilities

According to Seacord (2013, p. 283) "a vulnerability is a set of conditions that allows violation of an explicit or implicit security policy". Several situations can lead to failures in the operations with integers. A common case involves truncation errors generated by trying to store a value in a data type that is smaller than necessary to represent it. The following code shows an example of such an error. Although the size of the two arguments of the program is calculated and summed considering one more position for the null-terminator, the data type used to store the result of the arithmetic operation can produce a truncation error (line 3). A malicious user could enter arguments whose total sum cannot be stored in an unsigned short type. In a situation like that, the dynamical allocation (line 4) executed for holding the concatenation of the two informed strings (lines 5 and 6) would not reserve the correct number of memory positions because of a truncation error.

C
 




x



1
int main(int argc, int *argv[]) {
2
    unsigned short int total;
3
    total = strlen(argv[1]) + strlen(argv[2]) + 1;
4
    char *buff = (char *) malloc(total);
5
    strcpy(buff, argv[1]);
6
    strcpy(buff, argv[2]);
7
    /* ... */
8
}


Another integer-related vulnerability is known as wraparound. CWE (2006) states that this failure takes place "when the logic assumes that the resulting value will always be larger than the original value". The second code below presents a real sample of that vulnerability which was identified by Peslyak (2000) in JPEG files (Alexander Peslyak is better known as Solar Designer). Two bytes are dedicated to comments in a JPEG file. Because of this, the len parameter is decremented by 2 (line 3) and memory is allocated for storing the comment (line 4). The function getComment assumes the len value will always be larger than 2. Nevertheless, if an attacker passes 1 as len value, a negative value is informed to the malloc function. In this case, the behavior is dependent on the function implementation, which can lead to unsecured execution flows.

C
 




xxxxxxxxxx
1
12



1
void getComment(size_t len, char *src) {
2
    size_t size;
3
    size = len - 2;
4
    char *comment = (char *) malloc(size + 1);
5
    memcpy(comment, src, size);
6
    return;
7
}
8

           
9
int main(int argc, int *argv[]) {
10
    getComment(1, "Comment ");
11
    return 0;
12
}


As well as it can be observed in Integer errors, the number of String-related vulnerabilities is also widely known. A simple error that represents a threat to the security of any system involves the null-termination of strings. The third code below describes an example of this error which was presented by Seacord (2013, p. 48). The loop depends on a condition to be satisfied in order to interrupt its iterations (line 5). Nevertheless, the value stored in the ntbs string is from a copy done via the strncpy function which copies only the number of characters passed to it - the copy does not include a null-terminator. Consequently, the generated ntbs string is not null-terminated.

C
 




xxxxxxxxxx
1



1
int main (void) {
2
    char ntbs[16];
3
    strncpy(ntbs, "0123456789abcdef", sizeof(ntbs));
4
    for (size_t i = 0; i < sizeof(ntbs); i++) {
5
        if (ntbs[i] == '\0') break;
6
        /* ... */
7
    }
8
    return 0;
9
}


Avoiding Buffer Overflow Errors

All the presented vulnerabilities can be mitigated by simple interventions on the code. The described string null-terminator error can be worked around by adding a succinct excerpt of code that is responsible for setting a null-terminator at the last position of the string. The code below shows a version of the vulnerable code with the null-terminator error fixed.

C
 




xxxxxxxxxx
1
10



1
int main (void) {
2
    char ntbs[17];
3
    strncpy(ntbs, "0123456789abcdef", sizeof(ntbs) - 1);
4
    ntbs[sizeof(ntbs) - 1] = '\0';
5
    for (size_t i = 0; i < sizeof(ntbs); i++) {
6
        if (ntbs[i] == '\0') break;
7
        /* ... */
8
    }
9
    return 0;
10
}


The wraparound error detailed in the second presented code may be avoided through the inclusion of a straightforward checking of the parameter len so that to ensure it is in the range of allowed values. Another very simple modification can also fix the truncation vulnerability presented in the first code. Since the problem involves storing eventual values that cannot be represented by an unsigned short int type, changing the type of the total variable to size_t it will guarantee a sufficient precision to represent the value.


Conclusion

The three types of considered vulnerabilities showed that an accurate manner to develop software code is enough to avoid many of the most commons security errors. This is the case of the buffer overflow String-related failures analyzed. By simply ensuring that a null-terminator is set at the end of each string, a well-known error can be worked around. In the same way, many Integer-related errors can be prevented by doing simple numbers bounds checking before carrying out an operation. Additional help to detect vulnerabilities of this type can be the use of some compilers configurations like the -ftrapv flag from GCC which according to Seacord (2013, p. 75) "generates traps for signed overflow" on some arithmetic operations.

Buffer overflow Data Types code style Vulnerability Strings

Published at DZone with permission of Thiago Nascimento. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Tired of Messy Code? Master the Art of Writing Clean Codebases
  • DataWeave: Play With Dates (Part 1)
  • The Long Road to Java Virtual Threads
  • Exploring Exciting New Features in Java 17 With Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!