Virtual Patching

Virtual Patching is a security policy enforcement layer which prevents and reports the exploitation attempt of a known vulnerability. This layer analyzes the transactions and intercepts attacks in transit, so malicious traffic never reaches web application. The impact is that actual source code of app has not been modified so exploitation attempt does not succeed.

From purely technical perspective, best remediation would be to fix the code, but in real world business situations updating source code is not easy due to many reasons:

  • Lack of resources
  • 3rd Party software
  • Outsourced Application Development

Virtual patching is done by OpSec team while code fix is done by developers.

Goals of virtual patching is to :

  • Minimize time-to-fix
  • Attack surface reduction

Virtual patching tools:

  • Intermediary devices i.e. WAF or IPS appliance
  • Web server plugin i.e. ModSecurity
  • Application layer filter i.e. ESAPI WAF

Virtual Patching Methodology

Consistent repeatable process provides best chance of success. Virtual patching workflow adopted in organizations has following phases :

  • Preparation Phase
    • Public/Vendor Vulnerability Monitoring
    • Virtual Patching pre-authorization
    • Deploy virtual patching tool in advance
    • Increase HTTP Audit Logging (Request URI, Full request header & body, Full response header & body)
  • Identification Phase
    • It occurs when organization becomes aware of vulnerability in application.
    • Proactive identification: By assessing web security posture through DAST and source code reviews
    • Reactive identification: Vendor contact, Public disclosure, Security incident
  • Analysis Phase
    • Determine virtual patching applicability
    • Utilize bug tracking system
    • Verify name of vulnerability
    • Designate impact level
    • Specify which versions of software are impacted
    • List what configuration is required to trigger the problem
    • List PoC exploit code or payloads used during attack
  • Virtual Patch Creation Phase
    • No flase positives : Do not block legitimate traffic ever
    • No false negatives : Do not miss attacks ever
    • Manual Virtual Patch Creation
      • Whitelist virtual patches (recommended solution) – specifies characteristics of valid input
      • Blacklist virtual patches – a set of rules to detect specific known attacks
    • Automated Virtual Patch creation
      • OWASP ModSecurity Core Rule Set (CRS) Scripts – to auto-convert XML output from tools such as OWASP ZAP into ModSecurity Virtual Patches
      • ThreadFix Virtual Patching – automated tools for converting imported vulnerability XML data into virtual patches for security tools such as ModSecurity.
      • Direct importing to WAF device –  import of DAST tool XML report data leads to automatically adjustment of protection profiles by WAF devices
  • Implementation/Testing
    • Using web clients, Local proxy servers, ModSecurity AuditViewer
    • Implement virtual patches first in “Log Only” config to ensure no false positives
  • Recovery/Follow Up
    • Periodic re-assessments
    • Update data to ticketing system

Source : OWASP Virtual Patching Cheat sheet

Advertisements

8 – Perseverance, Persistence and Determination

Perseverance is one characteristic shared by all successful people throughout history. Perseverance is true essence of success.

Persistence – Act of holding firmly and steadfastly to a purpose, state, goal or undertaking despite obstacle, warning or setbacks.

Determination – Quality of mind which reaches definite conclusions, resoluteness

Perseverance – Persistent determination

Persistence is not insanity. Giving up your purpose or goal due to obstacles – that’s insanity.

The key to determination is word “decision”. You must decide what you want before you can get it. Determination takes great self-confidence and decisiveness. You must be willing to completely disregard all alternatives to your decision and set it clear in your mind that you must and you will.

Perseverance is great word that is defined by persistent determination.

 

From book “Year to Success” by Bo Bennett

7 – Using Humor Effectively

Laughter is best medicine known to mankind. Development of good sense of humor and ability to make people laugh can do more good for those you come into contact with.

Beside making people happy and feel good, humor can be used to make light of an awkward situation and ease both tension and ill feelings while building rapport. In speaking or writing situation, humor can keep audience interested and helps you to become better communicator.

People have different senses of humor, even though humor is recognized and effects of humor remains.

Here are some different kinds of humor that you can use :

  • The Joke.
  • The Funny Story
  • The impersonation
  • Physical Comedy
  • What ifs
  • Sarcasm
  • Slapstick comedy

Some “Rules of Humor”. Follow them and humor will serve you well. Break them and you’ll be subject of other people’s humor.

  1. Never ever take credit for someone else’s joke
  2. Make sure your joke or something funny is always to new audience
  3. Be appropriate
  4. Keep it short
  5. Be smooth
  6. Timing
  7. Relevancy
  8. Do not make joke at other people’s expense
  9. Dont overdo it
  10. Don’t be corny

When humor fails-

  • Cover up by asking question
  • Dont laugh at your own jokes and people may not think you were trying to be funny

Using humor effectively requires practice and self-confidence.

From book “Year to Success” by Bo Bennett

6 – Positive Mental Attitude

We have great sense of control over our attitude. We can choose to focus on negative or positive in a situation. A positive mental attitude is something everyone can adopt with little practice. It is also significant factor in success.

PMA is seeing good in situations rather than setbacks. More important, it is focusing on positive and using it to your advantage. It is the thriving force behind persistence and perseverance.

After adopting a positive mental attitude you will find more opportunities, successes and luck in your life than ever before. It has to do with focus and perception. It is a snowball effect, once begun, builds and grows stronger with each positive event in life.

Tips to build PMA –

  • Scrutinize every event in your life that appears negative and look for positive. List the positives from that situation. Do not give up until that list is equal or greater than negative.
  • Surround yourself with positive people. Negativity is contagious than common cold.
  • Read and listen to positive, motivational and inspirational material.
  • Avoid morning news and news before bedtime. Start and end your day with inspirational music or good conversation.
  • If you catch yourself thinking negative. STOP IMMEDIATELY. Take deep breath and do as first suggestion.

PMA will certainly bring one giant leap closer to success.

From book “Year to Success” by Bo Bennett

5 – General Life Purpose

What is your general purpose on earth? Does your existence make the world a better place?

Consider statements below and think where you currently fit in. There is no right or wrong answer.

  1.  I am here to live the highest quality life I can. This includes working towards constant self-improvement and engaging in leisure activities. My time on earth is limited, and I will do what I can do to get most self-gratification possible.
  2. It is my purpose to provide for my family and give my family highest quality of life possible. My free time should be spent with my family, for my family.
  3. My purpose on earth is to do good for as many people as possible within my lifetime. I realize that there is world beyond myself and my family needs something that I can provide.

Don’t confuse general life purpose with just “life purpose.” General life purpose is a starting point for determining your life purpose that helps you decide who and what is most important in your life right now. See this as a scale with your typical self-centered individual on one end and someone like Gandhi on the other end.

This exercise in finding your general life purpose is one of the many very important first steps to success. You must be at peace with yourself and feel no guilt as to what you desire from life. Once you have this confidence, the pursuit of your goals becomes easier and more enjoyable.

From book “Year to Success” by Bo Bennett

4 – Inspiration from Henry Ford

Henry ford was founder, VP and chief engineer of Ford Motor Company.

Success is age independent – Henry Ford constructed his first steam engine at age of 15.

Success is not formal education – Ford’s formal education was limited to be about 3 years.

Success is fueled by failure – After 2 unsuccessful attempt to establish automobile company, Ford Motor was incorporated in 1903 with Henry as VP and chief engineer.

Success is problem-solving – Even after unpleasant monotony of assembly-line work and repeated increase in production quotas assigned to workers, monthly labor turnover increased to 60 from 40 percent because of doubling daily wage and shaving one hour off the workday by Henry ford.

Success is overcoming competition – In 1905, 50 start-up companies tried into auto business, and ford succeeded.

Success is doing what you feel in your gut is right, despite public opinion – Wall street journal called raise to daily wage an “economic crime” and critics coined pejorative term “Fordism” to reflect disgust in ford’s practice.

Success is seeking out those who can help you with your goals – In 1903, ford found twelve people willing to invest a total of $28k in motor company. Ford begin production of Model A car which sold well and company’s profits reached $1,100,000 in 1907.

From book “Year to Success” by Bo Bennett

3 – Remembering and Using People’s Names

It has been said that person’s name is most important in the world to that person. Using a person’s name in conversation is one of best ways to build rapport.  So step one is remembering name.

Memory works by process of encoding and decoding, commonly referred as recall. Each time memory is recalled, it gets re-encoded, which means it changes over time.

Steps to follow when you meet people?

  1. Listen and pay attention to name.
  2. Repeat immediately
  3. Repeat often
  4. End conversation with person’s name
  5. Comment/ask questions about the name
  6. Review the name and face of person after conversation is over.

Memory is linked to senses and emotions. Mixing the emotion and senses into remembering name will make name difficult to forget.

Techniques used to remember names –

  1. Face association
  2. Substitution – associating name with some object that you can visualize with name
  3. Paint their name on their forehead in imagination
  4. Association with someone you know

From book “Year to Success” by Bo Bennett

2 – Why Success?

Humans are driven by desire to feel important. We all want to know that our lives make a difference in positive way. So in some way we want to know that world is better place because we are part of it. Success is a way of saying just that.

People who do not desire success will rarely achieve it. You must be ready for it and pursue it with passion.

To most people, success includes these :

  • living your dream
  • living every day with passion
  • having true wealth
  • learning appreciation and gratitude
  • positively influencing lives of others in some way
  • true happiness
  • having loved ones with whom to share it all

Consider “PERMA” – the five dimensions of well being when you define your success.

  • P – Positive emotions
  • E – Engagement
  • R – Relationships
  • M – Meaning/Purpose
  • A – Achievement

No matter what is your definition of success, pursue it with passion and determination.

Mark this day as day of commitment to change your life for better and start embracing life rather than just living it.

From book “Year to Success” by Bo Bennett

1 – Introduction

Success is best achieved by working on many aspects of personal development.

Well-being is measurable construct that is less nebulous than success and more comprehensive.

As learning beings, we must be open to change our beliefs and views based on new information.

Think of success as a game of chance in which you have control over the odds. Beginning to master the concepts in personal achievement increases the odds of achieving success. It has been said that one line of wisdom can change your life more than volumes of books.

Education + Inspiration + Action = Success

From book “Year to Success” by Bo Bennett

NIST – FIPS 140-2 (Approval of Cryptographic Modules)

FIPS stands for Federal Information Processing Standard.

FIPS 140-2 is IT security approval program for cryptographic modules produced by private sector vendors for use in govt and regulated industries that collect, store, share sensitive but unclassified information.

Four Security Levels

  • Level 1 : Lowest level of security. Use of one approved algorithm or function. Use of production grade component
  • Level 2 : Improvement on L1 by requiring features to show evidence of tampering to attain physical access to cryptographic keys and Critical Security Parameters (CSP) within module.
  • Level 3 : L3 attempts to prevent access to CSPs. Physical security may include use of strong enclosures and tamper-detection/response circuitry that zeroes all plaintext CSPs when removable doors of module are opened.
  • Level 4 : Immediate deletion of plaintext CSPs on penetration of cryptographic module enclosure. Useful for operation in physically unprotected environments.

 

Security requirements areas for secure design and implementation of cryptographic modules:

  1. Cryptographic Module Specification
  2. Cryptographic Module Ports and Interfaces
  3. Roles, Services and Authentication
  4. Finite State Model
  5. Physical Security
  6. Operational Environment
  7. Cryptographic Key Management
  8. Electromagnetic Interference or Compatibility
  9. Self Tests
  10. Design Assurance
  11. Mitigation of other attacks

 

Annex A – Approved Security Function

Symmetric Key Encryption and Decryption (AES, TDEA)

  1. AES
    • NIST AES
    • NIST Recommendation for Block Cipher Modes of Operation, Methods and Techniques
    • NIST Recommendation for Block Cipher Modes of Operation: 3 variant of ciphertext stealing for CBC mode
    • NIST Recommendation for Block Cipher Modes of Operation: CMM mode for auth and confidentiality
    • NIST Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC
    • NIST Recommendation for Block Cipher Modes of Operation: XTS-AES mode for confidentiality on storage
    • NIST Recommendation for Block Cipher Modes of Operation: Methods for Key wrapping
    • NIST Recommendation for Block Cipher Modes of Operation: Methods for format preserving encryption
  2. Triple DES Encryption Algorithm
    • NIST Recommendation for TDEA Block Cipher
    • NIST Recommendation for Block Cipher Modes of Operation, Methods and Techniques, Appendix-E
    • NIST Recommendation for Block Cipher Modes of Operation: Methods for key wrapping

Digital Signatures (DSA, RSA and ECDSA)

  • NIST DSS 186-4

Secure Hash Standard (SHS)

  1. Secure Hash Standard (SHA-1, SHA-224, SHA-256, SHA-384, SHA-512)
    • NIST SHS 180-4

SHA-3 Standard

  1. SHA-3 Hash Algorithm (SHA30224, SHA3-256, SHA3-384, SHA3-512)
    • NIST SHA3-Standard, 202
  2. SHA-3 Extendable-Output Functions (XOF) (SHAKE128, SHALE256)
    • NIST SHA3-Standard, 202

Message Authentication (Triple-DES, AES and HMAC)

  1. Triple-DES
    • NIST Recommendation for Block Cipher Modes of Operation: CMAC mode for authentication, 800-38B
  2. AES
    • NIST Recommendation for Block Cipher Modes of Operation: CMAC mode for authentication, 800-38B
    • NIST Recommendation for Block Cipher Modes of Operation: CMM mode for auth and confidentiality 800-38C
    • NIST Recommendation for Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC, 800-38D
  3. HMAC
    • NIST The Keyed Hash Message Authentication Code, 198-1
    • NIST Recommendation for Applications using Approved Hash algorithm, 800-107 Rv.1, Section-5.3

Annex B – Approved Protection Profiles

  1. NIAP Approved Protection Profile for OS
  2. NIAP Approved Protection Profile for Mobile Device Fundamentals

Software modules can only be validated up to security level 2

Annex C – Approved Random Number Generators

Transitions

  • NIST Recommendation for Transitioning the Use of Cryptographic Algorithms and Key Length

Deterministic RNG produces sequence of bits from initial value called seed

  • NIST Recommendation for Random Number Generation using Deterministic Random Bit Generators, 800-90A

Non Deterministic RNG produces output dependent on some unpredictable physical source outside of human control.

  • No FIPS approved

 

Annex D – Approved Key Establishment Techniques

  • FIPS 140-2 Implementation Guidance, Section D.2
  • NIST DSS: For key Establishment DSS is only used to define domain parameters & key pair generation
  • NIST Recommendation for pair-wise key establishment schemes using Discrete Logarithm cryptographically, 800-56A
  • NIST Recommendation for pair-wise key establishment schemes using Integer Factorization cryptographically
  • NIST Recommendation for Key Derivation Using Pseudorandom Functions
  • NIST Recommendation for password-based key derivation, Part 1 : Storage Apps, 800-132
  • NIST Recommendation for existing App-specific key derivation functions, 800-135rev1
  • NIST Recommendation for key derivation through extraction then expansion
  • NIST Recommendation for Block Cipher Modes of Operation: Methods for key wrapping
  • NIST Recommendation for cryptgraphic key generation, 800-133

WEB APPLICATION SECURITY TESTING – 8. ATTACKING ACCESS CONTROLS

This notes is for learning/educational purpose only. Use it at your own risks. 

Authentication and Session management ensure that you know who is using the application. Similarly, Access Controls is defense mechanism which limits what actions are possible for authenticated users. It must be tested for every request and operation.

COMMON VULNERABILITIES

Access controls can be divided into three broad categories – Vertical, Horizontal and Context-Dependent.

  • Vertical Privilege Escalation – allow user to access a different part of app’s functionality. Like, escalating from user to administrator.
  • Horizontal Privilege Escalation – allow user to access a wider range of resources of same type. Such as reading another user’s email.
  • Context-Dependent (Business Logic Exploitation) – User can do things that should not be possible in context. Like, performing tasks out of order. Or, bypassing payment step when checking out.

Completely Unprotected Functionality

  • Functionality can be accessed by anyone who knows the URL
  • OWASP refers this as “Unsecured Direct Object Access”, also known as “Security through Obscurity”
  • Inspecting client side code may reveal privileged URLs

Identifier-Based Functions

  • Identifier for a document passed to server in parameter
  • Access controls may be broken so everyone with URL can view the document. This often happens when developers find it too difficult to share session-based security model between servers using different technologies.
  • Document identifiers might be predictable.
  • URLs are not treated as secrets – often visible in logs or elsewhere in app

Multistage Functions

  • App may enforce access control in early step but not test it again in later step.
  • Attacker can skip steps and escalate privileges

Static Files

  • Anyone with direct link to file can view and/or download the file if app-level code is executed for access.

Platform Misconfiguration

  • Access to specified URL paths are restricted.
  • Platform level configuration allow or deny access based on following – HTTP request method, URL path, User role

Verb Tampering:

  • Access control rule may apply only to POST method. Using GET/HEAD may perform admin-level tasks.
  • Unrecognized HTTP methods may default to GET

Insecure Access Control Methods

  • Parameter based access control:
    • Privilege level in hidden form field, cookie or query string parameter.
    • Attacker can just add parameter to gain privileges
  • Referer based access control:
    • HTTP referer header grants access
    • User can modify that field to gain privilege
  • Location based access control:
    • Often uses geolocation of user’s IP address
    • Using web proxy based in required location might bypass this
    • Using VPN that terminates in required location might bypass this
    • Using mobile device that supports data roaming might bypass this
    • Direct manipulation of client-side mechanisms for geolocation can bypass this

ATTACKING ACCESS CONTROLS

Testing With Different User Accounts

  • Map contents of app using two user accounts and compare them

Testing Direct Access to Methods

  • Might be able to guess other methods from the ones you see
  • Test them to see if access is properly limited

Testing Controls Over Static Resources

  • Walk through app while logged in as admin
  • Note URLs of high privilege resources
  • Login as low privilege user
  • Try to access those URLs found earlier
  • Try to guess other sensitive URLs from the patterns of URLs you have found

Testing Restrictions on HTTP Methods

  • Login as admin and find sensitive requests
  • Try other methods, POST, GET, HEAD, invalid
  • Test with low privileged account

SECURING ACCESS CONTROLS

  • Do not rely on user’s ignorance of URLs or identifiers
  • Do not trust any user-supplied parameters like admin=True
  • Do not assume users will access pages in intended sequence
  • Do not trust user not to tamper with data; revalidate it before using it

Best Practices

  • Explicitly evaluate and document access control requirements for every unit of app functionality
  • Drive all access control decisions from user’s session
  • Use a central app component to check access controls; use it for every client request and mandate that every page must include an interface to this component
  • For sensitive functionality, restrict access by IP address
  • Protect static content by – passing filename to server side page that implements access control logic, or use HTTP authentication or other feature to restrict access
  • Do not trust resource id from client, validate them on server
  • Consider requiring re-authentication or two factor authentication for security-critical app functions
  • Log events using sensitive data or actions

Advantages of Central Access Control

  • It increases clarity of access control within application.
  • It makes maintainability more efficient and reliable, required changes are needed to be done once.
  • It improves adaptability. New access controls can be added and used easily.
  • It results in fewer mistakes and omissions.

WEB APPLICATION SECURITY TESTING – 7. ATTACKING SESSION MANAGEMENT

This notes is for learning/educational purpose only. Use it at your own risks. 

THE NEED FOR STATE

Session management enables application to identify a given user over number of different requests. It is fundamental security component and also a prime target for attackers.

With session management attacks, a user can masquerade as another user or escalate privileges to admin. Attack could be as simple as incrementing the value of a token.

Vulnerabilities are of two categories:

  • Weakness in generation of session tokens
  • Weakness in handling session tokens throughout their life cycle

Finding Real Session Token:

To find token, establish session and then replay request. Systematically remove each item you suspect of being real token.

Alternatives to Sessions:

  • HTTP Authentication – Pass credentials with every request in HTTP headers.
  • Sessionless State Mechanisms – App doesn’t issue session tokens or manage the state. Transmit all data required to manage the state via client in cookie or hidden form field. Example- ASP.NET ViewState

Securing ViewState:

  • Data must be protected, usually as binary blob that is encrypted or signed, to prevent re-use on another machine.
  • ViewState uses Base64 and hash made from Machine Authentication Code. Include’s machine’s MAC address.
  • Expiration time enforces session timeouts

Identifying Sessionless State Mechanisms:

  • Token-like data item with more than 100 bytes long. Possibly in response to every request.
  • Data is encrypted (structureless) or signed (structured + random bytes)
  • App rejects attempts to submit same item with more than one request

WEAKNESSES IN TOKEN GENERATION

Meaningful Tokens

  • Components in structured tokens are generally – username, userid, first name, last name, email address, user role, timestamp, client ip address, predictable number etc.
  • Common encoding schemes used are – XOR, Base64, Hexadecimal ASCII codes.

HACKSTEPS:

  1. Obtain token, modify it in systematic ways. Change it one byte or one bit at a time and resubmit to see if its still accepted. (Burp Intruder’s “char frobber” function)
  2. Login as several users at different times. Similar usernames or email addresses. Record tokens. Analyze tokens for correlations and look for encoding or obfuscation.
  3. Repeating letters produce repeating encoded characters if XOR is used.
  4. Use patterns found to try guessing tokens of other users.

Predictable Tokens

  • From a sample of tokens, it may be possible to predict valid tokens.
  • Commercial implementations such as web servers or app platforms may be more vulnerable. Because its easier to gather large sample of tokens from own test system.

Three common sources of predictable session tokens:

  • Concealed sequences: Base64 encoded. Decode it and use hex form. Calculate difference between tokens. It will reveal the concealed pattern.
  • Time dependency: Number increments based on time elapsed, probably in milliseconds.
  • Weak random number generation: Jetty is java based web server. It calculates pseudorandom session tokens with ‘linear congruential generator’. Multiplies previous number by constant, adds another constant and truncates to 48 bits. Given on values, others can be predicted.

 

  • PHP 5.3.2 and earlier uses session token generated from clients ip, epoch time at token creation, microseconds at token creation, and linear congruential generator.
  • Use burp sequencer to test randomness of tokens.

Encrypted Tokens

Attacker can sometime tamper token’s values without decrypting.

ECB Ciphers:

  • Electronic Code Book
  • Input broken up into blocks, often 8 bytes long
  • Symmetric encryption, no randomness
  • Each input block encodes to single output block.
  • Patterns of input is preserved in output

CBC Ciphers:

  • Cipher Block Chain mode
  • XOR’s each block of plaintext with preceding block of cipher text
  • Modify single byte of ciphertext, and that block will decrypt to junk but next block will be meaningful only slightly altered.
  • Test for CBC cipher manipulation vulnerability by bit flipping method. 8 requests per byte.

WEAKNESSES IN SESSION TOKEN HANDLING

SSL protects tokens in transmission, but some attacks like XSS to obtain token will still work.

Disclosure of Tokens on Network

  • Tokens transmitted without encryption can be eavesdropped.
  • Cookies containing session token when sent over HTTP can be captured. Using Firesheep firefox plugin.
  • Stealing user password may not work (may require OTP) but stealing session token and hijacking session may work (No notification of extra login).
  • App may use HTTPS during login but use HTTP to see authorized content.
  • If App uses same token as on preauth pages and on all subsequent pages after login, attacker can steal it.
  • If App uses new token & HTTPS on login and all subsequent pages, but user navigates to an HTTP page with back button exposing the token.
  • SSLstrip – Attacker alters page link to use HTTP and forwards requests to server via HTTPS.

Disclosure of Tokens in Logs

  • Transmitting token as URL query string might appear in system logs, user’s browser logs, web server logs, Logs og ISP proxy servers and Logs of reverse proxies.
  • If a mail app transmits session token in URL, then attacker can send his web server link to user via email, on clicking attacker will get session token in ‘Referer’ header.

Vulnerable Mapping of Tokens to Sessions

  • Weakness in mapping the creation and processing of session tokens to individual users.
  • Simple weakness is to allow multiple valid tokens concurrently assigned to same user account.
  • Another weakness would be using static tokens (same token sent to a user on every login)
  • Another flaw would be when session is base64 encoded of username and some random number, attacker can change username

Vulnerable Session Termination

  • Session may remain valid for days after last request is received
  • Ineffective logout functionality
  • Logout merely deletes cookie but does not invalidate it or logout runs on client side, server is unknown

Client Exposure to Token Hijacking

  • Attacker steals cookie, may be via XSS
  • Session Fixation – attacker feeds token to user, user logs in, attacker hijack the session.
  • Session fixation is possible if app doesn’t issue fresh token after second login or uses same token issued to unauthenticated user for login. If session token format is identified or token can be modified and app accepts it, its session fixation.
  • CSRF – Tricks user into submitting a request containing cookie that goes to attacker’s server

Liberal Cookie Scope

  • When cookie is set, server can set domain and path, cookie is used for. By default, all subdomains are included for which cookie is valid.
  • Path based restriction is more stricter than what is imposed by same-origin policy.

SECURING SESSION MANAGEMENT

Generate Strong Tokens

  • Use extremely large set of possible values
  • Contain strong source of pseudorandomness, ensuring an even and unpredictable spread of tokens across range of possible values.
  • Tokens should contain no meaning or structure.
  • All data about session owner and status should be on server in session object

Source of Entropy (Randomness):

  • Source IP address and port number from which request was received
  • User-Agent header in request
  • Time of request in milliseconds
  • Add secret known only to server and then hash it with SHA256 or stronger. Change secret on each reboot

Protect Tokens Throughout their Life Cycle

  • Transmit tokens only over HTTPS (secure and httponly)
  • Use HTTPS for every page in app
  • Don’t put session tokens in URL
  • Logout should invalidate session token on server
  • Session should expire after brief period of inactivity
  • Do not allow concurrent logins
  • Protect diagnostic or admin functions that save tokens or don’t save tokens in them
  • Restrict domain and path for session cookies
  • Audit codebase and remove XSS esp. second order or stored XSS
  • Don’t accept tokens submitted by unrecognized users
  • Use two factor authentication, makes CSRF and other methods difficult
  • Use hidden fields rather than session cookies
  • A new page token is created every time user requests an app page, if verification fails, terminate session. Also prevents pages being used out-of-order

Log, Monitor and Alert

  • Request with invalid tokens should raise IDS alerts.
  • Alert users of incidents relating to their sessions.

Reactive Session Termination

  • Terminate session if request has modified form field or URL query string parameter
  • Terminate session if strings associated with SQLi or XSS
    Terminate session if input violates validation checks

WEB APPLICATION SECURITY TESTING – 6. ATTACKING AUTHENTICATION

 

This notes is for learning/educational purpose only. Use it at your own risks. 

 AUTHENTICATION TECHNOLOGIES

Wide range of technologies are available for authentication mechanism :

  • HTML form-based authentication
  • Multifactor mechanism like combining password and physical tokens
  • Client SSL certificates and/or smartcards
  • HTTP authentication
  • Windows-integrated authentication using NTLM or Kerberos

90% of web apps use form based authentication.

  • More secure methods would be two-factor authentication i.e. PIN from token, SMS message or mobile app, in addition to password.
  • Cryptographic methods are client side SSL certificate, smartcards etc, but expensive.
  • HTTP authentication including windows integrated are often found on intranets, not on internet.
  • Third party authentication services i.e. using OAuth etc.

DESIGN FLAWS IN AUTHENTICATION MECHANISMS

Bad Passwords

  • Short or blank, dictionary based, same as username or set to default value.

Brute-forcible Login

  • Attackers use list of common passwords. Account lockout is the defense.

Verbose Failure Messages

  • Friendly for legitimate users but helpful for attackers i.e. harvesting valid username

Vulnerable Transmission of Credentials

  • Unencrypted credentials should never be sent even over HTTPS

Password Change Functionality

  • Periodic password change mitigates password compromise is dubious claim. Change password if its compromised.
  • Password change system is vulnerable if:
    • It reveals a username is valid
    • Allows unrestricted guesses of existing password field
    • Checks if new password and confirm new password have same value after validating existing password.

Forgotten Password Functionality

  • Often the weakest link, uses secondary challenge.
  • Small set of possible answers, can be brute-forced or found from public information.
  • Some apps let user in after challenge without login.
  • Some apps disclose password to user.
  • Some apps ask user email id for sending password reset link.

“Remember Me” Functionality

  • Sometimes a simple persistent cookie.
  • No need to login if username or session id can be guessed or found
  • If encrypted, it can be stolen via XSS or by getting acces to user device.

User Impersonation Functionality

  • Company personnel may have access to impersonate users, implemented either as hidden function, guessable session number or fixed backdoor password.

Incomplete validation of credentials

  • Some apps truncate passwords without telling users and also strip unusual characters.

Non-unique usernames

  • Rare, but it might be possible to create new account with same username.

Predictable usernames

  • Automatically generated usernames.

Predictable Initial passwords

  • Usually for user accounts created in large batches. All having same initial password.

Insecure distribution of credentials

  • Passwords sent by email, sms etc.
  • Activation URLs may be predictable.
  • Some apps email new password after each password change.

IMPLEMENTATION FLAWS IN AUTHENTICATION

Fail-Open Login Mechanisms

Blank, invalid username may cause exception in login routine, very long or short values or different character sets and allows the user in.

Defects in Multistage Login Mechanisms

  • May allow user to skip steps.
  • May trust data that passes step one, but let user change it, so invalid or locked out accounts remain available.
  • May assume that same username applied to all three stages but not verify this.
  • May use randomly chosen question to verify user, but let the attacker alter question in hidden HTML or cookie.

Insecure Storage of Credentials

  • Plain text passwords in database.
  • Hashes with MD5 or SHA1, easily cracked.

SECURING AUTHENTICATION

Use Strong Credentials

  • Minimum password length, use of alphanumeric and typographic characters.
    Avoid dictionary words, similar to username or old passwords

Unique usernames

  • Auto generated usernames or passwords should be long and random, so they cant be predicted.
  • Allow users to set strong password.

Handle Credentials Secretively

  • Protect them when created, stored and transmitted.
  • Whole login page should be HTTPS, not just login button.
  • Use POST and don’t put credentials in URL or cookies
  • Don’t transmit credentials back to client
  • Securely hash credentials on server
  • Hashing- Password hashes must be salted (adding random bytes to password before hash) and stretched (many rounds of hashing i.e. 5000 rounds for SHA512)
  • “Remember Me” functionality should remember only non-secret items i.e. usernames
  • If password is stored locally, it should be reversibly encrypted with key known to server only
  • Capture some login info with drop down list instead of text fields to defeat key-loggers

Validate Credentials Properly

  • Validate entire credentials with case-sensitivity
  • Terminate session on any exception
  • Review auththentication logic and code
  • Strictly control user impersonation
  • Multistage login-
    • All data and results of progress must be held in server-side session object not on client
    • No item of information should be submitted more than once by user
    • No means to modify data after submission
    • First task of every stage should be to verify that all prior stages have been correctly completed
    • Always proceed through all stages, don’t give attacker any info about which stage failed

Prevent Information Leakage

  • All authentication failures should use same code to produce same error message.
  • Account lockout can be used for username enumeration

Prevent Brute-Force Attacks

  • Using unpredictable usernames makes brute force attacks more difficult
  • Using different usernames with same password for an attack, can be mitigated with strong password rules i.e. CAPTCHA

Prevent Misuse of Password Change Function

  • Prevent changing username.
  • Require user to enter old password
  • Require new password twice
  • Show same error message for all failures
  • Out-of-band password change notification

Prevent Misuse of Account Recovery Function

  • For security critical apps, require out-of-band account recovery
  • Don’t use password hints
  • Email unique, time-limited, unguessable, single-use recovery URL
  • Don’t let users write their own challenge questions and don’t use questions with low-entropy answers

Log, Monitor and Notify

  • Log all authentication related events and protect logs from unauthorized access
  • Anomalies like brute force should trigger IDS alerts
    Notify users of any critical security events
    Notify users in-band of frequent security events i.e. time and source of last login

WEB APPLICATION SECURITY TESTING – 5. BYPASSING CLIENT-SIDE CONTROLS

This notes is for learning/educational purpose only. Use it at your own risks. 

 TRANSMITTING DATA VIA THE CLIENT

It is common for a server to send data to client and for client to repeat that same data back to server. Developers often assume that client wont modify the data. One might wonder why, server needs to transmit to client and get it back. Various reasons could be:

  • Removes the need of tracking all kind of data in user’s session, reducing amount of per session data stored on server, cam improve app’s performance.
  • If app is on multiple servers, user might interact with any of them, So sharing data between servers might not be straightforward than sending it to client.
  • Integration with third party component can also make it difficult.
  • Sometimes tracking a new piece of data might require updating core server-side API.

Hidden Form Fields – Capture with intercepting proxy, modify and replay.

HTTP Cookies – Capture with intercepting proxy, modify and replay.

URL Parameters – Capture with intercepting proxy, modify and replay.

The Referer Header –  Capture with intercepting proxy, modify and replay.
Opaque Data – Obfuscated or encrypted data i.e. session tokens, anti-csrf tokens, one-time access URLs.

  • If plaintext is known, decipher obfuscation algorithm.
  • By extrapolating app’s functionality, obtain required string.
  • If impenetrable, replay value in other context to achieve malicious effect.
    Else, attack server side logic that deobfuscate the opaque data by sending malformed variation i.e. containing overlong values, different character sets etc.

The ASP.NET ViewState – It contains serialized information about state of current page. Employed for server performance, it can also store arbitrary info across successive requests. It is base64 encoded string. Decoding from wrong position will show gibberish. Start from four adjacent offsets into encoded string. ViewState might be protected with MAC protection (indicated by presence of 20 byte hash at end of structure). MAC protection may be enabled or disabled on per page basis. Use burp to decode ViewState.

CAPTURING USER DATA: HTML Forms

Client side validation can improve performance and user experience but validation should not be trusted and must be repeated on server.

Length Limits 

  • If ‘304 Not Modified’ is received, then remove the If-Modified-Since and If-None-Match headers.

Script-Based Validation

  • Replace value after script runs, or disable JavaScript or modify the script.
    To test all cases, put invalid data in one field at a time.

Disabled Elements

  • Value of disabled parameter is not sent to server, so you can add the same parameter and server might fall for it.

NOTE: In Burp, goto Proxy > Options in ‘Response Modification’ provide options to remove webpage defenses.

CAPTURING USER DATA: Browser Extensions

Browser extensions can capture data in various ways – input forms, OS file system, registry etc. Developers might assume that they cannot be circumvented. So they can be fruitful target for discovering vulnerabilities in webapps.

Common Browser Extension Technologies

  • Java applets, flash, silverlight are common extensions. They are compiled to an intermediate bytecode and they execute within VM that provides sandbox environment for execution. They may use remoting frameworks to transmit complex data structures or serialized objects over HTTP.
  • Java applets run in JVM, sandboxed by Java Security Policy.
  • Flash runs in flash virtual machine, sandboxed from host computer. AS3 adds remoting capability with Action Message Format serialization.

Approaches to attack Browser Extensions

  • Intercept requests and responses in proxy, which can be encrypted, obfuscated or serialized. One may not explore all business logic of component from intercept unless component is closely analyzed.
  • De-compile bytecode and read source code or run it in debugger. Time consuming and requires detailed understanding of technologies.

Intercepting Traffic from Browser Extensions

  • It allows to defeat server-side controls.
  • Serialized data is tricky to modify. Unpack it, edit it and repack it correctly to avoid parsing errors. Serialization format can be inferred by type of client component but evident by close inspection of HTTP messages.
  • HTTP messages containing java serialized objects can be identified with Content-Type header having value of ‘application/x-java-serialized-object’. It can be modified with DSer plugin of burp suite.
  • Flash serialization can be identified with Content-Type header with ‘application/x-amf’ value. Burp natively supports AMF format.
  • Silverlight uses WCF employing .NET binary format for SOAP (NBFS) identified with Content-Type header with ‘application/soap+msbin1’ value. WCF binary SOAP plugin by Brian Holyfield can be helpful.

Obstacle to intercepting traffic from browser extension-

  • Components might be handling HTTP proxies or SSL or both.
  • Components may issue own HTTP requests outside browser APIs. So it cant be intercepted. Modify the hosts file and use invisible proxying.
  • If component is rejecting proxy cert, then configure proxy to use master CA certificate (used to sign valid per-host certificates for each site one visit) and install CA cert in computer’s trusted certificate store.
  • If component is using protocol other than HTTP, network sniffer or function hooking tool might be required like Echo Mirage.

TIPS: Ensure proxy is correctly intercepting all traffic, check with sniffer. Use appropriate serialization unpacker. Review responses from server that trigger client-side logic, you may be able to unlock a client GUI to reveal privilege actions. Look for correlation between critical actions and communications with server.

De-compiling Browser Extensions

Most thorough method is to decompile object and perform review of source code. Change the code if necessary and recompile it. Apps may use defensive measures to obfuscate bytecode.

Extension objects and decompiler:

  • Java applets are usually .jar files containing .class files with bytecode. Silverlight objects are .xap files containing .dll files with bytecode. Both are zip archive, rename extension & unzip it. Flash objects are .swf files, no unpacking required.
  • Use Jad decompiler for java. Flasm or Flare for flash. SWFScan was bundled into WebInspect. Silverlight use .NET reflector.

Working with Source code:

Review source code, understand how component works and what functionality it contains. Look for:

  • Input validation or security relevant logic and events.
  • Obfuscation or encryption routines used to wrap user input before sent to server.
  • Hidden client side functionality or references to server side functionality.

Recompile and Execute:

  • Use javac for java program to recompile.
  • Use flasm for flash file to reassemble modified bytecode.
  • Use Visual Studio to recompile for silverlight.

One can undo a lot of obfuscation by running obfuscated bytecode through obfuscator second time. Useful obfuscator for java is Jode.

Attaching a Debugger

Decompilation is most complete method of understanding and compromising browser extension. Because debugger is working at bytecode level, it can be used to control and understand flow of execution.

  • JavaSnoop is java debugger that can integrate Jad to decompile source code, trace variables, set breakpoints on methods and modify parameters. Run JavaSnoop before target applet is loaded.
  • JSwat is alternative tool for debugging java. Decompile, modify and recompile key class file and use JSwat to hotwap into running app. Launch applet using appletviewer and then connect JSwat to it.

Native Client Components

  • Some actions cannot be conducted from inside sandbox i.e. if user has anti-virus or proxy settings etc.
  • Such actions require use of native code components which integrate local app functionality with web app. Native client components are often delivered via ActiveX controls. It can be little hard to decipher as there is no intermediate byte code.
  • OllyDbg is windows debugger that can be used to step through native executable code, set breakpoints and apply patches to executables.
  • IDA Pro is disassembler that can produce assembly code from native executable code.

HANDLING CLIENT SIDE DATA SECURELY

Transmitting Data Via the Client

  • Don’t send critical data like prices from client. Send product id and lookup price on server.
  • If you must send, then sign and/or encrypt it to avoid user tampering. But it may be vulnerable to replay or other crypto attacks.

Validating Client-Generated Data

All client side validation methods are vulnerable. They can be useful for performance but they can never be trusted. So always validate on server.

Logging and Alerting

  • Server side intrusion detection defenses should be aware of client side validation.It should detect invalid data as probably malicious, triggering alerts and log entries.
  • May terminate user session or suspend user account.

 

WEB APPLICATION SECURITY TESTING – 4. APPLICATION MAPPING

This notes is for learning/educational purpose only. Use it at your own risks. 

First step to attack an application is to gather and examine some key information.

  • Enumerate application’s content and functionality.
  • Some functionality might be hidden requiring guesswork and luck to discover.
  • Examine every aspect of behavior, security mechanisms and technologies.
  • Helps in determining attack surface and vulnerabilities.

ENUMERATING CONTENT & FUNCTIONALITY

Majority of content and functionality can be identified via manual browsing. To perform rigorous inspection of enumerated content and to obtain comprehensive record of everything identified, more advanced techniques must be employed.

Web Spidering

  • Requesting web pages recursively by parsing.
  • Webapp Spiders can parse HTML forms, fill forms with preset or random values to submit.
  • Webapp Spiders can also parse client side JS to extract URLs.
  • Common web app spidering tools are – Burp Suite, WebScarab, ZAP and CAT.

Robots.txt

  • Intended to stop search engines from indexing urls.
  • May guide spiders to interesting content.

Limitations of Automatic Spidering

  • May fail to handle unusual navigation mechanisms i.e. Menus created dynamically.
  • Links buried in compiled client-side objects i.e. flash or java might be missed.
  • Forms may have validation checks.
  • Spiders fetch each URL once, but app using forms-based navigation may return different content and functions for same URL.
  • Some apps place volatile data within URLs i.e. timers or random number seeds. Spider will fetch same page over and over thinking its new and finally might freeze up.
  • Spiders must be able to submit valid credentials, perhaps using valid cookie. However, spiders often break authenticated session by requesting logout function or submitting invalid input to sensitive function or requesting pages out-of-sequence.
  • Spiders may find administrative page and click every link i.e. delete user, shut down db or server etc.

User directed Spidering

It is more sophisticated and controlled technique than automated spidering. User walks through app using browser connected to Burp. Proxy collects all requests and responses.

So user can follow complex navigation mechanisms. User can enter valid data where needed and avoid dangerous functionality.

TIP: Other tools useful during mapping are browser extensions performing HTTP and HTML analysis. i.e. IEWatch in IE. It analyzes every app page to display links, scripts, forms and think-client components.

HACKSTEPS For Spidering:

  1. Configure browser to use local proxy i.e. Burp or WebScarab
  2. Browse entire app normally, visit every link/url, submit every form, proceed with multistep functions. Try browsing with JS enabled and disabled, cookies enabled and disabled.
  3. Review sitemap generated. Identify if any app content/function you did not visit.
  4. Tell tool to actively spider site using already enumerated content. Identify URLs that are dangerous or likely to break app session & configure spider to exclude these from scope.

Discovering Hidden Content

  • Finding it requires automated testing, manual testing and luck.
  • It can be testing or debugging feature left in application. Or it can be feature for different category of users. There can be source files, backup copy of files, backup archive of entire source code, configuration files, log files or new functionality yet to be linked etc.

Brute Force Techniques
When the user-directed spidering has left with some URLs. Brute forcing the URLs for hidden directories or sub-directories using list of common directory names can be useful. This can be done with Brup Intruder.

NOTE: Some apps might respond to non-existent resource with 200 OK and error message and non-200 response for existent resource.

  • 302 Found – If redirect is to login page, resource might be accessible to authenticated users only. If redirect is to an error, this indicates a different reason. If redirect is to another location, redirect may be part of apps intended logic, & this should be investigated further.
  • 400 Bad Request – App may use custom naming scheme for directories and files within URLs. It is also possible that word list contains some whitespace or other invalid syntax.
  • 401 Unauthorized or 403 Forbidden – Requested resource exist but may not be accessed by any user.
  • 500 Internal Server Error – App expects certain parameters to be submitted when requesting resource.

HACKSTEPS for Discovering Hidden Content:

  1. Make manual requests for valid and invalid resources and identify how server handles
  2. Use sitemap as basis for automated discovery of hidden content
  3. Make automated requests for common filenames and directories to highlight results for invalid resources.
  4. Capture responses received from server and manually review them to identify valid resources.
  5. Perform exercise recursively as new content is discovered.

Inference from Published Content

  • Identify patterns if any from discovered URLs or content to customize enumeration exercise.
  • Names may use numbers or dates.
  • Comments may include DB names or SQL query strings.
  • Applets and ActiveX controls may have sensitive information.
  • Search for temp files created by tools and file editors. i.e. .tmp
  • .DS_Store – a directory index created by Mac OS X
  • Advanced search with site:, link:, related: google operators.

Dirbuster project

Useful when performing automated content discovery tasks. It includes large lists of directory names ordered by frequency of occurrence.

Google’s SkipFish

Vulnerability scanner but main strength is finding files and folders.

Nikto and Wikto

  • Scan servers for known vulnerable files and versions. Wikto is windows version and Nikto is Linux version.
  • Has false positives like other, verify results with manual testing.
# nikto -host blog.saurabh.world

Functional Paths

  • Different from old style tree-structured file system.
  • Every request goes to same URL, but parameters specify function.

HACKSTEPS for Enumerating Functional Paths:

  1. Identify any instance where functionality is accessed by passing name of function in parameter
  2. Identify system behavior with valid and invalid parameter values. Find attributes of responses that indicate ‘hits’. Breakdown enumeration in multiple steps if multiple parameters are used to access a function.
  3. Compile a map of app content based on functional paths, showing all enumerated functions and logical paths and dependencies between them.

Discovering Hidden Parameters

  1. Use list of common debug parameter names (debug, test, hide, source, etc.) and common values (true, yes, on, 1 etc.) to make requests to known app page or function. For POST requests, insert parameter to both URL query string and message body. Burp Intruder can do this using multiple payload set and cluster bomb attack type.
  2. Monitor all responses to identify any anomalies indicating any effect on app’s processing.
  3. Target different pages and functions, most likely to place like login, search, file upload and download etc. where debug logic might be implemented.

ANALYZING APPLICATIONS

The task of analyzing app’s functionality, behavior, and technologies employed to identify the key attack surfaces is also important.

Key areas are:

  • Core functionality
  • Peripheral behavior: off-site links, error messages, administrative and logging functions and redirects.
  • Core security mechanisms: session state, access control, authentication mechanism and supporting logic
  • Everywhere the app processes user-supplied input i.e. URL, query string, POST data, cookies
  • Client side technologies i.e. forms, scripts, thick-client components (Java applets, ActiveX controls and Flash) and cookies.
  • Server side technologies i.e. static & dynamic pages, request params, SSL, web server software, DB interactions, email systems and other backend components.

Entry Points for User Input

  • URL File paths
    • RESTful URLs put parameters where folder names would go.
  • Request Parameters
    • Some non standard parameter formats
      • /dir/file;foo=bar&foo2=bar2
      • /dir/file?foo=bar$foo2=bar2
      • /dir/file/foo%3dbar%26foo2%3dbar2
      • /dir/foo.bar/file
      • /dir/foo=bar/file
      • /dir/file?param=foo:bar
      • /dir/file?data=%3cfoo%3ebar%3c%2ffoo%3e%3cfoo2%3ebar2%3c%2ffoo2%3e
  • Placing payloads within embedded XML data fields may give critical bug like SQLi or path traversal
  • HTTP Headers
    • User-Agent is used to detect small screens and sometimes to modify content to boost search engine rankings. May allow XSS and other injection attacks. Also, may reveal different UI.
    • Apps behind load balancer or proxy may use ‘X-Forwarded-For’ header to identify source & log it.
    • Attacker can add additional headers too which app might process.

Out-Of-band Channels

Finding out of band channel from which app receives data can be difficult and usually requires understanding of wider context of functionality that app implements. Example-

  • Web mail app processes email received via SMTP.
  • Publishing app uses function to retrieve content via HTTP from another server.
  • IDS gathers data using sniffer and presents using web interface.
  • Application providing APIs.

Identifying Server-Side Technologies

  • Banner Grabbing
    • Version information of web server and other component might be disclosed.
    • Web page templates may have version information
    • Custom HTTP headers reveal possible web server software
    • URL query string parameters
  • HTTP Fingerprinting
    • Httprecon uses subtle clues to identify versions, not just banners.
  • Wapplyzer
  • File Extensions – Discloses platform or language
    • asp – Microsoft Active Server Pages
    • aspx – Microsoft ASP.NET
    • jsp – Java Server Pages
    • cfm – Cold Fusion
    • php – PHP language
    • d2w – WebSphere
    • pl – perl language
    • py – python language
    • dll – Compiled native code of C/C++
    • nsf/ntf – Lotus Domino
  • Error Messages
    • Error pages for known and unknown and invalid file extensions
  • Directory names
    • servlet – Java Servlets
    • pls – Oracle AppServer PL/SQL gateway
    • cfdocs/cfide – Cold Fusion
    • SilverStream – SilverStream Web server
    • WebObjects or {function}.woa – Apple WebObjects
    • rails – Ruby on Rails
  • Session Tokens
    • JSESSIONID – Java platform
    • ASPSESSIONID – Microsoft IIS Server
    • ASP.NET_SessionId – Microsoft ASP.NET
    • CFID/CFTOKEN – Cold Fusion
    • PHPSESSID – PHP
  • Third-Party Code components
    • Web app incorporate third party code to implement common functionality i.e. shopping carts, login mechanism etc. It can be open source or purchased. One can download and install to perform source code review or probe for defects in controlled way.

HACKSTEPS for Finding input points and identifying technologies employed:

  1. Identify all entry points for user input i.e. URLs, query string parameters, POST data, cookies, and HTTP headers
  2. Identify query string format; should be some variation on name/value pair.
  3. Identify out-of-bound channels for incoming data to app
  4. View HTTP Server banner.
  5. Check for software identifiers in HTTP header or HTML source code
  6. Run httprint to fingerprint web server
  7. Research software versions for vulnerabilities
  8. Review map of URLs and cookies to identify server side technologies

Identifying Server-Side Functionality

  • Dissecting Requests
    • Review names and values of all parameters being submitted to app in context to functionality
    • Think like programmer, imagine what server-side mechanism is likely being used to implement the behavior.
  • Extrapolating Application Behavior
    • Often application behaves consistently across range of its functionality. So if SQLi is filtered try somewhere else to see what filtering is done. If app obfuscates data, try somewhere original string is returned. Or try to deduce obfuscation scheme.
  • Isolating Unique Application Behavior
    • Note any functionality that diverges from standard appearance, parameter naming or navigation mechanism.
    • Note any functionality that have been added retrospectively i.e. debug functions, CAPTCHA controls, usage tracking and third-party code.
    • It is very much possible that standard defenses of framework might not be applied in such cases.

Mapping the Attack Surface

Identify attack surfaces exposed and possible vulnerabilities associated with each one.

  • Client side validation – Checks may not be replicated on server
  • Database interaction – SQLi
  • File upload/Download – Path traversal, Stored XSS
  • Display of user supplied data – XSS
  • Dynamic redirects – Redirection and Header injection
  • Social networking features – Username enumeration, Stored XSS
  • Login – Username enumeration, Weak passwords, Bruteforce
  • Multistage login – Logic flaws
  • Session state – Predictable tokens, Insecure handling of tokens
  • Access Controls – Horizontal and Vertical PE
  • User impersonation functions – PE
  • Cleartext communications – Session Hijacking, Credential/Sensitive data Sniffing
  • Off-Site Links – Leakage of query string parameters in ‘Referer’
  • Interface to external systems – Shortcuts in handling sessions and/or access controls
  • Error messages – Information leakage
  • E-mail interaction – Email and/or command injection
  • Native code components or interaction – Buffer overflow
  • Third party components – Known vulnerabilities
  • Identifiable web server software – Common config weakness, known software bugs

HACKSTEPS for Identifying functionality and mapping attack surface :

  1. Understand core functionality implemented within app and main security mechanism in use.
  2. Identify all features of apps functionality often associated with common vulnerabilities.
  3. Check third party code against public vulnerability database to determine any known issues.
  4. Formulate plan of attack, based on interesting functionality and serious vulnerability

WEB APPLICATION SECURITY TESTING – 3. WEB COMMUNICATIONS

This notes is for learning/educational purpose only. Use it at your own risks. 

THE HTTP PROTOCOL

The HTTP Protocol is connectionless protocol. Client sends HTTP request to web server, then gets HTTP response. No session is formed, nothing is remembered.

The HTTP Request

The first line of every HTTP request consists of three items, separated by spaces.

  1. Verb indicating HTTP method i.e. GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, CONNECT
  2. Requested URL for a particular resource
  3. HTTP Version being used i.e. HTTP/1.0, HTTP/1.1 etc.

Other lines in HEAD part of HTTP request contains other HTTP headers like Host, Referer, User-Agent, Cookie, Connection, Accept, Accept-Encoding etc.

  • The ‘Host’ header – mandatory in HTTP/1.1. It specifies hostname. Essential when multiple hosts run on same IP like in case of virtual hosting.
  • The ‘User-Agent’ header – provides info about browser or client software which generates request.
  • The ‘Referer’ header – contains URL from which request has been originated.
  • The ‘Cookie’ header – contains parameters (name value pairs) that server has issued to client.
  • The ‘Accept’ header – tells server what content client can accept i.e. image types, document formats etc.
  • The ‘Accept-Encoding’ header – tells server what content encoding client can accept.
  • The ‘Authorization’ header – submits credentials to server for HTTP authentication types.
  • The ‘If-Modified-Since’ header – tells when client last received requested resource. If resource is not modified since then client can use cached copy, using response status code 304.
  • The ‘If-None-Match’ header – specifies entity tag, an identifier denoting content of body. The client submits entity tag to server. Server determines with entity tag if client can use cached copy of resource.
  • The ‘Origin’ header – used in cross domain AJAX requests to indicate the domain from which request has originated.

The HTTP Response

The first line contains HTTP version, HTTP response status code, textual ‘phrase’ describing the response.

  • The ‘Server’ header – contains a banner indicating web server software being used. Information may or may not be accurate, often obfuscated due to security reason to prevent information gathering.
  • The ‘Set-Cookie’ header – issues browser a further cookie, this is submitted back in Cookie header of subsequent requests to this server.
  • The ‘Pragma’ header – tells browser not to store response in its cache.
  • The ‘Content-Length’ header – tells length of message body in bytes.
  • The ‘Expires’ header – specifies date & time when the content should expire and resource is re-requested.
  • The ‘Access-Control-Allow-Origin’ header – indicates if resource can be retrieved via cross domain AJAX requests.
  • The ‘Cache-Control’ header – tells caching directives to browser.
  • The ‘Etag’ header – specified an entity tag.
  • The ‘Expires’ header – tells browser how long content of body is valid.
  • The ‘Location’ header – used in redirection responses to specify target of redirect
  • The ‘WWW-Authenticate’ header – used in responses having 401 status code to provide authentication details
  • The ‘X-Frame-Options’ header – indicates whether and how current response may be loaded within browser.

Note: See Chapter 13 for explanation of few headers in relation to cross domain AJAX requests.

HTTP General headers

  • The ‘Connection’ header – tells other host if it should close TCP connection after HTTP transmission or keep it open.
  • The ‘Content-Encoding’ header – tells what encoding is used for content in body i.e. gzip – used by some apps to compress response for faster transmission
  • The ‘Content-Type’ header – tells type of content in message body i.e. text/html, text/xml, text/json etc.

The HTTP Methods

  • GET method for retrieving resources. It can send parameters in URL query string. URL might be logged on server. Never put sensitive information in query string.
  • POST method performs actions. Request parameters can be in URL query string and in body of message. Parameters in body aren’t saved in bookmarks or server logs.
  • HEAD method returns only header not the body. Used to check if resource is available.
  • OPTIONS shows what HTTP method is accepted by web server.
  • PUT uploads to server. Usually disabled, but might be used with APIs.

Cookies

Cookies are resubmitted in each request to same domain by client to server.
Optional attributes are:

  • expires – date when cookie becomes invalid. If not specified, cookie is valid till browser is closed.
  • domain – specified domain for which cookie is valid. This must be same from which cookie is received. “Same-Origin-Policy”
  • path – specifies URL path for which cookie is valid.
  • secure – if it is set, cookie is transmitted only in HTTPS requests.
  • HttpOnly – if it is set, cookie cant be accessed directly by JavaScript.

Status Code Groups

  • 1xx – Informational
  • 2xx – Request was successful.
  • 3xx – Client is redirected to different resource
  • 4xx – Request contains an error of some kind
  • 5xx – Server encountered an error fulfilling the request

Important Status Codes

  • “200 OK” – request succeeded, response body contains result
  • “301 Moved Permanently” – redirects browser to another location, client should use new URL in future
  • “302 Found” – temporary redirect
  • “304 Not Modified” – browser should use cached copy
  • “400 Bad Request” – invalid HTTP request
  • “401 Unauthorized” – requires HTTP authentication, ‘WWW-Authenticate’ tells type of authentication required
  • “403 Forbidden” – no one is allowed to access
  • “404 Not Found” – requested resource does not exist
  • “500 Internal Server Error” – unhandled exception, server side error
  • “503 Service Unavailable” – Web server is responding, but application it serves does not respond

Redirections from HTTP to HTTPS is not okay. One can hijack session and force to use unsecure connection.

Uniform Resource Locator (URL)

 protocol://hostname[:port]/[path/]file[?param=value]
  • If protocol is absent, it defaults to HTTP.
  • If port is absent, it uses default port for protocol i.e. 80 for HTTP, 443 for HTTPS etc.

Representational State Transfer (REST)

  • Architectural style for distributed systems.
  • In REST style, URL contains parameters in URL file path rather than query strong. i.e.
http://wahh.com/search?make=mercedes&model=s-class
  • Corresponds to REST style as:
http://wahh.com/search/mercedes/s-class

HTTP Authentication

HTTP has its own authentication mechanism using various schemes:

  • Basic : User sends credentials as base64 encoded string in request message.
  • NTLM : challenge-response mechanism and uses a version of Windows NTLM protocol
  • Digest : challenge-response mechanism and uses MD5 checksums of nonce with user credentials.

All schemes are cryptographically weak, so it is recommended to use HTTPS.

HTTPS

  • HTTP over SSL (Secure Socket Layer)
  • SSL is actually TLS (Transport Layer Security) now. Original versions of SSL is deprecated.
  • SSL encrypts data while in transit.

HTTP Proxies

  • Browser sends requests to proxy server. Proxy fetches resources and sends back to client.
  • Proxies can provide caching, authentication, and access control.
  • When HTTPS is used, browser cant perform SSL handshake with proxy as it breaks the secure tunnel. Hence browser must use proxy as pure TCP-level relay to pass data between browser and server in both direction. To establish this relay, browser makes HTTP request to proxy with CONNECT method specifying server hostname and port as URL. If proxy allows, it returns 200 OK and keeps TCP connection open.

HTTPS and MITM Attacks

  • HTTPS connections use public-key cryptography. Only endpoints can decrypt traffic.
  • Companies wanting to restrict HTTPS traffic have two choices:
    • Perform complete MITM (Man-In-The-Middle) with fake certificates or real root certificates from trusted CA’s.
    • Allow encrypted traffic to trusted domains without possibility of inspection.

Same Origin Policy

  • A residing on one domain can cause arbitrary request to another domain. But it cannot itself process the data returned from that request.
  • A page residing on one domain can load a script from another domain and execute this within its own context. This is because scripts are assumed to contain code rather than data. So cross domain access should not lead to disclosure of any sensitive information.
  • A page residing on one domain cannot read or modify cookies or other DOM data belonging to another domain.

Web 2.0

  • Heavy use of AJAX for asynchronous requests (behind the scene requests).
  • Increased cross-domain integration using various techniques.
  • Use of new technologies on client side i.e. XML, JSON and Flex.
  • Supports user-generated content, information sharing and interaction.

State and Sessions

Stateful data required to supplement stateless HTTP. This data is held in server-side structure called session. Some state data is stored on client, often cookies or hidden form fields.

ENCODING SCHEMES

URL Encoding:

URLs may contain only printable ASCII characters (0x20 to 0x7e, inclusive). To transfer other characters, characters must be url encoded.
URL encoded form has % prefix followed by character’s two digit ASCII code expressed in hex. i.e.

  • = (%3d)
  • % (%25)
  • Space (%20)
  • New Line (%0a)
  • Null byte (%00)

The + character represents URL encoded space.
Always encode following during web app security testing:

space % ? & = ; + #

Unicode Encoding:

  • Character encoding standard designed to support world’s all writing systems.
  • For using over HTTP, 16-bit Unicode encoding has %u as prefix followed by character’s unicode code point expressed in hexadecimal.
  • UTF-8 is variable length encoding standard employing one or more bytes to express each character. For multibyte character it uses each byte expressed in hexadecimal and preceded by % prefix. i.e.
    Copyright symbol is %c2%a9
  • It can be used sometimes to defeat input validation mechanisms.

HTML Encoding:

HTML entities to represent specific literal characters i.e.

" = “

 

' = ‘

 

& = &

 

&lt; = <

 

&gt; = >

Also, any character can be HTML encoded using its ASCII code in decimal form i.e.

" = "

 

' = '

OR, by using ASCII code in hex i.e.

" = "

 

' = '

HTML encoding user data before sending to another user is used to prevent XSS.

Base64 Encoding:

  • Represents binary data using 64 ASCII characters (A-Za-z0-9/=) using six bits at a time in block of 3 bytes. If final input block results in fewer than 3 chunks of output data, output is padded with one or two = characters.
  • Used to encode email attachments for sending via SMTP.

Hex Encoding:

Hexadecimal representation of each ASCII characters.

WEB APPLICATION SECURITY TESTING – 2. CORE DEFENSE MECHANISMS

This notes is for learning/educational purpose only. Use it at your own risks.

Core elements of defense mechanisms usually employed by Web Applications:

  • Handling user access to app’s data and functionality to prevent unauthorized access
  • Handling user input to prevent malformed input from causing undesirable behavior
  • Handling attackers by taking suitable defensive and offensive measures
  • Administrative monitoring and configuring application

HANDLING USER ACCESS

  • Authentication : Process contains core authentication mechanism, plus authentication related functions. Often it contains defects in both design and implementations.
  • Session Management : Using cookies for tracking user and requests. User is identified with session token. Session management is highly dependent on security of token. Defects in how tokens are generated enables token guessing and defects in how tokens are handled enables attacker to capture other users token.
  • Access Control : To make and enforce correct decisions about whether individual request should be permitted or denied. Due to complex nature of access control requirements it becomes source of security vulnerabilities.

HANDLING USER INPUT

Various types of inputs include arbitrary texts like blog posts, cookies, hidden form fields, parameters and http header fields like user agent.

Input Validation is most common solution. However input validation on client side, often written with JavaScript, can be bypassed.

Approaches to input handling

  • Rejecting Known bad or ‘Blacklisting’
    • Least effective method due to difficulty of identify all bad input.
    • If SELECT is blocked, try SeLeCT
    • If ‘or 1=1–‘ is blocked, try ‘or 2=2–‘
    • If alert(‘xss’) is blocked, try prompt(‘xss’)
  • Accepting Known Good or ‘Whitelisting’
    • Most effective technique
    • Sometimes not feasible in cases where input is blog post or names containing quotes.
  • Sanitization
    • Render dangerous input harmless
    • URL Encoding
    • Difficult is several kinds of data is present within input. So Boundary validation is a better option.
  • Safe Data Handling
    • Code that cant be fooled by malicious input i.e. SQL parameterized queries, not passing input to OS command line.
    • May be impossible to achieve it due to requirement of intensive training for all developers, often settled with devices like WAF etc.
  • Semantic Checks
    • Malicious input is identical to valid input like providing different user id.
    • Data must be validated in context i.e. input user id belongs to logged in user?

Note: In context where NULL bytes act as string delimiter, it can be used to terminate file name or query string. In context where NULL byte is ignored, arbitrary NULL bytes can be used to defeat some black-list based filters.

Problem with Simple Input Validation

  • User input is untrusted
  • Server side app is trusted. Apps may chain several processing steps together. Data may be harmless at one stage but can be harmful at another stage.

Boundary Validation

  • Trust boundary is required.
  • Clean data that passes a boundary
  • Each component treats its input as malicious
  • Data validation should be performed at each trust boundary. Not just between client and server.
  • Example:
    • Username and password is input. Allow only good characters, limits length, remove known attack signatures.
    • Escape dangerous characters in SQL query performing credential verification.
    • App server passes user profile data to SOAP service. XML metacharacters are encoded to block SOAP injection.
    • App displays user account information back to browser. User supplied data is HTML encoded to block XSS known as Output Sanitization.

Simple Filtering Issues:

  • Rejecting ‘<script>’ can be bypassed by ‘<sc<script>ript>’
  • Multistep filtering: First removing ‘../’, then ‘..\’ can be bypassed by ‘….\/’

Canonicalization

Canonicalization is process of converting or decoding data into common character set. If any canonicalization is done after filters have been applied, an attacker may use suitable encoding scheme to bypass validation mechanism.

  • App gets URL-encoded data from browser. To block apostrophe, app filters %27. But data is decoded twice by mistake so app gets %2527 as apostrophe which bypasses app filters.
  • If app strips apostrophe instead of encoding then performs canonicalization then %%2727 can be effective.

Note: Some browsers perform HTML decode of src parameter value. So if encoded input bypasses filters and is passed to app’s response then JavaScript executes. Canonicalization also raises issue when app converts data from one character set to another.

HANDLING ATTACKERS

Attackers are handled by implementing following measures:

  • Handling errors
  • Maintaining audit logs
  • Alerting administrators
  • Reacting to attacks

Handling Errors:

  • Show appropriate error messages
  • Unhandled errors lead to overly-informative error messages

Audit logs:

  • Authentication events like login success or failure, password change etc.
  • Key transactions like credit card payments or fund transfer
  • Access attempts that is blocked by Access control mechanisms
  • Requests containing known attack strings
  • For high security, log every client request in full with IP, time, cookie etc.
  • Store audit log to autonomous system that accepts only update messages from main app
  • Poorly protected log can be gold mine, disclosing sensitive info like session tokens and request parameters.

Alerting Administrators:

  • Use anomalies for alerting, like large number of requests from same IP or user
  • Business anomalies, like large number of fund transfers to/from same account
  • Requests containing known attack strings
  • Requests where hidden data has been modified.
  • WAF can detect generic attacks but not subtle ones.
  • Most effective security control is integrated with app’s input validation mechanisms.

Reacting to Attacks:

  • Attackers probe for vulnerabilities. Sending many similar requests.
  • Automated defenses include responding increasingly slowly to requests or terminating attacker’s session. Like Bro tool does.

MANAGING APPLICATIONS

To manage and monitor applications, administrative interfaces are often built in app itself or accessible through some other interface which may perform user account and roles management, access monitoring and audit functions, perform diagnostics and log management. So it is primary attraction for attacker as vehicle for PE (privilege escalation).

Attacking Admin interfaces:

  • Defeat weak authentication mechanisms
  • Poor implementation of access control mechanisms, provides access to admin functions with low privileges
  • Cookie theft and session hijack with XSS compromises admin level privileges/account

 

WEB APPLICATION SECURITY TESTING – 1. INTRODUCTION

This notes is for learning/educational purpose only. Use it at your own risks.

COMMON WEB APPLICATIONS

Most common Web applications used today are:

  • Shopping (Amazon)
  • Social Networking (Facebook)
  • Banking (CitiBank)
  • Web Search (Google)
  • Web Mail (Gmail)
  • Auctions (Ebay) etc.

Internal Web apps in organizations (Cloud services) are :

  • HR payroll information, performance reviews
  • Admin interfaces to servers, VM’s, workstations
  • Sharepoint, ERP, Outlook Web access, Office apps etc.

WEB APP SECURITY

State of Web app security:

  • Breaches are common. Attackers get sensitive data usually by gaining complete control of back end systems.
  • DoS (Denial of Service) at application level

Common Security flaws:

  • Broken Authentication and Access controls
  • SQL Injection
  • XSS (Cross Site Scripting – User input is script which gets executed in browser)
  • CSRF (Cross Site Request Forgery – Custom link created for execution in different context.)
  • Information Leak

THE FUNDAMENTAL SECURITY ISSUE is that users can supply arbitrary input. Malicious input can compromise site.

  • Alter parameters, cookies, HTTP headers
  • Client side controls cant be trusted
  • Developers must assume all input is malicious
  • Attacker have attack tools like burp, not restricted to use browsers

Scenario: Static Website

Information flows one way. Attacker who exploits web server can steal public data or deface the site.

Scenario: Web Applications

Two way information flow. User logs in and submit content. Lot of data is sensitive and private. Most apps are developed in house. And often developers are naive about security.

Various possible attacks at client side:

  • Change price of item
  • Modify session token to enter another user’s account
  • Remove parameters to exploit logic flaws
  • SQLi

Key Problem Factors for state of security:

  • Underdeveloped security awareness
  • Custom/In-house app development
  • Deceptive simplicity: Easy to make website (using frameworks etc.), but hard to secure it.
  • Rapidly evolving threat profile: Security steps taken at beginning might get outdated.
  • Resource and Time constraints
  • Overextended technologies
  • Increasing demands on functionality

The New Security Perimeter

  • Edge firewalls and bastion hosts are not enough to keep attacker out of critical systems, because user input is custom crafted.
  • Third party components can also have vulnerability which might break your security.
  • Attackers can attack client side controls instead of servers.

Future of Security

  • #1 security measure – updates
  • Some vulnerabilities are decreasing
  • Logic flaws and failure to use controls properly are not decreasing

Example of latest hack in Feb 2018 : SinVR Hack – 20k User credentials & information exposed. Hack was possible due to IDOR (Indirect Object Reference) weakness.

 

OverTheWire – BANDIT

ethical-hackers-for-businesses-articleLEVEL 0

Connect to  bandit.labs.overthewire.org on port 2220 with username bandit0 and password bandit0. Find the password for level 1 from readme file in home directory.

# ssh -p 2220 bandit0@bandit.labs.overthewire.org
# cd ~
# more readme
boJ9jbbUNNfktd78OOpsqOltutMc3MY1

LEVEL 1

Password for next level is stored in – file in home directory.

# ssh -p 2220 bandit1@bandit.labs.overthewire.org
# more ./-
CV1DtqXWVFXTvM2F0k09SHz0YwRINYA9

LEVEL 2

Password for next level is in the file called “spaces in this filename

# ssh -p 2220 bandit2@bandit.labs.overthewire.org
# more spaces\ in\ this\ filename
UmHadQclWmgdLOKQ3YNgjWxGoRMb5luK

LEVEL 3

Password for next level is stored in a hidden file in directory inhere.

# ssh -p 2220 bandit3@bandit.labs.overthewire.org
# cd ~/inhere
# ls -aul
# more .hidden
pIwrPrtPN36QITSp3EQaw936yaFoFgAB

LEVEL 4

Password for next level is stored in a human readable file in inhere directory

# ssh -p 2220 bandit4@bandit.labs.overthewire.org
# file ~/inhere/./-* | grep ASCII
# more ~/inhere/-file07
koReBOKuIDDepwhWk7jZC0RTdopnAYKh

Level 5

Password for next level is stored in a file somewhere under inhere directory that is human readable, 1033 bytes in size and is not executable

# ssh -p 2220 bandit5@bandit.labs.overthewire.org
# find ~/inhere/ -size 1033c -type f
# more ./maybehere07/.file2
DXjZPULLxYr17uwoI01bNLQbtFemEgo7

Level 6

Password for next level is stored somewhere on server in a file that is owned by user bandit7 and group bandit6 and is 33 byte in size.

# ssh -p 2220 bandit6@bandit.labs.overthewire.org
# find / -size 33c -user bandit7 -group bandit6 2>/dev/null
# more /var/lib/dpkg/info/bandit7.password
HKBPTKQnIay4Fw76bEy8PVxKEDQRKTzs

LEVEL 7

Password for next level is stored in file data.txt next to word millionth

# ssh -p 2220 bandit7@bandit.labs.overthewire.org
# more data.txt | grep millionth
cvX2JJa4CFALtqS87jk27qwqGhBM9plV

LEVEL 8

Password for next level is stored in a file data.txt in a line that occurs only once

# ssh -p 2220 bandit8@bandit.labs.overthewire.org
# more data.txt | sort | uniq -c | grep "1 "
1 UsvVyFSfZZWbi6wgC7dAFyFuR6jQQUhR

LEVEL 9

Password for next level is in file data.txt prefixed by several characters of “=”

# ssh -p 2220 bandit9@bandit.labs.overthewire.org
# strings data.txt | grep '='
truKLdjsbJ5g7yyJ2X2R0o3a5HQJFuLk

LEVEL 10

Password for next level is stored in file data.txt in base64 encoded format.

# ssh -p 2220 bandit10@bandit.labs.overthewire.org
# more data.txt 
VGhlIHBhc3N3b3JkIGlzIElGdWt3S0dzRlc4TU9xM0lSRnFyeEUxaHhUTkViVVBSCg==
# python
>> import base64
>> encoded_pass = "VGhlIHBhc3N3b3JkIGlzIElGdWt3S0dzRlc4TU9xM0lSRnFyeEUxaHhUTkViVVBSCg=="
>> base64.b64decode(encoded_pass);
'The password is IFukwKGsFW8MOq3IRFqrxE1hxTNEbUPR\n'

LEVEL 11

Password for next level is stored in a file data.txt where all txt has been rotated by 13 characters (ROT13 encryption)

# ssh -p 2220 bandit11@bandit.labs.overthewire.org
# more data.txt
Gur cnffjbeq vf 5Gr8L4qetPEsPk8htqjhRK8XSP6x2RHh
USE ROT13.com TO DECRYPT IT, OR DO AS BELOW.
# echo Gur cnffjbeq vf 5Gr8L4qetPEsPk8htqjhRK8XSP6x2RHh | tr [a-zA-Z] [n-za-mN-ZA-M]
The password is 5Te8Y4drgCRfCx8ugdwuEX8KFC6k2EUu

LEVEL 12

Password for next level is stored in data.txt, which is a hexdump of a file that is repeatedly compressed.

# ssh -p 2220 bandit12@bandit.labs.overthewire.org
# mkdir /tmp/hacker/
# xxd -r data.txt > /tmp/hacker/compressed_file
# cd /tmp/hacker
# file compressed_file
compressed_file: gzip compressed data, was "data2.bin", last modified: Mon Nov 13 14:58:07 2017, max compression, from Unix
# zcat compressed_file | file -
/dev/stdin: bzip2 compressed data, block size = 900k
# zcat compressed_file | bzcat| file -
/dev/stdin: gzip compressed data, was "data4.bin", last modified: Mon Nov 13 14:58:07 2017, max compression, from Unix
# zcat compressed_file | bzcat| zcat| file -
/dev/stdin: POSIX tar archive (GNU)
# zcat compressed_file | bzcat| zcat| tar xO |file -
/dev/stdin: POSIX tar archive (GNU)
# zcat compressed_file | bzcat| zcat| tar xO | tar xO|file -
/dev/stdin: bzip2 compressed data, block size = 900k
# zcat compressed_file | bzcat| zcat| tar xO | tar xO|bzcat |file -
/dev/stdin: POSIX tar archive (GNU)
# zcat compressed_file | bzcat| zcat | tar xO | tar xO | bzcat | tar xO | file -
/dev/stdin: gzip compressed data, was "data9.bin", last modified: Mon Nov 13 14:58:07 2017, max compression, from Unix
# zcat compressed_file | bzcat| zcat | tar xO | tar xO | bzcat | tar xO | zcat | file -
/dev/stdin: ASCII text
# zcat compressed_file | bzcat| zcat | tar xO | tar xO | bzcat | tar xO | zcat
The password is 8ZjyCRiBWFYkneahHwxCv3wb2a1ORpYL

 

LEVEL 13

Password for next level is stored in  /etc/bandit_pass/bandit14 and can only be read by user bandit14. You will get SSH private key for next level, not the password.

# ssh -p 2220 bandit13@bandit.labs.overthewire.org
# ssh -i sshkey.private bandit14@localhost
bandit14@bandit:~$ more /etc/bandit_pass/bandit14
4wcYUJFw0k0XLShlDzztnTBHiqxU3b3e

LEVEL 14

The password for the next level can be retrieved by submitting the password of the current level to port 30000 on localhost.

# ssh -p 2220 bandit14@bandit.labs.overthewire.org
# telnet localhost 30000
BfMYroe26WYalil77FoDi9qh59eK5xNr

 

LEVEL 15

Password for next level be retrieved by submitting the password of the current level to port 30001 on localhost using SSL encryption.

# ssh -p 2220 bandit15@bandit.labs.overthewire.org
# openssl s_client -ign_eof -connect localhost:30001
---
 Verify return code: 18 (self signed certificate)
---
BfMYroe26WYalil77FoDi9qh59eK5xNr
Correct!
cluFn7wTiGryunymYOu4RcffSxQluehd

LEVEL 16

Submit the password of the current level to a port on localhost in the range 31000 to 32000. First find out which of these ports have a server listening on them. Then find out which of those speak SSL and which don’t. There is only 1 server that will give the next credentials, the others will simply send back to you whatever you send to it.

# ssh -p 2220 bandit16@bandit.labs.overthewire.org
# nmap -p 31000-32000 -sV localhost
PORT STATE SERVICE VERSION
31046/tcp open echo
31518/tcp open ssl/echo
31691/tcp open echo
31790/tcp open ssl/unknown
31960/tcp open echo

# openssl s_client -ign_eof -connect localhost:31518
# openssl s_client -ign_eof -connect localhost:31790
cluFn7wTiGryunymYOu4RcffSxQluehd
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQwik7xfW+24pRNuDE6SFthOar69jp5RlLwD1NhPx3iBl
J9nOM8OJ0VToum43UOS8YxF8WwhXriYGnc1sskbwpXOUDc9uX4+UESzH22P29ovd
d8WErY0gPxun8pbJLmxkAtWNhpMvfe0050vk9TL5wqbu9AlbssgTcCXkMQnPw9nC
YNN6DDP2lbcBrvgT9YCNL6C+ZKufD52yOQ9qOkwFTEQpjtF4uNtJom+asvlpmS8A
vLY9r60wYSvmZhNqBUrj7lyCtXMIu1kkd4w7F77k+DjHoAXyxcUp1DGL51sOmama
+TOWWgECgYEA8JtPxP0GRJ+IQkX262jM3dEIkza8ky5moIwUqYdsx0NxHgRRhORT
8c8hAuRBb2G82so8vUHk/fur85OEfc9TncnCY2crpoqsghifKLxrLgtT+qDpfZnx
SatLdt8GfQ85yA7hnWWJ2MxF3NaeSDm75Lsm+tBbAiyc9P2jGRNtMSkCgYEAypHd
HCctNi/FwjulhttFx/rHYKhLidZDFYeiE/v45bN4yFm8x7R/b0iE7KaszX+Exdvt
SghaTdcG0Knyw1bpJVyusavPzpaJMjdJ6tcFhVAbAjm7enCIvGCSx+X3l5SiWg0A
R57hJglezIiVjv3aGwHwvlZvtszK6zV6oXFAu0ECgYAbjo46T4hyP5tJi93V5HDi
Ttiek7xRVxUl+iU7rWkGAXFpMLFteQEsRr7PJ/lemmEY5eTDAFMLy9FL2m9oQWCg
R8VdwSk8r9FGLS+9aKcV5PI/WEKlwgXinB3OhYimtiG2Cg5JCqIZFHxD6MjEGOiu
L8ktHMPvodBwNsSBULpG0QKBgBAplTfC1HOnWiMGOU3KPwYWt0O6CdTkmJOmL8Ni
blh9elyZ9FsGxsgtRBXRsqXuz7wtsQAgLHxbdLq/ZJQ7YfzOKU4ZxEnabvXnvWkU
YOdjHdSOoKvDQNWu6ucyLRAWFuISeXw9a/9p7ftpxm0TSgyvmfLF2MIAEwyzRqaM
77pBAoGAMmjmIJdjp+Ez8duyn3ieo36yrttF5NSsJLAbxFpdlc1gvtGCWW+9Cq0b
dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----

Copy private key to a file in tmp directory.

#chmod 600 priv17.key
# ssh -i priv17.key bandit17@localhost

LEVEL 17

There are two files in home directory password.old and password.new. The password.new contains the password for next level. Both files differ by one line.

bandit17@bandit:~$ diff passwords.new passwords.old
42c42
< kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
---
> 7cDk1R96wgw11eEuTk1zgbjAindhpUA5
bandit17@bandit:~$ ssh bandit18@localhost
bandit18@localhost's password: kfBf3eYk5BPBRzwjqutbbfE887SVc5Yd
Byebye !

 

LEVEL 18

Someone has modified .bashrc to log you out when logged in with ssh

# ssh bandit18@bandit.labs.overthewire.org "bash --norc"
ls
cat readme
IueksS7Ubh8G3DCwVzrTd8rAVOwq3M5x

LEVEL 19

To gain access to the next level, you should use the setuid binary in the homedirectory. Execute it without arguments to find out how to use it. The password for this level can be found in the usual place (/etc/bandit_pass), after you have used the setuid binary.

— will update from here soon!