Home > Articles > Programming > C/C++

From the book

Usage

The rules in this standard may be extended with organization-specific rules. However, the rules in the standard must be obeyed to claim conformance with the standard.

Training may be developed to educate software professionals regarding the appropriate application of coding standards. After passing an examination, these trained programmers may also be certified as coding professionals. For example, the Software Developer Certification (SDC) is a credentialing program developed at Carnegie Mellon University. The SDC uses authentic examination to

  1. Identify job candidates with specific programming skills.
  2. Demonstrate the presence of a well-trained software workforce.
  3. Provide guidance to educational and training institutions.

Once a coding standard has been established, tools and processes can be developed or modified to determine conformance with the standard.

Conformance Testing

To ensure that the source code conforms to this coding standard, it is necessary to have measures in place that check for rule violations. The most effective means of achieving this goal is to use one or more ISO/IEC TS 17961–conforming analyzers. Where a rule cannot be checked by a tool, a manual review is required.

The Source Code Analysis Laboratory (SCALe) provides a means for evaluating the conformance of software systems against this and other coding standards. CERT coding standards provide a normative set of rules against which software systems can be evaluated. Conforming software systems should demonstrate improvements in the safety, reliability, and security over nonconforming systems.

The SCALe team at the CERT Program, part of Carnegie Mellon University’s Software Engineering Institute, analyzes a developer’s source code and provides a detailed report of findings to guide the code’s repair. After the developer has addressed these findings and the SCALe team determines that the product version conforms to the standard, the CERT Program issues the developer a certificate and lists the system in a registry of conforming systems. This report details the SCALe process and provides an analysis of selected software systems.

Conformance

Conformance to the CERT® C Coding Standard requires that the code not contain any violations of the rules specified in this book. If an exceptional condition is claimed, the exception must correspond to a predefined exceptional condition, and the application of this exception must be documented in the source code.

Conformance with the recommendations on the wiki is not necessary to claim conformance with the CERT® C Coding Standard. Conformance to the recommendations will, in many cases, make it easier to conform to the rules; eliminating many potential sources of defects.

Deviation Procedure

Strict adherence to all rules is unlikely and, consequently, deviations associated with specific rule violations are necessary. Deviations can be used in cases where a true-positive finding is uncontested as a rule violation but the code is nonetheless determined to be correct. An uncontested true-positive finding may be the result of a design or architecture feature of the software or may occur for a valid reason that was unanticipated by the coding standard. In this respect, the deviation procedure allows for the possibility that coding rules are overly strict [Seacord 2012].

Deviations will not be approved for reasons of performance or usability. A software system that successfully passes conformance testing must not contain defects or exploitable vulnerabilities. Deviation requests are evaluated by the lead assessor, and if the developer can provide sufficient evidence that deviation will not result in a vulnerability, the deviation request is accepted. Deviations should be used infrequently because it is almost always easier to fix a coding error than it is to provide an argument that the coding error does not result in a vulnerability.

System Qualities

The goal of this coding standard is to produce safe, reliable, and secure systems. Additional requirements might exist for safety-critical systems, such as the absence of dynamic memory allocation. Other software quality attributes of interest include portability, usability, availability, maintainability, readability, and performance.

Many of these attributes are interrelated in interesting ways. For example, readability is an attribute of maintainability; both are important for limiting the introduction of defects during maintenance that can result in security flaws or reliability issues. In addition, readability aides code inspection by safety officers. Reliability and availability require proper resources management, which also contributes to the safety and security of the system. System attributes such as performance and security are often in conflict, requiring trade-offs to be considered.

How This Book Is Organized

This book is organized into 14 chapters containing rules in specific topic areas, three appendices, a bibliography, and an index. The first appendix is a glossary of terms used through this book. Terms that are listed in the glossary are printed in bold font the first time they appear and then in normal font in subsequent appearances. The second annex lists the undefined behavior from the C Standard, Annex J, J.2 [ISO/IEC 9899:2011], numbered and classified for easy reference. These numbered undefined behaviors are referenced frequently from the rules. The third annex contains unspecified behaviors from the C Standard, Annex J, J.1 [ISO/IEC 9899:2011]. These unspecified behaviors are occasionally referenced from the rules as well. The bibliography is a compendium of the small bibliography sections from each rule as well as other references cited throughout the book.

Most rules have a consistent structure. Each rule in this standard has a unique identifier, which is included in the title. The title and the introductory paragraphs define the rule and are typically followed by one or more pairs of noncompliant code examples and compliant solutions. Each rule also includes a risk assessment, related guidelines and a bibliography (where applicable). Rules may also include a table of related vulnerabilities. Recommendations on the CERT Coding Standards wiki are organized in a similar fashion.

Identifiers

Each rule and recommendation is given a unique identifier, which consists of three parts:

  • A three-letter mnemonic representing the section of the standard
  • A two-digit numeric value in the range of 00 to 99
  • The letter C indicating that this is a C language guideline

The three-letter mnemonic is used to group similar coding practices and to indicate to which category a coding practice belongs.

The numeric value is used to give each coding practice a unique identifier. Numeric values in the range of 00 to 29 are reserved for recommendations, and values in the range of 30 to 99 are reserved for rules. Rules and recommendations are frequently referenced from the rules in this book by their identifier and title. Rules can be found in the book’s table of contents, whereas recommendations can only be found on the wiki.

Noncompliant Code Examples and Compliant Solutions

Noncompliant code examples illustrate code that violate the guideline under discussion. It is important to note that these are only examples, and eliminating all occurrences of the example does not necessarily mean that the code being analyzed is now compliant with the guideline.

Noncompliant code examples are typically followed by compliant solutions, which show how the noncompliant code example can be recoded in a secure, compliant manner. Except where noted, noncompliant code examples should contain violations only of the rule under discussion. Compliant solutions should comply with all secure coding rules but may on occasion fail to comply with a recommendation.

Exceptions

Any rule or recommendation may specify a small set of exceptions detailing the circumstances under which the coding practice is not necessary to ensure the safety, reliability, or security of software. Exceptions are informative only and are not required to be followed.

Risk Assessment

Each guideline in The CERT® C Coding Standard, second edition contains a Risk Assessment section that attempts to provide software developers with an indication of the potential consequences of not addressing a particular vulnerability in their code (along with some indication of expected remediation costs). This information may be used to prioritize the repair of vulnerability classes by a development team. The metric is designed primarily for remediation projects. It is generally assumed that new code will be developed to be compliant with the entire coding standard and applicable recommendations.

Each rule and recommendation has an assigned priority. Priorities are assigned using a metric based on Failure Mode, Effects, and Criticality Analysis (FMECA) [IEC 60812]. Three values are assigned for each rule on a scale of 1 to 3 for severity, likelihood, and remediation cost.

Severity—How serious are the consequences of the rule being ignored?

Value

Meaning

Examples of Vulnerability

1

Low

Denial-of-service attack, abnormal termination

2

Medium

Data integrity violation, unintentional information disclosure

3

High

Run arbitrary code

Likelihood—How likely is it that a flaw introduced by ignoring the rule can lead to an exploitable vulnerability?

Value

Meaning

1

Unlikely

2

Probable

3

Likely

Remediation Cost—How expensive is it to comply with the rule?

Value

Meaning

Detection

Correction

1

High

Manual

Manual

2

Medium

Automatic

Manual

3

Low

Automatic

Automatic

The three values are then multiplied together for each rule. This product provides a measure that can be used in prioritizing the application of the rules. The products range from 1 to 27, although only the following 10 distinct values are possible: 1, 2, 3, 4, 6, 8, 9, 12, 18, and 27. Rules and recommendations with a priority in the range of 1 to 4 are Level 3 rules, 6 to 9 are Level 2, and 12 to 27 are Level 1. The following are possible interpretations of the priorities and levels:

Level

Priorities

Possible Interpretation

L1

12, 18, 27

High severity, likely, inexpensive to repair

L2

6, 8, 9

Medium severity, probable, medium cost to repair

L3

1, 2, 3, 4

Low severity, unlikely, expensive to repair

Specific projects may begin remediation by implementing all rules at a particular level before proceeding to lower priority rules, as shown in Figure P–2.

FIGURE P-2 Levels of compliance

Automated Detection

On the wiki, both rules and recommendations frequently have sections that describe automated detection. These sections provide additional information on analyzers that can automatically diagnose violations of coding guidelines. Most automated analyses for the C programming language are neither sound nor complete, so the inclusion of a tool in this section typically means that the tool can diagnose some violations of this particular rule. Although the C Secure Coding Validation Suite can be used to test the ability of analyzers to diagnose violations of rules from ISO/IEC TS 17961, no currently available conformance test suite can assess the ability of analyzers to diagnose violations of the rules in this book. Consequently, the information in Automated Detection sections on the wiki may be

  • Provided by the vendors
  • Determined by CERT by informally evaluating the analyzer
  • Determined by CERT by reviewing the vendor documentation

Where possible, we try to reference the exact version of the tool for which the results were obtained. Because tools these evolve continuously, this information can rapidly become dated and obsolete. Consequently, this information has been omitted from this book and maintained only on the wiki.

Related Vulnerabilities

The Related Vulnerabilities sections on the wiki contain a link to search for related vulnerabilities on the CERT Web site. Whenever possible, CERT Vulnerability Notes are tagged with a keyword corresponding to the unique ID of the coding guideline. This search provides you with an up-to-date list of real-world vulnerabilities that have been determined to be at least partially caused by a violation of this specific guideline. These vulnerabilities are labeled as such only when the vulnerability analysis team at the CERT/CC is able to evaluate the source code and precisely determine the cause of the vulnerability. Because many vulnerability notes refer to vulnerabilities in closed-source software systems, it is not always possible to provide this additional analysis. Consequently, the related vulnerabilities field tends to be somewhat sparsely populated.

To find the latest list of related vulnerabilities, enter the following URL:

https://www.kb.cert.org/vulnotes/bymetric?searchview&query=FIELD+KEYWORDS+contains+XXXNN-X

where XXXNN-X is the ID of the rule or recommendation for which you are searching.

Specific vulnerability (VU) identifiers and common vulnerabilities and exposures (CVE) identifiers are referenced throughout this book. You can create a unique URL to get more information on specific vulnerabilities by appending the relevant ID to the end of a fixed string. For example, to find more information about

Related Vulnerability sections are included only for specific rules in this book, when the information is both relevant and interesting.

Related Guidelines

This section contains links to guidelines in related standards, technical specifications, and guideline collections such as Information Technology—Programming Languages, Their Environments and System Software Interfaces—C Secure Coding Rules [ISO/IEC TS 17961:2013]; Information Technology—Programming Languages—Guidance to Avoiding Vulnerabilities in Programming Languages through Language Selection and Use [ISO/IEC TR 24772:2013]; MISRA C3: Guidelines for the Use of the C Language in Critical Systems [MISRA C:2012]; and CWE IDs in MITRE’s Common Weakness Enumeration (CWE) [MITRE 2013].

You can create a unique URL to get more information on CWEs by appending the relevant ID to the end of a fixed string. For example, to find more information about CWE ID 192, “Integer Coercion Error,” you can append 192.html to http://cwe.mitre.org/data/definitions/ and enter the resulting URL in your browser: http://cwe.mitre.org/data/definitions/192.html.

The other referenced technical specifications, technical reports, and guidelines are commercially available.

Bibliography

Most rules have a small bibliography section that list documents and sections in these documents that provide information relevant to the rule.

Automatically Generated Code

If a code-generating tool is to be used, it is necessary to select an appropriate tool and undertake validation. Adherence to the requirements of this document may provide one criterion for assessing a tool.

Coding guidance varies depending on how code is generated and maintained. Categories of code include the following:

  • Tool-generated, tool-maintained code that is specified and maintained in a higher-level format from which language-specific source code is generated. The source code is generated from this higher-level description and then provided as input to the language compiler. The generated source code is never viewed or modified by the programmer.
  • Tool-generated, hand-maintained code that is specified and maintained in a higher-level format from which language-specific source code is generated. It is expected or anticipated, however, that at some point in the development cycle, the tool will cease to be used and the generated source code will be visually inspected and/or manually modified and maintained.
  • Hand-coded code is manually written by a programmer using a text editor or interactive development environment; the programmer maintains source code directly in the source-code format provided to the compiler.

Source code that is written and maintained by hand must have the following properties:

  • Readability
  • Program comprehension

These requirements are not applicable for source code that is never directly handled by a programmer, although requirements for correct behavior still apply. Reading and comprehension requirements apply to code that is tool generated and hand maintained but do not apply to code that is tool generated and tool maintained. Tool-generated, tool-maintained code can impose consistent constraints that ensure the safety of some constructs that are risky in hand-generated code.

Government Regulations

Developing software to secure coding rules is a good idea and is increasingly a requirement. The National Defense Authorization Act for Fiscal Year 2013, Section 933, “Improvements in Assurance of Computer Software Procured by the Department of Defense,” requires evidence that government software development and maintenance organizations and contractors are conforming, in computer software coding, to approved secure coding standards of the Department of Defense (DoD) during software development, upgrade, and maintenance activities, including through the use of inspection and appraisals.

DoD acquisition programs are specifying The Application Security and Development Security Technical Implementation Guide (STIG), Version 2, Release 1 [DISA 2008] in requests for proposal (RFPs). Section 2.1.5, “Coding Standards,” requires that “the Program Manager will ensure the development team follows a set of coding standards.”

The proper application of this standard would enable a system to comply with the following requirements from the Application Security and Development STIG [DISA 2008]:

  • (APP2060.1: CAT II) The Program Manager will ensure the development team follows a set of coding standards.
  • (APP2060.2: CAT II) The Program Manager will ensure the development team creates a list of unsafe functions to avoid and document this list in the coding standards.
  • (APP3550: CAT I) The Designer will ensure the application is not vulnerable to integer arithmetic issues.
  • (APP3560: CAT I) The Designer will ensure the application does not contain format string vulnerabilities.
  • (APP3570: CAT I) The Designer will ensure the application does not allow Command Injection.
  • (APP3590.1: CAT I) The Designer will ensure the application does not have buffer overflows.
  • (APP3590.2: CAT I) The Designer will ensure the application does not use functions known to be vulnerable to buffer overflows.
  • (APP3590.3: CAT II) The Designer will ensure the application does not use signed values for memory allocation where permitted by the programming language.
  • (APP3600: CAT II) The Designer will ensure the application has no canonical representation vulnerabilities.
  • (APP3630.1: CAT II) The Designer will ensure the application is not vulnerable to race conditions.
  • (APP3630.2: CAT III) The Designer will ensure the application does not use global variables when local variables could be used.

Training programmers and software testers will satisfy the following requirements:

  • (APP2120.3: CAT II) The Program Manager will ensure developers are provided with training on secure design and coding practices on at least an annual basis.
  • (APP2120.4: CAT II) The Program Manager will ensure testers are provided annual training.
  • (APP2060.3: CAT II) The Designer will follow the established coding standards established for the project.
  • (APP2060.4: CAT II) The Designer will not use unsafe functions documented in the project coding standards.
  • (APP5010: CAT III) The Test Manager will ensure at least one tester is designated to test for security flaws in addition to functional testing.

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