You are on page 1of 3

Basic Training

Editors: Michael Howard, michael.howard@microsoft.com


James A. Whittaker, jw@se.fit.edu

Secure Coding in C and C++


Of Strings and Integers

C
and C++ are popular, widely adopted program- determine the length and once to
perform the copy. If you know the
ming languages, despite security analysts’ condem- destination buffer’s length, you can
stop counting after you’ve ex-
nation of them due to programmers’ tendencies ceeded the buffer’s length.
• The C-like approach is to copy the
to misuse them and their associated libraries in string as you go along, searching
for the null-termination character.
ways that lead to numerous, exploitable software vulnerabilities. Again, if you know the buffer’s
length, you can stop copying
ROBERT Although we can view their propen- guages and supporting tools needed when the destination buffer is full
S EACORD sity for misuse as a flaw, C and C++ most? Characters are a built-in type (leaving 1 byte for the terminating
CERT/CC, are reliable workhorses that develop- in C, whereas C-style strings are null character). If the string is too
Carnegie ers commonly select for new pro- represented by null-terminated long to completely copy, however,
Mellon jects, even in the absence of legacy arrays of characters. Some have the process has already modified
University code bases. argued that C lacks the basic mech- the destination buffer’s contents.
At the September 2005 meeting anisms necessary to ever support Although this isn’t ideal behavior
of the International Organization strings as a built-in type. in the event of an error, most
for Standardization/International A C-style string consists of a con- string-copy functions in C behave
Electrotechnical Commission’s C tiguous sequence of characters ter- in this fashion.
language standardization working minated by and including the first
group (www.open-std.org/jtc1/sc null character. Copying strings from Weaknesses in string representa-
22/wg14/) P.J. Plauger—president one memory location to another tion, string management, and string
of Dinkumware and, formerly, (for example, from an environment manipulation have caused a broad
senior editor of The C/C++ Users variable into a character array on the range of software vulnerabilities and
Journal and contributing editor to stack) can result in a buffer overflow exploits. Unbounded string copies,
Embedded Systems Programming— when the copy operation doesn’t null-termination errors, and string-
observed that programming lan- know the destination array’s length truncation errors have led to numer-
guage critics negatively contrast C to (for example, strcpy()). ous vulnerabilities in C and C++
languages that are implemented in C Even when the destination programs, including the ubiquitous
(Perl and Python, for example), buffer’s length is known, copying C- buffer overflow. However, help is ei-
which probably couldn’t be imple- style strings can be an interesting op- ther here or on the way.
mented directly in these languages. eration because the source string can C++ programmers can use the
Although the flexibility and be of arbitrary length, and its repre- standard std::string class de-
performance of C and C++ aren’t sentation makes it impossible to de- fined in ISO/IEC standard 14882.1
in question, security has increas- termine the string’s length until the The std::string class is the
ingly become an issue. The C and null-termination character is discov- char instantiation of the
C++ communities have recog- ered. Only two approaches exist for std::basic_string template
nized this and have taken steps to copying a string: class, and it uses a dynamic approach
improve security at all levels, in- to strings in that memory is allocated
cluding improved standards, com- • You could read each character as required—meaning that in all
piler implementations, and static until locating the terminating null cases, size() <= capacity().
and runtime analysis tools. character to determine the length. The std::string class is conve-
This isn’t very C-like because it re- nient because the language supports
Of strings quires the copy operation to tra- the class directly. Also, many existing
So, where are changes in these lan- verse the string twice—once to libraries already use this class, which

74 PUBLISHED BY THE IEEE COMPUTER SOCIETY ■ 1540-7993/06/$20.00 © 2006 IEEE ■ IEEE SECURITY & PRIVACY
Basic Training

simplifies integration. Problems can Like many other languages, ties in both C and C++. Safer, se-
still arise in converting from neither C nor C++ has built-in cure string libraries are available in
basic_string to C-style strings mechanisms to detect or handle error both languages, although errors
and in using the subscript operator conditions such as integer overflow leading to vulnerabilities are still pos-
[] (which doesn’t perform bounds or truncation, even though these sible. As a result, software developers
checking), but basic_string is conditions are often detected and re- should still follow a policy of defense
generally less prone to errors that re- ported at the hardware level (for in depth and not rely on a single
sult in security vulnerabilities. example, many 32-bit Intel Architec- strategy. Security audits, static and
For C users, the solution isn’t as ture processor instructions set carry dynamic analysis tools, effective test-
clear. Conventional solutions such as and overflow flags to indicate signed ing techniques, and runtime protec-
the use of strncpy() and and unsigned overflow). Some com- tion schemes can all help eliminate
strncat() are prone to buffer pilers provide mechanisms for detect- software vulnerabilities or prevent
overflows as well as truncation errors. ing integer overflow. For example, attackers from exploiting them.
Indeed, Visual C++ has deprecated gcc includes the –ftrapv flag, One promising technology that’s
these functions’ use in Visual Studio which generates traps for signed over- currently being commercially devel-
2005. Microsoft has developed a set of flow on addition, subtraction, and oped is Plum Hall’s Safe-Secure
string functions that can be effective multiplication operations, although it C/C++ (www.plumhall.com/sscc.
in remediating legacy code and has does nothing for overflow on un- html). This technology is designed
submitted them to the ISO/IEC signed overflows, perhaps because the to be integrated into compilers and
SC22 WG14 J11 International Stan- C99 standard5 specifies modulo be- software analysis tools to eliminate
dardization working group for the havior for unsigned integers. As of buffer overflows in C and C++.
Programming Language C. These Visual Studio 2005, Visual C++ Safe-Secure C/C++ uses a mixture
functions, along with others designed doesn’t support a similar option. of compile-time, link-time, and
to improve security in C applications, One solution for C++ users is to runtime tests to track bounds infor-
have been published in a type 2 tech- use the SafeInt template class, writ- mation and verify that fetch-and-
nical report.1 (ISO/IEC working ten by David LeBlanc.6 Before per- store operations are valid, thus
groups create type 2 technical reports forming operations, most SafeInt preventing buffer overflows.7
when the subject is still under tech- functions evaluate operands to de- Another interesting technology
nical development or whenever there termine whether an error will occur. under research is model checking,8
is a future but not immediate possibil- Because the class is declared as a tem- which exhaustively explores the
ity of agreement on an international plate, you can use it with any integer entire state-space for violations of
standard.) These string functions are type. It overrides nearly every rele- the property of interest. However,
designed to eliminate buffer over- vant operator (except for the model checking suffers from the
flows by requiring programmers to subscript operator []) so that arith- tate-explosion problem—that is,
specify destination buffer size. The metic operators can be used in nor- state-space size often exceeds the
committee is also considering pro- mal inline expressions. model-checking tool’s capacity.
posals for dynamic allocation functions 2 The challenge of applying model
and managed strings,3,4 which aim to Methods, checking to large software systems is
prevent buffer-overflow, string trun- tools, processes to tailor state-space reduction algo-
cation, and null-termination errors Safe integer operations aren’t rithms to the code security domain,
by using functions that dynamically necessarily the only solution to resulting in specialized model-
allocate memory as required. integer-overflow and other integer- checking algorithms for detecting
exception errors, but they do security vulnerabilities.
Of integers
An inherent problem in computing
is that digital representations of inte- Although the flexibility and performance of C
gers are always limited in the range of
values they can represent. As a result, and C++ aren’t in question, security has
operations on these integers can re-
sult in integer overflow, truncation, increasingly become an issue.
and sign errors. Attackers often ex-
ploit integers used as array indices, provide a safety net that is largely
loop counters, or lengths to create
buffer overflows and execute arbi-
missing in C. Input validation and
integer range checking are impor-
P rogramming language choice
can make or break your soft-
ware project. As a programming
trary code. tant mitigations against vulnerabili- language, C provides many oppor-

www.computer.org/security/ ■ IEEE SECURITY & PRIVACY 75


Basic Training

tunities for mistakes, but it never open-std.org/jtc1/sc22/wg14/ inating Buffer Overflows, Using
prevents you from achieving your www/docs/n1126.pdf. the Compiler or a Standalone
goals. Developing a security mind- 3. F. Long and R.C. Seacord, Speci- Tool,” NIST Workshop on Software
set from the beginning is essential fication for Managed Strings, Assurance Tools, Techniques, and
to developing secure systems. ISO/IEC JTC1 SC22 WG14 Metrics at ASE ’05; to be published
When programming in C and N1132, Int’l Organization for in 2006.
C++, a good start is to understand Standardization, Aug. 2005; www. 8. E. Clarke et al., “Predicate Abstrac-
the potential risks associated with open-std.org/jtc1/sc22/wg14/www/ tion of ANSI—C Programs using
strings and integers, devise a plan docs/n1132.pdf. SAT,” Formal Methods in System
for addressing them, and consis- 4. R. Seacord, “Managed String Li- Design (FMSD), vol. 25, Sept.–Nov.
tently apply it through the devel- brary for C,” C/C++ Users J., vol. 2004, pp. 105–127; www.kroening.
opment process. 23, no. 10, Oct. 2005, pp. 30–34; com/papers/dsn2003.pdf.
www.cuj.com/documents/s=818
References 8/cuj0510seacord/. Robert Seacord is a senior vulnerability
1. Specification for Safer, More Secure C 5. ISO/IEC 98899, Programming Lan- analyst at the CERT/CC at Carnegie Mel-
lon University’s Software Engineering
Library Functions, tech. report guages — C, 2nd ed., Int’l Organiza- Institute. His research interests include
ISO/IEC TR 24731, Int’l Orga- tion for Standardization/Int’l secure coding practices, legacy system
nization for Standardization, Sept. Electrotechnical Commission, 1999. modernization, and component-based
2005; www.open-std.org/jtc1/sc 6. D. LeBlanc, “Integer Handling software engineering. Seacord has a BS
in computer science from Rensselaer Poly-
22/wg14/www/docs/n1135.pdf. with the C++ SafeInt Class,” technic Institute. He is author of Secure
2. Specification for Safer C Library Func- Microsoft, 2004; http://msdn. Coding in C and C++ (Addison-Wesley,
tions—Part II: Dynamic Allocation microsoft.com/library/default.asp? 2005) and coauthor of Building Systems
from Commercial Components (Addi-
Functions, ISO/IEC WDTR url=/library/en-us/dncode/html/
son-Wesley, 2002) and Modernizing
24731-2, Int’l Organization for secure01142004.asp. Legacy Systems (Addison-Wesley, 2003).
Standardization, May 2005; www. 7. T. Plum and D.M. Keaton, “Elim- Contact him at rcs@cert.org.

ADVERTISER / PRODUCT INDEX JANUARY/FEBRUARY 2006


Advertiser Page Number Advertising Personnel

Black Hat Briefings & Training Europe 2006 Cover 2


Marion Delaney Sandy Brown
Infosec World Conference & Expo 2006 3 IEEE Media, Advertising Director IEEE Computer Society,
Phone: +1 212 419 7766 Business Development Manager
NetSec 2006 1 Fax: +1 212 419 7589 Phone: +1 714 821 8380
Email: md.ieeemedia@ieee.org Fax: +1 714 821 4010
RSA Conference 2006 Cover 3 Marian Anderson Email: sb.ieeemedia@ieee.org
Advertising Coordinator
Secure Software Engineering Symposium 2006 13 Phone: +1 714 821 8380
Fax: +1 714 821 4010
U.S. Navy Cover 4 Email: manderson@computer.org
Boldface denotes advertisements in this issue.

Advertising Sales Representatives


Mid Atlantic (product/recruitment) Midwest (product) Midwest/Southwest (recruitment) Northwest/Southern CA (recruitment)
Dawn Becker Dave Jones Darcy Giovingo Tim Matteson
Phone: +1 732 772 0160 Phone: +1 708 442 5633 Phone: +1 847 498-4520 Phone: +1 310 836 4064
Fax: +1 732 772 0161 Fax: +1 708 442 7620 Fax: +1 847 498-5911 Fax: +1 310 836 4067
Email: db.ieeemedia@ieee.org Email: dj.ieeemedia@ieee.org Email: dg.ieeemedia@ieee.org Email: tm.ieeemedia@ieee.org
Will Hamilton
New England (product) Phone: +1 269 381 2156 Southwest (product) Japan
Jody Estabrook Fax: +1 269 381 2556 Josh Mayer Tim Matteson
Phone: +1 978 244 0192 Email: wh.ieeemedia@ieee.org Phone: +1 972 423 5507 Phone: +1 310 836 4064
Fax: +1 978 244 0103 Joe DiNardo Fax: +1 972 423 6858 Fax: +1 310 836 4067
Email: je.ieeemedia@ieee.org Phone: +1 440 248 2456 Email: jm.ieeemedia@ieee.org Email: tm.ieeemedia@ieee.org
Fax: +1 440 248 2594
New England (recruitment) Email: jd.ieeemedia@ieee.org Northwest (product) Europe (product)
John Restchack Peter D. Scott Hilary Turnbull
Phone: +1 212 419 7578 Southeast (recruitment) Phone: +1 415 421-7950 Phone: +44 1875 825700
Fax: +1 212 419 7589 Thomas M. Flynn Fax: +1 415 398-4156 Fax: +44 1875 825701
Email: j.restchack@ieee.org Phone: +1 770 645 2944 Email: peterd@pscottassoc.com Email: impress@impressmedia.com
Fax: +1 770 993 4423
Connecticut (product) Email: flynntom@mindspring.com Southern CA (product)
Stan Greenfield Marshall Rubin
Phone: +1 203 938 2418 Southeast (product) Phone: +1 818 888 2407
Fax: +1 203 938 3211 Bill Holland Fax: +1 818 888 4907
Email: greenco@optonline.net Phone: +1 770 435 6549 Email: mr.ieeemedia@ieee.org
Fax: +1 770 435 0243
Email: hollandwfh@yahoo.com

76 IEEE SECURITY & PRIVACY ■ JANUARY/FEBRUARY 2006

You might also like