Click here to close now.

Welcome!

Linux Authors: Liz McMillan, Clinton Wolfe, Trevor Parsons, Carmen Gonzalez, Brett Hofer

Related Topics: Linux

Linux: 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
One of the biggest impacts of the Internet of Things is and will continue to be on data; specifically data volume, management and usage. Companies are scrambling to adapt to this new and unpredictable data reality with legacy infrastructure that cannot handle the speed and volume of data. In his session at @ThingsExpo, Don DeLoach, CEO and president of Infobright, will discuss how companies need to rethink their data infrastructure to participate in the IoT, including: Data storage: Understanding the kinds of data: structured, unstructured, big/small? Analytics: What kinds and how responsiv...
Cloudian, Inc., the leading provider of hybrid cloud storage solutions, today announced availability of Cloudian HyperStore 5.1 software. HyperStore 5.1 is an enhanced Amazon S3-compliant, plug-and-play hybrid cloud software solution that now features full Apache Hadoop integration. Enterprises can now transform big data into smart data by running Hadoop analytics on HyperStore software and appliances. This in-place analytics, with no need to offload data to other systems for Hadoop analyses, enables customers to derive meaningful business intelligence from their data quickly, efficiently and ...
Since 2008 and for the first time in history, more than half of humans live in urban areas, urging cities to become “smart.” Today, cities can leverage the wide availability of smartphones combined with new technologies such as Beacons or NFC to connect their urban furniture and environment to create citizen-first services that improve transportation, way-finding and information delivery. In her session at @ThingsExpo, Laetitia Gazel-Anthoine, CEO of Connecthings, will focus on successful use cases.
Sensor-enabled things are becoming more commonplace, precursors to a larger and more complex framework that most consider the ultimate promise of the IoT: things connecting, interacting, sharing, storing, and over time perhaps learning and predicting based on habits, behaviors, location, preferences, purchases and more. In his session at @ThingsExpo, Tom Wesselman, Director of Communications Ecosystem Architecture at Plantronics, will examine the still nascent IoT as it is coalescing, including what it is today, what it might ultimately be, the role of wearable tech, and technology gaps stil...
The true value of the Internet of Things (IoT) lies not just in the data, but through the services that protect the data, perform the analysis and present findings in a usable way. With many IoT elements rooted in traditional IT components, Big Data and IoT isn’t just a play for enterprise. In fact, the IoT presents SMBs with the prospect of launching entirely new activities and exploring innovative areas. CompTIA research identifies several areas where IoT is expected to have the greatest impact.
Wearable devices have come of age. The primary applications of wearables so far have been "the Quantified Self" or the tracking of one's fitness and health status. We propose the evolution of wearables into social and emotional communication devices. Our BE(tm) sensor uses light to visualize the skin conductance response. Our sensors are very inexpensive and can be massively distributed to audiences or groups of any size, in order to gauge reactions to performances, video, or any kind of presentation. In her session at @ThingsExpo, Jocelyn Scheirer, CEO & Founder of Bionolux, will discuss ho...
Roberto Medrano, Executive Vice President at SOA Software, had reached 30,000 page views on his home page - http://RobertoMedrano.SYS-CON.com/ - on the SYS-CON family of online magazines, which includes Cloud Computing Journal, Internet of Things Journal, Big Data Journal, and SOA World Magazine. He is a recognized executive in the information technology fields of SOA, internet security, governance, and compliance. He has extensive experience with both start-ups and large companies, having been involved at the beginning of four IT industries: EDA, Open Systems, Computer Security and now SOA.
When it comes to the Internet of Things, hooking up will get you only so far. If you want customers to commit, you need to go beyond simply connecting products. You need to use the devices themselves to transform how you engage with every customer and how you manage the entire product lifecycle. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, will show how “product relationship management” can help you leverage your connected devices and the data they generate about customer usage and product performance to deliver extremely compelling and reliabl...
SYS-CON Events announced today that GENBAND, a leading developer of real time communications software solutions, has been named “Silver Sponsor” of SYS-CON's WebRTC Summit, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. The GENBAND team will be on hand to demonstrate their newest product, Kandy. Kandy is a communications Platform-as-a-Service (PaaS) that enables companies to seamlessly integrate more human communications into their Web and mobile applications - creating more engaging experiences for their customers and boosting collaboration and productiv...
From telemedicine to smart cars, digital homes and industrial monitoring, the explosive growth of IoT has created exciting new business opportunities for real time calls and messaging. In his session at @ThingsExpo, Ivelin Ivanov, CEO and Co-Founder of Telestax, shared some of the new revenue sources that IoT created for Restcomm – the open source telephony platform from Telestax. Ivelin Ivanov is a technology entrepreneur who founded Mobicents, an Open Source VoIP Platform, to help create, deploy, and manage applications integrating voice, video and data. He is the co-founder of TeleStax, a...
The industrial software market has treated data with the mentality of “collect everything now, worry about how to use it later.” We now find ourselves buried in data, with the pervasive connectivity of the (Industrial) Internet of Things only piling on more numbers. There’s too much data and not enough information. In his session at @ThingsExpo, Bob Gates, Global Marketing Director, GE’s Intelligent Platforms business, to discuss how realizing the power of IoT, software developers are now focused on understanding how industrial data can create intelligence for industrial operations. Imagine ...
Operational Hadoop and the Lambda Architecture for Streaming Data Apache Hadoop is emerging as a distributed platform for handling large and fast incoming streams of data. Predictive maintenance, supply chain optimization, and Internet-of-Things analysis are examples where Hadoop provides the scalable storage, processing, and analytics platform to gain meaningful insights from granular data that is typically only valuable from a large-scale, aggregate view. One architecture useful for capturing and analyzing streaming data is the Lambda Architecture, representing a model of how to analyze rea...
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - is now accepting submissions to demo smart cars on the Expo Floor. Smart car sponsorship benefits include general brand exposure and increasing engagement with the developer ecosystem.
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
When it comes to the Internet of Things, hooking up will get you only so far. If you want customers to commit, you need to go beyond simply connecting products. You need to use the devices themselves to transform how you engage with every customer and how you manage the entire product lifecycle. In his session at @ThingsExpo, Sean Lorenz, Technical Product Manager for Xively at LogMeIn, will show how “product relationship management” can help you leverage your connected devices and the data they generate about customer usage and product performance to deliver extremely compelling and reliabl...
SYS-CON Events announced today that SoftLayer, an IBM company, has been named “Gold Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place June 9-11, 2015 at the Javits Center in New York City, NY, and the 17th International Cloud Expo®, which will take place November 3–5, 2015 at the Santa Clara Convention Center in Santa Clara, CA. SoftLayer operates a global cloud infrastructure platform built for Internet scale. With a global footprint of data centers and network points of presence, SoftLayer provides infrastructure as a service to leading-edge customers ranging from ...
The explosion of connected devices / sensors is creating an ever-expanding set of new and valuable data. In parallel the emerging capability of Big Data technologies to store, access, analyze, and react to this data is producing changes in business models under the umbrella of the Internet of Things (IoT). In particular within the Insurance industry, IoT appears positioned to enable deep changes by altering relationships between insurers, distributors, and the insured. In his session at @ThingsExpo, Michael Sick, a Senior Manager and Big Data Architect within Ernst and Young's Financial Servi...
SYS-CON Events announced today that Open Data Centers (ODC), a carrier-neutral colocation provider, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. Open Data Centers is a carrier-neutral data center operator in New Jersey and New York City offering alternative connectivity options for carriers, service providers and enterprise customers.
The IoT market is projected to be $1.9 trillion tidal wave that’s bigger than the combined market for smartphones, tablets and PCs. While IoT is widely discussed, what not being talked about are the monetization opportunities that are created from ubiquitous connectivity and the ensuing avalanche of data. While we cannot foresee every service that the IoT will enable, we should future-proof operations by preparing to monetize them with extremely agile systems.
There’s Big Data, then there’s really Big Data from the Internet of Things. IoT is evolving to include many data possibilities like new types of event, log and network data. The volumes are enormous, generating tens of billions of logs per day, which raise data challenges. Early IoT deployments are relying heavily on both the cloud and managed service providers to navigate these challenges. Learn about IoT, Big Data and deployments processing massive data volumes from wearables, utilities and other machines.