Safe and secure programming practices for embedded devices

Post on 04-Aug-2015

86 views 2 download

Tags:

Transcript of Safe and secure programming practices for embedded devices

1

Safe and secure programming practices for embedded devices

Soumitra Bhattacharyya

Engineering Manager- Sling Media Ltd.

website : www.slingmedia.comEmail : soumitrab@slingmedia.com Linkedin : http://www.linkedin.com/in/soumitra001

2

We live in un-trust worthy world of technology usage.

Can we afford security like this?

3

WWW

Cybercrime Evolution

• LAN environment

• First PC virus• Motivation:

damage

1986–1995

• Internet Era • “Big Worms”• Motivation:

damage

1995–2003

• OS, DB attacks• Spyware, Spam• Motivation:

Financial

2004+

• Targeted attacks• Social

engineering• Financial +

Political

2006+

Cost of U.S.

cybercrime:

About $70BSource: U.S. Government Accountability Office (GAO), FBI

2009+• Embedded devices• Virus , data theft , content theft• Damage , financial

4

Trend of cyber crime reported over the years

5

What are fraudsters looking for?

6

Need for security in devices

Devices getting integrated into personal and commercial networks

Consumer devices are ubiquitous

Pervasive use of Wireless communication

Portable devices communicate with changing network conditions

Gadgets can get stolen making them physically accessible .

7

8

9

An innocuous hack

No device is secure

10

Threats vary with the type of device and a single solution cannot

be applied to all

11

The threats are endless

Need for Security

12

Threats in a device

Theft of data ,keys and privacy

Loss of data consistency

Altering device firmware

Copy of digital content

Breaking access control

13

Embedded devices have different challenges compared to their

desktop counterparts.

14

Design challenges

Devices are constrained on their resources and capabilities

Defense mechanisms should not alter the response time of their key function

Physical accessibility of devices call for solutions different from ones applied to

traditional systems

15

Design challenges

Security concerns cannot be solved in a single abstraction layer of software

Software on devices becoming complex Quick time to market and increased cost

need simple yet robust solutions

16

Security should be part of product definition

17

Security requirements - Example All password and user data should be encrypted using 128bit AES

User and device should be authenticated before allowing streaming session

Device should use https for all transactions with the server

XXX 128 bit encryption should be used for content security

ATSC channels need not be protected.

18

What are the weak links intruders looking for ?

19

Areas prone to attack

Logical threats aiming to modify device firmware

Threats due to weakness in design and implementation

Unhandled system errors

20

Logical weaknessUn-validated user inputs Privileged process leaving some temp files. Weak language constructsConcurrent file access

Un checked bounds

21

Errors in systemBuffer overflows Race conditionCore dumps and error logging Errors in system calls Allocation or Deallocation without checks

22

Weak system designWeak encryption (for stored and transmitted data) Unsecure client/server authentication Programs running at

higher privilege than desired

23

Consequences for the device

Buffer Overflows

System crash

Arithmetic error

Changed execution

flow

Data Theft

Malware injection

Consequences

24

Business consequences

Products out of market

Loss of reputation

Financial loss

Lawsuits

Companies can be out of business due to security

breach .

25

Basic solutions to security issues

26

Core problems with ‘C’ language Language has no consideration for security

There are functions that can be used in unsecure way

Dynamic memory allocation needs careful manipulation

27

Core problems with ‘C’ languageVulnerable Function

Safe Version

strcpy() strncpy() & explicit null termination

strcat() strncat()(destination size–1)

sprintf() snprintf()scanf() family

scanf() (specify the maximum) length)

getc() / getchar()

This function can be vulnerable if used in a loop.

28

Unsecure program

int func( char * input){ char local [10]; int i=0; while (*input !=‘\0’) { local[i++]=*input++; } return 0; }

NO “NULL” CHECK

NO “Length of input “CHECK

29

Secure programming

A more appropriate program would be :

int func( char * input){ if((*input !=NULL) && (strlen(input) <=10)) { …… ……………. }} Return appropriately based on error

30

Reducing attack at the entry point is as important as trying

to get the code right

31

Input parameter validation

Perform validation at all inputs across modules

Assume all inputs are malicious

Reject data when in doubt

Parse the characters , commands and escape sequences

32

Check input data size

Validate email construct

Evaluate URL

Prevent attack from un- formatted strings

Input parameter validation

33

Checking constructs

void decode_file(char *buffer) { if(*buffer == 0xff && *(buffer+1)==0xd8) hw_decode_jpeg(buffer); else “ Invalid JPEG file” }

If invalid jpeg file is passed , decoder will fail

34

Arithmetic overflow

int ConcatBuffers(char *buf1, char *buf2, size_t len1, size_t len2){

char buf[0xFF];

if((len1 + len2) > 0xFF) return -1;

memcpy(buf, buf1, len1); memcpy(buf + len1, buf2, len2);

// do stuff with buf

return 0;

len1len2

0x103+ 0xFFFFFFFC

0xFF

Both memcpy functionsattempt to copy >255 bytes

35

Memory management Always free() dynamically allocated memory after it is not needed

Set the free pointer to NULL

Failure to release memory is problematic on embedded devices with limited memory

Attackers can use memory vulnerabilities to damage operation of

device

36

Error handling principles

Every error should be handled in a graceful way

At lowest level (e.g. drivers) try to recover from error

Internal errors should not be reported to users

Disable core dumps , stack trace , diagnostic information

37

Safe initialization

Initialize variables and file descriptors before using them.

Initialize and limit the use of env variables

Avoid passing data using env variables

Avoid execution of program at high privileges

38

Potential security bugs can creep in through uninitialized variable usage

int vuln_fn(int a) {  unsigned int result;  if (a > 0) { result = 256 % result; }  return result; }

uninitialized variable

Safe initialization

39

Compiler warnings

Warnings are first level of defense against any security flaw

Compiler warnings are effective at detecting programming flaws

It can catch bugs which are hard to find during testing.

Compile with the highest level of warning set as error

40

Flag setting for compilers

GNU C compiler :-Wall : enable all compiler warnings-Werror : treat compiler warnings as errors

ARM Developer Suite C compiler:-E+c : enable all implicit cast errors-E+l : errors on linkage disagreements-fv : reports unused declarations…

Greenhills Embedded MIPS compiler:

- check=all : enable all compile time error and warning-strict :enables strictest level of error checking

41

Create your coding guidelines

42

Basics of cryptographyEncryption is used to encode message only the group

communicating would understand

Encryption : move alphabets one step up

Decryption :move alphabets one step down

“ A SECRET MESSAGE” encrypted as

“ B TFDSFU NFTTBHF “

43

Keyed encryption algorithm

Encrypt : “A SECRET MESSAGE” Key : “C”Encrypted message “ C UGETGV OGUUCHG”

KEY value = “No of steps rotated by position of English alphabet”Encryption : Move up the alphabet

Cryptographic strength is measured in the time and resource it would require to recover the plain content

44

Advantages of keyed algorithm

Instead of communicating the algorithm , share the key in secret

With varying key sizes the encryption will get stronger (min 80 bits)

45

Public key cryptographyAsymmetric scheme using a pair of keys for encryption:

Public key is used to encrypt data Private key is used for decryption The public key is published to the world The private and public keys are mathematically

related but difficult to break

46

Hash functions o Validate integrity of data by sending a digest

Digital signatureo Checks authentication of origino Non - repudiation

SSL

Signature Encryption Hashing

DSARSA DES MD5 SHA1

Service

Mechanism

Algorithm

Other crypto mechanisms

47

Protect data stored in device

Encrypt private and confidential data like password , address book, database.

Do not store data in contiguous location.

In your design identify critical and non critical memory areas based on data stored

48

Securing Network transactions• SSL is Secure socket layer ,a global standard in transferring data• It creates encrypted link between server and web browser

Secure communication goals are privacy, message integrity and

authentication

49

Security within the device

Architecture of a secure processor

Secure SoC

Secure ROMSecure

BootloaderROM

(Internal)

RAM (Internal)

Processor

External RAM

Signed Firmware (Ext. ROM/Flash/HDD)

50

Secure boot loader

Boot functionality

Sign verification

Public key

Signed firmware

App code + data Signature

Private key

The Keys are generated by the device manufacturer

Firmware not signed by manufacturer will not work.

Signed Firmware binary

Key

51

Secure boot loader contains critical code to configure the hardware for limited access.

Secret keys are loaded into the internal RAM only

Secure boot loader checks the validity of firmware code by verifying the signature

Abort loading of device firmware if signature verification fails

Secure Boot

52

Check for compliance

System Security Audit

53

Security audit

Periodic audits will uncover security loopholes

Review the code for security violation

Review the system architecture

Look for unintended firmware installations

Check network and storage security

54

Module Audit step List Action required

Kernel modules

List and check if all modules are needed

x.ko , y.ko. Remove modules

not neededKernel debug

Is kernel debug enabled ? Yes Disable debug

Installed software

Is there any installed default software?

Rpc , pop3 , telnet

Remove these installed software

Field debug Check logging protocol Clear Encrypt logging mechanism

Example audit report

55

Module Audit step List Action required

Network Ports

Check which ports are available for connection using nmap.

Remove ports not reqd.

Stored data Check stored data Clear in file Use encryption

Media transmission

Check security of transmission

tiny encryption

Weak , use stronger encrypt

ServicesAny unintended services running?

Httpd, telnet Remove the services.

Example audit report (Contd..)

56

Rely on tools wherever possible

57

ToolsSome of the tools which un cover security issues

Does software analysis in depth.

Profiling and debugging tool

Tool for port scanning

Scans database server application

http://www.securecoding.org/companion/tools.php

58

Does hardware need to be secure too?

59

Hardware securityDisable debug ports in production build

Ensure debug port cannot access security critical assets

Use secure code to rewrite flash

Check on board sanity of clocks at boot

60

Hardware security (Contd) Keep critical data and

code in on-SOC memory Route critical lines through sub surface of PCB

Prevent extraction of off –SOC through probe on bus

Encrypt data transferring over bus

61

Let us be safe

62

Thank You