How to write secure C/C++ application code for your embedded design: Part 5 -

How to write secure C/C++ application code for your embedded design: Part 5

Many flaws are exploitable because the address space of the vulnerableprogram has memory that is both writable and executable. As a result,an attacker can write to memory using a buffer overflow, for example,and then transfer control to the address of the injected code.

This problem can be addressed by ensuring that memory pages have theminimal permissions required for proper operation (an application of the principle of leastprivilege). This is not a comprehensive defense against allexploits, but simply a mechanism designed to extend yourdefense-in-depth strategy by increasing the difficulty for an attackerto exploit a vulnerability.

Several existing systems enforce reduced privileges in the kernel sothat no part of the process address space is both writable andexecutable. This policy has been named “W xor X” or more concisely WAX.Enforcement of this policy results, for example, in a nonexecutablestack.

OpenBSD is an exampleof a system that implements a WAX policy. In OpenBSD, an applicationcan still request explicit permissions with mprotect() to override thedefault.

The implementation of a WnX policy depends on the central processingunit (CPU) and memory management unit (MMU) architecture. Forprocessors that feature an execute bit for each page of memory; OpenBSDimplements two changes to make this possible:

1. The signal trampoline isremoved from the stack. The signal trampoline page is given read andexecute permissions, while the stack segment is given read and writepermissions. By doing this, the stack becomes nonexecutable.

2. The mapping of sharedlibraries and heap memory space is changed so that the data segments donot contain objects which are read, write, and executable. This entailsmoving the shared library global offset table (GOT), the shared libraryprocedure linkage table (PLT), C++ constructors (.ctors), and C++destructors (.dtors).

The GOT and PLT are mapped onto their own pages, which are madenonwritable. Minor changes to the dynamic linker are needed toaccommodate this change. The . dtors and . ctors sections are moved inwith the GOT and consequently become nonwritable as well. Making thesechanges eliminates executable objects from the data segment.

The implementation for architectures that do not support a per-pageexecute bit (such as IA-32) is more involved but achieves a similarresult.

To supplement this scheme, OpenBSD also reduces permissions onreadonly strings and pointers stored as constant data. Historically,these objects were stored in the text segment and had permissions ofPROT READ IPROT EXEC. This meant that constant data could potentiallybe executed as shell code.

Because OpenBSD uses the ELF object file format, a new segment,aptly named . rodata, was created to store this data. As a result, thisbehavior was changed so that now these objects only have PROT READ andthey lose PROT EXEC.

Open BSD's PaX
PaX is a similar set of enhancements for Linux systems that predatesthe OpenBSD implementation. PaX implements nonexecutable memory pagesand address space layout randomization. The PaX implementation is alsodependent on the CPU and MMU of the underlying platform.

For systems that do not support the per-page execute bit, PaXimplements a technique termed virtual memory area mirroring thatduplicates every executable page in a data section in a correspondingcode section. If an attempt is made to fetch an instruction ataddresses located in the data segment that does not have any codelocated at the corresponding mirrored address, a page fault occurs andthe kernel kills the process.Data Execution Prevention
Microsoft Windows XP and Windows Server 2003 feature a similarkernellevel memory protection feature known as data executionprevention (DEP). DEP prevents code from being executed from memorypages such as the default heap, stacks, and memory pools.

If an application attempts to run code from a memory page that isprotected, a memory access violation exception occurs, and if theexception is not handled, the calling process is terminated. Under thissystem, if an application must run code from a memory page, it mustallocate and set the proper virtual memory protection attributes.

The memory must be marked PACE-EXECUTE, PAGE-EXECUTE-READ,PAGE_EXECUTE_READWRITE, or PAGE_EXECUTE_WRITECOPY on allocation. Heapallocations made by calling the mal 1 oc () and HeapAl 1 oc ()functions are nonexecutable. Applications cannot run code from thedefault process heap or the stack.

Defense in Depth
The idea behind defense in depth is to manage risk with multipledefensive strategies, so that if one layer of defense turns out to beinadequate, another layer of defense can prevent a security flaw frombecoming an exploitable vulnerability and/or limit the consequences ofa successful exploit.

For example, combining secure programming techniques with secureruntime environments should reduce the likelihood that vulnerabilitiesremaining in the code at deployment time can be exploited in theoperational environment.

The alternative to defense in depth is to rely on a single strategy.Complete input validation, for example, could theoretically eliminatethe need for other defenses.

If all input strings are verified to be of valid length, forexample, there would be no need to use bounded string copy operations,and strcpy(), memcpy() and similar operations could be used withoutconcern. Also, there would be no need to provide any type of runtimeprotection against stack- or heap-based overflows, because there is noopportunity for overflow.

While you could theoretically develop and secure a small programusing input validation, for real systems this is infeasible. Large,real-world programs are developed by teams of programmers.

Modules, once written, seldom remain unchanged. Maintenance canoccur even before first customer ship or initial deployment. Over time,these programs are likely to be modified by many programers formultiple reasons. Through all this change and complexity, it isdifficult to ensure that input validation alone will provide completesecurity.

Multiple layers of defense are useful in preventing exploitation atruntime, but are also useful for identifying changing assumptionsduring development and maintenance.

Team Software Process for Secure Software Development (TSP-Secure) wasdesigned to address some of the imprecise software engineeringpractices that can lead to vulnerable software: lack of clear securitygoals, unclear roles, inadequate planning and tracking, not recognizingsecurity risks early in the software development life cycle, andperhaps most important of' all, ignoring security and quality until theend of the software development life cycle.

TSPSecure is a TSP-based method that can predictably improve thesecurity of developed software. The SLI's Team Software Processprovides a framework, a set of processes, and disciplined methods forapplying software engineering principles at the team and individuallevel [Humphrey 02].

Software produced with the TSP has one or two orders of magnitudefewer defects than software produced with current practices (0 to 0.1defects per thousand lines of code, as opposed to 1 to 2 defects perthousand lines of code) [Davis03, McAndrews 00].

TSP-Secure extends the TSP to focus more directly on the security ofsoftware applications. TSP-Secure addresses secure software developmentin three ways:

First, because secure software is not built by accident, TSP-Secureaddresses planning for security. Also, because schedule pressures andpersonnel issues get in the way of implementing best practices,TSP-Secure helps to build self-directed development teams and then putthese teams in charge of their own work.

Second, because security and quality are closely related, TSPSecurehelps manage quality throughout the product development life cycle.

Finally, because people building secure software must have anawareness of software security issues, TSP-Secure includes securityawareness training for developers.Planning and Tracking
TSP-Secure teams build their own plans. Initial planning is conductedin a project launch, which takes place in nine meetings over three tofour days, as shown in Figure 8-9 below. The launch is led by aqualified team coach.

In a TSPSecure launch, the team reaches a common understanding ofthe work and the approach they will take to do the work, produces adetailed plan to guide the work, and obtains management support for theplan.

Figure8-9. TSP launch

At the end of the TSP-Secure launch, the team and management agreeon how the team will proceed with the project. As the tasks in thenear-term plans are completed, the team conducts a relaunch, where thenext cycle of work is planned in detail.

A relaunch is similar to a launch, but slightly shorter in duration.The cycle of plan and replan follows until the project is completed.After the launch, the team executes its plan and manages its own work.

A TSP coach works with the team to help them collect and analyzeschedule and quality data, follow their process, track issues andrisks; maintain their plan, track progress against their goals, andreport status to management.

Figure8-10. Filtering out vulnerabilities

Quality Management
Defects delivered in released software are a percentage of the totaldefects introduced during the software development life cycle. TheTSP-Secure quality management strategy is to have multiple defectremoval points in the software development life cycle.

Increasing defect removal points increases the likelihood of findingdefects soon after they are introduced, enabling the problems to bemore easily fixed and the root causes more easily determined andaddressed.

Each defect removal activity can be thought of as a filter thatremoves some percentage of defects that can lead to vulnerabilitiesfrom the software product, while other defects that can lead tovulnerabilities escape the filter and remain in the software, asillustrated by Figure 8-10 above .

The more defect removal filters there are in the softwaredevelopment life cycle, the fewer defects that can lead tovulnerabilities will remain in the software product when it isreleased.

Defects are measured as they are removed. Defect measurement.informs the team as to where they stand against their goals, helps themdecide whether to trove to the next step or to stop and take correctiveaction, and indicates where to fix their process to meet their goals.The earlier the defects are measured, the more time an organization hasto take corrective action early, in the software development lifecycle.

Software developers must be aware of those aspects of security thatimpact their software. Thus TSP-Secure includes an awareness workshopthat exposes participants to a limited set of security issues. TheTSP-Secure workshop begins with an overview of common vulnerabilities.Design; implementation, and testing practices to address the commoncauses of vulnerabilities are also presented.

Final Words
There are a number of existing practices, processes, tools, andtechniques that can be used to improvc the quality and security ofdeveloped software. Evidence of the effectiveness of these mitigationstrategies is primarily anecdotal, although many may well be effectivein preventing or eliminating vulnerabilities from code.

Steve Lipner and Michael Howard present empirical evidence thatsuggests that the activities of the SDL (such as threat modeling) havereduced security bulletins for conforming development efforts [Lipner 05].

Secure coding requires an accurate understanding of the problem anda uniform application of effective solutions. Secure system developmentrequires that secure coding practices be ubiquitously appliedthroughout the software development life cycle.

Further Reading
For more on input validation, read the “Input Validation” chapter fromJohn Viega's and Matt Messier's SecureProgramming Cookbook for C and C++. and also the “Validate AllInput” chapter from David Wheelers book, Secure Programming forLinux and UNIX HOWTO [Wheeler 03].

To read Part 1, go to “Secure software development principles.”
To read Part 2, go to “Systems Quality Requirements Engineeiring.”
To read Part 3, go to “Architecuteand Design“.
To read Part 4, go to “Staticanalysis and quality assurance.”

(Editor's note: For more onembedded security, check out the cover story in the Octoberissue of Embedded Systems Design Magazine: Embedded systems security has moved to theforefront”, as well as Employ a secure flavorof Linux.” )

This article is excerpted withpermission from the book titled “SecureCoding in C and C++“, by Robert C. Seacord, published and allcopyrights held by Addison Wesley/Pearson Education. It can bepurchased on line.

Robert Seacord is senior vulnerability analyst with the CERT/Corrdination Center of theSoftware Engineering Institute. Noopor Davis is a visiting scientistwith the SEI Software Engineering Management Program. Chad Dougherty isa member of the technical staff for the SEI Networked SystemsSurvivability Program. Nancy Mead is a senior member of the technicalstaff for the SEI Networked Systems Survivability Program. Robert Meadis a member of the technical staff for the SEI Networked SystemsSurvivability Program.

Other recent articles on security
Securingwireless MCUs is changing embedded systems design
Stateof security technology: embedded to enterprise
Securiingmobile and embedded devices: encryptioon is not security
Guidelinesfor designing secure PCI PED EFT terminals
Overcomingsecurity issues in embedded systems
Buildingmiddleware for security and safety-critical applications
Securityconsiderations for embedded operating systems
Diversityprotects embedded systems
Aproactive strategy for eliminating embedded software vulnerabilities
Understandingelliptic curve cryptography
Securingad hoc embedded wireless networks with public key cryptography

Aframework for considering security in embedded systems
Calculatingthe exploitability of your embedded software
Badassumptions lead to bad security

Securingembedded systems for networks
Implementingsolid security on a Bluetooth product
Smartsecurity improves battery life
Howto establish mobile security
Ensuringstrong security for mobile transactions
Securingan 802.11 network

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.