idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
11,400 | public void addReference ( String referenceSource , String referenceName , String referenceUrl ) { final Reference ref = new Reference ( ) ; ref . setSource ( referenceSource ) ; ref . setName ( referenceName ) ; ref . setUrl ( referenceUrl ) ; this . references . add ( ref ) ; } | Adds a reference . |
11,401 | public List < VulnerableSoftware > getVulnerableSoftware ( boolean sorted ) { final List < VulnerableSoftware > sortedVulnerableSoftware = new ArrayList < > ( this . vulnerableSoftware ) ; if ( sorted ) { Collections . sort ( sortedVulnerableSoftware ) ; } return sortedVulnerableSoftware ; } | Returns a sorted list of vulnerable software . This is primarily used for display within reports . |
11,402 | public int compareTo ( Vulnerability v ) { return new CompareToBuilder ( ) . append ( this . name , v . name ) . toComparison ( ) ; } | Compares two vulnerabilities . |
11,403 | private static boolean artifactsMatch ( org . apache . maven . model . Dependency d , Artifact a ) { return isEqualOrNull ( a . getArtifactId ( ) , d . getArtifactId ( ) ) && isEqualOrNull ( a . getGroupId ( ) , d . getGroupId ( ) ) && isEqualOrNull ( a . getVersion ( ) , d . getVersion ( ) ) ; } | Determines if the groupId artifactId and version of the Maven dependency and artifact match . |
11,404 | private static boolean isEqualOrNull ( String left , String right ) { return ( left != null && left . equals ( right ) ) || ( left == null && right == null ) ; } | Compares two strings for equality ; if both strings are null they are considered equal . |
11,405 | public void execute ( ) throws MojoExecutionException , MojoFailureException { generatingSite = false ; final boolean shouldSkip = Boolean . parseBoolean ( System . getProperty ( "dependency-check.skip" , Boolean . toString ( skip ) ) ) ; if ( shouldSkip ) { getLog ( ) . info ( "Skipping " + getName ( Locale . US ) ) ; } else { project . setContextValue ( "dependency-check-output-dir" , this . outputDirectory ) ; runCheck ( ) ; } } | Executes dependency - check . |
11,406 | protected File getCorrectOutputDirectory ( MavenProject current ) { final Object obj = current . getContextValue ( "dependency-check-output-dir" ) ; if ( obj != null && obj instanceof File ) { return ( File ) obj ; } File target = new File ( current . getBuild ( ) . getDirectory ( ) ) ; if ( target . getParentFile ( ) != null && "target" . equals ( target . getParentFile ( ) . getName ( ) ) ) { target = target . getParentFile ( ) ; } return target ; } | Returns the correct output directory depending on if a site is being executed or not . |
11,407 | private DependencyNode toDependencyNode ( ProjectBuildingRequest buildingRequest , DependencyNode parent , org . apache . maven . model . Dependency dependency ) throws ArtifactResolverException { final DefaultArtifactCoordinate coordinate = new DefaultArtifactCoordinate ( ) ; coordinate . setGroupId ( dependency . getGroupId ( ) ) ; coordinate . setArtifactId ( dependency . getArtifactId ( ) ) ; coordinate . setVersion ( dependency . getVersion ( ) ) ; final ArtifactType type = session . getRepositorySession ( ) . getArtifactTypeRegistry ( ) . get ( dependency . getType ( ) ) ; coordinate . setExtension ( type . getExtension ( ) ) ; coordinate . setClassifier ( type . getClassifier ( ) ) ; final Artifact artifact = artifactResolver . resolveArtifact ( buildingRequest , coordinate ) . getArtifact ( ) ; artifact . setScope ( dependency . getScope ( ) ) ; final DefaultDependencyNode node = new DefaultDependencyNode ( parent , artifact , dependency . getVersion ( ) , dependency . getScope ( ) , null ) ; return node ; } | Converts the dependency to a dependency node object . |
11,408 | private ExceptionCollection collectDependencyManagementDependencies ( ProjectBuildingRequest buildingRequest , MavenProject project , List < DependencyNode > nodes , boolean aggregate ) { if ( skipDependencyManagement || project . getDependencyManagement ( ) == null ) { return null ; } ExceptionCollection exCol = null ; for ( org . apache . maven . model . Dependency dependency : project . getDependencyManagement ( ) . getDependencies ( ) ) { try { nodes . add ( toDependencyNode ( buildingRequest , null , dependency ) ) ; } catch ( ArtifactResolverException ex ) { getLog ( ) . debug ( String . format ( "Aggregate : %s" , aggregate ) ) ; if ( exCol == null ) { exCol = new ExceptionCollection ( ) ; } exCol . addException ( ex ) ; } } return exCol ; } | Collect dependencies from the dependency management section . |
11,409 | protected void runCheck ( ) throws MojoExecutionException , MojoFailureException { try ( Engine engine = initializeEngine ( ) ) { ExceptionCollection exCol = scanDependencies ( engine ) ; try { engine . analyzeDependencies ( ) ; } catch ( ExceptionCollection ex ) { exCol = handleAnalysisExceptions ( exCol , ex ) ; } if ( exCol == null || ! exCol . isFatal ( ) ) { File outputDir = getCorrectOutputDirectory ( this . getProject ( ) ) ; if ( outputDir == null ) { outputDir = new File ( this . getProject ( ) . getBuild ( ) . getDirectory ( ) ) ; } try { final MavenProject p = this . getProject ( ) ; engine . writeReports ( p . getName ( ) , p . getGroupId ( ) , p . getArtifactId ( ) , p . getVersion ( ) , outputDir , getFormat ( ) ) ; } catch ( ReportException ex ) { if ( exCol == null ) { exCol = new ExceptionCollection ( ex ) ; } else { exCol . addException ( ex ) ; } if ( this . isFailOnError ( ) ) { throw new MojoExecutionException ( "One or more exceptions occurred during dependency-check analysis" , exCol ) ; } else { getLog ( ) . debug ( "Error writing the report" , ex ) ; } } showSummary ( this . getProject ( ) , engine . getDependencies ( ) ) ; checkForFailure ( engine . getDependencies ( ) ) ; if ( exCol != null && this . isFailOnError ( ) ) { throw new MojoExecutionException ( "One or more exceptions occurred during dependency-check analysis" , exCol ) ; } } } catch ( DatabaseException ex ) { if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( "Database connection error" , ex ) ; } final String msg = "An exception occurred connecting to the local database. Please see the log file for more details." ; if ( this . isFailOnError ( ) ) { throw new MojoExecutionException ( msg , ex ) ; } getLog ( ) . error ( msg , ex ) ; } finally { getSettings ( ) . cleanup ( ) ; } } | Executes the dependency - check scan and generates the necessary report . |
11,410 | private ExceptionCollection handleAnalysisExceptions ( ExceptionCollection currentEx , ExceptionCollection newEx ) throws MojoExecutionException { ExceptionCollection returnEx = currentEx ; if ( returnEx == null ) { returnEx = newEx ; } else { returnEx . getExceptions ( ) . addAll ( newEx . getExceptions ( ) ) ; if ( newEx . isFatal ( ) ) { returnEx . setFatal ( true ) ; } } if ( returnEx . isFatal ( ) ) { final String msg = String . format ( "Fatal exception(s) analyzing %s" , getProject ( ) . getName ( ) ) ; if ( this . isFailOnError ( ) ) { throw new MojoExecutionException ( msg , returnEx ) ; } getLog ( ) . error ( msg ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( returnEx ) ; } } else { final String msg = String . format ( "Exception(s) analyzing %s" , getProject ( ) . getName ( ) ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( msg , returnEx ) ; } } return returnEx ; } | Combines the two exception collections and if either are fatal throw an MojoExecutionException |
11,411 | public String getOutputName ( ) { if ( "HTML" . equalsIgnoreCase ( this . format ) || "ALL" . equalsIgnoreCase ( this . format ) ) { return "dependency-check-report" ; } else if ( "XML" . equalsIgnoreCase ( this . format ) ) { return "dependency-check-report.xml" ; } else if ( "JUNIT" . equalsIgnoreCase ( this . format ) ) { return "dependency-check-junit.xml" ; } else if ( "JSON" . equalsIgnoreCase ( this . format ) ) { return "dependency-check-report.json" ; } else if ( "CSV" . equalsIgnoreCase ( this . format ) ) { return "dependency-check-report.csv" ; } else { getLog ( ) . warn ( "Unknown report format used during site generation." ) ; return "dependency-check-report" ; } } | Returns the output name . |
11,412 | private String decryptServerPassword ( Server server ) throws SecDispatcherException { if ( securityDispatcher instanceof DefaultSecDispatcher ) { ( ( DefaultSecDispatcher ) securityDispatcher ) . setConfigurationFile ( "~/.m2/settings-security.xml" ) ; } return securityDispatcher . decrypt ( server . getPassword ( ) ) ; } | Obtains the configured password for the given server . |
11,413 | private String [ ] determineSuppressions ( ) { String [ ] suppressions = suppressionFiles ; if ( suppressionFile != null ) { if ( suppressions == null ) { suppressions = new String [ ] { suppressionFile } ; } else { suppressions = Arrays . copyOf ( suppressions , suppressions . length + 1 ) ; suppressions [ suppressions . length - 1 ] = suppressionFile ; } } return suppressions ; } | Combines the configured suppressionFile and suppressionFiles into a single array . |
11,414 | private Proxy getMavenProxy ( ) { if ( mavenSettings != null ) { final List < Proxy > proxies = mavenSettings . getProxies ( ) ; if ( proxies != null && ! proxies . isEmpty ( ) ) { if ( mavenSettingsProxyId != null ) { for ( Proxy proxy : proxies ) { if ( mavenSettingsProxyId . equalsIgnoreCase ( proxy . getId ( ) ) ) { return proxy ; } } } else { for ( Proxy aProxy : proxies ) { if ( aProxy . isActive ( ) ) { return aProxy ; } } } } } return null ; } | Returns the maven proxy . |
11,415 | private String determineEcosystem ( String baseEcosystem , String vendor , String product , String targetSw ) { if ( "ibm" . equals ( vendor ) && "java" . equals ( product ) ) { return "c/c++" ; } if ( "oracle" . equals ( vendor ) && "vm" . equals ( product ) ) { return "c/c++" ; } if ( "*" . equals ( targetSw ) || baseEcosystem != null ) { return baseEcosystem ; } return targetSw ; } | Attempts to determine the ecosystem based on the vendor product and targetSw . |
11,416 | private String determineDatabaseProductName ( Connection conn ) { try { final String databaseProductName = conn . getMetaData ( ) . getDatabaseProductName ( ) . toLowerCase ( ) ; LOGGER . debug ( "Database product: {}" , databaseProductName ) ; return databaseProductName ; } catch ( SQLException se ) { LOGGER . warn ( "Problem determining database product!" , se ) ; return null ; } } | Tries to determine the product name of the database . |
11,417 | private synchronized void open ( ) throws DatabaseException { try { if ( ! isOpen ( ) ) { connection = connectionFactory . getConnection ( ) ; final String databaseProductName = determineDatabaseProductName ( this . connection ) ; statementBundle = databaseProductName != null ? ResourceBundle . getBundle ( "data/dbStatements" , new Locale ( databaseProductName ) ) : ResourceBundle . getBundle ( "data/dbStatements" ) ; prepareStatements ( ) ; databaseProperties = new DatabaseProperties ( this ) ; } } catch ( DatabaseException e ) { releaseResources ( ) ; throw e ; } } | Opens the database connection . If the database does not exist it will create a new one . |
11,418 | public synchronized void close ( ) { if ( isOpen ( ) ) { clearCache ( ) ; closeStatements ( ) ; try { connection . close ( ) ; } catch ( SQLException ex ) { LOGGER . error ( "There was an error attempting to close the CveDB, see the log for more details." ) ; LOGGER . debug ( "" , ex ) ; } catch ( Throwable ex ) { LOGGER . error ( "There was an exception attempting to close the CveDB, see the log for more details." ) ; LOGGER . debug ( "" , ex ) ; } releaseResources ( ) ; connectionFactory . cleanup ( ) ; } } | Closes the database connection . Close should be called on this object when it is done being used . |
11,419 | private void prepareStatements ( ) throws DatabaseException { for ( PreparedStatementCveDb key : values ( ) ) { PreparedStatement preparedStatement = null ; try { final String statementString = statementBundle . getString ( key . name ( ) ) ; if ( key == INSERT_VULNERABILITY || key == INSERT_CPE ) { preparedStatement = connection . prepareStatement ( statementString , new String [ ] { "id" } ) ; } else { preparedStatement = connection . prepareStatement ( statementString ) ; } } catch ( SQLException ex ) { throw new DatabaseException ( ex ) ; } catch ( MissingResourceException ex ) { if ( ! ex . getMessage ( ) . contains ( "key MERGE_PROPERTY" ) ) { throw new DatabaseException ( ex ) ; } } if ( preparedStatement != null ) { preparedStatements . put ( key , preparedStatement ) ; } } } | Prepares all statements to be used . |
11,420 | private PreparedStatement prepareStatement ( PreparedStatementCveDb key ) throws DatabaseException { PreparedStatement preparedStatement = null ; try { final String statementString = statementBundle . getString ( key . name ( ) ) ; if ( key == INSERT_VULNERABILITY || key == INSERT_CPE ) { preparedStatement = connection . prepareStatement ( statementString , Statement . RETURN_GENERATED_KEYS ) ; } else { preparedStatement = connection . prepareStatement ( statementString ) ; } } catch ( SQLException ex ) { throw new DatabaseException ( ex ) ; } catch ( MissingResourceException ex ) { if ( ! ex . getMessage ( ) . contains ( "key MERGE_PROPERTY" ) ) { throw new DatabaseException ( ex ) ; } } return preparedStatement ; } | Creates a prepared statement from the given key . The SQL is stored in a properties file and the key is used to lookup the specific query . |
11,421 | private HttpURLConnection connect ( URL url ) throws IOException { LOGGER . debug ( "Searching Artifactory url {}" , url ) ; final URLConnectionFactory factory = new URLConnectionFactory ( settings ) ; final HttpURLConnection conn = factory . createHttpURLConnection ( url , useProxy ) ; conn . setDoOutput ( true ) ; conn . addRequestProperty ( "X-Result-Detail" , "info" ) ; final String username = settings . getString ( Settings . KEYS . ANALYZER_ARTIFACTORY_API_USERNAME ) ; final String apiToken = settings . getString ( Settings . KEYS . ANALYZER_ARTIFACTORY_API_TOKEN ) ; if ( username != null && apiToken != null ) { final String userpassword = username + ":" + apiToken ; final String encodedAuthorization = Base64 . getEncoder ( ) . encodeToString ( userpassword . getBytes ( StandardCharsets . UTF_8 ) ) ; conn . addRequestProperty ( "Authorization" , "Basic " + encodedAuthorization ) ; } else { final String bearerToken = settings . getString ( Settings . KEYS . ANALYZER_ARTIFACTORY_BEARER_TOKEN ) ; if ( bearerToken != null ) { conn . addRequestProperty ( "Authorization" , "Bearer " + bearerToken ) ; } } conn . connect ( ) ; return conn ; } | Makes an connection to the given URL . |
11,422 | protected List < MavenArtifact > processResponse ( Dependency dependency , HttpURLConnection conn ) throws IOException { final JsonObject asJsonObject ; try ( final InputStreamReader streamReader = new InputStreamReader ( conn . getInputStream ( ) , StandardCharsets . UTF_8 ) ) { asJsonObject = new JsonParser ( ) . parse ( streamReader ) . getAsJsonObject ( ) ; } final JsonArray results = asJsonObject . getAsJsonArray ( "results" ) ; final int numFound = results . size ( ) ; if ( numFound == 0 ) { throw new FileNotFoundException ( "Artifact " + dependency + " not found in Artifactory" ) ; } final List < MavenArtifact > result = new ArrayList < > ( numFound ) ; for ( JsonElement jsonElement : results ) { final JsonObject checksumList = jsonElement . getAsJsonObject ( ) . getAsJsonObject ( "checksums" ) ; final JsonPrimitive sha256Primitive = checksumList . getAsJsonPrimitive ( "sha256" ) ; final String sha1 = checksumList . getAsJsonPrimitive ( "sha1" ) . getAsString ( ) ; final String sha256 = sha256Primitive == null ? null : sha256Primitive . getAsString ( ) ; final String md5 = checksumList . getAsJsonPrimitive ( "md5" ) . getAsString ( ) ; checkHashes ( dependency , sha1 , sha256 , md5 ) ; final String downloadUri = jsonElement . getAsJsonObject ( ) . getAsJsonPrimitive ( "downloadUri" ) . getAsString ( ) ; final String path = jsonElement . getAsJsonObject ( ) . getAsJsonPrimitive ( "path" ) . getAsString ( ) ; final Matcher pathMatcher = PATH_PATTERN . matcher ( path ) ; if ( ! pathMatcher . matches ( ) ) { throw new IllegalStateException ( "Cannot extract the Maven information from the apth retrieved in Artifactory " + path ) ; } final String groupId = pathMatcher . group ( "groupId" ) . replace ( '/' , '.' ) ; final String artifactId = pathMatcher . group ( "artifactId" ) ; final String version = pathMatcher . group ( "version" ) ; result . add ( new MavenArtifact ( groupId , artifactId , version , downloadUri , MavenArtifact . derivePomUrl ( artifactId , version , downloadUri ) ) ) ; } return result ; } | Process the Artifactory response . |
11,423 | private void checkHashes ( Dependency dependency , String sha1 , String sha256 , String md5 ) throws FileNotFoundException { final String md5sum = dependency . getMd5sum ( ) ; if ( ! md5 . equals ( md5sum ) ) { throw new FileNotFoundException ( "Artifact found by API is not matching the md5 " + "of the artifact (repository hash is " + md5 + WHILE_ACTUAL_IS + md5sum + ") !" ) ; } final String sha1sum = dependency . getSha1sum ( ) ; if ( ! sha1 . equals ( sha1sum ) ) { throw new FileNotFoundException ( "Artifact found by API is not matching the SHA1 " + "of the artifact (repository hash is " + sha1 + WHILE_ACTUAL_IS + sha1sum + ") !" ) ; } final String sha256sum = dependency . getSha256sum ( ) ; if ( sha256 != null && ! sha256 . equals ( sha256sum ) ) { throw new FileNotFoundException ( "Artifact found by API is not matching the SHA-256 " + "of the artifact (repository hash is " + sha256 + WHILE_ACTUAL_IS + sha256sum + ") !" ) ; } } | Validates the hashes of the dependency . |
11,424 | public boolean preflightRequest ( ) { try { final URL url = buildUrl ( Checksum . getSHA1Checksum ( UUID . randomUUID ( ) . toString ( ) ) ) ; final HttpURLConnection connection = connect ( url ) ; if ( connection . getResponseCode ( ) != 200 ) { LOGGER . warn ( "Expected 200 result from Artifactory ({}), got {}" , url , connection . getResponseCode ( ) ) ; return false ; } return true ; } catch ( IOException e ) { LOGGER . error ( "Cannot connect to Artifactory" , e ) ; return false ; } } | Performs a pre - flight request to ensure the Artifactory service is reachable . |
11,425 | @ SuppressFBWarnings ( justification = "try with resources will clean up the input stream" , value = { "OBL_UNSATISFIED_OBLIGATION" } ) public AssemblyData parse ( File file ) throws GrokParseException { try ( FileInputStream fis = new FileInputStream ( file ) ) { return parse ( fis ) ; } catch ( IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } } | Parses the given XML file and returns the assembly data . |
11,426 | public AssemblyData parse ( InputStream inputStream ) throws GrokParseException { try ( InputStream schema = FileUtils . getResourceAsStream ( GROK_SCHEMA ) ) { final GrokHandler handler = new GrokHandler ( ) ; final SAXParser saxParser = XmlUtils . buildSecureSaxParser ( schema ) ; final XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setErrorHandler ( new GrokErrorHandler ( ) ) ; xmlReader . setContentHandler ( handler ) ; try ( Reader reader = new InputStreamReader ( inputStream , StandardCharsets . UTF_8 ) ) { final InputSource in = new InputSource ( reader ) ; xmlReader . parse ( in ) ; return handler . getAssemblyData ( ) ; } } catch ( ParserConfigurationException | FileNotFoundException ex ) { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } catch ( SAXException ex ) { if ( ex . getMessage ( ) . contains ( "Cannot find the declaration of element 'assembly'." ) ) { throw new GrokParseException ( "Malformed grok xml?" , ex ) ; } else { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } } catch ( IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new GrokParseException ( ex ) ; } } | Parses the given XML stream and returns the contained assembly data . |
11,427 | protected void runCheck ( ) throws MojoExecutionException , MojoFailureException { try ( Engine engine = initializeEngine ( ) ) { try { if ( ! engine . getSettings ( ) . getBoolean ( Settings . KEYS . AUTO_UPDATE ) ) { engine . getSettings ( ) . setBoolean ( Settings . KEYS . AUTO_UPDATE , true ) ; } } catch ( InvalidSettingException ex ) { engine . getSettings ( ) . setBoolean ( Settings . KEYS . AUTO_UPDATE , true ) ; } engine . doUpdates ( ) ; } catch ( DatabaseException ex ) { if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( "Database connection error" , ex ) ; } final String msg = "An exception occurred connecting to the local database. Please see the log file for more details." ; if ( this . isFailOnError ( ) ) { throw new MojoExecutionException ( msg , ex ) ; } getLog ( ) . error ( msg ) ; } catch ( UpdateException ex ) { final String msg = "An exception occurred while downloading updates. Please see the log file for more details." ; if ( this . isFailOnError ( ) ) { throw new MojoExecutionException ( msg , ex ) ; } getLog ( ) . error ( msg ) ; } } | Executes the dependency - check engine on the project s dependencies and generates the report . |
11,428 | protected Dependency createDependency ( Dependency dependency , String name , String version , String scope ) { final Dependency nodeModule = new Dependency ( new File ( dependency . getActualFile ( ) + "?" + name ) , true ) ; nodeModule . setEcosystem ( NPM_DEPENDENCY_ECOSYSTEM ) ; nodeModule . setSha1sum ( Checksum . getSHA1Checksum ( String . format ( "%s:%s" , name , version ) ) ) ; nodeModule . setSha256sum ( Checksum . getSHA256Checksum ( String . format ( "%s:%s" , name , version ) ) ) ; nodeModule . setMd5sum ( Checksum . getMD5Checksum ( String . format ( "%s:%s" , name , version ) ) ) ; nodeModule . addEvidence ( EvidenceType . PRODUCT , "package.json" , "name" , name , Confidence . HIGHEST ) ; nodeModule . addEvidence ( EvidenceType . VENDOR , "package.json" , "name" , name , Confidence . HIGH ) ; if ( ! StringUtils . isBlank ( version ) ) { nodeModule . addEvidence ( EvidenceType . VERSION , "package.json" , "version" , version , Confidence . HIGHEST ) ; nodeModule . setVersion ( version ) ; } if ( dependency . getName ( ) != null ) { nodeModule . addProjectReference ( dependency . getName ( ) + ": " + scope ) ; } else { nodeModule . addProjectReference ( dependency . getDisplayFileName ( ) + ": " + scope ) ; } nodeModule . setName ( name ) ; Identifier id ; try { final PackageURL purl = PackageURLBuilder . aPackageURL ( ) . withType ( StandardTypes . NPM ) . withName ( name ) . withVersion ( version ) . build ( ) ; id = new PurlIdentifier ( purl , Confidence . HIGHEST ) ; } catch ( MalformedPackageURLException ex ) { LOGGER . debug ( "Unable to generate Purl - using a generic identifier instead " + ex . getMessage ( ) ) ; id = new GenericIdentifier ( String . format ( "npm:%s@%s" , dependency . getName ( ) , version ) , Confidence . HIGHEST ) ; } nodeModule . addSoftwareIdentifier ( id ) ; return nodeModule ; } | Construct a dependency object . |
11,429 | public static Model readPom ( File file ) throws AnalysisException { try { final PomParser parser = new PomParser ( ) ; final Model model = parser . parse ( file ) ; if ( model == null ) { throw new AnalysisException ( String . format ( "Unable to parse pom '%s'" , file . getPath ( ) ) ) ; } return model ; } catch ( AnalysisException ex ) { throw ex ; } catch ( PomParseException ex ) { LOGGER . warn ( "Unable to parse pom '{}'" , file . getPath ( ) ) ; try { final File target = new File ( "~/Projects/DependencyCheck/core/target/" ) ; if ( target . isDirectory ( ) ) { FileUtils . copyFile ( file , target ) ; LOGGER . info ( "Unparsable pom was copied to {}" , target . toString ( ) ) ; } } catch ( IOException ex1 ) { throw new UnexpectedAnalysisException ( ex1 ) ; } LOGGER . debug ( "" , ex ) ; throw new AnalysisException ( ex ) ; } catch ( Throwable ex ) { LOGGER . warn ( "Unexpected error during parsing of the pom '{}'" , file . getPath ( ) ) ; LOGGER . debug ( "" , ex ) ; throw new AnalysisException ( ex ) ; } } | Reads in the specified POM and converts it to a Model . |
11,430 | public static Model readPom ( String path , JarFile jar ) throws AnalysisException { final ZipEntry entry = jar . getEntry ( path ) ; Model model = null ; if ( entry != null ) { try { final PomParser parser = new PomParser ( ) ; model = parser . parse ( jar . getInputStream ( entry ) ) ; if ( model == null ) { throw new AnalysisException ( String . format ( "Unable to parse pom '%s/%s'" , jar . getName ( ) , path ) ) ; } } catch ( AnalysisException ex ) { throw ex ; } catch ( SecurityException ex ) { LOGGER . warn ( "Unable to parse pom '{}' in jar '{}'; invalid signature" , path , jar . getName ( ) ) ; LOGGER . debug ( "" , ex ) ; throw new AnalysisException ( ex ) ; } catch ( IOException ex ) { LOGGER . warn ( "Unable to parse pom '{}' in jar '{}' (IO Exception)" , path , jar . getName ( ) ) ; LOGGER . debug ( "" , ex ) ; throw new AnalysisException ( ex ) ; } catch ( Throwable ex ) { LOGGER . warn ( "Unexpected error during parsing of the pom '{}' in jar '{}'" , path , jar . getName ( ) ) ; LOGGER . debug ( "" , ex ) ; throw new AnalysisException ( ex ) ; } } return model ; } | Retrieves the specified POM from a jar file and converts it to a Model . |
11,431 | public static void analyzePOM ( Dependency dependency , File pomFile ) throws AnalysisException { final Model pom = PomUtils . readPom ( pomFile ) ; JarAnalyzer . setPomEvidence ( dependency , pom , null , true ) ; } | Reads in the pom file and adds elements as evidence to the given dependency . |
11,432 | public synchronized void prepareAnalyzer ( Engine engine ) throws InitializationException { if ( rules . isEmpty ( ) ) { try { loadSuppressionBaseData ( ) ; } catch ( SuppressionParseException ex ) { throw new InitializationException ( "Error initializing the suppression analyzer: " + ex . getLocalizedMessage ( ) , ex , true ) ; } try { loadSuppressionData ( ) ; } catch ( SuppressionParseException ex ) { throw new InitializationException ( "Warn initializing the suppression analyzer: " + ex . getLocalizedMessage ( ) , ex , false ) ; } } } | The prepare method loads the suppression XML file . |
11,433 | public static void cleanup ( Driver driver ) { try { DriverManager . deregisterDriver ( driver ) ; } catch ( SQLException ex ) { LOGGER . debug ( "An error occurred unloading the database driver" , ex ) ; } catch ( Throwable unexpected ) { LOGGER . debug ( "An unexpected throwable occurred unloading the database driver" , unexpected ) ; } } | De - registers the driver . |
11,434 | public static Driver load ( String className ) throws DriverLoadException { final ClassLoader loader = DriverLoader . class . getClassLoader ( ) ; return load ( className , loader ) ; } | Loads the specified class using the system class loader and registers the driver with the driver manager . |
11,435 | @ SuppressWarnings ( "StringSplitter" ) public static Driver load ( String className , String pathToDriver ) throws DriverLoadException { final ClassLoader parent = ClassLoader . getSystemClassLoader ( ) ; final List < URL > urls = new ArrayList < > ( ) ; final String [ ] paths = pathToDriver . split ( File . pathSeparator ) ; for ( String path : paths ) { final File file = new File ( path ) ; if ( file . isDirectory ( ) ) { final File [ ] files = file . listFiles ( ) ; if ( files != null ) { for ( File f : files ) { try { urls . add ( f . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException ex ) { LOGGER . debug ( "Unable to load database driver '{}'; invalid path provided '{}'" , className , f . getAbsoluteFile ( ) , ex ) ; throw new DriverLoadException ( "Unable to load database driver. Invalid path provided" , ex ) ; } } } } else if ( file . exists ( ) ) { try { urls . add ( file . toURI ( ) . toURL ( ) ) ; } catch ( MalformedURLException ex ) { LOGGER . debug ( "Unable to load database driver '{}'; invalid path provided '{}'" , className , file . getAbsoluteFile ( ) , ex ) ; throw new DriverLoadException ( "Unable to load database driver. Invalid path provided" , ex ) ; } } } final URLClassLoader loader = AccessController . doPrivileged ( new PrivilegedAction < URLClassLoader > ( ) { public URLClassLoader run ( ) { return new URLClassLoader ( urls . toArray ( new URL [ urls . size ( ) ] ) , parent ) ; } } ) ; return load ( className , loader ) ; } | Loads the specified class by registering the supplied paths to the class loader and then registers the driver with the driver manager . The pathToDriver argument is added to the class loader so that an external driver can be loaded . Note the pathToDriver can contain a semi - colon separated list of paths so any dependencies can be added as needed . If a path in the pathToDriver argument is a directory all files in the directory are added to the class path . |
11,436 | private static Driver load ( String className , ClassLoader loader ) throws DriverLoadException { try { final Class < ? > c = Class . forName ( className , true , loader ) ; final Driver driver = ( Driver ) c . getDeclaredConstructor ( ) . newInstance ( ) ; final Driver shim = new DriverShim ( driver ) ; DriverManager . registerDriver ( shim ) ; return shim ; } catch ( ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex ) { final String msg = String . format ( "Unable to load database driver '%s'" , className ) ; LOGGER . debug ( msg , ex ) ; throw new DriverLoadException ( msg , ex ) ; } } | Loads the specified class using the supplied class loader and registers the driver with the driver manager . |
11,437 | private VelocityContext createContext ( String applicationName , List < Dependency > dependencies , List < Analyzer > analyzers , DatabaseProperties properties ) { final DateTime dt = new DateTime ( ) ; final DateTimeFormatter dateFormat = DateTimeFormat . forPattern ( "MMM d, yyyy 'at' HH:mm:ss z" ) ; final DateTimeFormatter dateFormatXML = DateTimeFormat . forPattern ( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ) ; final String scanDate = dateFormat . print ( dt ) ; final String scanDateXML = dateFormatXML . print ( dt ) ; final VelocityContext ctxt = new VelocityContext ( ) ; ctxt . put ( "applicationName" , applicationName ) ; ctxt . put ( "dependencies" , dependencies ) ; ctxt . put ( "analyzers" , analyzers ) ; ctxt . put ( "properties" , properties ) ; ctxt . put ( "scanDate" , scanDate ) ; ctxt . put ( "scanDateXML" , scanDateXML ) ; ctxt . put ( "enc" , new EscapeTool ( ) ) ; ctxt . put ( "rpt" , new ReportTool ( ) ) ; ctxt . put ( "WordUtils" , new WordUtils ( ) ) ; ctxt . put ( "VENDOR" , EvidenceType . VENDOR ) ; ctxt . put ( "PRODUCT" , EvidenceType . PRODUCT ) ; ctxt . put ( "VERSION" , EvidenceType . VERSION ) ; ctxt . put ( "version" , settings . getString ( Settings . KEYS . APPLICATION_VERSION , "Unknown" ) ) ; return ctxt ; } | Constructs the velocity context used to generate the dependency - check reports . |
11,438 | public void write ( String outputLocation , String format ) throws ReportException { Format reportFormat = null ; try { reportFormat = Format . valueOf ( format . toUpperCase ( ) ) ; } catch ( IllegalArgumentException ex ) { LOGGER . trace ( "ignore this exception" , ex ) ; } if ( reportFormat != null ) { write ( outputLocation , reportFormat ) ; } else { final File out = getReportFile ( outputLocation , null ) ; if ( out . isDirectory ( ) ) { throw new ReportException ( "Unable to write non-standard VSL output to a directory, please specify a file name" ) ; } processTemplate ( format , out ) ; } } | Writes the dependency - check report to the given output location . |
11,439 | protected File getReportFile ( String outputLocation , Format format ) { File outFile = new File ( outputLocation ) ; if ( outFile . getParentFile ( ) == null ) { outFile = new File ( "." , outputLocation ) ; } final String pathToCheck = outputLocation . toLowerCase ( ) ; if ( format == Format . XML && ! pathToCheck . endsWith ( ".xml" ) ) { return new File ( outFile , "dependency-check-report.xml" ) ; } if ( format == Format . HTML && ! pathToCheck . endsWith ( ".html" ) && ! pathToCheck . endsWith ( ".htm" ) ) { return new File ( outFile , "dependency-check-report.html" ) ; } if ( format == Format . JSON && ! pathToCheck . endsWith ( ".json" ) ) { return new File ( outFile , "dependency-check-report.json" ) ; } if ( format == Format . CSV && ! pathToCheck . endsWith ( ".csv" ) ) { return new File ( outFile , "dependency-check-report.csv" ) ; } if ( format == Format . JUNIT && ! pathToCheck . endsWith ( ".xml" ) ) { return new File ( outFile , "dependency-check-junit.xml" ) ; } return outFile ; } | Determines the report file name based on the give output location and format . If the output location contains a full file name that has the correct extension for the given report type then the output location is returned . However if the output location is a directory this method will generate the correct name for the given output format . |
11,440 | private void ensureParentDirectoryExists ( File file ) throws ReportException { if ( ! file . getParentFile ( ) . exists ( ) ) { final boolean created = file . getParentFile ( ) . mkdirs ( ) ; if ( ! created ) { final String msg = String . format ( "Unable to create directory '%s'." , file . getParentFile ( ) . getAbsolutePath ( ) ) ; throw new ReportException ( msg ) ; } } } | Validates that the given file s parent directory exists . If the directory does not exist an attempt to create the necessary path is made ; if that fails a ReportException will be raised . |
11,441 | private void pretifyJson ( String pathToJson ) throws ReportException { final String outputPath = pathToJson + ".pretty" ; final File in = new File ( pathToJson ) ; final File out = new File ( outputPath ) ; try ( JsonReader reader = new JsonReader ( new InputStreamReader ( new FileInputStream ( in ) , StandardCharsets . UTF_8 ) ) ; JsonWriter writer = new JsonWriter ( new OutputStreamWriter ( new FileOutputStream ( out ) , StandardCharsets . UTF_8 ) ) ) { prettyPrint ( reader , writer ) ; } catch ( IOException ex ) { LOGGER . debug ( "Malformed JSON?" , ex ) ; throw new ReportException ( "Unable to generate json report" , ex ) ; } if ( out . isFile ( ) && in . isFile ( ) && in . delete ( ) ) { try { org . apache . commons . io . FileUtils . moveFile ( out , in ) ; } catch ( IOException ex ) { LOGGER . error ( "Unable to generate pretty report, caused by: {}" , ex . getMessage ( ) ) ; } } } | Reformats the given JSON file . |
11,442 | private static void prettyPrint ( JsonReader reader , JsonWriter writer ) throws IOException { writer . setIndent ( " " ) ; while ( true ) { final JsonToken token = reader . peek ( ) ; switch ( token ) { case BEGIN_ARRAY : reader . beginArray ( ) ; writer . beginArray ( ) ; break ; case END_ARRAY : reader . endArray ( ) ; writer . endArray ( ) ; break ; case BEGIN_OBJECT : reader . beginObject ( ) ; writer . beginObject ( ) ; break ; case END_OBJECT : reader . endObject ( ) ; writer . endObject ( ) ; break ; case NAME : final String name = reader . nextName ( ) ; writer . name ( name ) ; break ; case STRING : final String s = reader . nextString ( ) ; writer . value ( s ) ; break ; case NUMBER : final String n = reader . nextString ( ) ; writer . value ( new BigDecimal ( n ) ) ; break ; case BOOLEAN : final boolean b = reader . nextBoolean ( ) ; writer . value ( b ) ; break ; case NULL : reader . nextNull ( ) ; writer . nullValue ( ) ; break ; case END_DOCUMENT : return ; default : LOGGER . debug ( "Unexpected JSON toekn {}" , token . toString ( ) ) ; break ; } } } | Streams from a json reader to a json writer and performs pretty printing . |
11,443 | private Process launchBundleAudit ( File folder ) throws AnalysisException { if ( ! folder . isDirectory ( ) ) { throw new AnalysisException ( String . format ( "%s should have been a directory." , folder . getAbsolutePath ( ) ) ) ; } final List < String > args = new ArrayList < > ( ) ; final String bundleAuditPath = getSettings ( ) . getString ( Settings . KEYS . ANALYZER_BUNDLE_AUDIT_PATH ) ; File bundleAudit = null ; if ( bundleAuditPath != null ) { bundleAudit = new File ( bundleAuditPath ) ; if ( ! bundleAudit . isFile ( ) ) { LOGGER . warn ( "Supplied `bundleAudit` path is incorrect: {}" , bundleAuditPath ) ; bundleAudit = null ; } } args . add ( bundleAudit != null && bundleAudit . isFile ( ) ? bundleAudit . getAbsolutePath ( ) : "bundle-audit" ) ; args . add ( "check" ) ; args . add ( "--verbose" ) ; final ProcessBuilder builder = new ProcessBuilder ( args ) ; builder . directory ( folder ) ; try { LOGGER . info ( "Launching: {} from {}" , args , folder ) ; return builder . start ( ) ; } catch ( IOException ioe ) { throw new AnalysisException ( "bundle-audit initialization failure; this error can be ignored if you are not analyzing Ruby. " + "Otherwise ensure that bundle-audit is installed and the path to bundle audit is correctly specified" , ioe ) ; } } | Launch bundle - audit . |
11,444 | public void prepareFileTypeAnalyzer ( Engine engine ) throws InitializationException { if ( engine != null ) { this . cvedb = engine . getDatabase ( ) ; } Process process = null ; try { process = launchBundleAudit ( getSettings ( ) . getTempDirectory ( ) ) ; } catch ( AnalysisException ae ) { setEnabled ( false ) ; final String msg = String . format ( "Exception from bundle-audit process: %s. Disabling %s" , ae . getCause ( ) , ANALYZER_NAME ) ; throw new InitializationException ( msg , ae ) ; } catch ( IOException ex ) { setEnabled ( false ) ; throw new InitializationException ( "Unable to create temporary file, the Ruby Bundle Audit Analyzer will be disabled" , ex ) ; } final int exitValue ; try { exitValue = process . waitFor ( ) ; } catch ( InterruptedException ex ) { setEnabled ( false ) ; final String msg = String . format ( "Bundle-audit process was interrupted. Disabling %s" , ANALYZER_NAME ) ; Thread . currentThread ( ) . interrupt ( ) ; throw new InitializationException ( msg ) ; } if ( 0 == exitValue ) { setEnabled ( false ) ; final String msg = String . format ( "Unexpected exit code from bundle-audit process. Disabling %s: %s" , ANALYZER_NAME , exitValue ) ; throw new InitializationException ( msg ) ; } else { try ( BufferedReader reader = new BufferedReader ( new InputStreamReader ( process . getErrorStream ( ) , StandardCharsets . UTF_8 ) ) ) { if ( ! reader . ready ( ) ) { LOGGER . warn ( "Bundle-audit error stream unexpectedly not ready. Disabling {}" , ANALYZER_NAME ) ; setEnabled ( false ) ; throw new InitializationException ( "Bundle-audit error stream unexpectedly not ready." ) ; } else { final String line = reader . readLine ( ) ; if ( line == null || ! line . contains ( "Errno::ENOENT" ) ) { LOGGER . warn ( "Unexpected bundle-audit output. Disabling {}: {}" , ANALYZER_NAME , line ) ; setEnabled ( false ) ; throw new InitializationException ( "Unexpected bundle-audit output." ) ; } } } catch ( UnsupportedEncodingException ex ) { setEnabled ( false ) ; throw new InitializationException ( "Unexpected bundle-audit encoding." , ex ) ; } catch ( IOException ex ) { setEnabled ( false ) ; throw new InitializationException ( "Unable to read bundle-audit output." , ex ) ; } } if ( isEnabled ( ) ) { LOGGER . info ( "{} is enabled. It is necessary to manually run \"bundle-audit update\" " + "occasionally to keep its database up to date." , ANALYZER_NAME ) ; } } | Initialize the analyzer . |
11,445 | protected void analyzeDependency ( Dependency dependency , Engine engine ) throws AnalysisException { if ( needToDisableGemspecAnalyzer ) { boolean failed = true ; final String className = RubyGemspecAnalyzer . class . getName ( ) ; for ( FileTypeAnalyzer analyzer : engine . getFileTypeAnalyzers ( ) ) { if ( analyzer instanceof RubyBundlerAnalyzer ) { ( ( RubyBundlerAnalyzer ) analyzer ) . setEnabled ( false ) ; LOGGER . info ( "Disabled {} to avoid noisy duplicate results." , RubyBundlerAnalyzer . class . getName ( ) ) ; } else if ( analyzer instanceof RubyGemspecAnalyzer ) { ( ( RubyGemspecAnalyzer ) analyzer ) . setEnabled ( false ) ; LOGGER . info ( "Disabled {} to avoid noisy duplicate results." , className ) ; failed = false ; } } if ( failed ) { LOGGER . warn ( "Did not find {}." , className ) ; } needToDisableGemspecAnalyzer = false ; } final File parentFile = dependency . getActualFile ( ) . getParentFile ( ) ; final Process process = launchBundleAudit ( parentFile ) ; final int exitValue ; try { exitValue = process . waitFor ( ) ; } catch ( InterruptedException ie ) { Thread . currentThread ( ) . interrupt ( ) ; throw new AnalysisException ( "bundle-audit process interrupted" , ie ) ; } if ( exitValue < 0 || exitValue > 1 ) { final String msg = String . format ( "Unexpected exit code from bundle-audit process; exit code: %s" , exitValue ) ; throw new AnalysisException ( msg ) ; } try { try ( BufferedReader errReader = new BufferedReader ( new InputStreamReader ( process . getErrorStream ( ) , StandardCharsets . UTF_8 ) ) ) { while ( errReader . ready ( ) ) { final String error = errReader . readLine ( ) ; LOGGER . warn ( error ) ; } } try ( BufferedReader rdr = new BufferedReader ( new InputStreamReader ( process . getInputStream ( ) , StandardCharsets . UTF_8 ) ) ) { processBundlerAuditOutput ( dependency , engine , rdr ) ; } } catch ( IOException | CpeValidationException ioe ) { LOGGER . warn ( "bundle-audit failure" , ioe ) ; } } | Determines if the analyzer can analyze the given file type . |
11,446 | private void processBundlerAuditOutput ( Dependency original , Engine engine , BufferedReader rdr ) throws IOException , CpeValidationException { final String parentName = original . getActualFile ( ) . getParentFile ( ) . getName ( ) ; final String fileName = original . getFileName ( ) ; final String filePath = original . getFilePath ( ) ; Dependency dependency = null ; Vulnerability vulnerability = null ; String gem = null ; final Map < String , Dependency > map = new HashMap < > ( ) ; boolean appendToDescription = false ; while ( rdr . ready ( ) ) { final String nextLine = rdr . readLine ( ) ; if ( null == nextLine ) { break ; } else if ( nextLine . startsWith ( NAME ) ) { appendToDescription = false ; gem = nextLine . substring ( NAME . length ( ) ) ; if ( ! map . containsKey ( gem ) ) { map . put ( gem , createDependencyForGem ( engine , parentName , fileName , filePath , gem ) ) ; } dependency = map . get ( gem ) ; LOGGER . debug ( "bundle-audit ({}): {}" , parentName , nextLine ) ; } else if ( nextLine . startsWith ( VERSION ) ) { vulnerability = createVulnerability ( parentName , dependency , gem , nextLine ) ; } else if ( nextLine . startsWith ( ADVISORY ) ) { setVulnerabilityName ( parentName , dependency , vulnerability , nextLine ) ; } else if ( nextLine . startsWith ( CRITICALITY ) ) { addCriticalityToVulnerability ( parentName , vulnerability , nextLine ) ; } else if ( nextLine . startsWith ( "URL: " ) ) { addReferenceToVulnerability ( parentName , vulnerability , nextLine ) ; } else if ( nextLine . startsWith ( "Description:" ) ) { appendToDescription = true ; if ( null != vulnerability ) { vulnerability . setDescription ( "*** Vulnerability obtained from bundle-audit verbose report. " + "Title link may not work. CPE below is guessed. CVSS score is estimated (-1.0 " + " indicates unknown). See link below for full details. *** " ) ; } } else if ( appendToDescription && null != vulnerability ) { vulnerability . setDescription ( vulnerability . getDescription ( ) + nextLine + "\n" ) ; } } } | Processes the bundler audit output . |
11,447 | private void setVulnerabilityName ( String parentName , Dependency dependency , Vulnerability vulnerability , String nextLine ) { final String advisory = nextLine . substring ( ADVISORY . length ( ) ) ; if ( null != vulnerability ) { vulnerability . setName ( advisory ) ; } if ( null != dependency ) { dependency . addVulnerability ( vulnerability ) ; } LOGGER . debug ( "bundle-audit ({}): {}" , parentName , nextLine ) ; } | Sets the vulnerability name . |
11,448 | private void addReferenceToVulnerability ( String parentName , Vulnerability vulnerability , String nextLine ) { final String url = nextLine . substring ( "URL: " . length ( ) ) ; if ( null != vulnerability ) { final Reference ref = new Reference ( ) ; ref . setName ( vulnerability . getName ( ) ) ; ref . setSource ( "bundle-audit" ) ; ref . setUrl ( url ) ; vulnerability . getReferences ( ) . add ( ref ) ; } LOGGER . debug ( "bundle-audit ({}): {}" , parentName , nextLine ) ; } | Adds a reference to the vulnerability . |
11,449 | private void addCriticalityToVulnerability ( String parentName , Vulnerability vulnerability , String nextLine ) { if ( null != vulnerability ) { final String criticality = nextLine . substring ( CRITICALITY . length ( ) ) . trim ( ) ; float score = - 1.0f ; Vulnerability v = null ; if ( cvedb != null ) { try { v = cvedb . getVulnerability ( vulnerability . getName ( ) ) ; } catch ( DatabaseException ex ) { LOGGER . debug ( "Unable to look up vulnerability {}" , vulnerability . getName ( ) ) ; } } if ( v != null && ( v . getCvssV2 ( ) != null || v . getCvssV3 ( ) != null ) ) { if ( v . getCvssV2 ( ) != null ) { vulnerability . setCvssV2 ( v . getCvssV2 ( ) ) ; } if ( v . getCvssV3 ( ) != null ) { vulnerability . setCvssV3 ( v . getCvssV3 ( ) ) ; } } else { if ( "High" . equalsIgnoreCase ( criticality ) ) { score = 8.5f ; } else if ( "Medium" . equalsIgnoreCase ( criticality ) ) { score = 5.5f ; } else if ( "Low" . equalsIgnoreCase ( criticality ) ) { score = 2.0f ; } vulnerability . setCvssV2 ( new CvssV2 ( score , "-" , "-" , "-" , "-" , "-" , "-" , criticality ) ) ; } } LOGGER . debug ( "bundle-audit ({}): {}" , parentName , nextLine ) ; } | Adds the criticality to the vulnerability |
11,450 | private Vulnerability createVulnerability ( String parentName , Dependency dependency , String gem , String nextLine ) throws CpeValidationException { Vulnerability vulnerability = null ; if ( null != dependency ) { final String version = nextLine . substring ( VERSION . length ( ) ) ; dependency . addEvidence ( EvidenceType . VERSION , "bundler-audit" , "Version" , version , Confidence . HIGHEST ) ; dependency . setVersion ( version ) ; dependency . setName ( gem ) ; try { final PackageURL purl = PackageURLBuilder . aPackageURL ( ) . withType ( "gem" ) . withName ( dependency . getName ( ) ) . withVersion ( dependency . getVersion ( ) ) . build ( ) ; dependency . addSoftwareIdentifier ( new PurlIdentifier ( purl , Confidence . HIGHEST ) ) ; } catch ( MalformedPackageURLException ex ) { LOGGER . debug ( "Unable to build package url for python" , ex ) ; final GenericIdentifier id = new GenericIdentifier ( "gem:" + dependency . getName ( ) + "@" + dependency . getVersion ( ) , Confidence . HIGHEST ) ; dependency . addSoftwareIdentifier ( id ) ; } vulnerability = new Vulnerability ( ) ; final VulnerableSoftwareBuilder builder = new VulnerableSoftwareBuilder ( ) ; final VulnerableSoftware vs = builder . part ( Part . APPLICATION ) . vendor ( gem ) . product ( String . format ( "%s_project" , gem ) ) . version ( version ) . build ( ) ; vulnerability . addVulnerableSoftware ( vs ) ; vulnerability . setMatchedVulnerableSoftware ( vs ) ; vulnerability . setCvssV2 ( new CvssV2 ( - 1 , "-" , "-" , "-" , "-" , "-" , "-" , "unknown" ) ) ; } LOGGER . debug ( "bundle-audit ({}): {}" , parentName , nextLine ) ; return vulnerability ; } | Creates a vulnerability . |
11,451 | private Dependency createDependencyForGem ( Engine engine , String parentName , String fileName , String filePath , String gem ) throws IOException { final File gemFile ; try { gemFile = File . createTempFile ( gem , "_Gemfile.lock" , getSettings ( ) . getTempDirectory ( ) ) ; } catch ( IOException ioe ) { throw new IOException ( "Unable to create temporary gem file" ) ; } final String displayFileName = String . format ( "%s%c%s:%s" , parentName , File . separatorChar , fileName , gem ) ; FileUtils . write ( gemFile , displayFileName , Charset . defaultCharset ( ) ) ; final Dependency dependency = new Dependency ( gemFile ) ; dependency . setEcosystem ( DEPENDENCY_ECOSYSTEM ) ; dependency . addEvidence ( EvidenceType . PRODUCT , "bundler-audit" , "Name" , gem , Confidence . HIGHEST ) ; dependency . setDisplayFileName ( displayFileName ) ; dependency . setFileName ( fileName ) ; dependency . setFilePath ( filePath ) ; engine . addDependency ( dependency ) ; return dependency ; } | Creates the dependency based off of the gem . |
11,452 | @ SuppressFBWarnings ( justification = "try with resources will clean up the input stream" , value = { "OBL_UNSATISFIED_OBLIGATION" } ) public void parseHints ( File file ) throws HintParseException { try ( InputStream fis = new FileInputStream ( file ) ) { parseHints ( fis ) ; } catch ( SAXException | IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new HintParseException ( ex ) ; } } | Parses the given XML file and returns a list of the hints contained . |
11,453 | public void parseHints ( InputStream inputStream ) throws HintParseException , SAXException { try ( InputStream schemaStream13 = FileUtils . getResourceAsStream ( HINT_SCHEMA_1_3 ) ; InputStream schemaStream12 = FileUtils . getResourceAsStream ( HINT_SCHEMA_1_2 ) ; InputStream schemaStream11 = FileUtils . getResourceAsStream ( HINT_SCHEMA_1_1 ) ; ) { final HintHandler handler = new HintHandler ( ) ; final SAXParser saxParser = XmlUtils . buildSecureSaxParser ( schemaStream13 , schemaStream12 , schemaStream11 ) ; final XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setErrorHandler ( new HintErrorHandler ( ) ) ; xmlReader . setContentHandler ( handler ) ; try ( Reader reader = new InputStreamReader ( inputStream , StandardCharsets . UTF_8 ) ) { final InputSource in = new InputSource ( reader ) ; xmlReader . parse ( in ) ; this . hintRules = handler . getHintRules ( ) ; this . vendorDuplicatingHintRules = handler . getVendorDuplicatingHintRules ( ) ; } } catch ( ParserConfigurationException | FileNotFoundException ex ) { LOGGER . debug ( "" , ex ) ; throw new HintParseException ( ex ) ; } catch ( SAXException ex ) { if ( ex . getMessage ( ) . contains ( "Cannot find the declaration of element 'hints'." ) ) { throw ex ; } else { LOGGER . debug ( "" , ex ) ; throw new HintParseException ( ex ) ; } } catch ( IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new HintParseException ( ex ) ; } } | Parses the given XML stream and returns a list of the hint rules contained . |
11,454 | protected void reset ( ) { super . reset ( ) ; versionEndExcluding = null ; versionEndIncluding = null ; versionStartExcluding = null ; versionStartIncluding = null ; vulnerable = true ; } | Resets the Vulnerable Software Builder to a clean state . |
11,455 | public VulnerableSoftwareBuilder cpe ( Cpe cpe ) { this . part ( cpe . getPart ( ) ) . wfVendor ( cpe . getWellFormedVendor ( ) ) . wfProduct ( cpe . getWellFormedProduct ( ) ) . wfVersion ( cpe . getWellFormedVersion ( ) ) . wfUpdate ( cpe . getWellFormedUpdate ( ) ) . wfEdition ( cpe . getWellFormedEdition ( ) ) . wfLanguage ( cpe . getWellFormedLanguage ( ) ) . wfSwEdition ( cpe . getWellFormedSwEdition ( ) ) . wfTargetSw ( cpe . getWellFormedTargetSw ( ) ) . wfTargetHw ( cpe . getWellFormedTargetHw ( ) ) . wfOther ( cpe . getWellFormedOther ( ) ) ; return this ; } | Adds a base CPE object to build a vulnerable software object from . |
11,456 | public List < Analyzer > getAnalyzers ( List < AnalysisPhase > phases ) { final List < Analyzer > analyzers = new ArrayList < > ( ) ; final Iterator < Analyzer > iterator = service . iterator ( ) ; boolean experimentalEnabled = false ; boolean retiredEnabled = false ; try { experimentalEnabled = settings . getBoolean ( Settings . KEYS . ANALYZER_EXPERIMENTAL_ENABLED , false ) ; retiredEnabled = settings . getBoolean ( Settings . KEYS . ANALYZER_RETIRED_ENABLED , false ) ; } catch ( InvalidSettingException ex ) { LOGGER . error ( "invalid experimental or retired setting" , ex ) ; } while ( iterator . hasNext ( ) ) { final Analyzer a = iterator . next ( ) ; if ( ! phases . contains ( a . getAnalysisPhase ( ) ) ) { continue ; } if ( ! experimentalEnabled && a . getClass ( ) . isAnnotationPresent ( Experimental . class ) ) { continue ; } if ( ! retiredEnabled && a . getClass ( ) . isAnnotationPresent ( Retired . class ) ) { continue ; } LOGGER . debug ( "Loaded Analyzer {}" , a . getName ( ) ) ; analyzers . add ( a ) ; } return analyzers ; } | Returns a list of all instances of the Analyzer interface that are bound to one of the given phases . |
11,457 | public List < Advisory > parse ( JSONObject jsonResponse ) { LOGGER . debug ( "Parsing JSON node" ) ; final List < Advisory > advisories = new ArrayList < > ( ) ; final JSONObject jsonAdvisories = jsonResponse . getJSONObject ( "advisories" ) ; final Iterator < ? > keys = jsonAdvisories . keys ( ) ; while ( keys . hasNext ( ) ) { final String key = ( String ) keys . next ( ) ; final Advisory advisory = parseAdvisory ( jsonAdvisories . getJSONObject ( key ) ) ; advisories . add ( advisory ) ; } return advisories ; } | Parses the JSON response from the NPM Audit API . |
11,458 | private Advisory parseAdvisory ( JSONObject object ) { final Advisory advisory = new Advisory ( ) ; advisory . setId ( object . getInt ( "id" ) ) ; advisory . setOverview ( object . optString ( "overview" , null ) ) ; advisory . setReferences ( object . optString ( "references" , null ) ) ; advisory . setCreated ( object . optString ( "created" , null ) ) ; advisory . setUpdated ( object . optString ( "updated" , null ) ) ; advisory . setRecommendation ( object . optString ( "recommendation" , null ) ) ; advisory . setTitle ( object . optString ( "title" , null ) ) ; advisory . setModuleName ( object . optString ( "module_name" , null ) ) ; advisory . setVulnerableVersions ( object . optString ( "vulnerable_versions" , null ) ) ; advisory . setPatchedVersions ( object . optString ( "patched_versions" , null ) ) ; advisory . setAccess ( object . optString ( "access" , null ) ) ; advisory . setSeverity ( object . optString ( "severity" , null ) ) ; advisory . setCwe ( object . optString ( "cwe" , null ) ) ; final JSONArray findings = object . optJSONArray ( "findings" ) ; for ( int i = 0 ; i < findings . length ( ) ; i ++ ) { final JSONObject finding = findings . getJSONObject ( i ) ; final String version = finding . optString ( "version" , null ) ; final JSONArray paths = finding . optJSONArray ( "paths" ) ; for ( int j = 0 ; j < paths . length ( ) ; j ++ ) { final String path = paths . getString ( j ) ; if ( path != null && path . equals ( advisory . getModuleName ( ) ) ) { advisory . setVersion ( version ) ; } } } final JSONArray jsonCves = object . optJSONArray ( "cves" ) ; final List < String > stringCves = new ArrayList < > ( ) ; if ( jsonCves != null ) { for ( int j = 0 ; j < jsonCves . length ( ) ; j ++ ) { stringCves . add ( jsonCves . getString ( j ) ) ; } advisory . setCves ( stringCves ) ; } return advisory ; } | Parses the advisory from Node Audit . |
11,459 | public boolean matchesAtLeastThreeLevels ( DependencyVersion version ) { if ( version == null ) { return false ; } if ( Math . abs ( this . versionParts . size ( ) - version . versionParts . size ( ) ) >= 3 ) { return false ; } final int max = ( this . versionParts . size ( ) < version . versionParts . size ( ) ) ? this . versionParts . size ( ) : version . versionParts . size ( ) ; boolean ret = true ; for ( int i = 0 ; i < max ; i ++ ) { final String thisVersion = this . versionParts . get ( i ) ; final String otherVersion = version . getVersionParts ( ) . get ( i ) ; if ( i >= 3 ) { if ( thisVersion . compareToIgnoreCase ( otherVersion ) >= 0 ) { ret = false ; break ; } } else if ( ! thisVersion . equals ( otherVersion ) ) { ret = false ; break ; } } return ret ; } | Determines if the three most major major version parts are identical . For instances if version 1 . 2 . 3 . 4 was compared to 1 . 2 . 3 this function would return true . |
11,460 | @ SuppressFBWarnings ( justification = "try with resource will clenaup the resources" , value = { "OBL_UNSATISFIED_OBLIGATION" } ) public List < SuppressionRule > parseSuppressionRules ( File file ) throws SuppressionParseException { try ( FileInputStream fis = new FileInputStream ( file ) ) { return parseSuppressionRules ( fis ) ; } catch ( SAXException | IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new SuppressionParseException ( ex ) ; } } | Parses the given XML file and returns a list of the suppression rules contained . |
11,461 | public List < SuppressionRule > parseSuppressionRules ( InputStream inputStream ) throws SuppressionParseException , SAXException { try ( InputStream schemaStream12 = FileUtils . getResourceAsStream ( SUPPRESSION_SCHEMA_1_2 ) ; InputStream schemaStream11 = FileUtils . getResourceAsStream ( SUPPRESSION_SCHEMA_1_1 ) ; InputStream schemaStream10 = FileUtils . getResourceAsStream ( SUPPRESSION_SCHEMA_1_0 ) ; ) { final SuppressionHandler handler = new SuppressionHandler ( ) ; final SAXParser saxParser = XmlUtils . buildSecureSaxParser ( schemaStream12 , schemaStream11 , schemaStream10 ) ; final XMLReader xmlReader = saxParser . getXMLReader ( ) ; xmlReader . setErrorHandler ( new SuppressionErrorHandler ( ) ) ; xmlReader . setContentHandler ( handler ) ; try ( Reader reader = new InputStreamReader ( inputStream , StandardCharsets . UTF_8 ) ) { final InputSource in = new InputSource ( reader ) ; xmlReader . parse ( in ) ; return handler . getSuppressionRules ( ) ; } } catch ( ParserConfigurationException | FileNotFoundException ex ) { LOGGER . debug ( "" , ex ) ; throw new SuppressionParseException ( ex ) ; } catch ( SAXException ex ) { if ( ex . getMessage ( ) . contains ( "Cannot find the declaration of element 'suppressions'." ) ) { throw ex ; } else { LOGGER . debug ( "" , ex ) ; throw new SuppressionParseException ( ex ) ; } } catch ( IOException ex ) { LOGGER . debug ( "" , ex ) ; throw new SuppressionParseException ( ex ) ; } } | Parses the given XML stream and returns a list of the suppression rules contained . |
11,462 | public InputStream fetch ( URL url ) throws DownloadFailedException { if ( "file" . equalsIgnoreCase ( url . getProtocol ( ) ) ) { final File file ; try { file = new File ( url . toURI ( ) ) ; } catch ( URISyntaxException ex ) { final String msg = format ( "Download failed, unable to locate '%s'" , url . toString ( ) ) ; throw new DownloadFailedException ( msg ) ; } if ( file . exists ( ) ) { try { return new FileInputStream ( file ) ; } catch ( IOException ex ) { final String msg = format ( "Download failed, unable to rerieve '%s'" , url . toString ( ) ) ; throw new DownloadFailedException ( msg , ex ) ; } } else { final String msg = format ( "Download failed, file ('%s') does not exist" , url . toString ( ) ) ; throw new DownloadFailedException ( msg ) ; } } else { if ( connection != null ) { LOGGER . warn ( "HTTP URL Connection was not properly closed" ) ; connection . disconnect ( ) ; connection = null ; } connection = obtainConnection ( url ) ; final String encoding = connection . getContentEncoding ( ) ; try { if ( encoding != null && "gzip" . equalsIgnoreCase ( encoding ) ) { return new GZIPInputStream ( connection . getInputStream ( ) ) ; } else if ( encoding != null && "deflate" . equalsIgnoreCase ( encoding ) ) { return new InflaterInputStream ( connection . getInputStream ( ) ) ; } else { return connection . getInputStream ( ) ; } } catch ( IOException ex ) { checkForCommonExceptionTypes ( ex ) ; final String msg = format ( "Error retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n" , url . toString ( ) , connection . getConnectTimeout ( ) , encoding ) ; throw new DownloadFailedException ( msg , ex ) ; } catch ( Exception ex ) { final String msg = format ( "Unexpected exception retrieving '%s'%nConnection Timeout: %d%nEncoding: %s%n" , url . toString ( ) , connection . getConnectTimeout ( ) , encoding ) ; throw new DownloadFailedException ( msg , ex ) ; } } } | Retrieves the resource identified by the given URL and returns the InputStream . |
11,463 | private HttpURLConnection obtainConnection ( URL url ) throws DownloadFailedException { HttpURLConnection conn = null ; try { LOGGER . debug ( "Attempting retrieval of {}" , url . toString ( ) ) ; conn = connFactory . createHttpURLConnection ( url , this . usesProxy ) ; conn . setRequestProperty ( "Accept-Encoding" , "gzip, deflate" ) ; conn . connect ( ) ; int status = conn . getResponseCode ( ) ; int redirectCount = 0 ; while ( ( status == HttpURLConnection . HTTP_MOVED_TEMP || status == HttpURLConnection . HTTP_MOVED_PERM || status == HttpURLConnection . HTTP_SEE_OTHER ) && MAX_REDIRECT_ATTEMPTS > redirectCount ++ ) { final String location = conn . getHeaderField ( "Location" ) ; try { conn . disconnect ( ) ; } finally { conn = null ; } LOGGER . debug ( "Download is being redirected from {} to {}" , url . toString ( ) , location ) ; conn = connFactory . createHttpURLConnection ( new URL ( location ) , this . usesProxy ) ; conn . setRequestProperty ( "Accept-Encoding" , "gzip, deflate" ) ; conn . connect ( ) ; status = conn . getResponseCode ( ) ; } if ( status != 200 ) { try { conn . disconnect ( ) ; } finally { conn = null ; } final String msg = format ( "Error retrieving %s; received response code %s." , url . toString ( ) , status ) ; LOGGER . error ( msg ) ; throw new DownloadFailedException ( msg ) ; } } catch ( IOException ex ) { try { if ( conn != null ) { conn . disconnect ( ) ; } } finally { conn = null ; } if ( "Connection reset" . equalsIgnoreCase ( ex . getMessage ( ) ) ) { final String msg = format ( "TLS Connection Reset%nPlease see " + "http://jeremylong.github.io/DependencyCheck/data/tlsfailure.html " + "for more information regarding how to resolve the issue." ) ; LOGGER . error ( msg ) ; throw new DownloadFailedException ( msg , ex ) ; } final String msg = format ( "Error downloading file %s; unable to connect." , url . toString ( ) ) ; throw new DownloadFailedException ( msg , ex ) ; } return conn ; } | Obtains the HTTP URL Connection . |
11,464 | private boolean isQuickQuery ( ) { boolean quickQuery ; try { quickQuery = settings . getBoolean ( Settings . KEYS . DOWNLOADER_QUICK_QUERY_TIMESTAMP , true ) ; } catch ( InvalidSettingException e ) { if ( LOGGER . isTraceEnabled ( ) ) { LOGGER . trace ( "Invalid settings : {}" , e . getMessage ( ) , e ) ; } quickQuery = true ; } return quickQuery ; } | Determines if the HTTP method GET or HEAD should be used to check the timestamp on external resources . |
11,465 | public void checkForCommonExceptionTypes ( IOException ex ) throws DownloadFailedException { Throwable cause = ex ; while ( cause != null ) { if ( cause instanceof java . net . UnknownHostException ) { final String msg = format ( "Unable to resolve domain '%s'" , cause . getMessage ( ) ) ; LOGGER . error ( msg ) ; throw new DownloadFailedException ( msg ) ; } if ( cause instanceof InvalidAlgorithmParameterException ) { final String keystore = System . getProperty ( "javax.net.ssl.keyStore" ) ; final String version = System . getProperty ( "java.version" ) ; final String vendor = System . getProperty ( "java.vendor" ) ; LOGGER . info ( "Error making HTTPS request - InvalidAlgorithmParameterException" ) ; LOGGER . info ( "There appears to be an issue with the installation of Java and the cacerts." + "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177" ) ; LOGGER . info ( "Java Info:\njavax.net.ssl.keyStore='{}'\njava.version='{}'\njava.vendor='{}'" , keystore , version , vendor ) ; throw new DownloadFailedException ( "Error making HTTPS request. Please see the log for more details." ) ; } cause = cause . getCause ( ) ; } } | Analyzes the IOException logs the appropriate information for debugging purposes and then throws a DownloadFailedException that wraps the IO Exception for common IO Exceptions . This is to provide additional details to assist in resolution of the exception . |
11,466 | public void remove ( ) { try { Runtime . getRuntime ( ) . removeShutdownHook ( this ) ; } catch ( IllegalStateException ex ) { LOGGER . trace ( "ignore as we are likely shutting down" , ex ) ; } } | Removes the shutdown hook . |
11,467 | public boolean canGenerateReport ( ) { populateSettings ( ) ; boolean isCapable = false ; for ( Artifact a : getProject ( ) . getArtifacts ( ) ) { if ( ! getArtifactScopeExcluded ( ) . passes ( a . getScope ( ) ) ) { isCapable = true ; break ; } } return isCapable ; } | Returns whether or not a the report can be generated . |
11,468 | private void skipToProject ( ) throws IOException { final byte [ ] buffer = new byte [ BUFFER_SIZE ] ; super . mark ( BUFFER_SIZE ) ; int count = super . read ( buffer , 0 , BUFFER_SIZE ) ; while ( count > 0 ) { final int pos = findSequence ( PROJECT , buffer ) ; if ( pos >= 0 ) { super . reset ( ) ; super . skip ( pos ) ; return ; } else if ( count - PROJECT . length == 0 ) { return ; } super . reset ( ) ; super . skip ( count - PROJECT . length ) ; super . mark ( BUFFER_SIZE ) ; count = super . read ( buffer , 0 , BUFFER_SIZE ) ; } } | Skips bytes from the input stream until it finds the < ; project> ; element . |
11,469 | protected static int findSequence ( byte [ ] sequence , byte [ ] buffer ) { int pos = - 1 ; for ( int i = 0 ; i < buffer . length - sequence . length + 1 ; i ++ ) { if ( buffer [ i ] == sequence [ 0 ] && testRemaining ( sequence , buffer , i ) ) { pos = i ; break ; } } return pos ; } | Finds the start of the given sequence in the buffer . If not found - 1 is returned . |
11,470 | public void addGivenProduct ( String source , String name , String value , boolean regex , Confidence confidence ) { givenProduct . add ( new EvidenceMatcher ( source , name , value , regex , confidence ) ) ; } | Adds a given product to the list of evidence to matched . |
11,471 | public void addGivenVendor ( String source , String name , String value , boolean regex , Confidence confidence ) { givenVendor . add ( new EvidenceMatcher ( source , name , value , regex , confidence ) ) ; } | Adds a given vendors to the list of evidence to matched . |
11,472 | public void addAddProduct ( String source , String name , String value , Confidence confidence ) { addProduct . add ( new Evidence ( source , name , value , confidence ) ) ; } | Adds a given product to the list of evidence to add when matched . |
11,473 | public void addAddVersion ( String source , String name , String value , Confidence confidence ) { addVersion . add ( new Evidence ( source , name , value , confidence ) ) ; } | Adds a given version to the list of evidence to add when matched . |
11,474 | public void addAddVendor ( String source , String name , String value , Confidence confidence ) { addVendor . add ( new Evidence ( source , name , value , confidence ) ) ; } | Adds a given vendor to the list of evidence to add when matched . |
11,475 | public void addRemoveVendor ( String source , String name , String value , boolean regex , Confidence confidence ) { removeVendor . add ( new EvidenceMatcher ( source , name , value , regex , confidence ) ) ; } | Adds a given vendor to the list of evidence to remove when matched . |
11,476 | public void addRemoveProduct ( String source , String name , String value , boolean regex , Confidence confidence ) { removeProduct . add ( new EvidenceMatcher ( source , name , value , regex , confidence ) ) ; } | Adds a given product to the list of evidence to remove when matched . |
11,477 | public void addRemoveVersion ( String source , String name , String value , boolean regex , Confidence confidence ) { removeVersion . add ( new EvidenceMatcher ( source , name , value , regex , confidence ) ) ; } | Adds a given version to the list of evidence to remove when matched . |
11,478 | public void addGivenVersion ( String source , String name , String value , boolean regex , Confidence confidence ) { givenVersion . add ( new EvidenceMatcher ( source , name , value , regex , confidence ) ) ; } | Adds a given version to the list of evidence to match . |
11,479 | public static void extractFiles ( File archive , File extractTo , Engine engine ) throws ExtractionException { if ( archive == null || extractTo == null ) { return ; } final String destPath ; try { destPath = extractTo . getCanonicalPath ( ) ; } catch ( IOException ex ) { throw new ExtractionException ( "Unable to extract files to destination path" , ex ) ; } ZipEntry entry ; try ( FileInputStream fis = new FileInputStream ( archive ) ; BufferedInputStream bis = new BufferedInputStream ( fis ) ; ZipInputStream zis = new ZipInputStream ( bis ) ) { while ( ( entry = zis . getNextEntry ( ) ) != null ) { if ( entry . isDirectory ( ) ) { final File d = new File ( extractTo , entry . getName ( ) ) ; if ( ! d . getCanonicalPath ( ) . startsWith ( destPath ) ) { final String msg = String . format ( "Archive (%s) contains a path that would be extracted outside of the target directory." , archive . getAbsolutePath ( ) ) ; throw new ExtractionException ( msg ) ; } if ( ! d . exists ( ) && ! d . mkdirs ( ) ) { final String msg = String . format ( "Unable to create '%s'." , d . getAbsolutePath ( ) ) ; throw new ExtractionException ( msg ) ; } } else { final File file = new File ( extractTo , entry . getName ( ) ) ; if ( engine == null || engine . accept ( file ) ) { if ( ! file . getCanonicalPath ( ) . startsWith ( destPath ) ) { final String msg = String . format ( "Archive (%s) contains a file that would be extracted outside of the target directory." , archive . getAbsolutePath ( ) ) ; throw new ExtractionException ( msg ) ; } try ( FileOutputStream fos = new FileOutputStream ( file ) ) { IOUtils . copy ( zis , fos ) ; } catch ( FileNotFoundException ex ) { LOGGER . debug ( "" , ex ) ; final String msg = String . format ( "Unable to find file '%s'." , file . getName ( ) ) ; throw new ExtractionException ( msg , ex ) ; } catch ( IOException ex ) { LOGGER . debug ( "" , ex ) ; final String msg = String . format ( "IO Exception while parsing file '%s'." , file . getName ( ) ) ; throw new ExtractionException ( msg , ex ) ; } } } } } catch ( IOException ex ) { final String msg = String . format ( "Exception reading archive '%s'." , archive . getName ( ) ) ; LOGGER . debug ( "" , ex ) ; throw new ExtractionException ( msg , ex ) ; } } | Extracts the contents of an archive into the specified directory . The files are only extracted if they are supported by the analyzers loaded into the specified engine . If the engine is specified as null then all files are extracted . |
11,480 | private static void extractArchive ( ArchiveInputStream input , File destination , FilenameFilter filter ) throws ArchiveExtractionException { ArchiveEntry entry ; try { final String destPath = destination . getCanonicalPath ( ) ; while ( ( entry = input . getNextEntry ( ) ) != null ) { if ( entry . isDirectory ( ) ) { final File dir = new File ( destination , entry . getName ( ) ) ; if ( ! dir . getCanonicalPath ( ) . startsWith ( destPath ) ) { final String msg = String . format ( "Archive contains a path (%s) that would be extracted outside of the target directory." , dir . getAbsolutePath ( ) ) ; throw new AnalysisException ( msg ) ; } if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) { final String msg = String . format ( "Unable to create directory '%s'." , dir . getAbsolutePath ( ) ) ; throw new AnalysisException ( msg ) ; } } else { extractFile ( input , destination , filter , entry ) ; } } } catch ( IOException | AnalysisException ex ) { throw new ArchiveExtractionException ( ex ) ; } finally { FileUtils . close ( input ) ; } } | Extracts files from an archive . |
11,481 | private static void createParentFile ( final File file ) throws ExtractionException { final File parent = file . getParentFile ( ) ; if ( ! parent . isDirectory ( ) && ! parent . mkdirs ( ) ) { final String msg = String . format ( "Unable to build directory '%s'." , parent . getAbsolutePath ( ) ) ; throw new ExtractionException ( msg ) ; } } | Ensures the parent path is correctly created on disk so that the file can be extracted to the correct location . |
11,482 | public static void extractGzip ( File file ) throws FileNotFoundException , IOException { final String originalPath = file . getPath ( ) ; final File gzip = new File ( originalPath + ".gz" ) ; if ( gzip . isFile ( ) && ! gzip . delete ( ) ) { LOGGER . debug ( "Failed to delete initial temporary file when extracting 'gz' {}" , gzip . toString ( ) ) ; gzip . deleteOnExit ( ) ; } if ( ! file . renameTo ( gzip ) ) { throw new IOException ( "Unable to rename '" + file . getPath ( ) + "'" ) ; } final File newFile = new File ( originalPath ) ; try ( FileInputStream fis = new FileInputStream ( gzip ) ; GZIPInputStream cin = new GZIPInputStream ( fis ) ; FileOutputStream out = new FileOutputStream ( newFile ) ) { IOUtils . copy ( cin , out ) ; } finally { if ( gzip . isFile ( ) && ! org . apache . commons . io . FileUtils . deleteQuietly ( gzip ) ) { LOGGER . debug ( "Failed to delete temporary file when extracting 'gz' {}" , gzip . toString ( ) ) ; gzip . deleteOnExit ( ) ; } } } | Extracts the file contained in a gzip archive . The extracted file is placed in the exact same path as the file specified . |
11,483 | public static void extractZip ( File file ) throws FileNotFoundException , IOException { final String originalPath = file . getPath ( ) ; final File zip = new File ( originalPath + ".zip" ) ; if ( zip . isFile ( ) && ! zip . delete ( ) ) { LOGGER . debug ( "Failed to delete initial temporary file when extracting 'zip' {}" , zip . toString ( ) ) ; zip . deleteOnExit ( ) ; } if ( ! file . renameTo ( zip ) ) { throw new IOException ( "Unable to rename '" + file . getPath ( ) + "'" ) ; } final File newFile = new File ( originalPath ) ; try ( FileInputStream fis = new FileInputStream ( zip ) ; ZipInputStream cin = new ZipInputStream ( fis ) ; FileOutputStream out = new FileOutputStream ( newFile ) ) { cin . getNextEntry ( ) ; IOUtils . copy ( cin , out ) ; } finally { if ( zip . isFile ( ) && ! org . apache . commons . io . FileUtils . deleteQuietly ( zip ) ) { LOGGER . debug ( "Failed to delete temporary file when extracting 'zip' {}" , zip . toString ( ) ) ; zip . deleteOnExit ( ) ; } } } | Extracts the file contained in a Zip archive . The extracted file is placed in the exact same path as the file specified . |
11,484 | public List < NugetPackageReference > parse ( InputStream stream ) throws MSBuildProjectParseException { try { final DocumentBuilder db = XmlUtils . buildSecureDocumentBuilder ( ) ; final Document d = db . parse ( stream ) ; final XPath xpath = XPathFactory . newInstance ( ) . newXPath ( ) ; final List < NugetPackageReference > packages = new ArrayList < > ( ) ; final NodeList nodeList = ( NodeList ) xpath . evaluate ( "//PackageReference" , d , XPathConstants . NODESET ) ; if ( nodeList == null ) { throw new MSBuildProjectParseException ( "Unable to parse MSBuild project file" ) ; } for ( int i = 0 ; i < nodeList . getLength ( ) ; i ++ ) { final Node node = nodeList . item ( i ) ; final NamedNodeMap attrs = node . getAttributes ( ) ; final Node include = attrs . getNamedItem ( "Include" ) ; final Node version = attrs . getNamedItem ( "Version" ) ; if ( include != null && version != null ) { final NugetPackageReference npr = new NugetPackageReference ( ) ; npr . setId ( include . getNodeValue ( ) ) ; npr . setVersion ( version . getNodeValue ( ) ) ; packages . add ( npr ) ; } } return packages ; } catch ( ParserConfigurationException | SAXException | IOException | XPathExpressionException | MSBuildProjectParseException e ) { throw new MSBuildProjectParseException ( "Unable to parse MSBuild project file" , e ) ; } } | Parses the given stream for MSBuild PackageReference elements . |
11,485 | protected static String getOpenSSLVersion ( long openSSLVersionConstant ) { final long major = openSSLVersionConstant >>> MAJOR_OFFSET ; final long minor = ( openSSLVersionConstant & MINOR_MASK ) >>> MINOR_OFFSET ; final long fix = ( openSSLVersionConstant & FIX_MASK ) >>> FIX_OFFSET ; final long patchLevel = ( openSSLVersionConstant & PATCH_MASK ) >>> PATCH_OFFSET ; final String patch = 0 == patchLevel || patchLevel > NUM_LETTERS ? "" : String . valueOf ( ( char ) ( patchLevel + 'a' - 1 ) ) ; final int statusCode = ( int ) ( openSSLVersionConstant & STATUS_MASK ) ; final String status = 0xf == statusCode ? "" : ( 0 == statusCode ? "-dev" : "-beta" + statusCode ) ; return String . format ( "%d.%d.%d%s%s" , major , minor , fix , patch , status ) ; } | Returns the open SSL version as a string . |
11,486 | private String getFileContents ( final File actualFile ) throws AnalysisException { try { return FileUtils . readFileToString ( actualFile , Charset . defaultCharset ( ) ) . trim ( ) ; } catch ( IOException e ) { throw new AnalysisException ( "Problem occurred while reading dependency file." , e ) ; } } | Retrieves the contents of a given file . |
11,487 | public boolean preflightRequest ( ) { final HttpURLConnection conn ; try { final URL url = new URL ( rootURL , "status" ) ; final URLConnectionFactory factory = new URLConnectionFactory ( settings ) ; conn = factory . createHttpURLConnection ( url , useProxy ) ; conn . addRequestProperty ( "Accept" , "application/xml" ) ; final String authHeader = buildHttpAuthHeaderValue ( ) ; if ( ! authHeader . isEmpty ( ) ) { conn . addRequestProperty ( "Authorization" , authHeader ) ; } conn . connect ( ) ; if ( conn . getResponseCode ( ) != 200 ) { LOGGER . warn ( "Expected 200 result from Nexus, got {}" , conn . getResponseCode ( ) ) ; return false ; } final DocumentBuilder builder = XmlUtils . buildSecureDocumentBuilder ( ) ; final Document doc = builder . parse ( conn . getInputStream ( ) ) ; if ( ! "status" . equals ( doc . getDocumentElement ( ) . getNodeName ( ) ) ) { LOGGER . warn ( "Expected root node name of status, got {}" , doc . getDocumentElement ( ) . getNodeName ( ) ) ; return false ; } } catch ( IOException | ParserConfigurationException | SAXException e ) { return false ; } return true ; } | Do a preflight request to see if the repository is actually working . |
11,488 | private String buildHttpAuthHeaderValue ( ) { final String user = settings . getString ( Settings . KEYS . ANALYZER_NEXUS_USER , "" ) ; final String pass = settings . getString ( Settings . KEYS . ANALYZER_NEXUS_PASSWORD , "" ) ; String result = "" ; if ( user . isEmpty ( ) || pass . isEmpty ( ) ) { LOGGER . debug ( "Skip authentication as user and/or password for nexus is empty" ) ; } else { final String auth = user + ':' + pass ; final String base64Auth = Base64 . getEncoder ( ) . encodeToString ( auth . getBytes ( StandardCharsets . UTF_8 ) ) ; result = new StringBuilder ( "Basic " ) . append ( base64Auth ) . toString ( ) ; } return result ; } | Constructs the base64 encoded basic authentication header value . |
11,489 | private PackageUrl parsePackageUrl ( final String value ) { try { return PackageUrl . parse ( value ) ; } catch ( PackageUrl . InvalidException e ) { log . warn ( "Invalid Package-URL: {}" , value , e ) ; return null ; } } | Helper to complain if unable to parse Package - URL . |
11,490 | private Map < PackageUrl , ComponentReport > requestReports ( final Dependency [ ] dependencies ) throws Exception { log . debug ( "Requesting component-reports for {} dependencies" , dependencies . length ) ; List < PackageUrl > packages = new ArrayList < > ( ) ; for ( Dependency dependency : dependencies ) { for ( Identifier id : dependency . getSoftwareIdentifiers ( ) ) { if ( id instanceof PurlIdentifier ) { PackageUrl purl = parsePackageUrl ( id . getValue ( ) ) ; if ( purl != null ) { packages . add ( purl ) ; } } } } if ( ! packages . isEmpty ( ) ) { return client . requestComponentReports ( packages ) ; } log . warn ( "Unable to determine Package-URL identifiers for {} dependencies" , dependencies . length ) ; return Collections . emptyMap ( ) ; } | Batch request component - reports for all dependencies . |
11,491 | private void enrich ( final Dependency dependency ) { log . debug ( "Enrich dependency: {}" , dependency ) ; for ( Identifier id : dependency . getSoftwareIdentifiers ( ) ) { if ( id instanceof PurlIdentifier ) { log . debug ( " Package: {} -> {}" , id , id . getConfidence ( ) ) ; PackageUrl purl = parsePackageUrl ( id . getValue ( ) ) ; if ( purl != null ) { try { ComponentReport report = reports . get ( purl ) ; if ( report == null ) { throw new IllegalStateException ( "Missing component-report for: " + purl ) ; } id . setUrl ( report . getReference ( ) . toString ( ) ) ; for ( ComponentReportVulnerability vuln : report . getVulnerabilities ( ) ) { Vulnerability v = transform ( report , vuln ) ; Vulnerability existing = dependency . getVulnerabilities ( ) . stream ( ) . filter ( e -> e . getName ( ) . equals ( v . getName ( ) ) ) . findFirst ( ) . orElse ( null ) ; if ( existing != null ) { existing . getReferences ( ) . addAll ( v . getReferences ( ) ) ; } else { dependency . addVulnerability ( v ) ; } } } catch ( Exception e ) { log . warn ( "Failed to fetch component-report for: {}" , purl , e ) ; } } } } } | Attempt to enrich given dependency with vulnerability details from OSS Index component - report . |
11,492 | private void calculateChecksums ( File file ) { try { this . md5sum = Checksum . getMD5Checksum ( file ) ; this . sha1sum = Checksum . getSHA1Checksum ( file ) ; this . sha256sum = Checksum . getSHA256Checksum ( file ) ; } catch ( NoSuchAlgorithmException | IOException ex ) { LOGGER . debug ( String . format ( "Unable to calculate checksums on %s" , file ) , ex ) ; } } | Calculates the checksums for the given file . |
11,493 | public void setActualFilePath ( String actualFilePath ) { this . actualFilePath = actualFilePath ; this . sha1sum = null ; this . sha256sum = null ; this . md5sum = null ; final File file = getActualFile ( ) ; if ( file . isFile ( ) ) { calculateChecksums ( this . getActualFile ( ) ) ; } } | Sets the actual file path of the dependency on disk . |
11,494 | public String getDisplayFileName ( ) { if ( displayName != null ) { return displayName ; } if ( ! isVirtual ) { return fileName ; } if ( name == null ) { return fileName ; } if ( version == null ) { return name ; } return name + ":" + version ; } | Returns the file name to display in reports ; if no display file name has been set it will default to constructing a name based on the name and version fields otherwise it will return the actual file name . |
11,495 | public synchronized void addSoftwareIdentifier ( Identifier identifier ) { assert ! ( identifier instanceof CpeIdentifier ) : "vulnerability identifier cannot be added to software identifiers" ; final Optional < Identifier > found = softwareIdentifiers . stream ( ) . filter ( id -> id . getValue ( ) . equals ( identifier . getValue ( ) ) ) . findFirst ( ) ; if ( found . isPresent ( ) ) { final Identifier existing = found . get ( ) ; if ( existing . getConfidence ( ) . compareTo ( identifier . getConfidence ( ) ) < 0 ) { existing . setConfidence ( identifier . getConfidence ( ) ) ; } if ( existing . getNotes ( ) != null && identifier . getNotes ( ) != null ) { existing . setNotes ( existing . getNotes ( ) + " " + identifier . getNotes ( ) ) ; } else if ( identifier . getNotes ( ) != null ) { existing . setNotes ( identifier . getNotes ( ) ) ; } if ( existing . getUrl ( ) == null && identifier . getUrl ( ) != null ) { existing . setUrl ( identifier . getUrl ( ) ) ; } } else { this . softwareIdentifiers . add ( identifier ) ; } } | Adds an entry to the list of detected Identifiers for the dependency file . |
11,496 | public void addAsEvidence ( String source , MavenArtifact mavenArtifact , Confidence confidence ) { if ( mavenArtifact . getGroupId ( ) != null && ! mavenArtifact . getGroupId ( ) . isEmpty ( ) ) { this . addEvidence ( EvidenceType . VENDOR , source , "groupid" , mavenArtifact . getGroupId ( ) , confidence ) ; } if ( mavenArtifact . getArtifactId ( ) != null && ! mavenArtifact . getArtifactId ( ) . isEmpty ( ) ) { this . addEvidence ( EvidenceType . PRODUCT , source , "artifactid" , mavenArtifact . getArtifactId ( ) , confidence ) ; } if ( mavenArtifact . getVersion ( ) != null && ! mavenArtifact . getVersion ( ) . isEmpty ( ) ) { this . addEvidence ( EvidenceType . VERSION , source , "version" , mavenArtifact . getVersion ( ) , confidence ) ; } boolean found = false ; if ( mavenArtifact . getArtifactUrl ( ) != null && ! mavenArtifact . getArtifactUrl ( ) . isEmpty ( ) ) { synchronized ( this ) { for ( Identifier i : this . softwareIdentifiers ) { if ( i instanceof PurlIdentifier ) { final PurlIdentifier id = ( PurlIdentifier ) i ; if ( mavenArtifact . getArtifactId ( ) . equals ( id . getName ( ) ) && mavenArtifact . getGroupId ( ) . equals ( id . getNamespace ( ) ) ) { found = true ; i . setConfidence ( Confidence . HIGHEST ) ; final String url = "http://search.maven.org/#search|ga|1|1%3A%22" + this . getSha1sum ( ) + "%22" ; i . setUrl ( url ) ; LOGGER . debug ( "Already found identifier {}. Confidence set to highest" , i . getValue ( ) ) ; break ; } } } } } if ( ! found && mavenArtifact . getGroupId ( ) != null && mavenArtifact . getArtifactId ( ) != null && mavenArtifact . getVersion ( ) != null ) { try { LOGGER . debug ( "Adding new maven identifier {}" , mavenArtifact ) ; final PackageURL p = new PackageURL ( "maven" , mavenArtifact . getGroupId ( ) , mavenArtifact . getArtifactId ( ) , mavenArtifact . getVersion ( ) , null , null ) ; final PurlIdentifier id = new PurlIdentifier ( p , Confidence . HIGHEST ) ; this . addSoftwareIdentifier ( id ) ; } catch ( MalformedPackageURLException ex ) { throw new UnexpectedAnalysisException ( ex ) ; } } } | Adds the Maven artifact as evidence . |
11,497 | public synchronized Set < Vulnerability > getVulnerabilities ( boolean sorted ) { final Set < Vulnerability > vulnerabilitySet ; if ( sorted ) { vulnerabilitySet = new TreeSet < > ( vulnerabilities ) ; } else { vulnerabilitySet = vulnerabilities ; } return Collections . unmodifiableSet ( vulnerabilitySet ) ; } | Get the unmodifiable list of vulnerabilities ; optionally sorted . |
11,498 | public synchronized Set < Vulnerability > getSuppressedVulnerabilities ( boolean sorted ) { final Set < Vulnerability > vulnerabilitySet ; if ( sorted ) { vulnerabilitySet = new TreeSet < > ( suppressedVulnerabilities ) ; } else { vulnerabilitySet = suppressedVulnerabilities ; } return Collections . unmodifiableSet ( vulnerabilitySet ) ; } | Get an unmodifiable optionally sorted . set of suppressedVulnerabilities . |
11,499 | private String determineHashes ( HashingFunction hashFunction ) { if ( isVirtual ) { return null ; } try { final File file = getActualFile ( ) ; return hashFunction . hash ( file ) ; } catch ( IOException | RuntimeException ex ) { LOGGER . warn ( "Unable to read '{}' to determine hashes." , actualFilePath ) ; LOGGER . debug ( "" , ex ) ; } catch ( NoSuchAlgorithmException ex ) { LOGGER . warn ( "Unable to use MD5 or SHA1 checksums." ) ; LOGGER . debug ( "" , ex ) ; } return null ; } | Determines the SHA1 and MD5 sum for the given file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.