Home > Articles > Programming > C/C++

Preface to The CERT® C Coding Standard, second edition

  • Print
  • + Share This
Robert Seacord introduces the second edition of The CERT® C Coding Standard: 98 Rules for Developing Safe, Reliable, and Secure Systems, which provides rules for coding in the C programming language safely, reliably, and securely.
From the book

The CERT® C Coding Standard, second edition, provides rules for coding in the C programming language. The goal of these rules is to develop safe, reliable, and secure systems, for example, by eliminating undefined behaviors that can lead to unexpected program behaviors and exploitable vulnerabilities. Conformance to the coding rules defined in this standard are necessary (but not sufficient) to ensure the safety, reliability, and security of software systems developed in the C programming language. It is also necessary, for example, to have a safe and secure design. Safety-critical systems typically have stricter requirements than are imposed by this coding standard, for example, requiring that all memory be statically allocated. However, the application of this coding standard will result in high-quality systems that are reliable, robust, and resistant to attack.

Each rule consists of a title, a description, and noncompliant code examples and compliant solutions. The title is a concise, but sometimes imprecise, description of the rule. The description specifies the normative requirements of the rule. The noncompliant code examples are examples of code that would constitute a violation of the rule. The accompanying compliant solutions demonstrate equivalent code that does not violate the rule, or any other rules in this coding standard.

A well-documented and enforceable coding standard is an essential element of coding in the C programming language. Coding standards encourage programmers to follow a uniform set of rules determined by the requirements of the project and organization rather than by the programmer’s familiarity. Once established, these standards can be used as a metric to evaluate source code (using manual or automated processes).

CERT’s Coding Standards are being widely adopted by industry. Cisco Systems, Inc., announced its adoption of the CERT C Secure Coding Standard as a baseline programming standard in its product development in October 2011 at Cisco’s annual SecCon conference. Recently, Oracle has integrated all of CERT’s secure coding standards into its existing Secure Coding Standards. Note that this adoption is the most recent step of a long collaboration: CERT and Oracle previously worked together in authoring The CERT® Oracle Secure Coding Standard for Java (Addison-Wesley, 2011).

Scope

The CERT® C Coding Standard, second edition, was developed specifically for versions of the C programming language defined by

  • ISO/IEC 9899:2011 ISO/IEC. Programming Languages—C, Third Edition. [ISO/IEC 9899:2011]
  • ISO/IEC 9899:2011/Cor.1:2012, Technical Corrigendum 1

The CERT® C Coding Standard, second edition, updates and replaces The CERT® C Secure Coding Standard (Addison-Wesley, 2008). The scope of the first edition of this book is C99 (the second edition of the C Standard). Although the rules in this book were developed for C11, they can also be applied to earlier versions of the C programming language, including C99. Variations between versions of the C Standard that would affect the proper application of these rules are noted where applicable.

Most rules have a noncompliant code example that is a C11-conforming program to ensure that the problem identified by the rule is within the scope of the standard. However, the best solutions to coding problems are often platform specific. In many cases, this standard provides appropriate compliant solutions for both POSIX and Windows operating systems. Language and library extensions that have been published as ISO/IEC technical reports or technical specifications are frequently given precedence, such as those described by ISO/IEC TR 24731-2 Extensions to the C Library—Part II: Dynamic Allocation Functions [ISO/IEC TR 24731-2:2010]. In many cases, compliant solutions are also provided for specific platforms such as Linux or OpenBSD. Occasionally, interesting or illustrative implementation-specific behaviors are described.

Rationale

A coding standard for the C programming language can create the highest value for the longest period of time by focusing on the C Standard (C11) and the relevant post-C11 technical reports.

The C Standard documents existing practice where possible. That is, most features must be tested in an implementation before being included in the standard. The CERT® C Coding Standard, second edition has a different purpose: to establish a set of best practices, which sometimes requires introducing new practices that may not be widely known or used when existing practices are inadequate. To put it a different way, The CERT® C Coding Standard, second edition, attempts to drive change rather than just document it.

For example, the optional but normative Annex K, “Bounds-Checking Interfaces,” introduced in C11, is gaining support but at present is implemented by only a few vendors. It introduces functions such as memcpy_s(), which serve the purpose of security by adding the destination buffer size to the API. A forward-looking document could not reasonably ignore these functions simply because they are not yet widely implemented. The base C Standard is more widely implemented than Annex K, but even if it were not, it is the direction in which the industry is moving. Developers of new C code, especially, need guidance that is usable on and makes the best use of the compilers and tools that are now being developed.

Some vendors have extensions to C, and some also have implemented only part of the C Standard before stopping development. Consequently, it is not possible to back up and discuss only C99, C95, or C90. The vendor support equation is too complicated to draw a line and say that a certain compiler supports exactly a certain standard. Whatever demarcation point is selected, different vendors are on opposite sides of it for different parts of the language. Supporting all possibilities would require testing the cross-product of each compiler with each language feature. Consequently, we have selected a demarcation point that is the most recent in time so that the rules defined by the standard will be applicable for as long as possible. As a result of the variations in support, source-code portability is enhanced when the programmer uses only the features specified by C99. This is one of many trade-offs between security and portability inherent to C language programming.

The value of forward-looking information increases with time before it starts to decrease. The value of backward-looking information starts to decrease immediately.

For all of these reasons, the priority of this standard is to support new code development using C11 and the post-C11 technical reports that have not been incorporated into the C Standard. A close-second priority is supporting remediation of old code using C99 and the technical reports.

This coding standard does make contributions to support older compilers when these contributions can be significant and doing so does not compromise other priorities. The intent is not to capture all deviations from the C Standard but to capture only a few important ones.

Issues Not Addressed

A number of issues are not addressed by this coding standard.

Coding Style

Coding style issues are subjective, and it has proven impossible to develop a consensus on appropriate style guidelines. Consequently, The CERT® C Coding Standard, second edition, does not require the enforcement of any particular coding style but only suggests that the appropriate development organization define or adopt style guidelines and apply these guidelines consistently. The easiest way to apply a coding style consistently is to use a code-formatting tool. Many interactive development environments (IDEs) provide such capabilities.

Controversial Rules

In general, the CERT coding standards try to avoid the inclusion of controversial rules that lack a broad consensus.

Who Should Read This Book

The CERT® C Coding Standard, second edition, is primarily intended for developers of C language programs but may also be used by software acquirers to define the requirements for bespoke software. This book is of particular interest to developers who are interested in building high-quality systems that are reliable, robust, and resistant to attack.

While not intended for C++ programmers, this book may also be of some value because the vast majority of issues identified for C language programs are also issues in C++ programs, although in many cases the solutions are different.

History

The idea of a CERT secure coding standard arose at the Spring 2006 meeting of the C Standards Committee (more formally, ISO/IEC JTC1/SC22/WG14) in Berlin, Germany [Seacord 2013a]. The C Standard is an authoritative document, but its audience is primarily compiler implementers, and, as noted by many, its language is obscure and often impenetrable. A secure coding standard would be targeted primarily toward C language programmers and would provide actionable guidance on how to code securely in the language.

The CERT C Secure Coding Standard was developed on the CERT Secure Coding wiki following a community-based development process. Experts from the community, including members of the WG14 C Standards Committee, were invited to contribute and were provided with edit privileges on the wiki. Members of the community can register for a free account on the wiki and comment on the coding standards and the individual rules. Reviewers who provided high-quality comments were frequently extended edit privileges so that they could directly contribute to the development and evolution of the coding standard. Today, the CERT Secure Coding wiki has 1,374 registered contributors.

This wiki-based community development process has many advantages. Most important, it engages a broad group of experts to form a consensus opinion on the content of the rules. The main disadvantage of developing a secure coding standard on a wiki is that the content is constantly evolving. This instability may be acceptable if you want the latest information and are willing to entertain the possibility that a recent change has not yet been fully vetted. However, many software development organizations require a static set of rules and recommendations that they can adopt as requirements for their software development process. Toward this end, a stable snapshot of the CERT C Secure Coding Standard was produced after two and a half years of community development and published as The CERT® C Secure Coding Standard. With the production of the manuscript for the book in June 2008, version 1.0 (the book) and the wiki versions of the secure coding standard began to diverge.

The CERT C Secure Coding guidelines were first reviewed by WG14 at the London meeting in April 2007 and again at the Kona, Hawaii, meeting in August 2007.

The topic of whether PL22.11 should submit the CERT C Secure Coding Standard to WG14 as a candidate for publication as a type 2 or type 3 technical report was discussed at the J11/U.S. TAG Meeting, April 15, 2008, as reported in the minutes. J11 is now Task Group PL22.11, Programming Language C, and this technical committee is the U.S. Technical Advisory Group to ISO/IEC JTC 1 SC22/WG14. A straw poll was taken on the question, “Who has time to work on this project?” for which the vote was 4 (has time) to 12 (has no time). Some of the feedback we received afterwards was that although the CERT C Secure Coding Standard was a strong set of guidelines that had been developed with input from many of the technical experts at WG14 and had been reviewed by WG14 on several occasions, WG14 was not normally in the business of “blessing” guidance to developers. However, WG14 was certainly in the business of defining normative requirements for tools such as compilers.

Armed with this knowledge, we proposed that WG14 establish a study group to consider the problem of producing analyzable secure coding guidelines for the C language. The study group first met on October 27, 2009. CERT contributed an automatically enforceable subset of the C secure coding rules to ISO/IEC for use in the standardization process.

Participants in the study group included analyzer vendors such as Coverity, Fortify, GammaTech, Gimpel, Klocwork, and LDRA; security experts; language experts; and consumers. A new work item to develop and publish ISO/IEC TS 17961, C Secure Coding Rules, was approved for WG14 in March 2012, and the study group concluded. Roberto Bagnara, the Italian National Body representative to WG 14, later joined the WG14 editorial committee. ISO/IEC TS 17961:2013(E), Information Technology—Programming Languages, Their Environments and System Software Interfaces—C Secure Coding Rules [ISO/IEC TS 17961:2013] was officially published in November 2013 and is available for purchase at the ISO store.

ISO/IEC TS 17961 C Secure Coding Rules

The purpose of ISO/IEC TS 17961 is to establish a baseline set of requirements for analyzers, including static analysis tools and C language compilers, to be applied by vendors that wish to diagnose insecure code beyond the requirements of the language standard. All rules are meant to be enforceable by static analysis. The criterion for selecting these rules is that analyzers that implement these rules must be able to effectively discover secure coding errors without generating excessive false positives.

To date, the application of static analysis to security has been performed in an ad hoc manner by different vendors, resulting in nonuniform coverage of significant security issues. ISO/IEC TS 17961 enumerates secure coding rules and requires analysis engines to diagnose violations of these rules as a matter of conformance to the specification. These rules may be extended in an implementation-dependent manner, which provides a minimum coverage guarantee to customers of any and all conforming static analysis implementations.

ISO/IEC TS 17961 specifies rules for secure coding in the C programming language and includes code examples for each rule. Noncompliant code examples demonstrate language constructs that have weaknesses with potentially exploitable security implications; such examples are expected to elicit a diagnostic from a conforming analyzer for the affected language construct. Compliant examples are expected not to elicit a diagnostic. ISO/IEC TS 17961 does not specify the mechanism by which these rules are enforced or any particular coding style to be enforced.

Table P–1 shows how ISO/IEC TS 17961 relates to other standards and guidelines. Of the publications listed, ISO/IEC TS 17961 is the only one for which the immediate audience is analyzers and not developers.

Table P–1. ISO/IEC TS 17961 compared with other standards

Coding Standard

C Standard

Security Standard

Safety Standard

International Standard

Whole Language

CWE

None/all

Yes

No

No

N/A

MISRA C2

C89

No

Yes

No

No

MISRA C3

C99

No

Yes

No

No

CERT C99

C99

Yes

No

No

Yes

CERT C11

C11

Yes

Yes

No

Yes

ISO/IEC

TS 17961

C11

Yes

No

Yes

Yes

A conforming analyzer must be capable of producing a diagnostic for each distinct rule in the technical specification upon detecting a violation of that rule in isolation. If the same program text violates multiple rules simultaneously, a conforming analyzer may aggregate diagnostics but must produce at least one diagnostic. The diagnostic message might be of the form

Accessing freed memory in function abc, file xyz.c, line nnn.

ISO/IEC TS 17961 does not require an analyzer to produce a diagnostic message for any violation of any syntax rule or constraint specified by the C Standard. Conformance is defined only with respect to source code that is visible to the analyzer. Binary-only libraries, and calls to them, are outside the scope of these rules.

An interesting aspect of the technical specification is the portability assumptions, known within the group as the “San Francisco rule” because the assumptions evolved at a meeting hosted by Coverity at its headquarters. The San Francisco rule states that a conforming analyzer must be able to diagnose violations of guidelines for at least one C implementation but does not need to diagnose a rule violation if the result is documented for the target implementation and does not cause a security flaw. Variations in quality of implementation permit an analyzer to produce diagnostics concerning portability issues. For example, the following program fragment can produce a diagnostic, such as the mismatch between %d and long int:

long i; printf("i = %d", i);

This mismatch might not be a problem for all target implementations, but it is a portability problem because not all implementations have the same representation for int and long.

In addition to other goals already stated, The CERT® C Coding Standard, second edition, has been updated for consistency with ISO/IEC TS 17961. Although both documents serve different audiences, consistency between the documents should improve the ability of developers to use ISO/IEC TS 17961–conforming analyzers to find violations of rules from this coding standard.

CERT has also developed the Secure Coding Validation Suite, a set of tests to validate the rules defined in ISO/IEC TS 17961. These tests are based on the examples in this technical specification and are distributed with a BSD-style license.

  • + 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