Sumário / Summary
Este artigo apresenta algumas linhas relativas a ataques do tipo Cross-site Scripting (XSS). Este é um ataque bastante severo e bem presente no seio de desenvolvimento e execução de aplicações baseadas na web (web-based). Inclusive, ao longo dos últimos anos tem ocupado um dos lugares do pódio do TOP de vulnerabilidades web segundo a OWASP. Mais para o final do artigo é proposto um modelo de uma ferramenta de deteção de sistemas web vulneráveis a ataques desta linha. É entregue informação relativa à engenharia e mencionados alguns blocos de código considerados relevantes pelo autor.
Também o código fonte da ferramenta é partilhado no GitHub.
https://github.com/sirpedrotavares/mxsscanner
This article presents some lines related to landscape of Cross-site Scripting (XSS) attacks on web-based applications. In recent years, it shows to be a serious problem. According to OWASP, it stays on top places of web vulnerabilities. Toward the end of the article, we propose a XSS detection tool for web-based systems. It is delivered information about the engineering and mentioned some code blocks considered relevant by the author.
Also, the tool’s source code is shared on GitHub.
Contextualização / Background
Muitas vezes referido como XSS no jargão da Segurança Informática, Cross-site Scripting tem assumido uma importância bastante crítica no contexto dos Cyber-Attacks e da Segurança da Informação. Infelizmente, esta é uma matéria que tem sido notícia ao longo dos anos, apesar de todo o esforço a fim de atenuar este tipo de ataques. Desta feita, pode-se considerar uma das técnicas de hacking mais frequente na atualidade. No gráfico circular apresentado abaixo, entregue pela Web Hacking Incident Database em 2014 (WHID), é visível que entre muitos tipos de ataques estão presentes o SQL Injection e o XSS. Notar que, muitos outros ataques, como p.ex., Information Disclosures, Content Spoofing e Stolen Credentials podem ser alimentados por efeitos colaterais provenientes do XSS.
Cross-site Scripting, many times referred as XSS in the Computer Security jargon, assumes a widespread and critical importance within the scope of the Cyber-Attacks and Information Security. Unfortunately, this is a subject that have been making headlines in recent years, despite of all the effort to attenuate this wild attack. Therefore, it represents generally one of the most common application layer hacking techniques. In the pie-chart below, delivered by the Web Hacking Incident Database dated from 2014 (WHID) clearly shows that whilst many different attack methods exist, SQL injection and XSS are the most popular. To add to this, many other attack methods, such as Information Disclosures, Content Spoofing and Stolen Credentials could all be side-effects of an XSS attack
De forma geral, XSS diz respeito a uma técnica que acopla vulnerabilidades junto do código da aplicação web, que por sua vez permite ao sujeito mal intencionado enviar código malicioso a partir de um utilizador final, normalmente a aplicação web, e obter informação confidencial da vítima infetada.
Neste tipo de ataques, o sujeito mal intencionado infeta a webpage alvo com conteúdo malicioso. Quando o utilizador visita essa página é infetado, isto é, o script é descarregado e executado no seu navegador de internet (web-browser). Dentro deste tema existem algumas variantes, como o XSS Persistente, Refletido e DOM-based (ver mais informação num artigo deste blog aqui). O diagrama abaixo apresenta uma visão de alto nível deste tipo de investidas maliciosas.
In general, XSS refers to a “de facto” hacking technique that leverages vulnerabilities in the code of a web application to allow an attacker to send malicious content from an end-user and collect some type of data from the victim.
In a typical XSS attack, an attacker infects a webpage with malicious content. When this page is visited, the user is infected, i.e., the script is downloaded to browser and executed. Regarding this matter, exists several modes, such as Persistence, Reflected and DOM-based XSS attacks (read more info here, only available in Portuguese version). A higher diagram that reflects the XSS attack life-cycle is depicted below.
Como mencionado no sumário, o objetivo deste artigo é fornecer algumas linhas relativas à (in)segurança dos sistemas e entregar uma solução para a prevenção de ataques desta natureza. Assim, o público-alvo, e a quem se destina este documento são maioritariamente desenvolvedores web, web-masters, programadores e empresas numa escala mais alargada. Sendo este um tema viral no mundo da cyber segurança, durante as restantes secções será apresentado um modelo proposto de um scanner/avaliador de XSS em páginas web. Todos os detalhes e trechos de código importantes serão devidamente realçados e comentados no decorrer do documento.
This article aims to give a guideline related to (in)security of applications against XSS attacks in the wild. Notice that, this point was briefly highlighted above, in summary section. The target audience comprise expressly the developers, web-masters, programmers and software development companies in a large scale. This matter achieves a hype-status in the industry and specifically on cyber-security context. Thus, detailed description about a proposal XSS massive scanner is delivered along this article. Important implementation details and code snippets are discussed towards the end of the document.
Ferramenta Proposta / Proposal Tool
A ferramenta aqui proposta tem o objetivo de motivar o estudo das técnicas para prevenção de ataques do tipo XSS. Nesse sentido, e com alguma naturalidade, este é um protótipo bastante primata, mas extremamente efetivo no que toca a identificar possíveis entradas maliciosas em parâmetros/inputs não sanitizados durante a fase de desenvolvimento de software. O esboço abaixo apresenta a arquitetura da ferramenta, assim como as tecnologias utilizadas na preparação do ambiente de teste.
The study and prevention of this type of attacks conducts and motivates the implementation of an effective XSS tool. In fact, the proposal tool seems to be extremely effective when it comes to identifying possible malign entries in parameters not sanitized during the software development phase. The architecture and used technologies are illustrated by the following diagram.
As ferramentas utilizadas para a conceção do ambiente de teste podem ser divídas em duas partes bastante distintas: (i): a Virtual Machine (VM), que possui as páginas web potencialmente vulneráveis, e (ii), a ferramenta proposta que procura analisar as páginas web contidas na VM e verificar se estas estão, ou não, expostas e, consequentemente, vulneráveis.
Docker – Ferramenta de virtualização utilizada para emular um kernel do Sistema Operativo (SO) CentOS a fim de simular um servidor remoto.
Apache & PHP – O Apache é o servidor web que suporta os websites. O PHP é o interpretador, mais especificamente uma linguagem de scripting, que interpreta os pedidos no lado do servidor.
Ruby – Foi a tecnologia selecionada para conceber a ferramenta massiva para explorar e catalogar sistemas potencialmente vulneráveis.
Notar que, o sistema operativo raiz é da família Linux, mais especificamente uma distribuição Arch Linux.
To build secure test environments, a widely group of technologies are indispensable. Regarding this tools, them can be divided into two distinct parts: (i) Virtual Machine (VM), which supports the websites, and (ii), the proposed XSS tool.
Docker – Virtualization tool used to emulate an Operating System kernel (OS) CentOS in order to simulate a remote server.
Apache & PHP – Apache represents the web server that supports the websites. PHP is the interpreter, namely a scripting language that interprets requests on server side.
Ruby – The selected technology to build the XSS tool and to explore and record potentially vulnerable systems.
Note that, the operating system is the Linux family, more specifically an Arch Linux distribution.
Implementação / Implementation
Antes de ser iniciada qualquer implementação é importante verificar a disponibilidade de uma das páginas de teste. Para isso, deve ser emitido o seguinte comando no terminal: curl 127.0.0.1.
Before any implementation, verify the test page availability represents a good premise. In this sense, must be tested the following command in the terminal: curl 127.0.0.1.
O resultado da página é bem visível na imagem acima, no entanto, esta página possui um parâmetro de entrada: 127.0.0.1/index.php?s=pipocaz.
The page results is highlighted on image above. However, this page possesses an input parameter as: 127.0.0.1/index.php?s=pipocaz.
Neste ponto, é importante observar e estudar o código PHP que possibilita o tratamento do paramentro $_GET -> s.
It is important pay attention and study the PHP code that processes the $_GET -> s parameter.
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Test</title> </head> <body> Hello: <?php $search=$_GET['s']; echo $search; ?> <br> Bye bye! </body> </html>
Do lado do servidor, o PHP recebe o parâmetro ‘s’ sem qualquer tipo de tratamento, e apresenta o seu valor bruto na página. Neste caso concreto serve para apresentar o nome de um utilizador. Notar que este é um ponto de entrada para códigos maliciosos XSS. É comum, programadores e desenvolvedores em geral, não aplicarem práticas de sanitização de inputs externos. Os resultados estão à vista.
Em seguida, serão detalhados todos os passos de implementação de uma ferramenta de deteção de sistemas potencialmente vulneráveis a este tipo de ataques. Notar que a página acima servirá como cobaia nesse exercício.
PHP receives the ‘s’ parameter in raw mode on server side, and presents the result to user. In this case, it exhibits the name of user. Note that, this represents an entry point for XSS malicious codes. Many programmers and developers generally do not apply sanity practices over external inputs.
The meaningful implementation steps are detailed below. Note that, the aforementioned page is a valuable piece in this exercise.
Para iniciar a implementação foram instaladas a seguintes gems:
To start with the implementation were installed the following gems:
gem install curb gem install colorize gem install artii gem install logger
Uma forma instantânea de preceder à sua instalação é o seguinte comando:
For an instantaneous installation, you can enter the following command on terminal:
bundle install
Nota: Se a gem bundle não estiver instalada no sistema use o seguinte comando no terminal:
Note: If you have not installed the bundle gem, use the following command on terminal:
gem install bundle
O curb serve como cliente http, muito semelhante ao cURL. O colorize possibilita definir marcadores de cor. Por fim, a gem artii viabiliza a criação do banner em ascii com o nome da ferramenta, e o logger, diz respeito a uma gem de logging.
The curb serves as HTTP client, a very similar tool to cURL. The colorize allows defines color markers. Finally, gem artii enables the banner creation in ascii mode and the logger relates to a logging gem.
A estrutura idealizada é apresentada em seguida.
The idealized structure is shown below.
. ├── evil.conf ├── Gemfile ├── Gemfile.lock ├── module.rb ├── mxsscanner.rb ├── targets.conf └── test
evil.conf – Possui todas as entradas maliciosas de teste consideradas para este artigo.
targets.conf – Possui nomes de ficheiros e potenciais parametrizações.
log.log – Ficheiro de log.
module.rb – Biblioteca que suporta toda a ferramenta.
mxsscanner.rb – Ficheiro de entrada, aquele que deve ser invocado no terminal.
test – Ficheiro de teste, que possui um conjunto de URLs a serem testados (opcional).
Gemfile – Ficheiro onde são especificadas as gems requeridas.
De forma a entender o fluxo interno é apresentado o seguinte diagrama de atividades.
evil.conf – Represents all test malicious entries considered for this article.
targets.conf – Includes filenames and potential parameterizations.
log.log – The log file.
module.rb – Library that supports the tool.
mxsscanner.rb – Input File, one that should be invoked in the terminal.
test – Test file, which has a set of URLs to be tested (optional).
Gemfile – File where required gems are specified.
In order to understand the internal flow is presented the following activities diagram.
Inicialmente, são carregados os ficheiros targets e evil, e executada a rotina de verificação de URL (se este é bem definido). Esse processo pode ser identificado facilmente no ficheiro mxsscaner.rb a seguir.
Initially, evil and target files are loaded, and triggered the URL check routine. This process can be easily identified on the following mxsscaner.rb file.
if __FILE__ == $0 puts XSS.initial_banner XSS.run_script XSS.getTargets, XSS.getEvil if XSS.readCMD end
Uma das mais importantes rotinas desta ferramenta é a função run_script.
def run_script targets, evil self.log('debug', "Execution starts") if @list self.log('debug', "Load and executes the list of URLs") #list of URLs @vulnerable=false group_or_urls=getLoadfile group_or_urls.each do |url| @vulnerable=false targets.each do |target| break if @vulnerable evil.each do |e| if url =~ /\A#{URI::regexp(['http', 'https'])}\z/ break if @vulnerable @url="#{url}#{target}#{e}" self.httpTest e else puts "$: " + "Bad URL in your file!".red exit end end end end else #singular URL self.log('debug', "Executs a single URL") targets.each do |target| evil.each do |e| @url="#{@url_base}#{target}#{e}" self.httpTest e end end end end
Esta rotina é dividida em dois ramos, (i): varrimento a um único URL, e (ii), varrimento a multiplos URLs. Por sua vez, é chamada em cada ramificação a função testhttp.
This routine is divided into two branches (i): scanning a unique URL, and (ii), scanning multiple URLs. Notice that, the testhttp function is called mutually in these branches.
def httpTest e c=Curl::Easy.perform(@url) do |curl| curl.headers["User-Agent"] = "xsscanner" #curl.verbose = true end c.perform body = c.body_str headers = c.header_str.split(/[\r\n]+/).map(&:strip) if headers[0].include?"HTTP/1.1 200" if body.include?(e) puts "$: " + "Vulnerable to XSS".red puts "$: " + "payload: [ #{@url} ]".yellow puts "" puts headers puts "" @vulnerable=true self.log('debug', "Page: #{@url} is vulnerable to XSS") self.log('debug', "#{headers}") self.log('debug', "") exit if !@list end end end
Esta função é responsável por enviar pedidos ao servidor, partindo do URL introduzido pelo utilizador, e acoplando também as possíveis combinações dos parâmetros e códigos de teste (payloads) precomputados. É pretendido depois, verificar se aquando da execução do request da página o código foi, ou não, bem-sucedido. A seguinte linha de código:
Requests are sent to server by the function presented in the previous figure. A permutation of a specific group of parameters and precomputed test codes (payloads) are performed. Thus, it is intended to check when the execution of the code was or not successful. The following line of code:
if headers[0].include?"HTTP/1.1 200"
verifica a disponibilidade da página para o payload executado, e.g., “localhost/main.php?id=<script>alert(1)</script>“, e a linha a seguir, verifica a sua execução:
it checks the availability of the page for a given payload, e.g,”localhost/main.php?id=<script>alert(1)</script>“, and the following line, verifies the execution result:
if body.include?(e)
Por fim, é apresentado no ecrã se a página está vulnerável a este tipo de ataques, e junto, alguma informação relativa à versão do SO e do servidor.
Finally, on screen appears the result of the performed experiment, namely, if the page is vulnerable to XSS. Some information about the server and OS version are presented herein.
Demonstração / Demonstration
A seguir, são apresentados alguns screens e linhas adicionais que demonstram o funcionamento da ferramenta proposta neste artigo.
Antes da inicialização da ferramenta deve ser criado o ficheiro de log.
touch log.log sudo chmod a+x log.log
Para inicar a aplicação emitir o seguinte comando:
To start the application enters the following command:
ruby mxsscanner.rb
A fim de consultar as opções deve ser digitado o comando “–h” ou “-h“.
Para identificar possíveis falhas de sanitização numa página web, o formato do comando a utilizar deve seguir o seguinte padrão:
To see the options should be typed the command “–h” or “-h”.
In order to identify possible flaws in a webpage, the command format used should follows the following format:
ruby mxsscanner.rb -u http://localhost
Analisando o payload no navegador web obtém-se o seguinte resultado:
After the payload test on web-browser the following result is expected:
No ficheiro de logs é também guardado os resultados da execuções:
In the log file is also saved the execution results:
D, [2015-06-16T21:55:00.854472 #4529] DEBUG -- : Execution starts D, [2015-06-16T21:55:00.854591 #4529] DEBUG -- : Executs a single URL D, [2015-06-16T21:55:05.808196 #4529] DEBUG -- : Page: http://localhost/index.php?s=<script>alert('insecure');</script> is vulnerable to XSS D, [2015-06-16T21:55:05.808388 #4529] DEBUG -- : ["HTTP/1.1 200 OK", "Date: Tue, 16 Jun 2015 20:55:05 GMT", "Server: Apache/2.4.12 (Unix) PHP/5.6.10", "X-Powered-By: PHP/5.6.10", "Content-Length: 183", "Content-Type: text/html; charset=UTF-8"] D, [2015-06-16T21:55:05.808491 #4529] DEBUG -- :
Caso seja pretendido testar um conjunto de URLs, pode ser indicada a opção “-l” ou “–load” aquando da execução da ferramenta.
If desired test a set and URLs, it may enter the option “-l” or “–load” .
ruby mxsscanner.rb -l test
Reflexão Final / Final Reflection
São numerosos os casos de XSS no dia-a-dia, falhas, esquecimentos, ou mesmo ignorância dos desenvolvedores que vão alimentado ataques desta natureza. É portanto, indispensável, o uso de soluções efetivas, que determinem o quão vulnerável um sistema se apresente. Assim, este artigo apresentou, de uma forma geral, uma intrudução ao XSS, e algumas linhas relativas à implementação de uma ferramenta de deteção de vulnerabilidades desta natureza.
O código da ferramenta pode ser descarregado da página do GitHub.
Day-to-Day are numerous the occurrences of XSS attacks, failures, omissions, or even ignorance of developers that nourishes attacks this nature. The use of effective solutions, seems to be crucial and may determines how vulnerable is a system. Thus, this article delivered a background on attacks-like XSS, and some lines how to a detector XSS tool should be implemented.
The source code can be downloaded from GitHub here.
One Reply to “Building a Massive XSS Scanner Tool”