Home > Articles > Programming

Silent Elimination of Bounds Checks

  • Print
  • + Share This
Increasingly, compiler writers are taking advantage of undefined behaviors in the C and C++ programming languages to improve optimizations. Frequently, these optimizations are interfering with the ability of developers to perform cause-effect analysis on their source code—that is, analyzing the dependence of downstream results on prior results. Expert programmer Robert C. Seacord, author of Secure Coding in C and C++, Second Edition, shows how these optimizations are eliminating causality in software and are increasing the probability of software faults, defects, and vulnerabilities.
Like this article? We recommend

The C language supports pointer arithmetic where one operand is a pointer to an object and the other operand is an integer. When an expression that has an integer type is added to a pointer, the result has the type of the pointer operand.

Pointer arithmetic in C is primarily meant to support the manipulation of a pointer within an array of elements, as in the following example:

int a[2] = {1, 2}; 
int main(void) { 
  int j = 0; 
  for (int * pi = &a[0]; pi < &a[2]; ++pi) j += *pi; 
  return j;
}

This same program can be rewritten in an equivalent form using array notation:

int a[2] = {1, 2}; 
int main(void) { 
  int j = 0;
  for (int i = 0; i < 2; ++i) j += a[i]; 
  return j; 
}

Array indexing is equivalent to pointer arithmetic, but it is pointer arithmetic performed by the compiler, not the coder. An expression such as a[i], for example, is translated to *(a+i).

Provided the pointer operand and the result point to elements of the same array object during pointer arithmetic, or to one past the last element of the array object, the evaluation is well defined; otherwise, the behavior is undefined.

Undefined Behaviors

C programmers are not always entirely familiar with the implications of undefined behavior. The C Standard [ISO/IEC 2011] defines undefined behavior as behavior, upon use of a nonportable or erroneous program construct or of erroneous data, for which the standard imposes no requirements. Conforming implementations can deal with undefined behavior in a variety of fashions, such as:

  • Ignoring the situation completely, with unpredictable results
  • Translating or executing the program in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message)
  • Terminating a translation or execution (with the issuance of a diagnostic message)

Undefined behaviors are extremely dangerous, both because they need not be diagnosed and because they can result in any behavior. Most of the security vulnerabilities described in my book, Secure Coding in C and C++, Second Edition, are the result of exploiting undefined behavior in code.

Another problem with undefined behavior is compiler optimizations. Because compilers are not obligated to generate code for undefined behavior, these behaviors are candidates for optimization. By assuming that undefined behavior will not occur, compilers can generate code with better performance characteristics.

Compiler Optimizations

The basic design of an optimizer for a C compiler is largely the same as that of an optimizer for any other procedural programming language. The fundamental principle of optimization is to replace a computation with a more efficient method that computes the same result.

However, some optimizations change behavior. In some cases, these optimizations are beneficial and eliminate undefined behaviors and vulnerabilities; in other cases, these optimizations may inadvertently introduce vulnerabilities.

Compiler developers may choose between several behavior models when translating code. However, compiler writers are not obligated to follow any particular model and are often opportunistic about which model to apply in any given situation.

The first of these is the hardware behavior model. Compilers that follow this model generate code as if the undefined behavior were defined to be whatever action the hardware instructions would take if the undefined behavior occurred. For example, if the hardware instruction wrapped around on signed integer overflow, the compiler would simply treat the wraparound as the defined behavior for integer overflow. For many years, this policy was nearly universal, so several generations of C and C++ programmers have assumed that all compilers behave this way.

Another model is super debug. Compiler vendors that follow this model provide an intensive debugging environment to trap (nearly) every undefined behavior. This policy severely degrades the application’s performance, so it is seldom used for building applications.

Finally, the total license model allows compiler writers to treat any possible undefined behavior as a “can’t-happen” condition, permitting aggressive optimizations.

Vulnerabilities Resulting from Undefined Behaviors

Increasingly, compiler writers are taking advantage of undefined behavior in the C programming languages to improve optimizations. These optimizations frequently interfere with the ability of developers to perform cause-effect analysis on their source code—that is, to analyze the dependence of downstream results on prior results. Consequently, these optimizations eliminate causality in software and increase the probability of software faults, defects, and vulnerabilities. One such occurrence afflicted Plan 9’s sprint() function and is further documented in CERT Vulnerability Note VU#162289, “C compilers may silently discard some wraparound checks.”

In general, a programmer might code a bounds-check such as

  char *ptr; // ptr to start of array
  char *max; // ptr to end of array
  size_t len; 
  if (ptr + len > max)
    return EINVAL;

No matter what behavior model is used, there is a bug. If len is very large, it can cause ptr + len to overflow, which creates undefined behavior. Under the hardware behavior model, the result would typically wrap around—pointing to an address that is actually lower in memory than ptr.

In attempting to fix the bug, the experienced programmer (who has internalized the hardware behavior model of undefined behavior) might write a check like this:

  if (ptr + len < ptr || ptr + len > max)
    return EINVAL;

However, compilers that follow the total license model may optimize out the first part of the check, leaving the whole bounds check defeated. This optimization is allowed because ptr plus (an unsigned) len can compare less than ptr only when an undefined behavior occurred during calculation of ptr + len. The compiler legitimately assumes that undefined behavior never happens; consequently, ptr + len < ptr is dead code and can be removed.

Optimizations may be performed for comparisons between P + V1 and P + V2, where P is the same pointer and V1 and V2 are variables of some integer type. The total license model permits this expression to be reduced to a comparison between V1 and V2.

In our example,

  if (ptr + len < ptr || ptr + len > max)
    return EINVAL;

this optimization translates as follows:

  ptr + len < ptr 
  ptr + len < ptr + 0
  len < 0 (impossible, len is unsigned)

However, if V1 or V2 are such that the sum with P overflows, then the comparison of V1 and V2 will not yield the same result as actually computing P + V1 and P + V2 and comparing the sums. Because of possible overflows, computer arithmetic does not always obey the algebraic identities of mathematics.

This problem is easy to remediate once it is called to the attention of the programmer. For example, if it is known that ptr is less than or equal to max, then the programmer could write

  if (len > max – ptr)
    return EINVAL;

This conditional expression eliminates the possibility of undefined behavior.

In this example, the expression buf + n may wrap for large values of n, resulting in undefined behavior.

  int f(char *buf, size_t n) {
    return buf + n < buf + 100;
  }

When compiled using GCC 4.3.0 with the -O2 option, for example, the expression

  buf + n < buf + 100 

is optimized to n < 100, eliminating the possibility of wrapping. This behavior is usually not an issue unless one expression wraps but the other does not. This code example is still incorrect, because it is not safe to rely on compiler optimizations for security.

The undefined behavior can be eliminated by performing the optimization by hand:

  int f(char * buf, size_t n) {
    return n < 100;
  }

Recommendations

The pointer overflow behavior that caused the vulnerability in Plan 9’s sprint() function changed as of GCC 4.2.4, GCC 4.3.1, and GCC 4.4.0, and all subsequent versions 4.2.x where x >= 4, versions 4.3.y where y >= 1, and versions 4.z where z >= 4.

The optimization is performed by default at -O2 and above, including –Os, but it is not performed by default at -O1 or -O0. The optimization may be enabled for -O1 with the -fstrict-overflow option or disabled for -O2 and above with the -fno-strict-overflow option. Cases where optimization occurs may be detected by using -Wstrict-overflow=N where N >= 3.

C and C++ programmers must be very careful to avoid undefined behaviors in their code. Compilers that implement the total license model are becoming increasingly common; such compilers have the latitude to change how they compile undefined behaviors at any time, and they frequently do so to further optimize code. Consequently, the results produced by code that depends on undefined behaviors can change arbitrarily without notice.

Programmers frequently overreact by disabling optimizations in their code. Optimizations are just as likely to eliminate vulnerabilities from code as they are to introduce them. Diagnostics such as -Wstrict-overflow can be very useful to identify cases where the compiler optimizes based on the assumption that signed overflow does not occur. Frequently these optimizations are harmless; sometimes they can be surprising.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020