Click here to close now.



Welcome!

Linux Containers Authors: Liz McMillan, Jnan Dash, Pat Romanski, XebiaLabs Blog, Elizabeth White

Related Topics: Linux Containers

Linux Containers: Article

Variadic Functions: How They Contribute To Security Vulnerabilities and How To Fix Them

Variadic functions are implemented using either the ANSI C stdarg approach or, historically, the UNIX System V vararg approach

C/C++ language variadic functions are functions that accept a variable number of arguments. Variadic functions are implemented using either the ANSI C stdarg approach or, historically, the UNIX System V vararg approach. Both approaches require that the contract between the developer and user of the variadic function not be violated by the user.

Many of the formatted I/O functions in the ISO/IEC 9899:1999 C language standard (C99) such as printf() and scanf() are defined as variadic functions (including formatted output functions that operate on a multibyte characters [e.g., ASCII] and wide characters [e.g., UNICODE]).

These functions accept a fixed format string argument that specifies, among other things, the number and type of arguments that are expected. If the contents of the format string are incorrect (by error or by malicious intent), the resulting behavior of the function is undefined.

Incautious use of formatted I/O functions have led to numerous, exploitable vulnerabilities. The majority of these vulnerabilities occur when a potentially malicious user is able to control all or some portion of the format specification string as shown in the following program:

1.  #include <stdio.h>
2.  #include <string.h>
3.  void usage(char *pname) {
4.  char usageStr[1024];
5.  snprintf(usageStr, 1024, "Usage: %s <target>\n", pname);
6.  printf(usageStr);
7.  }
8.  int main(int argc, char * argv[]) {
9.    if (argc < 2) {
10.      usage(argv[0]);
11.      exit(-1);
12.    }
13. }

These vulnerabilities are often referred to as "format string" vulnerabilities. Exploits take a variety of forms, the most dangerous of which involves using the %n conversion specifier to overwrite memory and transfer control to arbitrary code of the attacker's choosing. The easiest way to prevent format string vulnerabilities is to ensure that the format string does not include characters from untrusted sources. Because of internationalization, however, format strings and message text are often moved into external catalogs or files that the program opens at runtime. An attacker can alter the values of the formats and strings in the program by modifying the contents of these files. The entire topic of formatted output is covered in detail in my book on Secure Coding in C/C++.

Format string vulnerabilities have been discovered in a variety of deployed C language programs, including:

  • The Washington University FTP daemon wu-ftpd that is shipped with many distributions of Linux and other UNIX operating systems (CA-2000-13).
  • The common desktop environment (CDE), an integrated graphical user interface that runs on UNIX and Linux operating systems (CA-2001-27).
  • Helix Player, and media players based on the Helix Player, including Real Player for Linux systems (VU#361181).
The following is an example of a variadic function implementation using ANSI stdarg:

1.  int average(int first, ...) {
2.   int count = 0, sum = 0, i = first;
3.   va_list marker;
4.   va_start(marker, first);
5.   while (i != -1) {
6.     sum += i;
7.     count++;
8.     i = va_arg(marker, int);
9.     }
10.   va_end(marker);
11.   return(sum ? (sum / count) : 0);
12. }

Variadic functions are declared using a partial parameter list followed by the ellipsis notation. The variadic average() function accepts a single, fixed integer argument followed by a variable argument list. Like other functions, the arguments to the variadic function are pushed on the calling stack.

Variadic functions are problematic for a number of reasons. The first and foremost is that the implementation has no real way of knowing how many arguments were passed (even though this information is available at compile time). The termination condition for the argument list is a contract between the programmers who implement the library function and the programmers who use the function in an application. In this implementation of the average() function, termination of the variable argument list is indicated by an argument whose value is -1. This means, for example, that average(5, -1, 2, -1) is 5, not 2, as the programmer might expect. Also, if the programmer calling the function neglects to provide this argument, the average() function will continue to process the next argument indefinitely until a -1 value is encountered or an exception occurs.

A second problem with variadic functions is a complete lack of type checking. In the case of formatted output functions, the type of the arguments is determined by the corresponding conversion specifier in the format string. For example, if a %d conversion specifier is encountered, the formatted output function assumes that the corresponding argument is an integer. If a %s is found, the corresponding argument is interpreted as a pointer to a string. This could result in a program fault, for example, if the corresponding argument was actually a small integer value.

Every time a variadic function consumes an argument, an internal argument pointer is incremented to reference the next argument on the stack. If there is some type confusion, it is possible that the argument pointer is incorrectly incremented. This happens less than you might imagine on a 32-bit architecture such as the 32-bit Intel Architecture (IA-32) because almost all arguments (including addresses, char, short, int, and long int) use four bytes. However, conversion specifiers such as a, A, e, E, f, F, g, or G are used to output a 64-bit floating-point number, thereby incrementing the argument pointer by 8.

The standard C formatted output functions need modifications to print 64-bit integer and pointer values in hexadecimal. The %x modifier will only print out the first 32 bits of the value that is passed to it and increment the internal argument pointer by 4 bytes. To print out a 64-bit pointer, the ANSI C %p directive needs to be used rather than %x or %u. To print 64-bit integers, you need to use the one size specifier.

Solutions
One property of format string exploits is that the number of arguments referenced by the attacker's format string is greater than the arguments in the call to the formatted output function. Unfortunately, there is currently no mechanism by which a variadic function implementation can determine the number of arguments (or preferably the number of bytes) passed, so it is impossible to determine when this limit has been exceeded. If such a mechanism existed, variadic functions (such as printf()) could be implemented in such a way as to prevent most format string vulnerabilities.

More Stories By Robert Seacord

Robert C. Seacord is a senior vulnerability analyst at the CERT/Coordination Center (CERT/CC) at the Software Engineering Institute (SEI) in Pittsburgh, PA, and author of Secure Coding in C and C++ (Addison-Wesley, 2005). An eclectic technologist, Robert is coauthor of two previous books, Building Systems from Commercial Components (Addison-Wesley, 2002) and Modernizing Legacy Systems (Addison-Wesley, 2003).

Comments (1) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
LinuxWorld News Desk 12/06/05 04:18:44 PM EST

LinuxWorld Feature - Variadic Functions: How They Contribute To Security Vulnerabilities and How To Fix Them. C/C++ language variadic functions are functions that accept a variable number of arguments. Variadic functions are implemented using either the ANSI C stdarg approach or, historically, the UNIX System V vararg approach. Both approaches require that the contract between the developer and user of the variadic function not be violated by the user.

@ThingsExpo Stories
SYS-CON Events announced today that Commvault, a global leader in enterprise data protection and information management, has been named “Bronze Sponsor” of SYS-CON's 18th International Cloud Expo, which will take place on June 7–9, 2016, at the Javits Center in New York City, NY, and the 19th International Cloud Expo, which will take place on November 1–3, 2016, at the Santa Clara Convention Center in Santa Clara, CA. Commvault is a leading provider of data protection and information management...
The cloud promises new levels of agility and cost-savings for Big Data, data warehousing and analytics. But it’s challenging to understand all the options – from IaaS and PaaS to newer services like HaaS (Hadoop as a Service) and BDaaS (Big Data as a Service). In her session at @BigDataExpo at @ThingsExpo, Hannah Smalltree, a director at Cazena, will provide an educational overview of emerging “as-a-service” options for Big Data in the cloud. This is critical background for IT and data profes...
SYS-CON Events announced today that VAI, a leading ERP software provider, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. VAI (Vormittag Associates, Inc.) is a leading independent mid-market ERP software developer renowned for its flexible solutions and ability to automate critical business functions for the distribution, manufacturing, specialty retail and service sectors. An IBM Premier Business Part...
SYS-CON Events announced today that Alert Logic, Inc., the leading provider of Security-as-a-Service solutions for the cloud, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Alert Logic, Inc., provides Security-as-a-Service for on-premises, cloud, and hybrid infrastructures, delivering deep security insight and continuous protection for customers at a lower cost than traditional security solutions. Ful...
Fortunately, meaningful and tangible business cases for IoT are plentiful in a broad array of industries and vertical markets. These range from simple warranty cost reduction for capital intensive assets, to minimizing downtime for vital business tools, to creating feedback loops improving product design, to improving and enhancing enterprise customer experiences. All of these business cases, which will be briefly explored in this session, hinge on cost effectively extracting relevant data from ...
With the Apple Watch making its way onto wrists all over the world, it’s only a matter of time before it becomes a staple in the workplace. In fact, Forrester reported that 68 percent of technology and business decision-makers characterize wearables as a top priority for 2015. Recognizing their business value early on, FinancialForce.com was the first to bring ERP to wearables, helping streamline communication across front and back office functions. In his session at @ThingsExpo, Kevin Roberts...
SYS-CON Events announced today that Interoute, owner-operator of one of Europe's largest networks and a global cloud services platform, has been named “Bronze Sponsor” of SYS-CON's 18th Cloud Expo, which will take place on June 7-9, 2015 at the Javits Center in New York, New York. Interoute is the owner-operator of one of Europe's largest networks and a global cloud services platform which encompasses 12 data centers, 14 virtual data centers and 31 colocation centers, with connections to 195 ad...
With an estimated 50 billion devices connected to the Internet by 2020, several industries will begin to expand their capabilities for retaining end point data at the edge to better utilize the range of data types and sheer volume of M2M data generated by the Internet of Things. In his session at @ThingsExpo, Don DeLoach, CEO and President of Infobright, will discuss the infrastructures businesses will need to implement to handle this explosion of data by providing specific use cases for filte...
As enterprises work to take advantage of Big Data technologies, they frequently become distracted by product-level decisions. In most new Big Data builds this approach is completely counter-productive: it presupposes tools that may not be a fit for development teams, forces IT to take on the burden of evaluating and maintaining unfamiliar technology, and represents a major up-front expense. In his session at @BigDataExpo at @ThingsExpo, Andrew Warfield, CTO and Co-Founder of Coho Data, will dis...
SYS-CON Events announced today that Fusion, a leading provider of cloud services, will exhibit at SYS-CON's 18th International Cloud Expo®, which will take place on June 7-9, 2016, at the Javits Center in New York City, NY. Fusion, a leading provider of integrated cloud solutions to small, medium and large businesses, is the industry's single source for the cloud. Fusion's advanced, proprietary cloud service platform enables the integration of leading edge solutions in the cloud, including clou...
Most people haven’t heard the word, “gamification,” even though they probably, and perhaps unwittingly, participate in it every day. Gamification is “the process of adding games or game-like elements to something (as a task) so as to encourage participation.” Further, gamification is about bringing game mechanics – rules, constructs, processes, and methods – into the real world in an effort to engage people. In his session at @ThingsExpo, Robert Endo, owner and engagement manager of Intrepid D...
Eighty percent of a data scientist’s time is spent gathering and cleaning up data, and 80% of all data is unstructured and almost never analyzed. Cognitive computing, in combination with Big Data, is changing the equation by creating data reservoirs and using natural language processing to enable analysis of unstructured data sources. This is impacting every aspect of the analytics profession from how data is mined (and by whom) to how it is delivered. This is not some futuristic vision: it's ha...
WebRTC has had a real tough three or four years, and so have those working with it. Only a few short years ago, the development world were excited about WebRTC and proclaiming how awesome it was. You might have played with the technology a couple of years ago, only to find the extra infrastructure requirements were painful to implement and poorly documented. This probably left a bitter taste in your mouth, especially when things went wrong.
Learn how IoT, cloud, social networks and last but not least, humans, can be integrated into a seamless integration of cooperative organisms both cybernetic and biological. This has been enabled by recent advances in IoT device capabilities, messaging frameworks, presence and collaboration services, where devices can share information and make independent and human assisted decisions based upon social status from other entities. In his session at @ThingsExpo, Michael Heydt, founder of Seamless...
The IoT's basic concept of collecting data from as many sources possible to drive better decision making, create process innovation and realize additional revenue has been in use at large enterprises with deep pockets for decades. So what has changed? In his session at @ThingsExpo, Prasanna Sivaramakrishnan, Solutions Architect at Red Hat, discussed the impact commodity hardware, ubiquitous connectivity, and innovations in open source software are having on the connected universe of people, thi...
WebRTC: together these advances have created a perfect storm of technologies that are disrupting and transforming classic communications models and ecosystems. In his session at WebRTC Summit, Cary Bran, VP of Innovation and New Ventures at Plantronics and PLT Labs, provided an overview of this technological shift, including associated business and consumer communications impacts, and opportunities it may enable, complement or entirely transform.
There are so many tools and techniques for data analytics that even for a data scientist the choices, possible systems, and even the types of data can be daunting. In his session at @ThingsExpo, Chris Harrold, Global CTO for Big Data Solutions for EMC Corporation, showed how to perform a simple, but meaningful analysis of social sentiment data using freely available tools that take only minutes to download and install. Participants received the download information, scripts, and complete end-t...
For manufacturers, the Internet of Things (IoT) represents a jumping-off point for innovation, jobs, and revenue creation. But to adequately seize the opportunity, manufacturers must design devices that are interconnected, can continually sense their environment and process huge amounts of data. As a first step, manufacturers must embrace a new product development ecosystem in order to support these products.
Manufacturing connected IoT versions of traditional products requires more than multiple deep technology skills. It also requires a shift in mindset, to realize that connected, sensor-enabled “things” act more like services than what we usually think of as products. In his session at @ThingsExpo, David Friedman, CEO and co-founder of Ayla Networks, discussed how when sensors start generating detailed real-world data about products and how they’re being used, smart manufacturers can use the dat...
When it comes to IoT in the enterprise, namely the commercial building and hospitality markets, a benefit not getting the attention it deserves is energy efficiency, and IoT’s direct impact on a cleaner, greener environment when installed in smart buildings. Until now clean technology was offered piecemeal and led with point solutions that require significant systems integration to orchestrate and deploy. There didn't exist a 'top down' approach that can manage and monitor the way a Smart Buildi...