Today I’m going to be writing about one the most, if not the most, common yet dangerous vulnerabilities that hackers can take advantage of, called cross-site scripting. Cross-site scripting is similar to SQL injections in that it takes advantage of the fact that a developer wasn’t one hundred percent careful when creating their web application. Basically, it is the injection of malicious code into a website through its user input fields. 

Here’s how it works. Let’s suppose you have a website with a commenting functionality. All a user has to do to leave a comment is to type it into the comment box and press “submit”. Your website was most likely created with HTML. HTML is a tag-based language, where text is written in between specialised tags that dictate how the text is interpreted by the site. For example, writing text between a <b> and a closing </b> tag would make the text in between appear bolded. There is also a specialised <script> tag that will execute any JavaScript command inside it, and that is invisible to users. If your website’s commenting functionality isn’t written to escape the tag so that the script can’t run, the website will essentially belong to the malicious hacker.

Since cross-site scripting attacks rely on the host website in order to harm its users, it can be said that there are two broad types of attacks: Persistent Scripts and Non-Persistent Scripts. Non-Persistent Scripts only run once and are usually done for test purposes to see whether or not a vulnerability exists. Persistent Scripts, however, are the ones that actually do the damage. If someone was to write a persistent script on your website’s comment section, it would be completely invisible, and it can do anything from stealing cookie information in order to gain access to a user’s account, to setting a worm in a user’s MySpace account, which would make any other MySpace user add the first as a friend, and then bring the worm over to their own account, resulting in a user gaining millions of friends overnight. The latter really happened, and the perpetrator got three years probation and a twenty thousand dollars fine. Just goes to show the importance of being careful as a security professional (or criminal).

  • Password encryption
    • Never store passwords in plain text
    • Ideal is one way encryption
    • Don’t use MD5 anymore, good choices are SHA-1, SHA-2 (SHA-256, SHA-512), Whirlpool, Tiger, AES, Blowfish
    • The best is Blowfish it’s secure, free, easy, and slow
  • Salting passwords
    • Salt is an additional data added to the password before encryption, the main purpose of salts is to defend against dictionary attacks
    • Unique to each user salts can be created
    • Salts can be created using pseudo random string using time functions, in this case salts need to be saved in the database, salts can be hashed as well
  • Password requirements
    • Require certain length, but not limit length
    • Require non-alphanumeric characters
    • Ask user to confirm password
    • Report password strength to user
    • Do not record password hint
    • Security questions may be vulnerable to attacks, internet research could reveal information to security questions, user’s friends or family members might know answers to security questions
  • Brute force attacks
    • Hacker tries all possible passwords over and over again until the correct solution is found
    • To strengthen the password allow all characters and long strings
    • Enforce clipping level and slow password hashing algorithms as well as timing and throttling
  • SSL
    • Provides communication security
    • Verifies authenticity of remote server
    • Encrypts all data exchanged with server
    • Prevents snooping, session hijacking
    • Requires all assets on a webpage such as JavaScript, CSS, images to be secure
    • With SSL you must encrypt all credit card transactions, username/passwords being sent to the server
  • Protecting Cookies
  • Regulating Access Privilege
    • Least privileges
    • Make privileges easy to revoke
    • Restrict access to access privilege administration tools
    • Divide restricted actions into “privilege areas”
    • Regulate access by user access level or category
  • Handling Forgotten Passwords
    • Ask about privileged information
    • Ask security challenge questions
    • Since the email of the person is his identity we can send email with with reset token
  • Multi factor authentication
    • Authentication requires two or more factors
    • Something only the user knows, something only the user has, something only the use is
  • Cross-Site Scripting (“XSS“)
    • Hackers can inject JavaScript into a web page
    • Used to steal cookies a session data
    • Often very successful just because browser trusts JavaScript
      • Protection:
        • Sanitize any dynamic context that gets output to browser (HTML, JavaScript, JSON, XML…)
        • Pay special attention to data that come directly from URLs or forms
        • Be careful about database data, cookies, session data
        • Use Whitelists to allow certain HTML tags and sanitize everything else
    • Cross-Site Request Forgery (CSRF)
      • Hackers tricks user into making a request to your server
      • Used for fraudulent clicks
      • Forging login request
        • Protection
          • Accept POST request only
          • Use a “form token” in user’s section
          • Add a hidden field to forms with form token as value
          • Compare session form token and submitted form token
          • Store the token generation time in user’s session
    • SQL Injection
      • Hacker is able to execute arbitrary SQL request in order to probe database schema, steal data(usernames, passwords, credit cards, encrypted data), assign elevated privileges, truncate or drop tables
        • Protection
          • Use limited privileges to application’s database user
          • Sanitize input
          • Escape for SQL using libraries
          • Use prepared statements
    • URL manipulation
      • Editing the URL string to probe the site
      • Can be used for revealing private information, performing restricted actions
        • Protection
      • Remember that URLs are exposed and easily editable
      • Implement proper access control
      • Keep error messages vague
      • Clarify your GET and POST requests, only POST requests should be used for making changes
    • Cookie Stealing
      • Cookie data is visible to users
      • Cookies can be stolen using XSS attack
      • Remember that cookies can be sniffed by observing network traffic by using packet analyzers (most popular Wireshark)
        • Protection
          • Put only non sensitive data in cookies
          • Use HttpOnly cookies
        • Use HTTPs cookies
        • Set cookie expiration date
        • Set cookie domain, sub domain and path
        • Encrypt cookie data
        • User server side sessions instead of client side cookies
    • Session hijacking
      • Stealing session ID is similar to stealing cookie but much more valuable
      • Can be used to steal personal info, passwords
      • Often done by network sniffing
      • Never use open wireless networks at coffee shops for transmitting sensitive data
      • Variation of session hijacking is session fixation
      • Session fixation is opposite to session hijacking, it trick a user into a hacker provided session identifier
        • Protection
          • Use SSL
          • Save user agent in session and confirm it (not ideal method)
          • Check IP address of a computer who is making a request (not ideal as well)
          • Use HttpOnly cookies
          • Regenerate session ID periodically, at key points, especially important to regenerate after log in
          • Expire and remove old session files regularly and keep track of last activity in session
        • Do not accept session identifier from from GET or POST variables, session identifier should come from only one place – cookies
    • Remote system execution attack

      • It’s the most dangerous attack when hacker remotely run operating system commands on a web server
        • Protection
          • Avoid system execution keywords (they are language specific)
          • Perform system execution with extra caution
          • Sanitize any dynamic data carefully
          • Understand system commands and their syntax
          • Add additional data validation
    • File upload abuse
      • Can be used to upload too much data (quantity, file size)
      • Can be used to upload warm or virus
        • Protection
          • Require user authentication, no anonymous uploads
          • Limit maximum upload size
          • Limit allowable file formats, file extensions
          • Use caution when opening uploaded file
          • Do not host uploaded files which have not been verified
    • Denial of Service (DoS) attack

      • Attempt to make a server unavailable to users
      • Usually performed by overloading a server with requests
      • Includes DNS and routing disruption
      • If performed by distributed network pf computers it called DDoS
        • Protection
          • Properly configure firewalls, IDS, switches, load balancers and routers
        • Collection of reverse proxies
        • Map you infrastructure
        • Keep infrastructure up to date
        • Make network traffic visible
        • Develop DRP plan
        • Consider changing IP address
        • “Black hole” or “null route” traffic
  • Regulate Request Method
    • Make sure that your application accepts only the request methods that you expect (for examples, for GET requests: URLs, links; for POST request: forms) and ignores all overs
  • Validating Input
    • Is the input acceptable?
    • Determine data expectations (preventing bugs, as well as hacks)
    • Consider application and database requirements
    • Regulate the data inputs to your application and only allow expected data
    • Set good default values, default should prevail
  • Common Validations
    • Presence of data
    • Length of data
    • Type of data
    • Format of the data
    • Uniqueness
    • Double check validation logic
    • Search on a web for your programming language for “logical pitfalls”
  • Sanitizing data
    • It’s the most important step that can be taken toward more secure web server
    • In order to neutralize the thread we should use type casting, not type juggling this way you maintain control over the process
    • Sanitize any SQL, HTML, JavaScript, XML in general any data that you receiving, all power characters should be sanitizing, power characters depend on programming language you are using
    • Add escape characters before powerful characters
    • Do not write custom sanitization methods, use well tested, language specific functions instead
    • Do not remove or correct invalid data, stick to encoding and escaping
    • Consider where the data goes
    • Consider where the data might go later
    • Sanitize early and continue sanitize it constantly
  • Labeling Data
    • Use names to identify condition of data (for example dirty, raw, unsafe…), when we sanitize data variable names can be changed to “clean”,”filtered”,”safe”
  • Keep Code Private
    • Be sure that libraries directories are not accessible by the web server
    • Web Server should be configured properly: set document root, allow/deny access for all directories/files and so on
  • Keep Credential That Your Code Uses Private
    • Plain text credentials are dangerous
    • Keep them separate form code
    • Keep credential file out of version control
    • Have as few copies of password as necessary
    • Don’t reuse passwords, passwords should be unique for each computer,database, environment
    • Hash password whenever possible, public key cryptography is an excellent choice
  • Keep Error Message Vague
    • Turn off detailed error reporting for production server
    • Return only generic error pages
    • Configure web server to use same error pages
  • Smart Logging
    • Errors
    • Sensitive actions
    • Possible attacks
    • Data worth logging:
      • Date and Time
      • Source (user, IP)
      • Action
      • Target
      • Cookie
      • Session
      • URL and all parameters
      • Backtrace
    • Review logs routinely
    • Don’t log sensitive data such as passwords , beware POST psarameters and database quires
    • Filter out passwords, keys, tokens from logging
    • Keep an old content, so it can be easily restored
  • Least Privilege  “Every program and every privileged user of the system should operate using the least amount of privilege necessary to complete the job.” —  Jerome Saltzer 
  • Least Privilege Benefits:
    • Code stability
    • Controlled data access
    • System security
    • Vulnerabilities are limited and localized
    • Easier to test actions and interactions
  • Simple Is More Secure
    • Use clearly named functions and variables
    • Write code comments
    • Break up long sections of code into small, more manageable functions
    • Don’t repeat yourself
    • Legacy code is a security concern
    • Try to use built-in functions whenever possible
    • Disable all unused features when possible
  • Never Trust Your Users
    • People are prone to mistakes
    • Don’t trust even admins
    • Identity can be stolen
    • Use cation with contractors
    • Establish the process that allows to revoke user access instantaneously
    • Remember that hacks happen offline as well(Phone, printouts…)
  • Defense In Depth
    • You should have a number of layers of defense
    • Over time attacks lose momentum
    • Redundant Security
      • People (security policy, best practices implementation …)
      • Technology (IDS, SIEM, system administration, encryption, access controls…)
      • Operations(periodic security reviews, data handling procedures, threads handling…)
  •  Security Through Obscurity
    • More info benefits hackers
    • Limit exposed information
    • Limit feedback
    • Obscurity doesn’t mean misdirection
  • Whitelisting Is Much More Secure Than Blacklisting
    • Whitelisting means restricting by default which is much more secure approach
  • Map Exposure Points
    • Incoming Exposure Points
      • URLs
      • Forms
      • Cookies
      • Sessions
      • Database reads
      • Public APIs
    • Outgoing Exposure Points
      • HTML
      • JavaScrip/JSON/XML/RSS
      • Cookies
      • Sessions
      • Database writes
      • Third-party APIs
  • Map Data Passageways
    • What paths does data takes?
    • Know your site topography and your environment architectural landscape
    • Ideally you should have a graphical representation of all of your access points
  • It’s important to remember what total security is unachievable.

“The only secure computer is one that’s unplugged, locked in a safe, and buried 20 feet under the ground in a secret location… and I’m not even too sure about that one.”
—Dennis Hughes, FBI

  • Zero-day attacks are becoming very common now-days and occur when a system or application weakness is discovered and attacked within one day. Zero-day exploits name came from the fact that developer or a company has “zero days” of awareness of a problem. We can’t achieve  100% security, our security level should match our needs and goals.
  • Security level has to be re-evaluated periodically. Security has to be a concern of everyone, all the time, it can’t be just one person.  Executive support will be crucial to success, it’s very important to establish regular security reviews. We need  to review all technologies in use (hardware, software), review code in use and still in development, review procedures, access privileges.
  • Better development practices has to be implemented. Developers might be asked to write software tests for common security vulnerabilities, for example if a Cross-site request forgery (CSRF) is a concern for the company developers might be asked to write  test that attempt to perform CSRF on a company website.
  • Write a Security Policy. Security policy has to communicate how information assets are protected, establish rules and guidelines to work with that assets. All stakeholders should be involved, everyone can be a stakeholder: developers, business users, executives and so on. Policy should be reviewed periodically.
  • How to write Security Policy:
  1.                    Define the scope.
  2.                    Identify and classify data to be protected or controlled (databases, source code even images).
  3.                    Map the interaction of people and systems.
  4.                    Define the handling procedures for each type of data.
  5.                    Designate user or department responsibilities.