Application Security -
     Science or Quality Assurance?




Nazar Tymoshyk Ph.D, Security Consultant, R&D at SoftServe
Famous Security Professionals



   Richard Stallman       Linus Torvalds   Tsutomu Shimomura




          Robert Morris             Stephen Wozniak
Famous “Security Professionals”




  Adrian Lamo       Kevin Mitnick        Kevin Poulsen




         Gary McKinnon         Jonathan James
What about famous QA professionals?
So you know where to move ;)


                     Security is also metric
                       of Software Quality

         “The simple truth is that catching
           security holes earlier costs an
       organization less to remediate, which
           makes good business sense. ”
QA Engineer                                   Security Analyst




           In functional and performance
        testing, the expected results are    In security testing, the quality
documented before the test begins, and       assurance team is concerned only
the quality assurance team looks at how      with unexpected results and testing
     well the expected results match the     for the unknown.
                            actual results
Weapon




Passion           Tools
Persistence     Guides
Research      Checklists
Collaboration and Team work

   “ IT security and quality   IT security
         assurance working     department, which will
together are exponentially     help remove more risk
 more powerful. The result     and provide better
   will be a more security-    continuity ”
  oriented QA department
        and a more quality-
                   oriented
OWASP




  SAMM   WAF   Development
                             Testing guide   ASVS
                  guide
Microsoft approach
Testing security with Tools


Core Impact                        Burp
Accunetix WVS                      w3af
HP WebInspect                 OWASP ZAP
IBM Rational            OWASP Mantra
AppScan
DEMO
Let’s test small web-site with
commercial and free tools
Applying       Get tools from:
             http://goo.gl/eHl2u

Science
approach



                  Targets:
           http://192.168.195.34
           http://192.168.195.80
Smashing the app



   Remote code execution – one of the most dangerous vulnerabilities in
   web-apps


   How to achieve a goal:
   •   Upload scripts to server
   •   Remote File Inclusion (RFI)
   •   Local File Inclusion (LFI)
Unrestricted file upload

 File upload – vulnerability allow remote attacker to upload
 files/scripts on server with special content or random extension.
 This vulnerability exist through incorrect file extension implementation.

 Incorrect methods of uploaded file extension validation :
 • Validation of MIME-type of uploading file vs validation of
     file extention
 •    Black-list extension validation
 •    Other errors…
 Unsecure web-server/application server configuration play also important
 role.
Upload your shell
Changing MIME type
 Validation sample:

 <?php
 $imageTypes = array("image/gif", "image/jpg", "image/png");

 if(isset($_FILES["image"])) {
            if(!in_array($_FILES["image"]["type"],              $imageTypes)) {
                       die("Hacking Attempt!");    }
            copy($_FILES["image"]["tmp_name"], "images/{$_FILES["image"]["name"]}");
 } ?>

 Problem: It’s easy to change type of file – as it’s setting by
 browser in HTTP-request. And all variables that are set by
 browser – can be easily changed by user.
Content                  Black list:
validation               Wrong way
             <?php if(isset($_FILES["image"])) {
             if(preg_match('#.((php)|(php3)|(
             php4)|(php5))$#i',$_FILES["image
             "]["name"])
             ){
             die("Hacking Attempt!");
             }
             copy($_FILES["image"]["tmp_nam
             e"], "images/{$_FILES["image"]["n
             ame"]}"); } ?>
Regular expressions
 <?php
 if(isset($_FILES["image"])) {
 if(preg_match('#.jpg#i',         $_FILES["image"]["name"])) {
          copy($_FILES["image"]["tmp_name"], "images/{$_FILES["image"]["name"]}
 ");
 } } ?>


 In this sample name of uploaded file is checking for
 string .jpg. But regular expression is working as control
 symbol $ that indicate EOL is missed,.

 As a result file shell.jpg.php will be successes fully
 uploaded.
Right way

 <?php
 if(isset($_FILES["image"])) {
 if(preg_match('#^[a-z0-9-
 _]+.((jpg)|(png)|(bmp))$#i', $_FILES["image"]["name"])
         ){
         move_uploaded_file($_FILES["image"]["tmp_name"], "ima
 ges/{$_FILES["image"]["name"]}");
 }     }
 ?>                                        White list
                                           validation
Local File
Inclusion

 Local File Inclusion – allow to include local files on remote server
 and execute arbitrary code.

 Reason: incorrect linked file validation, vulnerable server
 configuration

 Successfully LFI exploitation have three main task :
 • Removing of postfix
 •   Directory Traversal
 •   Searching files for code injection
Directory
Traversal
 Filtration can prevent Directory Traversal.
 Very often developers apply Filtration of ../ :
    <?php include(str_replace("../", "", $_GET["page"]).".inc"); ?>
    ../../../etc/passwd --> Filtration --> etc/passwd --> fail 
    But such filtration is not enough – it’s not recursive:
    ..././..././..././etc/passwd --> Filtration --> ../../../etc/passwd --> profit 
Secure Validation

 Secure Validation – validation of filename for service
 symbols
 if(preg_match('#[^a-z0-9-_]#i', $page)) {
       die("Hacking Attempt!");
 }
 include("{$page}.inc");


 In this sample if we will try to add file with symbols
 other than A-Z, a-z, 0-9 and symbol «-» & «_» execution
 of PHP-script will be interrupted.
So, how to become Security Analyst


Use OWASP                      Researches
Ask and share              Participate in
                            community
Samurai WTF

            talk on Security
                 Hole 
Feedbacks & Questions

 Contact Nazar:
 skype: root_nt
 email: root.nt@gmail.com



 Presentation & Files:
 http://goo.gl/eHl2u
                            ?
Leave your Feedbacks:           Join OWASP Lviv:
http://goo.gl/FW4ar             https://www.owasp.org
                                /index.php/Lviv

Security hole #5 application security science or quality assurance

  • 2.
    Application Security - Science or Quality Assurance? Nazar Tymoshyk Ph.D, Security Consultant, R&D at SoftServe
  • 3.
    Famous Security Professionals Richard Stallman Linus Torvalds Tsutomu Shimomura Robert Morris Stephen Wozniak
  • 4.
    Famous “Security Professionals” Adrian Lamo Kevin Mitnick Kevin Poulsen Gary McKinnon Jonathan James
  • 5.
    What about famousQA professionals?
  • 6.
    So you knowwhere to move ;) Security is also metric of Software Quality “The simple truth is that catching security holes earlier costs an organization less to remediate, which makes good business sense. ”
  • 7.
    QA Engineer Security Analyst In functional and performance testing, the expected results are In security testing, the quality documented before the test begins, and assurance team is concerned only the quality assurance team looks at how with unexpected results and testing well the expected results match the for the unknown. actual results
  • 8.
    Weapon Passion Tools Persistence Guides Research Checklists
  • 9.
    Collaboration and Teamwork “ IT security and quality IT security assurance working department, which will together are exponentially help remove more risk more powerful. The result and provide better will be a more security- continuity ” oriented QA department and a more quality- oriented
  • 10.
    OWASP SAMM WAF Development Testing guide ASVS guide
  • 11.
  • 12.
    Testing security withTools Core Impact Burp Accunetix WVS w3af HP WebInspect OWASP ZAP IBM Rational OWASP Mantra AppScan
  • 13.
    DEMO Let’s test smallweb-site with commercial and free tools
  • 14.
    Applying Get tools from: http://goo.gl/eHl2u Science approach Targets: http://192.168.195.34 http://192.168.195.80
  • 15.
    Smashing the app Remote code execution – one of the most dangerous vulnerabilities in web-apps How to achieve a goal: • Upload scripts to server • Remote File Inclusion (RFI) • Local File Inclusion (LFI)
  • 16.
    Unrestricted file upload File upload – vulnerability allow remote attacker to upload files/scripts on server with special content or random extension. This vulnerability exist through incorrect file extension implementation. Incorrect methods of uploaded file extension validation : • Validation of MIME-type of uploading file vs validation of file extention • Black-list extension validation • Other errors… Unsecure web-server/application server configuration play also important role.
  • 17.
  • 18.
    Changing MIME type Validation sample: <?php $imageTypes = array("image/gif", "image/jpg", "image/png"); if(isset($_FILES["image"])) { if(!in_array($_FILES["image"]["type"], $imageTypes)) { die("Hacking Attempt!"); } copy($_FILES["image"]["tmp_name"], "images/{$_FILES["image"]["name"]}"); } ?> Problem: It’s easy to change type of file – as it’s setting by browser in HTTP-request. And all variables that are set by browser – can be easily changed by user.
  • 19.
    Content Black list: validation Wrong way <?php if(isset($_FILES["image"])) { if(preg_match('#.((php)|(php3)|( php4)|(php5))$#i',$_FILES["image "]["name"]) ){ die("Hacking Attempt!"); } copy($_FILES["image"]["tmp_nam e"], "images/{$_FILES["image"]["n ame"]}"); } ?>
  • 20.
    Regular expressions <?php if(isset($_FILES["image"])) { if(preg_match('#.jpg#i', $_FILES["image"]["name"])) { copy($_FILES["image"]["tmp_name"], "images/{$_FILES["image"]["name"]} "); } } ?> In this sample name of uploaded file is checking for string .jpg. But regular expression is working as control symbol $ that indicate EOL is missed,. As a result file shell.jpg.php will be successes fully uploaded.
  • 21.
    Right way <?php if(isset($_FILES["image"])) { if(preg_match('#^[a-z0-9- _]+.((jpg)|(png)|(bmp))$#i', $_FILES["image"]["name"]) ){ move_uploaded_file($_FILES["image"]["tmp_name"], "ima ges/{$_FILES["image"]["name"]}"); } } ?> White list validation
  • 22.
    Local File Inclusion LocalFile Inclusion – allow to include local files on remote server and execute arbitrary code. Reason: incorrect linked file validation, vulnerable server configuration Successfully LFI exploitation have three main task : • Removing of postfix • Directory Traversal • Searching files for code injection
  • 23.
    Directory Traversal Filtration canprevent Directory Traversal. Very often developers apply Filtration of ../ : <?php include(str_replace("../", "", $_GET["page"]).".inc"); ?> ../../../etc/passwd --> Filtration --> etc/passwd --> fail  But such filtration is not enough – it’s not recursive: ..././..././..././etc/passwd --> Filtration --> ../../../etc/passwd --> profit 
  • 24.
    Secure Validation SecureValidation – validation of filename for service symbols if(preg_match('#[^a-z0-9-_]#i', $page)) { die("Hacking Attempt!"); } include("{$page}.inc"); In this sample if we will try to add file with symbols other than A-Z, a-z, 0-9 and symbol «-» & «_» execution of PHP-script will be interrupted.
  • 25.
    So, how tobecome Security Analyst Use OWASP Researches Ask and share Participate in community Samurai WTF talk on Security Hole 
  • 26.
    Feedbacks & Questions Contact Nazar: skype: root_nt email: root.nt@gmail.com Presentation & Files: http://goo.gl/eHl2u ? Leave your Feedbacks: Join OWASP Lviv: http://goo.gl/FW4ar https://www.owasp.org /index.php/Lviv

Editor's Notes

  • #4 Еще его называют «Воз» или «Стив из Apple» (ведь Возняк на пару с Джобсом основали AppleComputer). Воз начал заниматься хакерством с создания блю-боксов, которые позволяют пользователям обходить механизмы переключения в телефонных линиях, для того чтобы совершать междугородные звонки бесплатно. Джобс и Воз продавали эти блю-боксы сокурсникам и даже использовали один из них сами для звонка Папе Римскому, притворяясь Генри Киссинджером (госсекретарем США).ТсутомуШимомура осознанно открыл свой компьютер для второй атаки, чтобы выследить Митника. Вскоре после обнаружения взлома он собрал команду и продолжил работу по поимке
  • #5 Адриан Ламо — известен взломом Yahoo, Citigroup, BankofAmerica иCingular.Джонатан Джеймс — американский хакер, стал первым несовершеннолетним, осужденным за хакерство.Кевин Поулсен — взломал базу данных ФБР и получил доступ к засекреченной информации, касающейся прослушивания телефонных разговоров. Поулсен долго скрывался, изменяя адреса и даже внешность, но в конце концов он был пойман и осужден на 5 лет. После выхода из тюрьмы работал журналистом, затем стал главным редактором WiredNews. Его самая популярная статья описывает процесс идентификации 744 сексуальных маньяков по их профилям в MySpace.Гэри Маккиннон — обвиняется во взломе 53-х компьютеров Пентагона и НАСА в 2001—2002 годах в поисках информации об НЛО.Джеймс стал самым молодым хакером в истории. Еще в 16 лет его отправили в тюрьму за компьютерные атаки на подразделения Министерства обороны США. Благодаря этому взлому он получил доступ к именам пользователей и паролям, а также смог просматривать письма высокой секретности. Среди его «побед» нужно отметить проникновение в сеть NASA (он умудрился украсть ПО на сумму больше чем в $1,5 млн). После обнаружения взлома NASA пришлось отключить систему для проверки, что обошлось налогоплательщикам в $41 000. Сейчас Джеймс, как многие другие его коллеги-«черношапочники», стал законопослушным гражданином и планирует открыть компанию по обеспечению компьютерной безопасности. 
  • #20 Завжди знайдеться розширення файлу яке не входить в список