62
Safe and secure programming practices for embedded devices Soumitra Bhattacharyya Engineering Manager- Sling Media Ltd. website : www.slingmedia.com Email : [email protected] Linkedin : http ://www.linkedin.com/in/soumitra001 1

Safe and secure programming practices for embedded devices

Embed Size (px)

Citation preview

Page 1: 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 : [email protected] Linkedin : http://www.linkedin.com/in/soumitra001

Page 2: Safe and secure programming practices for embedded devices

2

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

Can we afford security like this?

Page 3: Safe and secure programming practices for embedded devices

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

Page 4: Safe and secure programming practices for embedded devices

4

Trend of cyber crime reported over the years

Page 5: Safe and secure programming practices for embedded devices

5

What are fraudsters looking for?

Page 6: Safe and secure programming practices for embedded devices

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 .

Page 7: Safe and secure programming practices for embedded devices

7

Page 8: Safe and secure programming practices for embedded devices

8

Page 9: Safe and secure programming practices for embedded devices

9

An innocuous hack

No device is secure

Page 10: Safe and secure programming practices for embedded devices

10

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

be applied to all

Page 11: Safe and secure programming practices for embedded devices

11

The threats are endless

Need for Security

Page 12: Safe and secure programming practices for embedded devices

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

Page 13: Safe and secure programming practices for embedded devices

13

Embedded devices have different challenges compared to their

desktop counterparts.

Page 14: Safe and secure programming practices for embedded devices

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

Page 15: Safe and secure programming practices for embedded devices

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

Page 16: Safe and secure programming practices for embedded devices

16

Security should be part of product definition

Page 17: Safe and secure programming practices for embedded devices

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.

Page 18: Safe and secure programming practices for embedded devices

18

What are the weak links intruders looking for ?

Page 19: Safe and secure programming practices for embedded devices

19

Areas prone to attack

Logical threats aiming to modify device firmware

Threats due to weakness in design and implementation

Unhandled system errors

Page 20: Safe and secure programming practices for embedded devices

20

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

Un checked bounds

Page 21: Safe and secure programming practices for embedded devices

21

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

Page 22: Safe and secure programming practices for embedded devices

22

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

higher privilege than desired

Page 23: Safe and secure programming practices for embedded devices

23

Consequences for the device

Buffer Overflows

System crash

Arithmetic error

Changed execution

flow

Data Theft

Malware injection

Consequences

Page 24: Safe and secure programming practices for embedded devices

24

Business consequences

Products out of market

Loss of reputation

Financial loss

Lawsuits

Companies can be out of business due to security

breach .

Page 25: Safe and secure programming practices for embedded devices

25

Basic solutions to security issues

Page 26: Safe and secure programming practices for embedded devices

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

Page 27: Safe and secure programming practices for embedded devices

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.

Page 28: Safe and secure programming practices for embedded devices

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

Page 29: Safe and secure programming practices for embedded devices

29

Secure programming

A more appropriate program would be :

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

Page 30: Safe and secure programming practices for embedded devices

30

Reducing attack at the entry point is as important as trying

to get the code right

Page 31: Safe and secure programming practices for embedded devices

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

Page 32: Safe and secure programming practices for embedded devices

32

Check input data size

Validate email construct

Evaluate URL

Prevent attack from un- formatted strings

Input parameter validation

Page 33: Safe and secure programming practices for embedded devices

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

Page 34: Safe and secure programming practices for embedded devices

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

Page 35: Safe and secure programming practices for embedded devices

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

Page 36: Safe and secure programming practices for embedded devices

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

Page 37: Safe and secure programming practices for embedded devices

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

Page 38: Safe and secure programming practices for embedded devices

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

Page 39: Safe and secure programming practices for embedded devices

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

Page 40: Safe and secure programming practices for embedded devices

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

Page 41: Safe and secure programming practices for embedded devices

41

Create your coding guidelines

Page 42: Safe and secure programming practices for embedded devices

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 “

Page 43: Safe and secure programming practices for embedded devices

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

Page 44: Safe and secure programming practices for embedded devices

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)

Page 45: Safe and secure programming practices for embedded devices

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

Page 46: Safe and secure programming practices for embedded devices

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

Page 47: Safe and secure programming practices for embedded devices

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

Page 48: Safe and secure programming practices for embedded devices

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

Page 49: Safe and secure programming practices for embedded devices

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)

Page 50: Safe and secure programming practices for embedded devices

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

Page 51: Safe and secure programming practices for embedded devices

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

Page 52: Safe and secure programming practices for embedded devices

52

Check for compliance

System Security Audit

Page 53: Safe and secure programming practices for embedded devices

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

Page 54: Safe and secure programming practices for embedded devices

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

Page 55: Safe and secure programming practices for embedded devices

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..)

Page 56: Safe and secure programming practices for embedded devices

56

Rely on tools wherever possible

Page 57: Safe and secure programming practices for embedded devices

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

Page 58: Safe and secure programming practices for embedded devices

58

Does hardware need to be secure too?

Page 59: Safe and secure programming practices for embedded devices

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

Page 60: Safe and secure programming practices for embedded devices

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

Page 61: Safe and secure programming practices for embedded devices

61

Let us be safe

Page 62: Safe and secure programming practices for embedded devices

62

Thank You