Programming For Security

You might also like

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 25

Programming for Security

Alosh Bennett
What is computer security?

Protection of information and property from theft and corruption while allowing it to remain
accessible and productive to the intended users.
~wikipedia

 Information and property should be


 Kept out of reach of unauthorized users
 Can only be modified by those who has permission to do so
 Accessible to intended users

 Security applies to
 Information
 Computer System

 A resource is secure if it is
 Confidential
 Integral
 Available
Building a secure application

 Why do you have to make an application secure?


 Loss of confidential and personal data
 System becomes unusable
 Loss of trust and credibility
 Very costly

 How to make an application secure?


 Make application free of vulnerabilities

 What causes vulnerabilities?


 Bad design
 Coding errors
 Lack of subject knowledge
 Lack of awareness
How does a hacker work?

 Find out about the system


 What OS is the system running?
 What are the input/output?
 Probe the system
 Interact with the system
 Push the buttons
 Make the system verbose
 Make system talk back
 Are there log files?
 Make the system unstable
 Give wrong inputs
 Overload the system
 Get access to the system/ gain more privileges
 Try guest user
 Is there any task running with elevated privileges?
Hacking – Know the system

 Scan for open ports and interfaces


 URLs and ports tell you about the services running
 There could be known exploits for the OS and server versions

 Packet Sniffing
 Using packet sniffing you could listen to the data sent by the system
 There could be confidential information like passwords

 Look for password files


 Unix stores passwords in the file /etc/shadow

 Defending against attacks:


 Do not run any unwanted service
 Store password files with correct permissions
 Do not store passwords in plain text
Hacking – Probe the system

 Try different URLs


 If there is http://mysite.com/php/login.php
 http://mysite.com/php/ could do a directory listing
 Editors mostly leave backup files login.php~
 Look for test files test.php
 Login and test files could have database username, password and validation logic
hard-coded

 Try for default accounts/ master passwords


 Look for plain text files

 Defending against attacks:


 Keep application clean by removing backup files and test files
 Never hard-code username/password into the code
 Do not leave sensitive plain text files in the server directory
 Disable/change default accounts
 Never keep a master password.
Hacking – Make system talk

 Make an application verbose by running in debug mode


 In most of the applications
 --debug runs the application in debug mode
 -v or -–verbose makes it verbose

 Get hold of log files


 Log files sometimes contain sensitive data
 They tell you more about the internal working of the system

 Defending against attacks:


 Do not put internal details into log files
 Do not put confidential information into log files
 Keep log files out of reach of normal users
Hacking – Unstable system

 Give incorrect input


 Give string where number is expected
 If this is not handled, the program would crash
 Give negative numbers for quantity
 Ordering an item in negative will bring down the total bill
 Give past dates/future dates

 Give huge requests


 Enter 3 to 4 lines for the name field
 This could cause buffer overflow!
 Give huge numbers
 In C, int 32768 is lesser than 32767

 Give lot of requests


 Swamping an application with request could crash it

 Force the application to error.


 If error conditions are not handled they are displayed to the user
 Error logs and core dumps are gold mines of information
Hacking – Unstable system

 Defending against attacks:


 Always validate the inputs
 Reject input larger that you expect
 Handle error cases
 Put a limit on the load you can accept
Hacking – Escalation of privileges

 Find tasks which run with admin privileges


 Replace the tasks with your tasks
 Disrupt a task running with admin privilege could give a command prompt
with admin privileges

 Windows XP run screen saver as admin user


 Replace screen saver with a command prompt
 Windows will now launch an empty command prompt as admin user

 Defending against attacks:


 Rule of least privilege – Run the task only with required privilege
 Handle error cases without crashing
Common vulnerabilities

 Packet Sniffing
 Man in the Middle
 Race Condition
 Buffer Overflow
 SQL Injection
 Cross Site Scripting
 Hidden Field Manipulation
 Cookie Poisoning
Exploit – Packet Sniffing

 Wireless networks broadcast all the packets to everyone


 Each machine accepts packets addressed to it and discards the rest
 Using network monitoring tools it is possible to accept all packages
 Using these tools, you can easily reconstruct the entire html content
 Not only the page being displayed, but data sent to a site can be seen
 If your application sends username/password and other sensitive
information it could be seen

 When building applications


 All sensitive information should be encrypted
 Use standard encryption algorithms
 ‘terces’ and ‘vhfuhw’ are not safe encryptions of ‘secret’
 Secure the network to restrict outsider access
 Avoid broadcasting if possible
Exploit – Man in the Middle

 Hacker sees user trying to contact the server


 Hacker intercepts the message and connect to client pretending to be the server
 Hacker also connects to the server pretending to be the user
 This way he can control and manipulate the conversation

 In desktop scenario,
 Consider a trusted program /bin/ssh
 Hacker installs /opt/temp/ssh
 Hacker changes environment variable $path to /opt/temp
 Invoking ‘ssh’ would now invoke the malicious code along with the password you
give

 When building applications


 Establish identity of the person or code you are talking to
 Digital certificates and signatures help establish identity in web applications
 Use complete path instead of relative path when dealing with commands/files
Exploit – Race condition

 This exploit uses the delay in a program between verifying input and executing.
 You start by passing valid input, but change it in between verification and execution
 Consider a script to upload assignments to college server
 Script allows only .c files and files lesser than 100 KB in size
 You want to bypass the check to upload mp3s and movies
 Consider following code, is it safe?
cd to upload_directory
for files in dir
if filename does not end with .c or filesize > 100
print("not a valid assignment file")
exit 1
end loop.
for files in dir
upload file to server
end loop.

 When building applications


 Atomic operations are operations which should be done as a single unit
 Verification and execution should be done as a single unit
 In your application, keep a note of all externals that could change during running
 Race conditions are more common in multi threaded application
Exploit – Buffer overflow

 Accounts for more than 80% of all vulnerabilities


 Caused by writing more data into a variable than it can hold
 Consider two variables with values
 UserName = “SHEROO”
 Type = “GUEST”

UserName Type
S H E R O O G U E S T

 If you store “SHEROOLIONADMIN” in the variable UserName, Type gets overwritten

UserName Type
S H E R O O L I O N A D M I N

 Using buffer overflows you can


 Overwrite and modify protected variables
 Overwrite call stack return address to a particular address and execute target code
 Cause the program to crash and core dump, revealing sensitive information
Exploit – Buffer overflow

 When building applications


 Always check the bound conditions and size of array and other data storages
 Use fgets(username, 10) instead of gets(name)
 Use free and overflow safe APIs for strings and arrays instead of standard library
 “Better String Library” and vstr are such safe libraries
 Use languages which does the memory and pointer management
 Languages like java, python allocates and de-allocates memory for you
 They have bound checks built into the application
 Supports variable length lists instead of arrays
 Do not give pointers to any memory location
Exploit – SQL Injection

 Happens when user input is used to prepare SQL statements


 Consider following code which prepares the SQL
String userName;
String password;
String sql = “select count(*) from users where username = ‘“+username
+”’ and password = ‘“+password+”’ “;

 If the userName is “Sheroo” and password is “topsecret”, sql becomes

select count(*) from users where username = ‘Sheroo’ and password = ‘topsecret’

 If a hacker enters a password as anything’ or 1=1 --

select count(*) from users where username = ‘Sheroo’ and password = ‘anything’ or 1=1 –- ’

 This sql would work for any username, thereby granting him access to any user account
Exploit – SQL Injection

 When building applications


 Always check input for unwanted characters
 Never build SQL dynamically
 Use binding or other safe mechanism for creating sql

String userName;
String password;
String sql = “select count(*) from users where username = :1 and password = :2 ”;
sql.bind(1, userName);
Sql.bind(2, password);
Exploit – Cross Site Scripting

 XSS tries to execute custom javascript on any website by passing javascript snippets
as data
 The website displays this data by adding it into html without verification
 Consider the following jsp code
<body>
<br>
<%
String name = request.getParameter("name");
out.println("hello "+name);
%>
<br>
</body>

 If you enter ‘Sheroo’ as the name, the html generated will be

<body>
<br>
hello Sheroo
<br>
</body>
Exploit – Cross Site Scripting

 If you enter the name as <script type="text/javascript">alert('hacked');</script>

<body>
<br>
hello = <script type="text/javascript">alert('hacked');</script>
<br>
</body>

 Using XSS you could,


 Extract the information in the page
 Modify the contents
 Steal the cookies
 The javascript could be persisted by putting them as comments

 When building application,


 Do not trust user input
 Check the input for unwanted characters
 Remove any script tag
Exploit – Hidden field tampering

 Any information displayed in an html form could be edited, including hidden fields
and dropdowns
 Consider a college site which allows you to download course material for courses you
have registered
 When you log in, there would be a dropdown to select the course.
 It is possible to edit and add more options to the dropdown from the browser
 If hidden fields are used to store critical information like user_id, they could be edited
as well

 When building application,


 Do not send critical information like user_id to browser. Store them in session
 In case user selects a value from a list, validate the selection at the server once
more
 In case where you have to send a value to browser and you don’t want it to be
tampered, append the value with hash functions
Exploit – Cookie Poisoning

 Cookies contain user login details


 Cookies are stored as text files on the user’s machine
 When you open a site, cookies belonging to that site is sent automatically by the
browser
 Consider a cookie user=sheroo:session_ticket=HJGAS12827KH6
 It tells the user is sheroo
 It contains the session_ticket.
 If the ticket is a valid one, user is automatically logged in
 It is possible to modify this cookie to user=admin:session_ticket=HJGAS12827KH6
 This could log the user automatically as admin

 When building application,


 The username should not be stored in a way it can be tampered.
 It should be stored with a valid hash appended to it.
Tips to secure your code

 Design application with security in mind


 Security cannot be added as an additional layer
 Eg. unix operating system
 Write error free code
 Buffer overflows are result of programming errors
 Use absolute path over relative path
 Handle errors properly
 Maintain clean code
 Good access control mechanism
 Store and transmit username/password in a secure manner
 Different users have different privileges
 Least Privilege Rule
 Run your application with least privileges
 Secure default accounts
 Defense in depth
 Cryptography and Sensitive information
 Passwords should be stored encrypted and without access to others
 Use standard cryptography methods like Public Key Cryptography
 Do not log sensitive data
Tips to secure your code

 Sanitize input data


 Do not trust user input
 Clean data avoids SQL injection, Buffer overflow, XSS
 Secure running environment
 Do not let user specify log locations
 Do not rely on unsafe environment paths
 Remove test and backup files
 Run untrusted code on virtual machines
References

 Secure Coding: The State of the Practice by Mark G. Graff


 http://en.wikipedia.org/

 http://www.securecoding.org/

 http://java.sun.com/security/seccodeguide.html

 Slides available at
 http://www.aloshbennett.in/weblog/

Thank You

You might also like