SECURE PROGRAMMING A.A. 2018/2019

Similar documents
Lecture 12 Integers. Computer and Network Security 19th of December Computer Science and Engineering Department

PROGRAMMAZIONE I A.A. 2017/2018

CS61B Lecture #14: Integers. Last modified: Wed Sep 27 15:44: CS61B: Lecture #14 1

CYSE 411/AIT681 Secure Software Engineering Topic #10. Secure Coding: Integer Security

2/9/18. Readings. CYSE 411/AIT681 Secure Software Engineering. Introductory Example. Secure Coding. Vulnerability. Introductory Example.

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

CS61B Lecture #14: Integers

Security Coding Module Integer Error You Can t Count That High CS1

Review: Exam 1. Your First C++ Program. Declaration Statements. Tells the compiler. Examples of declaration statements

1.3b Type Conversion

Operators and Expressions:

CS 261 Fall Mike Lam, Professor Integer Encodings

Scientific Computing. Error Analysis

Computer System and programming in C

Visual C# Instructor s Manual Table of Contents

These are reserved words of the C language. For example int, float, if, else, for, while etc.

Programming in C++ 5. Integral data types

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

Data Representa5on. CSC 2400: Computer Systems. What kinds of data do we need to represent?

CS 107 Lecture 3: Integer Representations

2.1. Unit 2. Integer Operations (Arithmetic, Overflow, Bitwise Logic, Shifting)

CS 31: Introduction to Computer Systems. 03: Binary Arithmetic January 29

Arithmetic and Bitwise Operations on Binary Data

CSE 127 Computer Security

COMP2611: Computer Organization. Data Representation

Integers. Today. Next time. ! Numeric Encodings! Programming Implications! Basic operations. ! Floats

But first, encode deck of cards. Integer Representation. Two possible representations. Two better representations WELLESLEY CS 240 9/8/15

Arithmetic type issues

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Data Types. Data Types. Integer Types. Signed Integers

Page 1. Today. Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right? Compiler requirements CPP Volatile

More Programming Constructs -- Introduction

LESSON 5 FUNDAMENTAL DATA TYPES. char short int long unsigned char unsigned short unsigned unsigned long

Chapter 7. Basic Types

ECE 250 / CS 250 Computer Architecture. C to Binary: Memory & Data Representations. Benjamin Lee

Basic Definition INTEGER DATA. Unsigned Binary and Binary-Coded Decimal. BCD: Binary-Coded Decimal

Chapter 3. Section 3.10 Type of Expressions and Automatic Conversion. CS 50 Hathairat Rattanasook

Data Types and Variables in C language

CS429: Computer Organization and Architecture

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

Arithmetic and Bitwise Operations on Binary Data

Module 2: Computer Arithmetic

Number Systems, Scalar Types, and Input and Output

A Fast Review of C Essentials Part I

10.1. Unit 10. Signed Representation Systems Binary Arithmetic

Bits, Bytes, and Integers

Expressions. Arithmetic expressions. Logical expressions. Assignment expression. n Variables and constants linked with operators

2. MACHINE REPRESENTATION OF TYPICAL ARITHMETIC DATA FORMATS (NATURAL AND INTEGER NUMBERS).

As stated earlier, the declaration

Number Systems (2.1.1)

(T) x. Casts. A cast converts the value held in variable x to type T

Number Systems. Binary Numbers. Appendix. Decimal notation represents numbers as powers of 10, for example

3. EXPRESSIONS. It is a sequence of operands and operators that reduce to a single value.

Computers Programming Course 5. Iulian Năstac

Jin-Soo Kim Systems Software & Architecture Lab. Seoul National University. Integers. Spring 2019

Chapter 2: Using Data

Integer primitive data types

Groups of two-state devices are used to represent data in a computer. In general, we say the states are either: high/low, on/off, 1/0,...

Bits, Bytes and Integers

PROGRAMMAZIONE I A.A. 2017/2018

Chapter 2. Data Representation in Computer Systems

Chapter 3. Fundamental Data Types

Representing and Manipulating Integers. Jo, Heeseung

CS107, Lecture 3 Bits and Bytes; Bitwise Operators

PROGRAMMAZIONE I A.A. 2017/2018

Computer Systems CEN591(502) Fall 2011

Integers II. CSE 351 Autumn Instructor: Justin Hsia

Representing and Manipulating Floating Points

Arithmetic Operators. Portability: Printing Numbers

Declaration. Fundamental Data Types. Modifying the Basic Types. Basic Data Types. All variables must be declared before being used.

The Design of C: A Rational Reconstruction

DEPARTMENT OF MATHS, MJ COLLEGE

Representing and Manipulating Floating Points. Computer Systems Laboratory Sungkyunkwan University

Lecture 5-6: Bits, Bytes, and Integers

Basics of Programming

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Chapter 3: Arithmetic for Computers

The Design of C: A Rational Reconstruction"

THE FUNDAMENTAL DATA TYPES

5.Coding for 64-Bit Programs

CSCE 548 Building Secure Software Integers & Integer-related Attacks & Format String Attacks. Professor Lisa Luo Spring 2018

Lecture 05 Integer overflow. Stephen Checkoway University of Illinois at Chicago

CHAPTER 5: Representing Numerical Data

Important From Last Time

Internal representation. Bitwise operators

Page 1. Today. Important From Last Time. Is the assembly code right? Is the assembly code right? Which compiler is right?

This is CS50. Harvard University Fall Quiz 0 Answer Key

CS107, Lecture 2 Bits and Bytes; Integer Representations

Fundamentals of Programming

Computer Architecture and System Software Lecture 02: Overview of Computer Systems & Start of Chapter 2

Internal representation. Bitwise operators

Internal representation. Bitwise operators

Overview of C. Basic Data Types Constants Variables Identifiers Keywords Basic I/O

World Inside a Computer is Binary

EL2310 Scientific Programming

Decimal & Binary Representation Systems. Decimal & Binary Representation Systems

Digital Arithmetic. Digital Arithmetic: Operations and Circuits Dr. Farahmand

ESc101 : Fundamental of Computing

Bits, Bytes, and Integers Part 2

Transcription:

SECURE PROGRAMMING A.A. 2018/2019

INTEGER SECURITY

SECURITY FLAWS The integers are formed by the natural numbers including 0 (0, 1, 2, 3,...) together with the negatives of the nonzero natural numbers ( 1, 2, 3,...). Integers represent a growing and underestimated source of vulnerabilities in C programs, primarily because boundary. When developing secure systems, we cannot assume that a program will operate normally, given a range of expected inputs, because attackers are looking for input values that produce an abnormal effect.

REPRESENTATION So, how are integer represented in C? Sign magnitude or two s complement?

TWO S COMPLEMENT Binary value Two's complement Unsigned 00000000 0 0 00000001 1 1 01111110 126 126 01111111 127 127 10000000 128 128 10000001 127 129 10000010 126 130 11111110 2 254 11111111 1 255 In two's-complement, there is only one zero, represented as 00000000. Negating a number (whether negative or positive) is done by inverting all the bits and then adding one to that result

HOW TO GET THE COMPLEMENTARY From a number to its complement: from 5 to -5 Flip all the bits and then + 1 0000 0101 (value 5) ü1111 1010 (flip) ü1111 1011 (+1) You can do the inverse algorithm: when an integer number starts with 1 it means that it is negative ü1111 1011 value (-5) ü1111 1010 (-1) ü0000 0101 (flip)

HOW MANY NUMBERS CAN I REPRESENT? With n bits üfrom (-2 N 1 ) to (2 N 1 1) ü There is no -0, so it is possible to represent one more negative number For instance, with 8 bits, üfrom -128 to + 127 1000 0000 0111 1111 The rule in the previous slide to get the complimentary does not work because 128 is not representable with 8 bits in two s complement

OPERATION EXAMPLES 0000 1111 (15) + 1111 1011 ( 5) Ok! 11111 111 (carry) 0000 1111 (15) + 1111 1011 ( 5) ================== 0000 1010 (10) 0111 (7) + 0011 (3) 0000 1111 (15) 1111 1011 ( 5) Arithmetic overflow! 0111 (carry) 0111 (7) + 0011 (3) ============= 1010 ( 6) invalid! Ok! 11110 000 (borrow) 0000 1111 (15) 1111 1011 ( 5) =========== 0001 0100 (20)

UNSIGNED TYPES

WRAPAROUND A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is 1 greater than the largest value that can be represented by the resulting type.

EXAMPLE

EXAMPLE for (unsigned i = n; --i >= 0; ) // will never terminate This type of software failure occurred on Saturday, December 25, 2004, when Comair halted all operations and grounded 1,100 flights after a crash of its flight-crewscheduling software. The software failure was the result of a 16-bit counter that limits the number of changes to 32,768 in any given month. Storms earlier in the month caused many crew reassignments, and the 16-bit value was exceeded.

CHECKS

CHECKS

OPERATORS AND WRAPS

SIGNED TYPES

SIGNED TYPES In C, each unsigned integer type, excluding the type _Bool, has a corresponding signed integer type that occupies the same amount of storage. üsigned char üshort int üint ülong int ülong long int

WHY SO MANY SIGNED TYPES? Most integer variables are used as sizes, counters, or indices that require only nonnegative values. So why not declare them as unsigned integers that have a greater range of positive values? One possible explanation is the lack of an exceptionhandling mechanism in C. As a result, C programmers have developed various mechanisms for returning status from functions.

WRAP WHEEL Two s complement

FROM GREATEST TO LOWEST

EXAMPLES

TABLE OF OPERATORS

SIGNED AND UNSIGNED CHAR The CERT C Secure Coding Standard, INT07-C. Use only explicitly signed or unsigned char type for numeric values üit is the only portable way to guarantee the signedness of the character types.

TYPE CONVERSIONS

HIERARCHY OF TYPES When arithmetic operands have different types, the implicit type conversion is governed by the types conversion rank. üany two unsigned integer types have different conversion ranks. If one is wider than the other, then it has a higher rank. üeach signed integer type has the same rank as the corresponding unsigned type. üthe standard integer types are ranked in the order: _Bool < char < short < int < long < long long üthe floating-point types are ranked in the following order: float < double < long double üthe lowest-ranked floating-point type, float, has a higher rank than any integer type. üenum have the same rank as int.

INTEGER PROMOTION In any expression, you can always use a value whose type ranks lower than int in place of an operand of type int or unsigned int. In these cases, the compiler applies integer promotion: any operand whose type ranks lower than int is automatically converted to the type int, provided int is capable of representing all values of the operand s original type. If int is not sufficient, the operand is converted to unsigned int. Operations in the CPU are executed on 4 bytes at least

EXAMPLE #include <stdio.h> int main() { char a = 30, b = 40, c = 10; char d = (a * b) / c; printf ("%d ", d); return 0; } 120 At first look, the expression (a*b)/c seems to cause arithmetic overflow because signed characters can have values only from -128 to 127 (in most of the C compilers), and the value of subexpression (a*b) is 1200 which is greater than 128. But integer promotion happens here in arithmetic done on char types and we get the appropriate result without any overflow.

WHAT DOES IT HAPPEN? The usual arithmetic conversions are applied as follows: üif either operand has a floating-point type, then the operand with the lower conversion rank is converted to a type with the same rank as the other operand. Real types are converted only to real types. üif both operands are integers, integer promotion is first performed on both operands. If after integer promotion the operands still have different types, conversion continues as follows: If one operand has an unsigned type T whose conversion rank is at least as high as that of the other operand s type, then the other operand is converted to type T. Otherwise, one operand has a signed type T whose conversion rank is higher than that of the other operand s type. The other operand is converted to type T only if type T is capable of representing all values of its previous type. If not, then both operands are converted to the unsigned type that corresponds to the signed type T.

EXAMPLES int x = 0; int i = -1; unsigned int limit = 200U; long n = 30L; if ( i < limit ) x = limit * n; printf( %d\n, x); 0 In this example, to evaluate the comparison in the if condition, the value of i, 1, must first be converted to the type unsigned int. The result is a large positive number (next slide). Hence, the if condition is false. In the if, the value of limit is converted to n s type, long, if the value range of long contains the whole value range of unsigned int. If not for example, if both int and long are 32 bits wide then both multiplicands are converted to unsigned long.

CONVERSIONS TO UNSIGNED INTEGER TYPES Integer values are always preserved if they are within the range of the new unsigned type übetween 0 and Utype_MAX For values outside the new unsigned type s range, the value after conversion is the value obtained by adding (Utype_MAX + 1) as many times as necessary until the result is within the range of the new type. unsigned short n = 1000; n = -1; // The value 1000 is within the range of // unsigned short // the value 1 must be converted. 1 + (USHRT_MAX + 1) = USHRT_MAX, the final statement in the previous example is equivalent to n = USHRT_MAX;

INTEGER VULNERABILITIES

EXAMPLE JPEG COM Marker Processing Vulnerability in Netscape Browsers size_t is always an alias for an unsigned type What if 1 is passed as length?

CONVERSION ERRORS malloc() takes size_t as argument What if 1 negative?

TRUNCATION 65,500 chars for argv[1] 536 chars for argv[2] +1 = 65,537 An UINT_MAX is 65535 A string of 1 char is allocated: buffer overflow!

MITIGATION STRATEGIES

ERRORS As we have seen, integer vulnerabilities result from integer type range errors. For example, integer overflows occur when integer operations generate a value that is out of range for a particular integer type. Truncation errors occur when a value is stored in a type that is too small to represent the result. Conversions, particularly those resulting from assignment or casts, can result in values that are out of the range of the resulting type.

EXAMPLE OF TRUNCATION b: 1 #include<stdio.h> a: 9223372032559808513 #include<limits.h> int main() { long long int a= (LLONG_MAX-UINT_MAX)+1; int b= a; } printf("b: %d\n", b); printf("a: %lld\n", a); 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111110-11111111 11111111 11111111 11111111 00000000 00000000 00000000 00000000 = 00000000 00000000 00000000 00000000 11111111 11111111 11111111 11111110 + 10000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 = 10000000 00000000 00000000 00000000 11111111 11111111 11111111 11111110

INTEGER TYPE SELECTION The first step in developing secure code is to select the appropriate data types. An integer type provides a model of a finite subset of the mathematical set of integers. Select integer types that can represent the range of possible runtime values, and then ensure that these ranges are not exceeded.

SIZES Say, for example, that you need to represent the size of an object as an integer. You could represent the size of the object as a short int, as in the following declaration: üshort total = strlen(argv[1])+ 1; Variables of type size_t are guaranteed to be precise enough to represent the size of an object, as in the following example: üsize_t total = strlen(argv[1])+ 1; INT01-C. Use size_t for all integer values representing the size of an object.

EXAMPLE Solved? NO Now yes

TYPE RANGE CHECKING Because all integer vulnerabilities are type range errors, type range checking if properly applied can eliminate all integer vulnerabilities The CERT C Secure Coding Standard has several rules to prevent range errors: üint30-c. Ensure that unsigned integer operations do not wrap. üint31-c. Ensure that integer conversions do not result in lost or misinterpreted data. üint32-c. Ensure that operations on signed integers do not result in overflow.

PRE-CONDITION One approach to eliminating integer exceptional conditions is to test the values of the operands before an operation to prevent overflow and wrapping from occurring.

PRE-CONDITION WITH SIGNED

POST-CONDITION Postcondition tests can be used to detect unsigned integer wrapping, for example, because these operations are well defined as having modulo behavior.

SECURE INTEGER LIBRARIES Michael Howard has written parts of a safe integer library that detects integer overflow conditions using architecture-specific mechanisms.

COMPILER CHECKS GCC provides an -ftrapv compiler option that offers limited support for detecting integer overflows at runtime. üthe GCC runtime system generates traps for signed overflow on addition, subtraction, and multiplication operations for programs compiled with the -ftrapv flag.

TESTING AND STATIC ANALYSIS Static analysis, by either the compiler or a static analyzer, can be used to detect potential integer range errors in source code.

ARIANE 5, JUNE 6 1996 Start. 37 seconds of flight. KABOOM! 10 years and 7 billion dollars are turning into dust. The programmers were to blame for everything

REASON The investigation revealed that this software module contained seven variables involved in type conversion operations. It turned out that the developers performed the analysis for the vulnerability of all operations, capable of throwing an exception. It was their conscious action to add adequate protection to four variables, and leave three of them including BH unprotected. The ground for this decision was the certainty that overflow is not possible in these variables in general. This confidence was supported by the evaluations, showing that the expected range of physical parameters that was taken as the basis for the determination of the values of the mentioned variables can never lead to an undesirable situation. And it was true but for the trajectory evaluated for Ariane 4.

ADA CODE

REASON Specifically a 64 bit floating point number relating to the horizontal velocity of the rocket with respect to the platform was converted to a 16 bit signed integer. The number was larger than 32,767, the largest integer storeable in a 16 bit signed integer, and thus the conversion failed.

WHY The new generation Ariane 5 rocket launched on an entirely different trajectory, for which no evaluations were carried out. Meanwhile, it turned out that the horizontal velocity (together with the initial acceleration) exceeded the estimated (for Ariane 4) more than five times. The protection of all 7 (including BH) variables wasn t provided because the developers had to look for ways to reduce unnecessary evaluation expenses, and they weakened the protection in that fragment where theoretically the accident could not happen.