Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Vulnerability assessment and secure coding in Web Applications

Paolo Perego
November 30, 2017

Vulnerability assessment and secure coding in Web Applications

This is the talk I delivered for "The Hack Week" event in Università di Parma, the 30th November 2017.

The event was organised by Unione degli Universitari - UDU Parma.

The talk is a very beginner oriented introduction into vulnerability assessment, safe coding hints for the new Owasp Top 10 2017 and a web2root path attacking Railsgoat application, part of the Owasp Broken Web Application project.

During the demo, we will show:
* how to gain info from 0-knowledge to understand the technology behind the target
* how to gain a low privileged shell, using malicious code upload into the broken web application
* how to gain a root shell using the right kernel exploit

Event link: https://www.facebook.com/events/148538812565644/
Organizer: https://www.facebook.com/uduparma/

Paolo Perego

November 30, 2017
Tweet

More Decks by Paolo Perego

Other Decks in Technology

Transcript

  1. self.inspect • 15+ years in application security • Lead a

    purple team • Blogger @ https://codiceinsicuro.it • Social as @thesp0nge • Husband, Dad and Taekwon-Do ITF athlete and trainer • Send comments or questions to [email protected]
  2. Agenda • The Red side • What’s a vulnerability? •

    Testing 172.16.202.241 • The Blue side • What’s safe coding? • The Owasp Top 10 2017 • Testing Railsgoat • Bonus track
  3. cyber |ˈsʌɪbə| adjective relating to or characteristic of the culture

    of computers, information technology, and virtual reality: the cyber age. security |sɪˈkjʊərɪti, sɪˈkjɔːrɪti| noun (plural securities) 1 [mass noun] the state of being free from danger or threat: the system is designed to provide maximum security against toxic spills | job security.
  4. assess |əˈsɛs| verb [with object] evaluate or estimate the nature,

    ability, or quality of: the committee must assess the relative importance of the issues | [with clause] : it is difficult to assess whether this is a new trend. assessment |əˈsɛsmənt| noun [mass noun] the action of assessing someone or something: the assessment of educational needs | assessments of market value.
  5. vulnerability |vʌln(ə)rəˈbɪlɪti| noun (plural vulnerabilities) [mass noun] the quality or

    state of being exposed to the possibility of being attacked or harmed, either physically or emotionally: conservation authorities have realized the vulnerability of the local population | he is confined in isolation because of his vulnerability to infection | [count noun] : con artists are great at spotting our vulnerabilities.
  6. Putting all together A vulnerability assessment is the action of

    evaluating or estimating a system for the quality or state of being exposed to the possibility of being attacked or harmed
  7. The goal • A vulnerability assessment is something magic (in

    term of execution) with some defined rules: • A system has vulnerabilities • Those vulnerabilities can be (sometime) exploited
  8. Vulnerability Assessment workflow • During a vulnerability assessment we •

    Understand the nature of our target • Recognise running services • Enumerate vulnerabilities for those services • Exploit them • Celebrate
  9. Enumerate • Assess web server configuration • Look for interesting

    folders in web sites • Look for interesting folders in target application
  10. Exploit • Look for local root exploits • Please wait

    until we get a non privileged shell… :-)
  11. What’s safe code? • Coding is an art • Safe

    coding is the art of creating working code in a secure way • Safe coding means also create a secure environment for the running program • Choosing right technologies • Hardening configuration
  12. Your skillset • Curious • Lateral thinker • Precise •

    Fast learner • Attitude to code • Good listener • Patient • Attitude to talk and teach
  13. A1 - Injection • Segregation between commands and queries •

    Use Object Relational Mapping API to access data in a parameterised way • Use positive or "whitelist" server-side input validation. • Escape special characters (‘, &, -, ;)

  14. Don’t def update message = false user = User.find(:first, :conditions

    => "user_id = '#{params[:user][:user_id]}'") user.skip_user_id_assign = true user.update_attributes(params[:user].reject { |k| k == ("password" || "password_confirmation") || "user_id" }) pass = params[:user][:password] user.password = pass if !(pass.blank?) message = true if user.save! respond_to do |format| format.html { redirect_to user_account_settings_path(:user_id => current_user.user_id) } format.json { render :json => {:msg => message ? "success" : "false "} } end end
  15. Do def update message = false user = current_user user.skip_user_id_assign

    = true user.update_attributes(params[:user].reject { |k| k == ("password" || "password_confirmation") || "user_id" }) pass = params[:user][:password] user.password = pass if !(pass.blank?) message = true if user.save! respond_to do |format| format.html { redirect_to user_account_settings_path(:user_id => current_user.user_id) } format.json { render :json => {:msg => message ? "success" : "false "} } end end
  16. A2 - Broken Authentication • Multi factor authentication • Not

    use default credentials • Implement checks against weak passwords • Harden API against enumeration • Limit logins attempt & use account lockout mechanisms • Generate a secure session ID server side
  17. A3 - Sensitive Data Exposure • Classify your data against

    local rules ( PCI, SOX, GDPR ) • Encrypt all sensitive data at rest • Protect communication channel with TLS • Disable caching sensitive data • Store passwords using strong adaptive and salted hashing functions
  18. Don’t before_save :hash_password def self.authenticate(email, password) auth = nil user

    = find_by_email(email) if user if user.password == Digest::MD5.hexdigest(password) auth = user else raise "Incorrect Password!" end else raise "#{email} doesn't exist!" end return auth end def hash_password if self.password.present? self.password = Digest::MD5.hexdigest(password) end end
  19. Do def self.authenticate(email, password) user = find_by_email(email) if user and

    user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) user else "Invalid Credentials Supplied" end end def hash_password if self.password.present? self.password_salt = BCrypt::Engine.generate_salt self.password_hash = BCrypt::Engine.hash_secret(self.password, self.password_salt) end end
  20. A4 - XML External Entities (XXE) • Use less complex

    data formats (JSON) • Avoid serialise sensitive data • Disable XML entity and DTD processing • Implement positive ("whitelisting") server-side input validation, filtering, or sanitization
  21. A5 - Broken Access Control • Only public resources must

    be granted. Deny by default • Implement access control mechanisms • Disable directory listing • Implement logging for unauthorised resources • Implement rate limit for API
  22. A6 - Security Misconfiguration • Implement hardening procedures • Remove

    unnecessary tools and frameworks (libraries, daemons, compilers, …) • Review system configurations (e.g. with lynis)
  23. A7 - Cross-Site Scripting (XSS) • Use frameworks that automatically

    escape XSS • Don’t trust user inputs. Validate them, using encoding and whitelist approach
  24. A8 - Insecure Deserialization • Enforce security controls when receiving

    a serialised object • Running the code managing serialised object with as lower privileges as you can • Log and monitor the code managing serialisation, in particular for incoming and outgoing connections
  25. A9 - Using Components with Known Vulnerabilities • Remove any

    unnecessary library or dependency • Create and maintain an asset inventory for all technologies used in your application and follow their security life • Run security assessment tool for third party libraries and mitigate all security issues
  26. A10 - Insufficient Logging & Monitoring • Avoid logging sensitive

    information on files • Centralise your logs on a SIEM solution (e.g. splunk) • Protect logs against tampering
  27. Knockin’on a broken door • Target web application is vulnerable

    to user enumeration • Detailed error messages can lead an attacker to understand between non existent user and wrong password
  28. Knockin’on a broken door • Simple python script is able

    to give me valid credentials for web interface • We can use cewl tool to create a wordlist specific for the website • As we can see password is trivial to guess so no strict password policy is in place
  29. def create begin user = User.authenticate(params[:email], params[:password]) rescue Exception =>

    e end if user session[:user_id] = user.user_id if User.where(:user_id => user.user_id).exists? redirect_to home_dashboard_index_path else flash[:error] = "Either your username and password is incorrect" #e.message render "new" end end
  30. Getting a shell • Web application has the capability of

    uploading a file • No controls on the type of file we upload • Attempt is made to upload a PHP script spawning a shell • Eventually the attempt succeeded
  31. Getting a root shell • We are regular users on

    Ubuntu 10.04 • We look for exploits • We transfer exploit on target using HTTP • We compile the exploit • Root dance
  32. def self.make_backup(file, data_path, full_file_name) accepted_formats = [".txt", ".pdf"] return false

    unless accepted_formats.include? File.extname(full_file_name) FileUtils.cp "#{full_file_name}", "#{data_path}/bak#{Time.now.to_i} _#{file.original_filename}" end
  33. Access arbitrary info • On the Work Info section, the

    user identifier in the URL is used to retrieve information • Anyone can tamper the URL retrieving information about other users • Metacorp is more generous with Jack rather then Jim… Jim is not happy about that
  34. def index @user = current_user if !(@user) || @user.admin flash[:error]

    = "Apologies, looks like something went wrong" redirect_to home_dashboard_index_path end end
  35. Access Admin panel • To access admin panel, the user

    id is retrieved from URL • Tampering the URL, it is possible to go into administrative portal to manage users
  36. Executing code client side • Users can register on the

    target application • Target application doesn’t validate user first name • It is possible to store javascript on the database • The javascript is executed when rendering user’s page
  37. <% @users.each do |u|%> <tr> <td style="word-wrap:break-word;"> <%= u.first_name %>

    <%= "#{u.last_name}"%> # removed .html_safe in app/views/layouts/admin/_get_all_users.html.erb <li style="color: #FFFFFF"> <!-- I'm going to use HTML safe because we had some weird stuff going on with funny chars and jquery, plus it says safe so I'm guessing nothing bad will happen --> Welcome, <%= current_user.first_name %> </li> # removed .html_safe in app/views/layouts/shared/_header.html.erb
  38. Changing the paradigma • From a ‘devops’ world into a

    ‘secdevops’ world • Agile teams • Everyone committed to bring the code into production • Adding the ‘sec’ part means ton of stuff
  39. Sec Dev Ops • Bring security the agile way •

    Continuous security tests • Continuous mitigation • Continuous vulnerability management
  40. How to achieve Sec Dev Ops? • Create awareness programs

    • Write secure coding guidelines • Automate security tests into development pipeline
  41. Some links • To practice in break • https://www.vulnhub.com/ •

    https://www.hackthebox.eu/ • https://pentesterlab.com/exercises/ • https://medium.com/@a.hilton83/oscp-training-vms-hosted-on-vulnhub-com-22fa061bf6a1 • To pipeline automation • https://codiceinsicuro.it/chicchi/automatizzare-owasp-zap-in-mac-os-x/ • https://www.aspectsecurity.com/blog/secure-devops-with-an-application-security-pipeline • https://www.appsecpipeline.org/ • To read: https://codiceinsicuro.it
  42. Q&A