--- title: Horusec CLI tags: Honda --- ## Sumário [TOC] # Instalação Horusec é uma ferramenta de análise de segurança de código fonte que pode ser usada para detectar vulnerabilidades e ameaças em projetos de software. Para implementar o Horusec em um projeto, siga os seguintes passos: 1. Instale o Horusec na máquina ou servidor usando um dos métodos abaixo: * Faça o download do binário para o seu sistema operacional a partir do site oficial (https://docs.horusec.io/docs/cli/installation). * Use o gerenciador de pacotes da sua distribuição Linux para instalar o Horusec. 2. Inicialize o Horusec com o comando `horusec start` e siga as instruções para configurar as opções necessárias, como a API key para integração com plataformas de gerenciamento de código. 3. Navegue até o diretório do seu projeto e execute o comando `horusec analyze` para iniciar a análise de segurança. 5. Aguarde o Horusec concluir a análise e fornecer um relatório com as vulnerabilidades e ameaças encontradas no seu projeto. 5. Analise os resultados e tome as medidas necessárias para corrigir as vulnerabilidades e ameaças identificadas. 6. Repita o processo de análise de segurança com o Horusec regularmente para garantir a segurança contínua do seu projeto. Além disso, o Horusec também pode ser integrado em pipelines de CI/CD para automatizar a análise de segurança em projetos em um ambiente de desenvolvimento ágil. </br> # Integração CI/CD ## Freestyle Para integrar o **Horusec** com o **Jenkins** (no modo *freestyle*) siga os seguintes passos: 1. Instale o plugin do Horusec no Jenkins através do **Gerenciador de Plugins do Jenkins**. Para isso, acesse a página de configuração do Jenkins, selecione "Gerenciar Jenkins" e, em seguida, "Gerenciar Plugins". Procure pelo plugin do Horusec na aba "Disponíveis" e instale-o. 2. Depois de instalar o plugin, acesse a página de configuração do projeto que deseja analisar com o Horusec. Em seguida, vá até a seção "Build" e adicione uma etapa de build. 3. Na etapa de build, adicione um passo "Execute Shell" ou "Execute comandos no shell" e adicione o comando "horusec start" para inicializar o Horusec. 4. Adicione uma nova etapa de build para executar a análise de segurança com o Horusec. Para isso, adicione um passo `Execute Shell` ou `Execute comandos no shell` e adicione o comando `horusec analyze`. É possível adicionar opções de configuração para personalizar a análise, como definir um arquivo de configuração do Horusec ou um arquivo de saída para o relatório. 5. Execute o build do projeto no Jenkins para executar a análise de segurança com o Horusec. 6. O relatório de análise de segurança será gerado no formato JSON pelo Horusec e poderá ser acessado através do plugin do Horusec no Jenkins. Para visualizar o relatório, acesse a página de relatórios do Horusec no Jenkins. Com essa integração, a análise de segurança com o Horusec será executada automaticamente no Jenkins sempre que o build do projeto for executado. </br> ## Pipe as Code Para integrar o Horusec com o *pipeline as code*/ *declarativo* do Jenkins, siga os seguintes passos: 1. Instale o plugin do Horusec no Jenkins através do Gerenciador de Plugins do Jenkins. Para isso, acesse a página de configuração do Jenkins, selecione "Gerenciar Jenkins" e, em seguida, "Gerenciar Plugins". Procure pelo plugin do Horusec na aba "Disponíveis" e instale-o. 2. Crie um arquivo Jenkinsfile na raiz do seu repositório e adicione as etapas do pipeline. Por exemplo: ```gherkin= pipeline { agent any stages { stage('Security Horusec Start') { steps { sh 'curl -fsSL https://raw.githubusercontent.com/ZupIT/horusec/main/deployments/scripts/install.sh | bash -s latest' sh 'horusec start -p="./" -e="true"' } } stage('Analyze Security') { steps { sh 'horusec analyze' } } } post { always { horusecReport( reportPath: '.horusec/report.json', reportFormat: 'HTML' ) } } } ``` 3. O trecho de código acima cria o pipeline com duas etapas: "Start Horusec" e "Analyze Security". A primeira etapa inicia o Horusec e a segunda executa a análise de segurança. A seção "post" cria um passo que sempre será executado após a conclusão do pipeline, gerando o relatório de análise de segurança em formato HTML. 4. Configure o Jenkins para usar o arquivo "Jenkinsfile" criado. Para fazer isso, crie um novo job e selecione a opção "Pipeline" na seção "Tipo de Projeto". 5. Insira o código indicado do passo 3 no campo "Definição do Pipeline". 6. Execute o job no Jenkins e verifique se a análise de segurança com o Horusec foi executada com sucesso e se o relatório HTML foi gerado. Com essa integração, a análise de segurança com o Horusec será executada automaticamente no pipeline declarativo do Jenkins sempre que o job for executado. O relatório HTML gerado pelo Horusec pode ser acessado através do plugin do Horusec no Jenkins. </br> # Requisitos para instalação do Plugin Seguem os **requisitos necessários** para implantar e usar o plugin Horusec no Jenkins: 1. O Jenkins instalado e configurado para uso. 2. Acesso administrativo ao Jenkins para instalar o plugin do Horusec. 3. O plugin do Horusec instalado no Jenkins. 4. O Horusec instalado na máquina que executará os testes de segurança. 5. Um repositório de código contendo o aplicativo a ser testado. 6. Um arquivo de configuração do Horusec contendo as configurações de segurança que serão usadas nos testes. 7. Um arquivo de relatório do Horusec para armazenar os resultados dos testes. </br> # Caso de Uso Abaixo segue um cenário de caso de uso utilizando-se uma aplicação vulnerável escrita em Java. Para realização da anáise SAST (Static application security testing) você deve: - Clonar a aplicaçao vulnerável: https://github.com/appsecco/dvja - Instalar o CLI Horusec - Instalar o Docker ```gherkin= horusec --help ``` ```bash Horusec is an open source tool that orchestrates other security tools and identifies security flaws and vulnerabilities. See more in https://docs.horusec.io/docs/overview Usage: horusec [flags] horusec [command] Examples: # Horusec will ask in which directory the analysis should be performed. Default is the current path. horusec start # Use the current directory to run the analysis. horusec start -p . # Use a different path than the current one. # Note that the configuration file will still be searched in the current path if "--config-file-path" flag is not passed. horusec start -p="/home/user/projects/my-project" Available Commands: completion Generate the autocompletion script for the specified shell generate Generate horusec configuration help Help about any command start Start analysis version Shows the current version of installed Horusec Flags: --config-file-path string Path of the configuration file (default "C:\\Users\\Roberto Lopes\\OneDrive - ibliss.com.br\\Desktop\\ibliss\\honda\\horusec-config.json") -h, --help help for horusec -l, --log-file-path string Path of log file (default "C:\\Users\\ROBERT~1\\AppData\\Local\\Temp\\horusec-2023-03-17-10-05-39.log") --log-level string Set log level ("panic"|"fatal"|"error"|"warn"|"info"|"debug"|"trace") (default "info") Use "horusec [command] --help" for more information about a command. ``` </br> ```gherkin= horusec start --help ``` ```shell Start the Horusec analysis in the current path Usage: horusec start [flags] Examples: horusec start Flags: -t, --analysis-timeout int The timeout threshold for the Horusec CLI wait for the analysis to complete. The minimum time is 10 (default 600) -a, --authorization string Authorization token to use on Horusec server. Read more: https://docs.horusec.io/docs/tutorials/how-to-create-an-authorization-token (default "00000000-0000-0000-0000-000000000000") -C, --certificate-path string Path to certificate of authority. Example -C="example/ca.crt" -P, --container-bind-project-path string Project path in host to be used on Docker when running Horusec inside a container -c, --custom-rules-path string Path with custom rules that should be used by Horusec engine -D, --disable-docker Run Horusec without docker. If enabled it will only run the following tools: horusec-csharp, horusec-kotlin, horusec-java, horusec-kubernetes, horusec-leaks, horusec-javascript, horusec-dart, horusec-nginx -G, --enable-commit-author Enable to search commit author of vulnerabilities --enable-git-history Run Gitleaks and search for vulnerabilities in all git history of the project https://github.com/zricethezav/gitleaks -w, --enable-owasp-dependency-check Run Owasp Dependency Check tool https://github.com/jeremylong/DependencyCheck -j, --enable-shellcheck Run ShellCheck tool https://github.com/koalaman/shellcheck -F, --false-positive strings Ignore a vulnerability by hash and set it to be false positive. Example -F="hash1, hash2" --headers stringToString Custom headers to send on request to Horusec API. Example --headers='{"X-Auth-Service": "value"}' (default []) -h, --help help for start -u, --horusec-url string The Horusec server address to send analysis results (default "http://0.0.0.0:8000") -i, --ignore strings Paths to ignore in the analysis. Example: -i="/path/to/ignore, **/*_test.go, **/assets/**" (default [*tmp*,**/.vscode/**]) -s, --ignore-severity strings The level of vulnerabilities to ignore in the output ("LOW"|"MEDIUM"|"HIGH"). Example: -s="LOW, HIGH" (default [INFO]) -I, --information-severity Enable information severity vulnerabilities. Information vulnerabilities can contain a lot of false positives -S, --insecure-skip-verify Disable the certification validation. PLEASE, try not to use it -O, --json-output-file string Output file to write analysis result. This flag should be used with --output-format -o, --output-format string Output format of analysis ("text"|"json"|"sarif"|"sonarqube"). For json, sarif, and sonarqube --json-output-file is required -p, --project-path string Path to run an analysis. If this value is not passed, Horusec will ask if you want to run the analysis in the current directory (default "C:\\Users\\Roberto Lopes\\OneDrive - ibliss.com.br\\Desktop\\ibliss\\honda") -n, --repository-name string Send repository name to Horusec server, by default sends the actual directory name (default "honda") -r, --request-timeout int The timeout threshold for the request to the Horusec server. The minimum time is 10 (default 300) -e, --return-error Return exit code 1 if found vulnerabilities. Default value is false (exit code 0) -R, --risk-accept strings Ignore a vulnerability by hash and set it to be risk accept. Example -R="hash1, hash2" --show-vulnerabilities-types strings Show vulnerabilities by types ("Vulnerability"|"Risk Accepted"|"False Positive"|"Corrected"). Example --show-vulnerabilities-types="Vulnerability, Risk Accepted" (default [Vulnerability]) Global Flags: --config-file-path string Path of the configuration file (default "C:\\Users\\Roberto Lopes\\OneDrive - ibliss.com.br\\Desktop\\ibliss\\honda\\horusec-config.json") -l, --log-file-path string Path of log file (default "C:\\Users\\ROBERT~1\\AppData\\Local\\Temp\\horusec-2023-03-17-10-10-21.log") --log-level string Set log level ("panic"|"fatal"|"error"|"warn"|"info"|"debug"|"trace") (default "info") ``` </br> > com o parâmetro **--json-output-file** é possível integrar o arquivo de saída com o **Sonarqube** </br> Navegue dentro da raiz do diretório contendo a aplicação vulnerável: ```bash= cd .\dvja\ ``` Execute o comando para o escaneamento de todos os arquivos contidos no diretório: ```bash= horusec start . --information-severity=true --json-output-file results.txt ``` Trechos da saída gerada: > tempo estimado para análise ```shell ================================================================================== HORUSEC ENDED THE ANALYSIS WITH STATUS OF "success" AND WITH THE FOLLOWING RESULTS: ================================================================================== Analysis StartedAt: 2023-03-17 10:24:47 Analysis FinishedAt: 2023-03-17 10:25:19 ================================================================================== ``` </br> > Severidade e detalhes do apontamento com a devida referência à categoria da vulnerabilidade dada pelo MITRE CWE-312. ```shell Language: Leaks Severity: CRITICAL Line: 41 Column: 1322 SecurityTool: HorusecEngine Confidence: MEDIUM File: C:\Users\Roberto Lopes\OneDrive - ibliss.com.br\Desktop\ibliss\honda\dvja\src\main\webapp\assets\fa\fonts\FontAwesome.otf Code: twitterfacebookgithubunlockcredit_cardrsshddbullhornbellcertificatehand_righthand_lefthand_uphand_do RuleID: HS-LEAKS-7 Type: Vulnerability ReferenceHash: e4a2d486f4b29457539dff9aa21b64c473400973500240fa36eacb94bb855be3 Details: (1/1) * Possible vulnerability detected: Twitter Client ID When use Twitter Client ID is recommended use vault or environment variable encrypted for the best security. For more information checkout the CWE-312 (https://cwe.mitre.org/data/definitions/312.html) advisory. ``` </br> > Detalhes dos apontamentos relacionados a SCA (Software Composition Analysis) com as devidas referências as CVEs (Common Vulnerabilities and Exposures) indicadas para as versões vulneráveis das bibliotecas **dom4j** e **log4j**: ```shell Language: Generic Severity: CRITICAL Line: Column: 0 SecurityTool: Trivy Confidence: MEDIUM File: C:\Users\Roberto Lopes\OneDrive - ibliss.com.br\Desktop\ibliss\honda\dvja\pom.xml Code: RuleID: CVE-2020-10683 Type: Vulnerability ReferenceHash: 89fa8571dca89cb66667a0ab0272f7d3acbfb343a6547cd8c713d558f68c2bd3 Details: (1/11) * Possible vulnerability detected: dom4j before 2.0.3 and 2.1.x before 2.1.3 allows external DTDs and External Entities by default, which might enable XXE attacks. However, there is popular external documentation from OWASP showing how to enable the safe, non-default behavior in any application that uses dom4j. PrimaryURL: https://avd.aquasec.com/nvd/cve-2020-10683. Cwe Links: (https://cwe.mitre.org/data/definitions/611.html) (2/11) * Possible vulnerability detected: By design, the JDBCAppender in Log4j 1.2.x accepts an SQL statement as a configuration parameter where the values to be inserted are converters from PatternLayout. The message converter, %m, is likely to always be included. This allows attackers to manipulate the SQL by entering crafted strings into input fields or headers of an application that are logged allowing unintended SQL queries to be executed. Note this issue only affects Log4j 1.x when specifically configured to use the JDBCAppender, which is not the default. Beginning in version 2.0-beta8, the JDBCAppender was re-introduced with proper support for parameterized SQL queries and further customization over the columns written to in logs. Apache Log4j 1.2 reached end of life in August 2015. Users should upgrade to Log4j 2 as it addresses numerous other issues from the previous versions. PrimaryURL: https://avd.aquasec.com/nvd/cve-2022-23305. Cwe Links: (https://cwe.mitre.org/data/definitions/89.html) ``` </br> >Identificação de código vulnerável **Javascript** de severidade **alta** com a referência de localização (linha e coluna) do arquivo (**File**), a engine Horusec utilizada para detecção (**HorusecEngine**), a confiabilidade do tipo **média**, tipo da detecção (**Vulnerability** ou **Leaks**) e os detalhes inerentes. O **ReferenceHash** deve ser utilizado para gerenciar dentro da Manager (gestora de vulnerabilidades). ```shell Language: JavaScript Severity: HIGH Line: 3 Column: 10700 SecurityTool: HorusecEngine Confidence: MEDIUM File: C:\Users\Roberto Lopes\OneDrive - ibliss.com.br\Desktop\ibliss\honda\dvja\src\main\webapp\assets\showdown.min.js Code: Math.random())](a);else{var c=Math.random();a=c>.9?b[2](a):c>.45?b[1](a):b[0](a)}return a})},"undefi RuleID: HS-JAVASCRIPT-6 Type: Vulnerability ReferenceHash: 512471397d5dec54f65830c9a9cdb89df61145f7b40c17bc371399001df07146 Details: (1/1) * Possible vulnerability detected: No use weak random number generator When software generates predictable values in a context requiring unpredictability, it may be possible for an attacker to guess the next value that will be generated, and use this guess to impersonate another user or access sensitive information. As the Math.random() function relies on a weak pseudorandom number generator, this function should not be used for security-critical applications or for protecting sensitive data. In such context, a cryptographically strong pseudorandom number generator (CSPRNG) should be used instead. For more information checkout the CWE-338 (https://cwe.mitre.org/data/definitions/338.html) advisory. ``` </br> > Sumário com total de vulnerabilidades encontradas dividas por categoria de criticidade. ```shell ================================================================================== In this analysis, a total of 81 possible vulnerabilities were found and we classified them into: Total of Vulnerability CRITICAL is: 23 Total of Vulnerability HIGH is: 30 Total of Vulnerability MEDIUM is: 21 Total of Vulnerability LOW is: 3 Total of Vulnerability UNKNOWN is: 2 Total of Vulnerability INFO is: 2 ================================================================================== ``` </br> # Material para Consulta 1. Lista de comandos: https://docs.horusec.io/docs/cli/commands-and-flags/#3-flags 2. Instalação da Aplicação Web Horusec-Manager: https://docs.horusec.io/docs/web/installation/install-with-docker-compose/ 3. Laboratório: https://blog.4linux.com.br/deixe-sua-aplicacao-mais-segura-utilizando-o-horusec/ 4. Boas práticas: https://www.zup.com.br/blog/desenvolvimento-seguro-horusec 5. Integração Horusec com o Sonarqube: https://blog.knoldus.com/horusec-with-sonarqube/ 6. Playlist ZUP: https://youtube.com/playlist?list=PLkX9oUrQ1ev6-rAWMgj2PH41EP6TOu6Hj