
En un artículo anterior, le mostré cómo detectar vulnerabilidades de terceros en Python. Este artículo muestra cómo escanear su código Java para el mismo problema.
Ejemplo 1: escanear bibliotecas para proyectos de código abierto
El software es complicado, pero gracias. fuente abierta, puedo desarrollar rápidamente nuevas aplicaciones aprovechando los esfuerzos de las personas que eligen compartir su trabajo. Desafortunadamente, las nuevas características del software también introducen nuevos errores que los atacantes malintencionados pueden explotar.
Para ilustrar, descargaré una versión vulnerable de un conocido servidor de aplicaciones de código abierto:
$ curl --location --fail --output ~/Downloads/XXXX-A.B.C-zzzz.zip https://XXX.ZZZZ.org/dist/XXX/server/A.B.C/XXXX-A.B.C-zzzz.zip
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 88.8M 100 88.8M 0 0 5142k 0 0:00:17 0:00:17 --:--:-- 1194k
cd ~/Downloads
unzip XXXX-A.B.C-zzzz.zip
Existen muchas herramientas que analizan las vulnerabilidades de las aplicaciones.Voy a demostrar cómo hacer esto Analizador de dependencias OWASP Jeremy Long, consigue una copia:
$ curl --fail --output ~/Downloads/dependency-check-6.5.3-release.zip --location https://github.com/jeremylong/DependencyCheck/releases/download/v6.5.3/dependency-check-6.5.3-release.zip
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 669 100 669 0 0 4430 0 --:--:-- --:--:-- --:--:-- 4430
100 23.0M 100 23.0M 0 0 7653k 0 0:00:03 0:00:03 --:--:-- 8899k
Úselo para verificar esta aplicación en busca de vulnerabilidades:
$ ~/Downloads/dependency-check/bin/dependency-check.sh --prettyPrint --format HTML -scan /home/josevnz/Downloads/XXXX-A.B.C-zzzz/lib/
[INFO] Checking for updates
[INFO] Download Started for NVD CVE - Modified
[INFO] Download Complete for NVD CVE - Modified (278 ms)
[INFO] Processing Started for NVD CVE - Modified
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.fasterxml.jackson.module.afterburner.util.MyClassLoader (file:/home/josevnz/Downloads/dependency-check/lib/jackson-module-afterburner-2.13.1.jar) to method java.lang.ClassLoader.findLoadedClass(java.lang.String)
WARNING: Please consider reporting this to the maintainers of com.fasterxml.jackson.module.afterburner.util.MyClassLoader
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
[INFO] Processing Complete for NVD CVE - Modified (5150 ms)
[INFO] Begin database maintenance
[INFO] Updated the CPE ecosystem on 116793 NVD records
[INFO] Cleaned up 2 orphaned NVD records
[INFO] End database maintenance (24739 ms)
[INFO] Begin database defrag
[INFO] End database defrag (4660 ms)
[INFO] Check for updates complete (39967 ms)
[INFO]
Dependency-Check is an open source tool performing a best effort analysis of 3rd party dependencies; false positives and false negatives may exist in the analysis performed by the tool. Use of the tool and the reporting provided constitutes acceptance for use in an AS IS condition, and there are NO warranties, implied or otherwise, with regard to the analysis or its use. Any use of the tool and the reporting provided is at the user's risk. In no event shall the copyright holder or OWASP be held liable for any damages whatsoever arising out of or in connection with the use of this tool, the analysis performed, or the resulting report.
About ODC: https://jeremylong.github.io/DependencyCheck/general/internals.html
False Positives: https://jeremylong.github.io/DependencyCheck/general/suppression.html
💖 Sponsor: https://github.com/sponsors/jeremylong
[INFO] Analysis Started
[INFO] Finished Archive Analyzer (1 seconds)
[INFO] Finished File Name Analyzer (0 seconds)
[INFO] Finished Jar Analyzer (1 seconds)
[INFO] Finished Central Analyzer (9 seconds)
[ERROR] ----------------------------------------------------
[ERROR] .NET Assembly Analyzer could not be initialized and at least one ''exe'' or ''dll'' was scanned. The ''dotnet'' executable could not be found on the path; either disable the Assembly Analyzer or add the path to dotnet core in the configuration.
[ERROR] ----------------------------------------------------
[INFO] Finished Dependency Merging Analyzer (0 seconds)
[INFO] Finished Version Filter Analyzer (0 seconds)
[INFO] Finished Hint Analyzer (0 seconds)
[INFO] Created CPE Index (2 seconds)
[INFO] Finished CPE Analyzer (6 seconds)
[INFO] Finished False Positive Analyzer (0 seconds)
[INFO] Finished NVD CVE Analyzer (0 seconds)
[INFO] Finished Sonatype OSS Index Analyzer (3 seconds)
[INFO] Finished Vulnerability Suppression Analyzer (0 seconds)
[INFO] Finished Dependency Bundling Analyzer (0 seconds)
[INFO] Analysis Complete (23 seconds)
[INFO] Writing report to: /home/josevnz/Downloads/./dependency-check-report.html
El informe muestra que mi versión elegida tiene varios problemas. El proveedor ha solucionado todos estos problemas en la última versión.
No todo es perfecto, herramientas. Puede generar falsos positivospero sigue siendo un buen comienzo.
A continuación, te mostraré un proyecto diferente que puedes arreglar tú mismo.
Ejemplo 2: Análisis de un reportero estadístico de Covid-19 de cosecha propia en la ciudad
El proyecto descarga datos de Covid-19 del portal del gobierno de Connecticut y realiza un filtrado básico antes de mostrar los resultados.
descargar y compilar cuna:
git clone https://github.com/josevnz/Covid19Informer.git
$ gradle test jar
$ gradle distTar
$ /bin/tar --directory $HOME --extract --verbose --file build/distributions/Covid19Informer-0.0.1.tar
notas: También puede instalar manualmente de esta manera (me gusta el envoltorio de Gradle lo suficiente como para evitar esto):
/bin/mkdir --parent --verbose $HOME/Covid19Informer-0.0.1
/bin/cp --verbose build/libs/Covid19Informer-0.0.1.jar $HOME/Covid19Informer-0.0.1
/bin/curl --fail --location --output $HOME/Covid19Informer-0.0.1/lanterna-3.1.1.jar --url https://repo1.maven.org/maven2/com/googlecode/lanterna/lanterna/3.1.1/lanterna-3.1.1.jar
/bin/curl --fail --location --output $HOME/Covid19Informer-0.0.1/commons-io-2.11.0.jar --url https://repo1.maven.org/maven2/commons-io/commons-io/2.11.0/commons-io-2.11.0.jar
A continuación, ejecute Covid19Informer para ver qué hace esta pequeña aplicación.no suelo usar uber.jar En producción, implemente la aplicación Java y sus dependencias (jars) en el directorio de implementación:
$ $HOME/Covid19Informer-0.0.1/bin/Covid19Informer
...
INFO: Covid19DataPerTown[lastUpdateDate=2022-01-19, townNumber=135, town='Stamford', totalCases=26239, confirmedCases=24448, probableCases=1791, caseRate=135.0, totalDeaths=349, confirmedDeaths=308, probableDeaths=41, peopleTested=121435, rateTestedPer100k=93672.0, numberOfTests=383071, numberOfPositives=33471, numberOfNegatives=308, numberOfIndeterminates=422]
Jan 20, 2022 7:39:13 PM com.kodegeek.covid19.towndata.TownDataRetriever$Covid19DataPerTown lambda$printCovidData$1
INFO: Covid19DataPerTown[lastUpdateDate=2022-01-19, townNumber=151, town='Waterbury', totalCases=29064, confirmedCases=25500, probableCases=3564, caseRate=151.0, totalDeaths=444, confirmedDeaths=378, probableDeaths=66, peopleTested=99611, rateTestedPer100k=92603.0, numberOfTests=423805, numberOfPositives=36882, numberOfNegatives=378, numberOfIndeterminates=787]
Analizar dependencias:
$ ~/Downloads/dependency-check/bin/dependency-check.sh --prettyPrint --format HTML -scan $HOME/Covid19Informer-0.0.1/lib
[INFO] Checking for updates
[INFO] Skipping NVD check since last check was within 4 hours.
[INFO] Skipping RetireJS update since last update was within 24 hours.
[INFO] Check for updates complete (62 ms)
[INFO]
Dependency-Check is an open source tool performing a best effort analysis of 3rd party dependencies; false positives and false negatives may exist in the analysis performed by the tool. Use of the tool and the reporting provided constitutes acceptance for use in an AS IS condition, and there are NO warranties, implied or otherwise, with regard to the analysis or its use. Any use of the tool and the reporting provided is at the user'suser's risk. In no event shall the copyright holder or OWASP be held liable for any damages whatsoever arising out of or in connection with the use of this tool, the analysis performed, or the resulting report.
About ODC: https://jeremylong.github.io/DependencyCheck/general/internals.html
False Positives: https://jeremylong.github.io/DependencyCheck/general/suppression.html
💖 Sponsor: https://github.com/sponsors/jeremylong
[INFO] Analysis Started
[INFO] Finished Archive Analyzer (0 seconds)
[INFO] Finished File Name Analyzer (0 seconds)
[INFO] Finished Jar Analyzer (0 seconds)
[INFO] Finished Central Analyzer (0 seconds)
[INFO] Finished Dependency Merging Analyzer (0 seconds)
[INFO] Finished Version Filter Analyzer (0 seconds)
[INFO] Finished Hint Analyzer (0 seconds)
[INFO] Created CPE Index (1 seconds)
[INFO] Finished CPE Analyzer (2 seconds)
[INFO] Finished False Positive Analyzer (0 seconds)
[INFO] Finished NVD CVE Analyzer (0 seconds)
[INFO] Finished Sonatype OSS Index Analyzer (0 seconds)
[INFO] Finished Vulnerability Suppression Analyzer (0 seconds)
[INFO] Finished Dependency Bundling Analyzer (0 seconds)
[INFO] Analysis Complete (2 seconds)
[INFO] Writing report to: /home/josevnz/Documents/Covid19Informer/./dependency-check-report.html
La aplicación está limpia, pero eso no significa que haya encontrado todos los problemas. Permítanme elaborar:
- No verifiqué las dependencias de prueba o integración (si corresponde). Solo verifiqué las dependencias de tiempo de ejecución (que es lo suficientemente bueno para la mayoría de los casos).
- Este enfoque es pasivo, lo que significa que encontraré el problema. espalda Ocurre, no durante el ciclo de desarrollo.
Las cosas mejorarán cuando tenga acceso al código fuente.
[ Download the eBook to Get ready for your Red Hat remote exam. ]
Ejemplo 3: escanear Covid19Informer al compilar código
Para usar la herramienta como parte de la integración continua, agréguela a build.gradle.kts
.
plugins {
`java-library`
application
id("org.owasp.dependencycheck") version "6.5.3"
}
Para usarlo simplemente llama a Gradle así:
$ gradle dependencyCheckAnalyze --info
...
One or more dependencies were identified with known vulnerabilities in Covid19Informer:
h2-1.4.199.jar (pkg:maven/com.h2database/[email protected], cpe:2.3:a:h2database:h2:1.4.199:*:*:*:*:*:*:*) : CVE-2021-23463, CVE-2021-42392
See the dependency-check report for more details.
Element event queue destroyed: org.apache.commons.jcs.engine.control.event.ElementEventQueue@12440215
In DISPOSE, [NODEAUDIT] fromRemote [false]
In DISPOSE, [NODEAUDIT] auxiliary [NODEAUDIT]
...
BUILD SUCCESSFUL in 4s
2 actionable tasks: 2 executed
Some of the file system contents retained in the virtual file system are on file systems that Gradle doesn't support watching. The relevant state was discarded to ensure changes to these locations are properly detected. You can override this by explicitly enabling file system watching.
Watching 24 directories to track changes
Algunos puntos a tener en cuenta:
- Compilación completada con advertencia: se encontró un .jar vulnerable en mi caché de Gradle (ruta del archivo:
/home/josevnz/.gradle/caches/modules-2/files-2.1/com.h2database/h2/1.4.199/7bf08152984ed8859740ae3f97fae6c72771ae45/h2-1.4.199.jar
). Es de una prueba anterior, así que tenlo en cuenta si obtienes algunos falsos positivos con esta herramienta. - Este escáner Gradle descarga una gran cantidad de datos por primera vez. Después de eso, se estabilizó usando el contenido del caché local.
Por esta razón, le mostraré un complemento de Gradle diferente para buscar vulnerabilidades.
[ Learn the benefits of modernizing your network in the eBook Network automation for everyone. ]
Ejemplo 4: escanear Covid19Informer con diferentes herramientas después de la compilación
La gente de Sonatype creó un complemento de Gradle para escanear su proyecto llamado Buscar complementos de GradleEsto está hecho por Directorio de índice OSS.
A estas alturas, probablemente ya hayas visto hacia dónde se dirige. Al tener esta verificación en su conjunto de herramientas de compilación de Java, su herramienta de integración continua puede ejecutar este análisis cada vez que su código cambia, y le informa cualquier anomalía antes de que su código se implemente en producción.
Para hacer esto, agregue lo siguiente a build.gradle.kts
documento:
plugins {
`java-library`
id ("org.sonatype.gradle.plugins.scan") version "2.2.2"
}
ossIndexAudit {
username = System.getenv("ossindexaudit_user")
password = System.getenv("ossindexaudit_password")
}
Luego busque vulnerabilidades (Sonatype recomienda crear un cuenta gratis No hay límite en el número de veces que se puede llamar al servicio):
$ gradlew test jar
# These 2 variables will be ''injected'' on your continuous integration environment
$ read -r -p "Please enter your Sonatype user (like [email protected]): " ossindexaudit_user
$ read -r -p -s ""Please enter your Sonatype account password"" ossindexaudit_user
$ export ossindexaudit_user ossindexaudit_user
$ gradle ossIndexAudit
> Task :ossIndexAudit
________ ________ ________ ________ ___ _______ ________ ________ ________ ________
|\ ____\|\ __ \|\ __ \|\ ___ \|\ \ |\ ___ \ |\ ____\|\ ____\|\ __ \|\ ___ \
\ \ \___|\ \ \|\ \ \ \|\ \ \ \_|\ \ \ \ \ \ __/| \ \ \___|\ \ \___|\ \ \|\ \ \ \\ \ \
\ \ \ __\ \ _ _\ \ __ \ \ \ \\ \ \ \ \ \ \_|/__ \ \_____ \ \ \ \ \ __ \ \ \\ \ \
\ \ \|\ \ \ \\ \\ \ \ \ \ \ \_\\ \ \ \____\ \ \_|\ \ \|____|\ \ \ \____\ \ \ \ \ \ \\ \ \
\ \_______\ \__\\ _\\ \__\ \__\ \_______\ \_______\ \_______\ ____\_\ \ \_______\ \__\ \__\ \__\\ \__\
\|_______|\|__|\|__|\|__|\|__|\|_______|\|_______|\|_______| |\_________\|_______|\|__|\|__|\|__| \|__|
\|_________|
_ _ _ _
/_) /_`_ _ _ _/_ _ _ (/ /_`_._ _ _/ _
/_)/_/ ._//_// //_|/ /_//_//_' (_X / ///_'/ //_/_\
_/ _//
Gradle Scan version: 2.2.2
------------------------------------------------------------------------------------------------------------------------------------------------------
Checking vulnerabilities in 1 dependencies
No vulnerabilities found!
BUILD SUCCESSFUL in 758ms
1 actionable task: 1 executed
Así que todo está bien, ¿verdad?
incompleto. Echa un vistazo más de cerca a mi proyecto:
dependencies {
implementation("com.googlecode.lanterna:lanterna:3.1.1")
implementation("commons-cli:commons-cli:20040117.000000")
testImplementation("junit:junit:4.13")
}
El escáner encontró mis dependencias de compilación pero ignoró mis dependencias de prueba; en este caso, junitResulta que la versión que estaba usando en el archivo de compilación era vulnerable a partir de 2020: JUnit CVE-2020-15250.
¿Por qué está pasando esto?necesitas tener isAllConfigurations = true
propiedad establecida en verdadero build.gradle.kts
:
ossIndexAudit {
username = System.getenv("ossindexaudit_user")
password = System.getenv("ossindexaudit_password")
isAllConfigurations = true
}
Lo intentaré otra vez:
$ gradle jar; gradle ossIndexAudit
BUILD SUCCESSFUL in 2s
3 actionable tasks: 3 up-to-date
> Task :ossIndexAudit FAILED
________ ________ ________ ________ ___ _______ ________ ________ ________ ________
|\ ____\|\ __ \|\ __ \|\ ___ \|\ \ |\ ___ \ |\ ____\|\ ____\|\ __ \|\ ___ \
\ \ \___|\ \ \|\ \ \ \|\ \ \ \_|\ \ \ \ \ \ __/| \ \ \___|\ \ \___|\ \ \|\ \ \ \\ \ \
\ \ \ __\ \ _ _\ \ __ \ \ \ \\ \ \ \ \ \ \_|/__ \ \_____ \ \ \ \ \ __ \ \ \\ \ \
\ \ \|\ \ \ \\ \\ \ \ \ \ \ \_\\ \ \ \____\ \ \_|\ \ \|____|\ \ \ \____\ \ \ \ \ \ \\ \ \
\ \_______\ \__\\ _\\ \__\ \__\ \_______\ \_______\ \_______\ ____\_\ \ \_______\ \__\ \__\ \__\\ \__\
\|_______|\|__|\|__|\|__|\|__|\|_______|\|_______|\|_______| |\_________\|_______|\|__|\|__|\|__| \|__|
\|_________|
_ _ _ _
/_) /_`_ _ _ _/_ _ _ (/ /_`_._ _ _/ _
/_)/_/ ._//_// //_|/ /_//_//_' (_X / ///_'/ //_/_\
_/ _//
Gradle Scan version: 2.2.2
------------------------------------------------------------------------------------------------------------------------------------------------------
Checking vulnerabilities in 2 dependencies
Found vulnerabilities in 1 dependencies
[1/1] - pkg:maven/junit/[email protected] - 1 vulnerability found!
Vulnerability Title: [CVE-2020-15250] In JUnit4 from version 4.7 and before 4.13.1, the test rule TemporaryFolder cont...
ID: 7ea56ad4-8a8b-4e51-8ed9-5aad83d8efb1
Description: In JUnit4 from version 4.7 and before 4.13.1, the test rule TemporaryFolder contains a local information disclosure vulnerability. On Uni...
CVSS Score: (5.5/10, Medium)
CVSS Vector: CVSS:3.0/AV:L/AC:L/PR:N/UI:R/S:U/C:H/I:N/A:N
CVE: CVE-2020-15250
Reference: https://ossindex.sonatype.org/vulnerability/7ea56ad4-8a8b-4e51-8ed9-5aad83d8efb1?component-type=maven&component-name=junit.junit&utm_source=ossindex-client&utm_medium=integration&utm_content=1.7.0
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':ossIndexAudit'.
> Vulnerabilities detected, check log output to review them
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use ''--warning-mode all'' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 1s
1 actionable task: 1 executed
¡estupendo!Arreglar esto es fácil: simplemente actualice Junit a las últimas coordenadas (en este punto junit:junit:4.13.2
) existe build.gradle.kts
y vuelve a compilar:
dependencies {
implementation("com.googlecode.lanterna:lanterna:3.1.1")
implementation("commons-io:commons-io:2.11.0")
testImplementation("junit:junit:4.13.2")
}
Checking vulnerabilities in 3 dependencies
No vulnerabilities found!
Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use ''--warning-mode all'' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0/userguide/command_line_interface.html#sec:command_line_warnings
BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed
¿Le dirá el IDE si está utilizando una versión anterior de la biblioteca?
La mayoría de los entornos de desarrollo integrados (IDE) informan de estos problemas y no debe ignorar estas advertencias.Por ejemplo, la edición comunitaria de IntelliJ atrapó el viejo Junit y etiquetó el mío build.gradle.kts
Archivo con advertencia:
Otros IDE como VS Code hacen lo mismo.
Qué aprendiste
- Cómo analizar el uso del proyecto Comprobación de dependencias de OWASP.
- Cómo arreglar el proyecto si se encuentra una dependencia vulnerable (en este caso, arreglando
build.gradle.kts
documento). - cómo añadir Comprobación de vulnerabilidad Integración continua usando sonatype-scan-gradle-plugin.
Ahora puede inspeccionar más completamente sus proyectos Java en busca de vulnerabilidades de terceros.