output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
|---|---|---|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(proxyValue, proxyUser, proxyPass);
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
updateValuesWithConfig();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = this.isForcingCache || getBoolean("wdm.forceCache")
|| !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
versionToDownload, driverInCache.get());
exportDriver(getExportParameter(), driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + myOsName + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(proxyValue, proxyUser, proxyPass);
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
if (isForcingDownload) {
downloader.forceDownload();
}
updateValuesWithConfig();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = this.isForcingCache || getBoolean("wdm.forceCache")
|| !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
versionToDownload, driverInCache.get());
exportDriver(getExportParameter(), driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + myOsName + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public BrowserManager useTaobaoMirror() {
return useTaobaoMirror("wdm.geckoDriverTaobaoUrl");
}
|
#vulnerable code
@Override
public BrowserManager useTaobaoMirror() {
String taobaoUrl = null;
try {
taobaoUrl = WdmConfig
.getString(WdmConfig.getString("wdm.geckoDriverTaobaoUrl"));
driverUrl = new URL(taobaoUrl);
} catch (MalformedURLException e) {
String errorMessage = "Malformed URL " + taobaoUrl;
log.error(errorMessage, e);
throw new WebDriverManagerException(errorMessage, e);
}
return instance;
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
preferenceKey = getDriverManagerType().getNameInLowerCase();
Optional<String> browserVersion = empty();
if (usePreferences()
&& preferences.checkKeyInPreferences(preferenceKey)) {
browserVersion = Optional.of(
preferences.getValueFromPreferences(preferenceKey));
}
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
// Calculate driverVersion using browserVersion
preferenceKey = getDriverManagerType().getNameInLowerCase()
+ browserVersion.get();
if (usePreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
driverVersion = preferences
.getValueFromPreferences(preferenceKey);
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromRepository = getDriverVersionFromRepository(
browserVersion);
if (driverVersionFromRepository.isPresent()) {
driverVersion = driverVersionFromRepository.get();
}
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromProperties = getDriverVersionFromProperties(
preferenceKey);
if (driverVersionFromProperties.isPresent()) {
driverVersion = driverVersionFromProperties.get();
}
} else {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion,
getDriverManagerType(), browserVersion.get());
}
if (usePreferences()) {
preferences.putValueInPreferencesIfEmpty(
getDriverManagerType().getNameInLowerCase(),
browserVersion.get());
preferences.putValueInPreferencesIfEmpty(preferenceKey,
driverVersion);
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> getDriversFromGitHub() throws IOException {
List<URL> urls;
URL driverUrl = getDriverUrl();
log.info("Reading {} to seek {}", driverUrl, getDriverName());
Optional<URL> mirrorUrl = getMirrorUrl();
if (mirrorUrl.isPresent() && config.isUseMirror()) {
urls = getDriversFromMirror(mirrorUrl.get());
} else {
String driverVersion = driverVersionToDownload;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)))) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader,
GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersionFromGitHub(releaseArray, driverVersion) };
}
urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url")
.toString()));
}
}
}
}
}
return urls;
}
|
#vulnerable code
protected List<URL> getDriversFromGitHub() throws IOException {
List<URL> urls;
URL driverUrl = getDriverUrl();
log.info("Reading {} to seek {}", driverUrl, getDriverName());
Optional<URL> mirrorUrl = getMirrorUrl();
if (mirrorUrl.isPresent() && config.isUseMirror()) {
urls = getDriversFromMirror(mirrorUrl.get());
} else {
String driverVersion = versionToDownload;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)))) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader,
GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersion(releaseArray, driverVersion) };
}
urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url")
.toString()));
}
}
}
}
}
return urls;
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static final File extract(File compressedFile, String export)
throws IOException {
log.trace("Compressed file {}", compressedFile);
File file = null;
if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) {
file = unBZip2(compressedFile, export);
} else if (compressedFile.getName().toLowerCase().endsWith("gz")) {
file = unGzip(compressedFile);
} else {
ZipFile zipFolder = new ZipFile(compressedFile);
Enumeration<?> enu = zipFolder.entries();
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = zipEntry.getName();
long size = zipEntry.getSize();
long compressedSize = zipEntry.getCompressedSize();
log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)",
name, size, compressedSize);
file = new File(
compressedFile.getParentFile() + File.separator + name);
if (!file.exists() || WdmConfig.getBoolean("wdm.override")) {
if (name.endsWith("/")) {
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
InputStream is = zipFolder.getInputStream(zipEntry);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int length;
while ((length = is.read(bytes)) >= 0) {
fos.write(bytes, 0, length);
}
is.close();
fos.close();
file.setExecutable(true);
} else {
log.debug(file + " already exists");
}
}
zipFolder.close();
}
file = checkPhantom(compressedFile, export);
log.trace("Resulting binary file {}", file.getAbsoluteFile());
return file.getAbsoluteFile();
}
|
#vulnerable code
public static final File extract(File compressedFile, String export)
throws IOException {
log.trace("Compressed file {}", compressedFile);
File file = null;
if (compressedFile.getName().toLowerCase().endsWith("tar.bz2")) {
file = unBZip2(compressedFile, export);
} else if (compressedFile.getName().toLowerCase().endsWith("gz")) {
file = unGzip(compressedFile);
} else {
ZipFile zipFolder = new ZipFile(compressedFile);
Enumeration<?> enu = zipFolder.entries();
while (enu.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enu.nextElement();
String name = zipEntry.getName();
long size = zipEntry.getSize();
long compressedSize = zipEntry.getCompressedSize();
log.trace("Unzipping {} (size: {} KB, compressed size: {} KB)",
name, size, compressedSize);
file = new File(
compressedFile.getParentFile() + File.separator + name);
if (!file.exists() || WdmConfig.getBoolean("wdm.override")) {
if (name.endsWith("/")) {
file.mkdirs();
continue;
}
File parent = file.getParentFile();
if (parent != null) {
parent.mkdirs();
}
InputStream is = zipFolder.getInputStream(zipEntry);
FileOutputStream fos = new FileOutputStream(file);
byte[] bytes = new byte[1024];
int length;
while ((length = is.read(bytes)) >= 0) {
fos.write(bytes, 0, length);
}
is.close();
fos.close();
file.setExecutable(true);
} else {
log.debug(file + " already exists");
}
}
zipFolder.close();
}
log.trace("Resulting binary file {}", file.getAbsoluteFile());
return file.getAbsoluteFile();
}
#location 55
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private static File checkPhantom(File archive, String export)
throws IOException {
File target = null;
String phantomName = "phantomjs";
if (export.contains(phantomName)) {
String fileNoExtension = archive.getName().replace(".tar.bz2", "")
.replace(".zip", "");
File phantomjs = null;
try {
phantomjs = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension + File.separator
+ "bin" + File.separator).listFiles()[0];
} catch (Exception e) {
String extension = IS_OS_WINDOWS ? ".exe" : "";
phantomjs = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension + File.separator
+ phantomName + extension);
}
target = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + phantomjs.getName());
phantomjs.renameTo(target);
File delete = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension);
log.trace("Folder to be deleted: {}", delete);
FileUtils.deleteDirectory(delete);
} else {
File[] ls = archive.getParentFile().listFiles();
for (File f : ls) {
if (f.canExecute()) {
target = f;
break;
}
}
}
return target;
}
|
#vulnerable code
private static File checkPhantom(File archive, String export)
throws IOException {
File target;
String phantomName = "phantomjs";
if (export.contains(phantomName)) {
String fileNoExtension = archive.getName().replace(".tar.bz2", "")
.replace(".zip", "");
File phantomjs = null;
try {
phantomjs = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension + File.separator
+ "bin" + File.separator).listFiles()[0];
} catch (Exception e) {
String extension = IS_OS_WINDOWS ? ".exe" : "";
phantomjs = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension + File.separator
+ phantomName + extension);
}
target = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + phantomjs.getName());
phantomjs.renameTo(target);
File delete = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension);
log.trace("Folder to be deleted: {}", delete);
FileUtils.deleteDirectory(delete);
} else {
target = archive.getParentFile().listFiles()[0];
}
return target;
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static final synchronized void download(URL url, String version,
String export) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary;
if (!targetFile.getParentFile().exists()
|| WdmConfig.getBoolean("wdm.override")) {
log.debug("Downloading {} to {}", url, targetFile);
FileUtils.copyURLToFile(url, targetFile);
if (export.contains("edge")) {
binary = extractMsi(targetFile);
} else {
binary = unZip(targetFile);
}
targetFile.delete();
} else {
binary = FileUtils
.listFiles(targetFile.getParentFile(), null, true)
.iterator().next();
log.debug("Using binary driver previously downloaded {}", binary);
}
if (export != null) {
BrowserManager.exportDriver(export, binary.toString());
}
}
|
#vulnerable code
public static final synchronized void download(URL url, String version,
String export) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary;
if (!targetFile.getParentFile().exists()
|| WdmConfig.getBoolean("wdm.override")) {
log.debug("Downloading {} to {}", url, targetFile);
FileUtils.copyURLToFile(url, targetFile);
binary = unZip(targetFile);
targetFile.delete();
} else {
binary = targetFile.getParentFile().listFiles()[0];
log.debug("Using binary driver previously downloaded {}", binary);
}
if (export != null) {
BrowserManager.exportDriver(export, binary.toString());
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public BrowserManager useTaobaoMirror() {
return useTaobaoMirror("wdm.chromeDriverTaobaoUrl");
}
|
#vulnerable code
@Override
public BrowserManager useTaobaoMirror() {
String taobaoUrl = null;
try {
taobaoUrl = WdmConfig.getString(
WdmConfig.getString("wdm.chromeDriverTaobaoUrl"));
driverUrl = new URL(taobaoUrl);
} catch (MalformedURLException e) {
String errorMessage = "Malformed URL " + taobaoUrl;
log.error(errorMessage, e);
throw new WebDriverManagerException(errorMessage, e);
}
return instance;
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? getLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by OS
if (!getDriverName().contains("IEDriverServer")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored versions
candidateUrls = filterByIgnoredVersions(candidateUrls);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
String driverNameString = listToString(getDriverName());
log.info(
"No binary found for {} {} ... seeking another version",
driverNameString, versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
|
#vulnerable code
protected List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? getLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by OS
if (!getDriverName().contains("IEDriverServer")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Extra round of filter phantomjs 2.5.0 in Linux
if (config().getOs().equalsIgnoreCase("linux")
&& getDriverName().contains("phantomjs")) {
candidateUrls = urlFilter.filterByDistro(candidateUrls,
"2.5.0");
}
// Filter by ignored version
if (config().getIgnoreVersions() != null
&& !candidateUrls.isEmpty()) {
candidateUrls = urlFilter.filterByIgnoredVersions(candidateUrls,
config().getIgnoreVersions());
}
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
String driverNameString = listToString(getDriverName());
log.info(
"No binary found for {} {} ... seeking another version",
driverNameString, versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// For Chromium snap
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// For Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected File postDownload(File archive) {
log.trace("Post processing for Opera: {}", archive);
File extractFolder = archive.getParentFile()
.listFiles(getFolderFilter())[0];
if (!extractFolder.isFile()) {
log.trace("Opera extract folder (to be deleted): {}",
extractFolder);
File[] listFiles = extractFolder.listFiles();
int i = 0;
File operadriver;
do {
operadriver = listFiles[0];
i++;
} while (!config().isExecutable(operadriver)
|| i >= listFiles.length);
log.trace("Operadriver binary: {}", operadriver);
File target = new File(archive.getParentFile().getAbsolutePath(),
operadriver.getName());
log.trace("Operadriver target: {}", target);
downloader.renameFile(operadriver, target);
downloader.deleteFolder(extractFolder);
return target;
} else {
return super.postDownload(archive);
}
}
|
#vulnerable code
@Override
protected File postDownload(File archive) {
log.trace("Post processing for Opera: {}", archive);
File extractFolder = archive.getParentFile()
.listFiles(getFolderFilter())[0];
if (!extractFolder.isFile()) {
log.trace("Opera extract folder (to be deleted): {}",
extractFolder);
File operadriver = extractFolder.listFiles()[0];
log.trace("Operadriver binary: {}", operadriver);
File target = new File(archive.getParentFile().getAbsolutePath(),
operadriver.getName());
log.trace("Operadriver target: {}", target);
downloader.renameFile(operadriver, target);
downloader.deleteFolder(extractFolder);
return target;
} else {
return super.postDownload(archive);
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
preferenceKey = getDriverManagerType().getNameInLowerCase();
Optional<String> browserVersion = empty();
if (usePreferences()
&& preferences.checkKeyInPreferences(preferenceKey)) {
browserVersion = Optional.of(
preferences.getValueFromPreferences(preferenceKey));
}
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
// Calculate driverVersion using browserVersion
preferenceKey = getDriverManagerType().getNameInLowerCase()
+ browserVersion.get();
if (usePreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
driverVersion = preferences
.getValueFromPreferences(preferenceKey);
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromRepository = getDriverVersionFromRepository(
browserVersion);
if (driverVersionFromRepository.isPresent()) {
driverVersion = driverVersionFromRepository.get();
}
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromProperties = getDriverVersionFromProperties(
preferenceKey);
if (driverVersionFromProperties.isPresent()) {
driverVersion = driverVersionFromProperties.get();
}
} else {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion,
getDriverManagerType(), browserVersion.get());
}
if (usePreferences()) {
preferences.putValueInPreferencesIfEmpty(
getDriverManagerType().getNameInLowerCase(),
browserVersion.get());
preferences.putValueInPreferencesIfEmpty(preferenceKey,
driverVersion);
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> getCandidateUrls(String driverVersion)
throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean getLatest = isUnknown(driverVersion);
Architecture arch = config().getArchitecture();
boolean continueSearchingVersion;
do {
// Get the latest or concrete driver version
String shortDriverName = getShortDriverName();
candidateUrls = getLatest
? filterDriverListByLatest(urls, shortDriverName)
: filterDriverListByVersion(urls, shortDriverName,
driverVersion);
log.trace("Candidate URLs: {}", candidateUrls);
if (driverVersionToDownload == null) {
break;
}
// Filter by OS
if (!getDriverName().equalsIgnoreCase("IEDriverServer")
&& !getDriverName()
.equalsIgnoreCase("selenium-server-standalone")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored driver versions
candidateUrls = filterByIgnoredDriverVersions(candidateUrls);
// Filter by beta
candidateUrls = urlFilter.filterByBeta(candidateUrls,
config().isUseBetaVersions());
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.info(
"No proper driver found for {} {} ... seeking another version",
getDriverName(), driverVersionToDownload);
urls = removeFromList(urls, driverVersionToDownload);
driverVersionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
|
#vulnerable code
protected List<URL> getCandidateUrls(String driverVersion)
throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean getLatest = isUnknown(driverVersion);
Architecture arch = config().getArchitecture();
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
String shortDriverName = getShortDriverName();
candidateUrls = getLatest ? checkLatest(urls, shortDriverName)
: getVersion(urls, shortDriverName, driverVersion);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null) {
break;
}
// Filter by OS
if (!getDriverName().equalsIgnoreCase("IEDriverServer")
&& !getDriverName()
.equalsIgnoreCase("selenium-server-standalone")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored versions
candidateUrls = filterByIgnoredVersions(candidateUrls);
// Filter by beta
candidateUrls = urlFilter.filterByBeta(candidateUrls,
config().isUseBetaVersions());
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.info(
"No proper driver found for {} {} ... seeking another version",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
getLatest = isNullOrEmpty(version);
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
Optional<String> optionalBrowserVersion = config()
.isAvoidAutoVersion() ? empty() : getBrowserVersion();
if (optionalBrowserVersion.isPresent()) {
String browserVersion = optionalBrowserVersion.get();
preferenceKey = getDriverManagerType().name().toLowerCase()
+ browserVersion;
if (getLatest && !config.isOverride()
&& !config().isAvoidAutoVersion()
&& !config().isAvoidPreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
version = preferences
.getValueFromPreferences(preferenceKey);
} else {
version = getVersionForInstalledBrowser(
getDriverManagerType());
}
getLatest = version.isEmpty();
}
}
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(driverManagerType);
getLatest = version.isEmpty();
}
if (version.equals("insiders")) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(
systemRoot + File.separator + "System32"
+ File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
driverName, arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
driverName, latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", driverName,
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = driverName + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(driverManagerType);
getLatest = version.isEmpty();
}
if (version.equals("insiders")) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(
systemRoot + File.separator + "System32"
+ File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
driverName, arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
driverName, latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver {} {} found in cache", driverName,
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = driverName + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 46
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void exportDriver(String variableValue) {
downloadedDriverVersion = driverVersionToDownload;
binaryPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Resulting binary {}", variableValue);
}
}
|
#vulnerable code
protected void exportDriver(String variableValue) {
downloadedVersion = versionToDownload;
binaryPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Resulting binary {}", variableValue);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static File unBZip2(File archive, String export) throws IOException {
Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR,
CompressionType.BZIP2);
archiver.extract(archive, archive.getParentFile());
log.trace("Unbzip2 {}", archive);
File target = checkPhantom(archive, export);
return target;
}
|
#vulnerable code
public static File unBZip2(File archive, String export) throws IOException {
Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR,
CompressionType.BZIP2);
archiver.extract(archive, archive.getParentFile());
log.trace("Unbzip2 {}", archive);
File target;
String phantomjsName = "phantomjs";
if (export.contains(phantomjsName)) {
String fileNoExtension = archive.getName().replace(".tar.bz2", "");
File phantomjs = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension + File.separator + "bin"
+ File.separator + phantomjsName);
target = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + phantomjsName);
phantomjs.renameTo(target);
File delete = new File(archive.getParentFile().getAbsolutePath()
+ File.separator + fileNoExtension);
log.trace("Folder to be deleted: {}", delete);
FileUtils.deleteDirectory(delete);
} else {
target = archive.getParentFile().listFiles()[0];
}
return target;
}
#location 23
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<String> getBetaVersions() {
List<String> betaVersions = new ArrayList<>();
DriverManagerType[] browsersWithBeta = { CHROME };
for (DriverManagerType driverManagerType : browsersWithBeta) {
String key = driverManagerType.name().toLowerCase() + BETA;
Optional<String> betaVersionString = getDriverVersionForBrowserFromProperties(
key, true);
if (betaVersionString.isPresent()) {
betaVersions.addAll(
Arrays.asList(betaVersionString.get().split(",")));
}
}
return betaVersions;
}
|
#vulnerable code
protected List<String> getBetaVersions() {
List<String> betaVersions = new ArrayList<>();
DriverManagerType[] browsersWithBeta = { CHROME };
for (DriverManagerType driverManagerType : browsersWithBeta) {
String key = driverManagerType.name().toLowerCase() + BETA;
Optional<String> betaVersionString = getDriverVersionForBrowserFromProperties(
key);
if (betaVersionString.isPresent()) {
betaVersions.addAll(
Arrays.asList(betaVersionString.get().split(",")));
}
}
return betaVersions;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
preferenceKey = getDriverManagerType().getNameInLowerCase();
Optional<String> browserVersion = empty();
if (usePreferences()
&& preferences.checkKeyInPreferences(preferenceKey)) {
browserVersion = Optional.of(
preferences.getValueFromPreferences(preferenceKey));
}
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
// Calculate driverVersion using browserVersion
preferenceKey = getDriverManagerType().getNameInLowerCase()
+ browserVersion.get();
if (usePreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
driverVersion = preferences
.getValueFromPreferences(preferenceKey);
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromRepository = getDriverVersionFromRepository(
browserVersion);
if (driverVersionFromRepository.isPresent()) {
driverVersion = driverVersionFromRepository.get();
}
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromProperties = getDriverVersionFromProperties(
preferenceKey);
if (driverVersionFromProperties.isPresent()) {
driverVersion = driverVersionFromProperties.get();
}
} else {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion,
getDriverManagerType(), browserVersion.get());
}
if (usePreferences()) {
preferences.putValueInPreferencesIfEmpty(
getDriverManagerType().getNameInLowerCase(),
browserVersion.get());
preferences.putValueInPreferencesIfEmpty(preferenceKey,
driverVersion);
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized void download(URL url, String version, String export,
List<String> driverName) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary = null;
// Check if binary exists
boolean download = !targetFile.getParentFile().exists()
|| (targetFile.getParentFile().exists()
&& targetFile.getParentFile().list().length == 0)
|| override;
if (download) {
File temporaryFile = new File(targetFile.getParentFile(),
randomUUID().toString());
log.info("Downloading {} to {}", url, temporaryFile);
WdmHttpClient.Get get = new WdmHttpClient.Get(url)
.addHeader("User-Agent", "Mozilla/5.0")
.addHeader("Connection", "keep-alive");
try {
copyInputStreamToFile(httpClient.execute(get).getContent(),
temporaryFile);
} catch (IOException e) {
temporaryFile.delete();
throw e;
}
log.info("Renaming {} to {}", temporaryFile, targetFile);
temporaryFile.renameTo(targetFile);
if (!export.contains("edge")) {
binary = extract(targetFile, export);
} else {
binary = targetFile;
}
if (targetFile.getName().toLowerCase().endsWith(".msi")) {
binary = extractMsi(targetFile);
}
} else {
// Check if existing binary is valid
Collection<File> listFiles = listFiles(targetFile.getParentFile(),
null, true);
for (File file : listFiles) {
for (String s : driverName) {
if (file.getName().startsWith(s) && file.canExecute()) {
binary = file;
log.debug(
"Using binary driver previously downloaded {}",
binary);
download = false;
break;
} else {
download = true;
}
}
if (!download) {
break;
}
}
}
if (export != null && binary != null) {
browserManager.exportDriver(export, binary.toString());
}
}
|
#vulnerable code
public synchronized void download(URL url, String version, String export,
List<String> driverName) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary = null;
// Check if binary exists
boolean download = !targetFile.getParentFile().exists()
|| (targetFile.getParentFile().exists()
&& targetFile.getParentFile().list().length == 0)
|| override;
if (!download) {
// Check if existing binary is valid
Collection<File> listFiles = FileUtils
.listFiles(targetFile.getParentFile(), null, true);
for (File file : listFiles) {
for (String s : driverName) {
if (file.getName().startsWith(s) && file.canExecute()) {
binary = file;
log.debug(
"Using binary driver previously downloaded {}",
binary);
download = false;
break;
} else {
download = true;
}
}
if (!download) {
break;
}
}
}
if (download) {
File temporaryFile = new File(targetFile.getParentFile(), UUID.randomUUID().toString());
log.info("Downloading {} to {}", url, temporaryFile);
WdmHttpClient.Get get = new WdmHttpClient.Get(url)
.addHeader("User-Agent", "Mozilla/5.0")
.addHeader("Connection", "keep-alive");
try {
FileUtils.copyInputStreamToFile(
httpClient.execute(get).getContent(), temporaryFile);
}
catch (IOException e) {
temporaryFile.delete();
throw e;
}
log.info("Renaming {} to {}", temporaryFile, targetFile);
temporaryFile.renameTo(targetFile);
if (!export.contains("edge")) {
binary = extract(targetFile, export);
} else {
binary = targetFile;
}
if (targetFile.getName().toLowerCase().endsWith(".msi")) {
binary = extractMsi(targetFile);
}
}
if (export != null) {
browserManager.exportDriver(export, binary.toString());
}
}
#location 66
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
useBetaVersions = false;
mirrorLog = false;
isForcingCache = false;
isForcingDownload = false;
listVersions = null;
architecture = null;
driverUrl = null;
version = null;
proxyValue = null;
proxyUser = null;
proxyPass = null;
ignoredVersions = null;
}
|
#vulnerable code
protected void reset() {
useBetaVersions = getBoolean("wdm.useBetaVersions");
mirrorLog = false;
isForcingCache = false;
isForcingDownload = false;
listVersions = null;
architecture = null;
driverUrl = null;
versionToDownload = null;
version = null;
proxyValue = null;
binaryPath = null;
proxyUser = null;
proxyPass = null;
ignoredVersions = null;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void handleDriver(URL url, String driver, List<URL> out) {
if (!config().isUseBetaVersions()
&& url.getFile().toLowerCase().contains("beta")) {
return;
}
if (url.getFile().contains(driver)) {
String currentVersion = getCurrentVersion(url, driver);
if (currentVersion.equalsIgnoreCase(driver)) {
return;
}
if (versionToDownload == null) {
versionToDownload = currentVersion;
}
if (versionCompare(currentVersion, versionToDownload) > 0) {
versionToDownload = currentVersion;
out.clear();
}
if (url.getFile().contains(versionToDownload)) {
out.add(url);
}
}
}
|
#vulnerable code
protected void handleDriver(URL url, String driver, List<URL> out) {
if (!useBeta && url.getFile().toLowerCase().contains("beta")) {
return;
}
if (url.getFile().contains(driver)) {
String currentVersion = getCurrentVersion(url, driver);
if (currentVersion.equalsIgnoreCase(driver)) {
return;
}
if (versionToDownload == null) {
versionToDownload = currentVersion;
}
if (versionCompare(currentVersion, versionToDownload) > 0) {
versionToDownload = currentVersion;
out.clear();
}
if (url.getFile().contains(versionToDownload)) {
out.add(url);
}
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public BrowserManager useTaobaoMirror() {
return useTaobaoMirror("wdm.operaDriverTaobaoUrl");
}
|
#vulnerable code
@Override
public BrowserManager useTaobaoMirror() {
String taobaoUrl = null;
try {
taobaoUrl = getString(getString("wdm.operaDriverTaobaoUrl"));
driverUrl = new URL(taobaoUrl);
} catch (MalformedURLException e) {
String errorMessage = "Malformed URL " + taobaoUrl;
log.error(errorMessage, e);
throw new WebDriverManagerException(errorMessage, e);
}
return instance;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected Optional<String> handleCache(Architecture arch, String version,
String os, boolean getLatest, boolean cache) {
Optional<String> driverInCache = empty();
if (cache || !getLatest) {
driverInCache = getDriverFromCache(version, arch, os);
}
if (!version.isEmpty()) {
storeVersionToDownload(version);
}
return driverInCache;
}
|
#vulnerable code
protected Optional<String> handleCache(Architecture arch, String version,
String os, boolean getLatest, boolean cache) {
Optional<String> driverInCache = empty();
if (cache || !getLatest) {
driverInCache = getDriverFromCache(version, arch, os);
}
if (!version.isEmpty()) {
versionToDownload = version;
}
return driverInCache;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
}
|
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
downloadedVersion = null;
driverManagerType = null;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void exportDriver(String variableValue) {
driverPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
}
|
#vulnerable code
protected void exportDriver(String variableValue) {
binaryPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// For Chromium snap
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// For Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 53
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void handleDriver(URL url, String driver, List<URL> out) {
if (!useBetaVersions && !getBoolean("wdm.useBetaVersions")
&& url.getFile().toLowerCase().contains("beta")) {
return;
}
if (url.getFile().contains(driver)) {
String currentVersion = getCurrentVersion(url, driver);
if (currentVersion.equalsIgnoreCase(driver)) {
return;
}
if (versionToDownload == null) {
versionToDownload = currentVersion;
}
if (versionCompare(currentVersion, versionToDownload) > 0) {
versionToDownload = currentVersion;
out.clear();
}
if (url.getFile().contains(versionToDownload)) {
out.add(url);
}
}
}
|
#vulnerable code
protected void handleDriver(URL url, String driver, List<URL> out) {
if (!useBetaVersions && url.getFile().toLowerCase().contains("beta")) {
return;
}
if (url.getFile().contains(driver)) {
String currentVersion = getCurrentVersion(url, driver);
if (currentVersion.equalsIgnoreCase(driver)) {
return;
}
if (versionToDownload == null) {
versionToDownload = currentVersion;
}
if (versionCompare(currentVersion, versionToDownload) > 0) {
versionToDownload = currentVersion;
out.clear();
}
if (url.getFile().contains(versionToDownload)) {
out.add(url);
}
}
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<URL> getDrivers() throws IOException {
URL driverUrl = getDriverUrl();
String driverVersion = versionToDownload;
BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersion(releaseArray, driverVersion) };
}
List<URL> urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(
asset.get("browser_download_url").toString()));
}
}
}
reader.close();
return urls;
}
|
#vulnerable code
@Override
public List<URL> getDrivers() throws IOException {
URL driverUrl = getDriverUrl();
String driverVersion = versionToDownload;
BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class);
GitHubApi release;
if (driverVersion == null || driverVersion.isEmpty() || driverVersion
.equalsIgnoreCase(DriverVersion.LATEST.name())) {
log.debug("Connecting to {} to check latest OperaDriver release",
driverUrl);
driverVersion = releaseArray[0].getName();
log.debug("Latest driver version: {}", driverVersion);
release = releaseArray[0];
} else {
release = getVersion(releaseArray, driverVersion);
}
if (release == null) {
throw new RuntimeException("Version " + driverVersion
+ " is not available for OperaDriver");
}
List<LinkedTreeMap<String, Object>> assets = release.getAssets();
List<URL> urls = new ArrayList<>();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url").toString()));
}
reader.close();
return urls;
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void handleException(Exception e, Architecture arch,
String version) {
String errorMessage = String.format(
"There was an error managing %s %s (%s)", getDriverName(),
version, e.getMessage());
if (!config().isForcingCache()) {
config().setForcingCache(true);
log.warn("{} ... trying again forcing to use cache", errorMessage);
manage(arch, version);
} else {
log.error("{}", errorMessage, e);
throw new WebDriverManagerException(e);
}
}
|
#vulnerable code
protected void handleException(Exception e, Architecture arch,
String version) {
if (!config().isForcingCache()) {
config().setForcingCache(true);
log.warn(
"There was an error managing {} {} ({}) ... trying again forcing to use cache",
getDriverName(), version, e.getMessage());
manage(arch, version);
} else {
throw new WebDriverManagerException(e);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> getVersion(List<URL> list, String driver,
String version) {
List<URL> out = new ArrayList<>();
for (URL url : list) {
if (url.getFile().contains(driver)
&& url.getFile().contains(version)
&& !url.getFile().contains("-symbols")) {
out.add(url);
}
}
if (versionToDownload != null && !versionToDownload.equals(version)) {
versionToDownload = version;
log.info("Using {} {}", driver, version);
}
return out;
}
|
#vulnerable code
protected List<URL> getVersion(List<URL> list, String driver,
String version) {
List<URL> out = new ArrayList<>();
if (getDriverName().contains("msedgedriver")) {
int i = listVersions.indexOf(version);
if (i != -1) {
out.add(list.get(i));
}
}
for (URL url : list) {
if (url.getFile().contains(driver)
&& url.getFile().contains(version)
&& !url.getFile().contains("-symbols")) {
out.add(url);
}
}
if (versionToDownload != null && !versionToDownload.equals(version)) {
versionToDownload = version;
log.info("Using {} {}", driver, version);
}
return out;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public WebDriverManager useTaobaoMirror(String taobaoUrl) {
driverUrl = getUrl(taobaoUrl);
return instanceMap.get(driverManagerType);
}
|
#vulnerable code
public WebDriverManager useTaobaoMirror(String taobaoUrl) {
driverUrl = getUrl(taobaoUrl);
return instance;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void handleException(Exception e, Architecture arch,
String version) {
String versionStr = isNullOrEmpty(version) ? "(latest version)"
: version;
String errorMessage = String.format(
"There was an error managing %s %s (%s)", getDriverName(),
versionStr, e.getMessage());
if (!config().isForceCache() && retryCount == 0) {
config().setForceCache(true);
config().setUseMirror(true);
retryCount++;
log.warn("{} ... trying again using mirror", errorMessage);
manage(arch, version);
} else if (retryCount == 1) {
config().setAvoidAutoVersion(true);
version = "";
retryCount++;
log.warn("{} ... trying again using latest from cache",
errorMessage);
manage(arch, version);
} else {
log.error("{}", errorMessage, e);
throw new WebDriverManagerException(e);
}
}
|
#vulnerable code
protected void handleException(Exception e, Architecture arch,
String version) {
String versionStr = isNullOrEmpty(version) ? "(latest version)"
: version;
String errorMessage = String.format(
"There was an error managing %s %s (%s)", getDriverName(),
versionStr, e.getMessage());
if (!config().isForceCache() && retry) {
config().setForceCache(true);
config().setUseMirror(true);
retry = false;
log.warn("{} ... trying again using cache and mirror",
errorMessage);
manage(arch, version);
} else {
log.error("{}", errorMessage, e);
throw new WebDriverManagerException(e);
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> getDriversFromGitHub() throws IOException {
List<URL> urls;
URL driverUrl = getDriverUrl();
log.info("Reading {} to seek {}", driverUrl, getDriverName());
Optional<URL> mirrorUrl = getMirrorUrl();
if (mirrorUrl.isPresent() && config.isUseMirror()) {
urls = getDriversFromMirror(mirrorUrl.get());
} else {
String driverVersion = driverVersionToDownload;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)))) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader,
GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersionFromGitHub(releaseArray, driverVersion) };
}
urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url")
.toString()));
}
}
}
}
}
return urls;
}
|
#vulnerable code
protected List<URL> getDriversFromGitHub() throws IOException {
List<URL> urls;
URL driverUrl = getDriverUrl();
log.info("Reading {} to seek {}", driverUrl, getDriverName());
Optional<URL> mirrorUrl = getMirrorUrl();
if (mirrorUrl.isPresent() && config.isUseMirror()) {
urls = getDriversFromMirror(mirrorUrl.get());
} else {
String driverVersion = versionToDownload;
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)))) {
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader,
GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersion(releaseArray, driverVersion) };
}
urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url")
.toString()));
}
}
}
}
}
return urls;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public BrowserManager useTaobaoMirror() {
return useTaobaoMirror("wdm.phantomjsDriverTaobaoUrl");
}
|
#vulnerable code
@Override
public BrowserManager useTaobaoMirror() {
String taobaoUrl = null;
try {
taobaoUrl = getString(getString("wdm.phantomjsDriverTaobaoUrl"));
driverUrl = new URL(taobaoUrl);
} catch (MalformedURLException e) {
String errorMessage = "Malformed URL " + taobaoUrl;
log.error(errorMessage, e);
throw new WebDriverManagerException(errorMessage, e);
}
return instance;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected File postDownload(File archive) {
log.trace("Post processing for Opera: {}", archive);
final String operaDriverName = getDriverName().get(0);
FilenameFilter filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return dir.isDirectory()
&& name.toLowerCase().startsWith(operaDriverName + "_");
}
};
File extractFolder = archive.getParentFile().listFiles(filter)[0];
if (!extractFolder.isFile()) {
log.trace("Opera extract folder (to be deleted): {}",
extractFolder);
File operadriver = extractFolder.listFiles()[0];
log.trace("Operadriver binary: {}", operadriver);
File target = new File(archive.getParentFile().getAbsolutePath(),
operadriver.getName());
log.trace("Operadriver target: {}", target);
downloader.renameFile(operadriver, target);
downloader.deleteFolder(extractFolder);
return target;
} else {
return super.postDownload(archive);
}
}
|
#vulnerable code
@Override
protected File postDownload(File archive) {
log.trace("Post processing for Opera: {}", archive);
File extractFolder = archive.getParentFile().listFiles()[0];
if (!extractFolder.isFile()) {
log.trace("Opera extract folder (to be deleted): {}",
extractFolder);
File operadriver = extractFolder.listFiles()[0];
log.trace("Operadriver binary: {}", operadriver);
File target = new File(archive.getParentFile().getAbsolutePath(),
operadriver.getName());
log.trace("Operadriver target: {}", target);
downloader.renameFile(operadriver, target);
downloader.deleteFolder(extractFolder);
return target;
} else {
return super.postDownload(archive);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public WebDriverManager browserPath(String browserPath) {
config().setBinaryPath(browserPath);
return instanceMap.get(driverManagerType);
}
|
#vulnerable code
public WebDriverManager browserPath(String browserPath) {
browserBinaryPath = browserPath;
return instanceMap.get(driverManagerType);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected String resolveDriverVersion(String driverVersion) {
String preferenceKey = getKeyForPreferences();
Optional<String> browserVersion = empty();
browserVersion = getValueFromPreferences(preferenceKey, browserVersion);
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
preferenceKey = getKeyForPreferences() + browserVersion.get();
driverVersion = preferences.getValueFromPreferences(preferenceKey);
Optional<String> optionalDriverVersion = empty();
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromRepository(
browserVersion);
}
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromProperties(
preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
} else if (!isUnknown(driverVersion)) {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion, getDriverManagerType(),
browserVersion.get());
storeInPreferences(preferenceKey, driverVersion,
browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
}
|
#vulnerable code
protected String resolveDriverVersion(String driverVersion) {
preferenceKey = getKeyForPreferences();
Optional<String> browserVersion = empty();
browserVersion = getValueFromPreferences(browserVersion);
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
preferenceKey = getKeyForPreferences() + browserVersion.get();
driverVersion = preferences.getValueFromPreferences(preferenceKey);
Optional<String> optionalDriverVersion = empty();
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromRepository(
browserVersion);
}
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromProperties(
preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
} else if (!isUnknown(driverVersion)) {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion, getDriverManagerType(),
browserVersion.get());
storeInPreferences(driverVersion, browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String exportValue;
if (driverInCache.isPresent() && !config().isOverride()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getDriverVersionLabel(driverVersion));
storeVersionToDownload(driverVersion);
exportValue = driverInCache.get();
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String exportValue;
if (driverInCache.isPresent() && !config().isOverride()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getLabel(driverVersion));
storeVersionToDownload(driverVersion);
exportValue = driverInCache.get();
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void handleException(Exception e, Architecture arch,
String version) {
String versionStr = isNullOrEmpty(version) ? "(latest version)"
: version;
String errorMessage = String.format(
"There was an error managing %s %s (%s)", getDriverName(),
versionStr, e.getMessage());
if (!config().isForceCache() && retryCount == 0) {
config().setForceCache(true);
config().setUseMirror(true);
retryCount++;
log.warn("{} ... trying again using mirror", errorMessage);
manage(arch, version);
} else if (retryCount == 1) {
config().setAvoidAutoVersion(true);
version = "";
retryCount++;
log.warn("{} ... trying again using latest from cache",
errorMessage);
manage(arch, version);
} else {
log.error("{}", errorMessage, e);
throw new WebDriverManagerException(e);
}
}
|
#vulnerable code
protected void handleException(Exception e, Architecture arch,
String version) {
String versionStr = isNullOrEmpty(version) ? "(latest version)"
: version;
String errorMessage = String.format(
"There was an error managing %s %s (%s)", getDriverName(),
versionStr, e.getMessage());
if (!config().isForceCache() && retry) {
config().setForceCache(true);
config().setUseMirror(true);
retry = false;
log.warn("{} ... trying again using cache and mirror",
errorMessage);
manage(arch, version);
} else {
log.error("{}", errorMessage, e);
throw new WebDriverManagerException(e);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
String filterName = getDriverName().equalsIgnoreCase("msedgedriver")
? "edgedriver"
: getDriverName();
candidateUrls = getLatest ? checkLatest(urls, filterName)
: getVersion(urls, filterName, version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null) {
break;
}
// Filter by OS
if (!getDriverName().equalsIgnoreCase("IEDriverServer")
&& !getDriverName()
.equalsIgnoreCase("selenium-server-standalone")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored versions
candidateUrls = filterByIgnoredVersions(candidateUrls);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.info(
"No binary found for {} {} ... seeking another version",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
|
#vulnerable code
protected List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? checkLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by OS
if (!getDriverName().equalsIgnoreCase("IEDriverServer")
&& !getDriverName()
.equalsIgnoreCase("selenium-server-standalone")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored versions
candidateUrls = filterByIgnoredVersions(candidateUrls);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.info(
"No binary found for {} {} ... seeking another version",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected Optional<String> getDriverVersionFromProperties(String key) {
// Chromium values are the same than Chrome
if (key.contains("chromium")) {
key = key.replace("chromium", "chrome");
}
boolean online = config().getVersionsPropertiesOnlineFirst();
String onlineMessage = online ? ONLINE : LOCAL;
log.debug("Getting driver version for {} from {} versions.properties",
key, onlineMessage);
String value = getVersionFromProperties(online).getProperty(key);
if (value == null) {
String notOnlineMessage = online ? LOCAL : ONLINE;
log.debug(
"Driver for {} not found in {} properties (using {} version)",
key, onlineMessage, notOnlineMessage);
versionsProperties = null;
value = getVersionFromProperties(!online).getProperty(key);
}
return value == null ? empty() : Optional.of(value);
}
|
#vulnerable code
protected Optional<String> getDriverVersionFromProperties(String key) {
boolean online = config().getVersionsPropertiesOnlineFirst();
String onlineMessage = online ? ONLINE : LOCAL;
log.debug("Getting driver version for {} from {} versions.properties",
key, onlineMessage);
String value = getVersionFromProperties(online).getProperty(key);
if (value == null) {
String notOnlineMessage = online ? LOCAL : ONLINE;
log.debug(
"Driver for {} not found in {} properties (using {} version)",
key, onlineMessage, notOnlineMessage);
versionsProperties = null;
value = getVersionFromProperties(!online).getProperty(key);
}
return value == null ? empty() : Optional.of(value);
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void handleDriver(URL url, String driver, List<URL> out) {
if (!useBetaVersions && !getBoolean("wdm.useBetaVersions")
&& url.getFile().toLowerCase().contains("beta")) {
return;
}
if (url.getFile().contains(driver)) {
String currentVersion = getCurrentVersion(url, driver);
if (currentVersion.equalsIgnoreCase(driver)) {
return;
}
if (versionToDownload == null) {
versionToDownload = currentVersion;
}
if (versionCompare(currentVersion, versionToDownload) > 0) {
versionToDownload = currentVersion;
out.clear();
}
if (url.getFile().contains(versionToDownload)) {
out.add(url);
}
}
}
|
#vulnerable code
protected void handleDriver(URL url, String driver, List<URL> out) {
if (!useBetaVersions && url.getFile().toLowerCase().contains("beta")) {
return;
}
if (url.getFile().contains(driver)) {
String currentVersion = getCurrentVersion(url, driver);
if (currentVersion.equalsIgnoreCase(driver)) {
return;
}
if (versionToDownload == null) {
versionToDownload = currentVersion;
}
if (versionCompare(currentVersion, versionToDownload) > 0) {
versionToDownload = currentVersion;
out.clear();
}
if (url.getFile().contains(versionToDownload)) {
out.add(url);
}
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCache() throws Exception {
BrowserManager browserManager = WebDriverManager
.getInstance(driverClass);
browserManager.architecture(architecture).version(driverVersion)
.setup();
Downloader downloader = new Downloader(browserManager);
Method method = BrowserManager.class.getDeclaredMethod(
"existsDriverInCache", String.class, String.class,
Architecture.class);
method.setAccessible(true);
String driverInChachePath = (String) method.invoke(browserManager,
downloader.getTargetPath(), driverVersion, architecture);
assertThat(driverInChachePath, notNullValue());
}
|
#vulnerable code
@Test
public void testCache() throws Exception {
BrowserManager browserManager = null;
if (browserManagerClass.equals(ChromeDriverManager.class)) {
browserManager = ChromeDriverManager.getInstance();
} else if (browserManagerClass.equals(OperaDriverManager.class)) {
browserManager = OperaDriverManager.getInstance();
} else if (browserManagerClass.equals(PhantomJsDriverManager.class)) {
browserManager = PhantomJsDriverManager.getInstance();
} else if (browserManagerClass.equals(FirefoxDriverManager.class)) {
browserManager = FirefoxDriverManager.getInstance();
}
browserManager.architecture(architecture).version(driverVersion)
.setup();
Downloader downloader = new Downloader(browserManager);
Method method = BrowserManager.class.getDeclaredMethod(
"existsDriverInCache", String.class, String.class,
Architecture.class);
method.setAccessible(true);
String driverInChachePath = (String) method.invoke(browserManager,
downloader.getTargetPath(), driverVersion, architecture);
assertThat(driverInChachePath, notNullValue());
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected List<URL> getCandidateUrls(String driverVersion)
throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean getLatest = isUnknown(driverVersion);
Architecture arch = config().getArchitecture();
boolean continueSearchingVersion;
do {
// Get the latest or concrete driver version
String shortDriverName = getShortDriverName();
candidateUrls = getLatest
? filterDriverListByLatest(urls, shortDriverName)
: filterDriverListByVersion(urls, shortDriverName,
driverVersion);
log.trace("Candidate URLs: {}", candidateUrls);
if (driverVersionToDownload == null) {
break;
}
// Filter by OS
if (!getDriverName().equalsIgnoreCase("IEDriverServer")
&& !getDriverName()
.equalsIgnoreCase("selenium-server-standalone")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored driver versions
candidateUrls = filterByIgnoredDriverVersions(candidateUrls);
// Filter by beta
candidateUrls = urlFilter.filterByBeta(candidateUrls,
config().isUseBetaVersions());
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.info(
"No proper driver found for {} {} ... seeking another version",
getDriverName(), driverVersionToDownload);
urls = removeFromList(urls, driverVersionToDownload);
driverVersionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
|
#vulnerable code
protected List<URL> getCandidateUrls(String driverVersion)
throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean getLatest = isUnknown(driverVersion);
Architecture arch = config().getArchitecture();
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
String shortDriverName = getShortDriverName();
candidateUrls = getLatest ? checkLatest(urls, shortDriverName)
: getVersion(urls, shortDriverName, driverVersion);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null) {
break;
}
// Filter by OS
if (!getDriverName().equalsIgnoreCase("IEDriverServer")
&& !getDriverName()
.equalsIgnoreCase("selenium-server-standalone")) {
candidateUrls = urlFilter.filterByOs(candidateUrls,
config().getOs());
}
// Filter by architecture
candidateUrls = urlFilter.filterByArch(candidateUrls, arch,
forcedArch);
// Filter by distro
candidateUrls = filterByDistro(candidateUrls);
// Filter by ignored versions
candidateUrls = filterByIgnoredVersions(candidateUrls);
// Filter by beta
candidateUrls = urlFilter.filterByBeta(candidateUrls,
config().isUseBetaVersions());
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.info(
"No proper driver found for {} {} ... seeking another version",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
#location 48
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
if (isUnknown(driverVersion)) {
preferenceKey = getDriverManagerType().getNameInLowerCase();
Optional<String> browserVersion = empty();
if (usePreferences()
&& preferences.checkKeyInPreferences(preferenceKey)) {
browserVersion = Optional.of(
preferences.getValueFromPreferences(preferenceKey));
}
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
// Calculate driverVersion using browserVersion
preferenceKey = getDriverManagerType().getNameInLowerCase()
+ browserVersion.get();
if (usePreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
driverVersion = preferences
.getValueFromPreferences(preferenceKey);
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromRepository = getDriverVersionFromRepository(
browserVersion);
if (driverVersionFromRepository.isPresent()) {
driverVersion = driverVersionFromRepository.get();
}
}
if (isUnknown(driverVersion)) {
Optional<String> driverVersionFromProperties = getDriverVersionFromProperties(
preferenceKey);
if (driverVersionFromProperties.isPresent()) {
driverVersion = driverVersionFromProperties.get();
}
} else {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion,
getDriverManagerType(), browserVersion.get());
}
if (usePreferences()) {
preferences.putValueInPreferencesIfEmpty(
getDriverManagerType().getNameInLowerCase(),
browserVersion.get());
preferences.putValueInPreferencesIfEmpty(preferenceKey,
driverVersion);
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
}
downloadAndExport(driverVersion);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected File postDownload(File archive) {
log.trace("PhatomJS package name: {}", archive);
File extractFolder = archive.getParentFile()
.listFiles(getFolderFilter())[0];
log.trace("PhatomJS extract folder (to be deleted): {}", extractFolder);
File binFolder = new File(
extractFolder.getAbsoluteFile() + separator + "bin");
// Exception for older version of PhantomJS
int binaryIndex = 0;
if (!binFolder.exists()) {
binFolder = extractFolder;
binaryIndex = 3;
}
log.trace("PhatomJS bin folder: {} (index {})", binFolder, binaryIndex);
File phantomjs = binFolder.listFiles()[binaryIndex];
log.trace("PhatomJS binary: {}", phantomjs);
File target = new File(archive.getParentFile().getAbsolutePath(),
phantomjs.getName());
log.trace("PhatomJS target: {}", target);
downloader.renameFile(phantomjs, target);
downloader.deleteFolder(extractFolder);
return target;
}
|
#vulnerable code
@Override
protected File postDownload(File archive) {
log.trace("PhatomJS package name: {}", archive);
File extractFolder = archive.getParentFile().listFiles()[0];
log.trace("PhatomJS extract folder (to be deleted): {}", extractFolder);
File binFolder = new File(
extractFolder.getAbsoluteFile() + separator + "bin");
// Exception for older version of PhantomJS
int binaryIndex = 0;
if (!binFolder.exists()) {
binFolder = extractFolder;
binaryIndex = 3;
}
log.trace("PhatomJS bin folder: {} (index {})", binFolder, binaryIndex);
File phantomjs = binFolder.listFiles()[binaryIndex];
log.trace("PhatomJS binary: {}", phantomjs);
File target = new File(archive.getParentFile().getAbsolutePath(),
phantomjs.getName());
log.trace("PhatomJS target: {}", target);
downloader.renameFile(phantomjs, target);
downloader.deleteFolder(extractFolder);
return target;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected Optional<String> getLatestVersion() {
String url = config().getChromeDriverUrl() + "LATEST_RELEASE";
Optional<String> version = Optional.empty();
try {
InputStream response = httpClient
.execute(httpClient.createHttpGet(new URL(url))).getEntity()
.getContent();
version = Optional.of(IOUtils.toString(response, defaultCharset()));
} catch (Exception e) {
log.warn("Exception reading {} to get latest version of {}", url,
getDriverName(), e);
}
if (version.isPresent()) {
log.debug("Latest version of {} according to {} is {}",
getDriverName(), url, version.get());
}
return version;
}
|
#vulnerable code
@Override
protected Optional<String> getLatestVersion() {
String url = config().getChromeDriverUrl() + "LATEST_RELEASE";
HttpGet request = new HttpGet(url);
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response;
Optional<String> version = Optional.empty();
try {
response = httpClient.execute(request);
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
version = Optional.of(IOUtils.toString(rd));
} catch (IOException e) {
log.warn("Exception reading {} to get latest version of {}", url,
getDriverName(), e);
}
log.debug("Latest version of {} according to {} is {}", getDriverName(),
url, version);
return version;
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
}
|
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
downloadedVersion = null;
driverManagerType = null;
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(driverManagerType);
getLatest = version.isEmpty();
}
if (version.equals("insiders")) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(
systemRoot + File.separator + "System32"
+ File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
driverName, arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
driverName, latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", driverName,
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = driverName + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(driverManagerType);
getLatest = version.isEmpty();
}
if (version.equals("insiders")) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(
systemRoot + File.separator + "System32"
+ File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
driverName, arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
driverName, latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver {} {} found in cache", driverName,
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = driverName + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<URL> getDrivers() throws IOException {
URL driverUrl = getDriverUrl();
String driverVersion = versionToDownload;
BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class);
if (driverVersion != null) {
releaseArray = new GitHubApi[] {
getVersion(releaseArray, driverVersion) };
}
List<URL> urls = new ArrayList<>();
for (GitHubApi release : releaseArray) {
if (release != null) {
List<LinkedTreeMap<String, Object>> assets = release
.getAssets();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(
asset.get("browser_download_url").toString()));
}
}
}
reader.close();
return urls;
}
|
#vulnerable code
@Override
public List<URL> getDrivers() throws IOException {
URL driverUrl = getDriverUrl();
String driverVersion = versionToDownload;
BufferedReader reader = new BufferedReader(
new InputStreamReader(openGitHubConnection(driverUrl)));
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
GitHubApi[] releaseArray = gson.fromJson(reader, GitHubApi[].class);
GitHubApi release;
if (driverVersion == null || driverVersion.isEmpty() || driverVersion
.equalsIgnoreCase(DriverVersion.LATEST.name())) {
log.debug(
"Connecting to {} to check latest MarionetteDriver release",
driverUrl);
driverVersion = releaseArray[0].getName();
release = releaseArray[0];
} else {
release = getVersion(releaseArray, driverVersion);
}
if (release == null) {
throw new RuntimeException("Version " + driverVersion
+ " is not available for MarionetteDriver");
}
List<LinkedTreeMap<String, Object>> assets = release.getAssets();
List<URL> urls = new ArrayList<>();
for (LinkedTreeMap<String, Object> asset : assets) {
urls.add(new URL(asset.get("browser_download_url").toString()));
}
reader.close();
return urls;
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(proxyValue, proxyUser, proxyPass);
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(this, wdmHttpClient);
urlFilter = new UrlFilter();
if (isForcingDownload) {
downloader.forceDownload();
}
updateValuesWithConfig();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = this.isForcingCache || getBoolean("wdm.forceCache")
|| !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
versionToDownload, driverInCache.get());
exportDriver(getExportParameter(), driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + myOsName + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new WdmHttpClient.Builder().proxy(proxyValue)
.proxyUser(proxyUser).proxyPass(proxyPass).build();
try (WdmHttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(this, wdmHttpClient);
urlFilter = new UrlFilter();
if (isForcingDownload) {
downloader.forceDownload();
}
updateValuesWithConfig();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = this.isForcingCache || getBoolean("wdm.forceCache")
|| !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
versionToDownload, driverInCache.get());
exportDriver(getExportParameter(), driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + myOsName + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? getLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by architecture and OS
candidateUrls = filterByOs(candidateUrls);
candidateUrls = filterByArch(candidateUrls, arch);
// Extra round of filter phantomjs 2.5.0 in Linux
if (IS_OS_LINUX && getDriverName().contains("phantomjs")) {
candidateUrls = filterByDistro(candidateUrls, getDistroName(),
"2.5.0");
}
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.trace("No valid binary found for {} {}", getDriverName(),
versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
|
#vulnerable code
private List<URL> filterCandidateUrls(Architecture arch, String version,
boolean getLatest) throws IOException {
List<URL> urls = getDrivers();
List<URL> candidateUrls;
log.trace("All URLs: {}", urls);
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
candidateUrls = getLatest ? getLatest(urls, getDriverName())
: getVersion(urls, getDriverName(), version);
log.trace("Candidate URLs: {}", candidateUrls);
if (versionToDownload == null
|| this.getClass().equals(EdgeDriverManager.class)) {
break;
}
// Filter by architecture and OS
candidateUrls = filter(candidateUrls, arch);
// Exception for phantomjs 2.5.0 in Linux
if (IS_OS_LINUX && getDriverName().contains("phantomjs")) {
candidateUrls = filterByDistro(candidateUrls, getDistroName(),
"2.5.0");
}
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty() && getLatest;
if (continueSearchingVersion) {
log.trace("No valid binary found for {} {}", getDriverName(),
versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
} while (continueSearchingVersion);
return candidateUrls;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String exportValue;
if (driverInCache.isPresent() && !config().isOverride()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getDriverVersionLabel(driverVersion));
storeVersionToDownload(driverVersion);
exportValue = driverInCache.get();
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
|
#vulnerable code
protected void manage(String driverVersion) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
if (isUnknown(driverVersion)) {
driverVersion = resolveDriverVersion(driverVersion);
}
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String exportValue;
if (driverInCache.isPresent() && !config().isOverride()) {
log.debug("Driver {} {} found in cache", getDriverName(),
getLabel(driverVersion));
storeVersionToDownload(driverVersion);
exportValue = driverInCache.get();
} else {
exportValue = download(driverVersion);
}
exportDriver(exportValue);
} catch (Exception e) {
handleException(e, driverVersion);
}
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static final synchronized void download(URL url, String version,
String export, List<String> driverName) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary = null;
// Check if binary exists
boolean download = !targetFile.getParentFile().exists()
|| (targetFile.getParentFile().exists()
&& targetFile.getParentFile().list().length == 0)
|| WdmConfig.getBoolean("wdm.override");
if (!download) {
// Check if existing binary is valid
Collection<File> listFiles = FileUtils
.listFiles(targetFile.getParentFile(), null, true);
for (File file : listFiles) {
for (String s : driverName) {
if (file.getName().startsWith(s) && file.canExecute()) {
binary = file;
log.debug(
"Using binary driver previously downloaded {}",
binary);
download = false;
break;
} else {
download = true;
}
}
if (!download) {
break;
}
}
}
if (download) {
log.info("Downloading {} to {}", url, targetFile);
HttpURLConnection conn = getConnection(url);
int responseCode = conn.getResponseCode();
log.debug("Response HTTP {}", responseCode);
if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER) {
// HTTP Redirect
URL newUrl = new URL(conn.getHeaderField("Location"));
log.debug("Redirect to {}", newUrl);
conn = getConnection(newUrl);
}
FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile);
if (!export.contains("edge")) {
binary = extract(targetFile, export);
targetFile.delete();
} else {
binary = targetFile;
}
}
if (export != null) {
BrowserManager.exportDriver(export, binary.toString());
}
}
|
#vulnerable code
public static final synchronized void download(URL url, String version,
String export, List<String> driverName) throws IOException {
File targetFile = new File(getTarget(version, url));
File binary = null;
// Check if binary exists
boolean download = !targetFile.getParentFile().exists()
|| (targetFile.getParentFile().exists()
&& targetFile.getParentFile().list().length == 0)
|| WdmConfig.getBoolean("wdm.override");
if (!download) {
// Check if existing binary is valid
Collection<File> listFiles = FileUtils
.listFiles(targetFile.getParentFile(), null, true);
for (File file : listFiles) {
for (String s : driverName) {
if (file.getName().startsWith(s) && file.canExecute()) {
binary = file;
log.debug(
"Using binary driver previously downloaded {}",
binary);
download = false;
break;
} else {
download = true;
}
}
if (!download) {
break;
}
}
}
if (download) {
log.info("Downloading {} to {}", url, targetFile);
URLConnection conn = url.openConnection();
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.addRequestProperty("Connection", "keep-alive");
conn.connect();
FileUtils.copyInputStreamToFile(conn.getInputStream(), targetFile);
if (!export.contains("edge")) {
binary = extract(targetFile, export);
targetFile.delete();
} else {
binary = targetFile;
}
}
if (export != null) {
BrowserManager.exportDriver(export, binary.toString());
}
}
#location 41
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
if (version.equals(INSIDERS)) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(systemRoot,
"System32" + File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
downloadedVersion = INSIDERS;
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
if (version.equals(INSIDERS)) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(systemRoot,
"System32" + File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
downloadedVersion = INSIDERS;
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 50
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// For Chromium snap
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// For Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 47
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
if (!config.isAvoidPreferences()) {
storeVersionToDownload(version);
}
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest && !config().isAvoidAutoVersion()) {
version = getVersionForInstalledBrowser(getDriverManagerType());
getLatest = version.isEmpty();
}
if (version.equals(INSIDERS)) {
String systemRoot = System.getenv("SystemRoot");
File microsoftWebDriverFile = new File(systemRoot,
"System32" + File.separator + "MicrosoftWebDriver.exe");
if (microsoftWebDriverFile.exists()) {
downloadedVersion = INSIDERS;
exportDriver(microsoftWebDriverFile.toString());
return;
} else {
retry = false;
throw new WebDriverManagerException(
"MicrosoftWebDriver.exe should be installed in an elevated command prompt executing: "
+ "dism /Online /Add-Capability /CapabilityName:Microsoft.WebDriver~~~~0.0.1.0");
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
if (!config.isAvoidPreferences()) {
storeVersionToDownload(version);
}
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected String resolveDriverVersion(String driverVersion) {
String preferenceKey = getKeyForPreferences();
Optional<String> browserVersion = empty();
browserVersion = getValueFromPreferences(preferenceKey, browserVersion);
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
preferenceKey = getKeyForPreferences() + browserVersion.get();
driverVersion = preferences.getValueFromPreferences(preferenceKey);
Optional<String> optionalDriverVersion = empty();
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromRepository(
browserVersion);
}
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromProperties(
preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
} else if (!isUnknown(driverVersion)) {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion, getDriverManagerType(),
browserVersion.get());
storeInPreferences(preferenceKey, driverVersion,
browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
}
|
#vulnerable code
protected String resolveDriverVersion(String driverVersion) {
preferenceKey = getKeyForPreferences();
Optional<String> browserVersion = empty();
browserVersion = getValueFromPreferences(browserVersion);
if (!browserVersion.isPresent()) {
browserVersion = detectBrowserVersion();
}
if (browserVersion.isPresent()) {
preferenceKey = getKeyForPreferences() + browserVersion.get();
driverVersion = preferences.getValueFromPreferences(preferenceKey);
Optional<String> optionalDriverVersion = empty();
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromRepository(
browserVersion);
}
if (isUnknown(driverVersion)) {
optionalDriverVersion = getDriverVersionFromProperties(
preferenceKey);
}
if (optionalDriverVersion.isPresent()) {
driverVersion = optionalDriverVersion.get();
}
if (isUnknown(driverVersion)) {
log.debug(
"The driver version for {} {} is unknown ... trying with latest",
getDriverManagerType(), browserVersion.get());
} else if (!isUnknown(driverVersion)) {
log.info(
"Using {} {} (since {} {} is installed in your machine)",
getDriverName(), driverVersion, getDriverManagerType(),
browserVersion.get());
storeInPreferences(driverVersion, browserVersion.get());
}
}
// if driverVersion is still unknown, try with latest
if (isUnknown(driverVersion)) {
Optional<String> latestDriverVersionFromRepository = getLatestDriverVersionFromRepository();
if (latestDriverVersionFromRepository.isPresent()) {
driverVersion = latestDriverVersionFromRepository.get();
}
}
return driverVersion;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
config().reset();
mirrorLog = false;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isSnap = false;
}
|
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isLatest = true;
isSnap = false;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retryCount = 0;
isLatest = true;
}
|
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
forcedOs = false;
retry = true;
isLatest = true;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected String download(String driverVersion) throws IOException {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = String.format(
"%s %s for %s %s not found in %s", getDriverName(),
getDriverVersionLabel(driverVersion), os, arch.toString(),
getDriverUrl());
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
return downloader.download(url, driverVersionToDownload,
getDriverName());
}
|
#vulnerable code
protected String download(String driverVersion) throws IOException {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = String.format(
"%s %s for %s %s not found in %s", getDriverName(),
getLabel(driverVersion), os, arch.toString(),
getDriverUrl());
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
return downloader.download(url, versionToDownload, getDriverName());
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
getLatest = isNullOrEmpty(version);
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
Optional<String> optionalBrowserVersion = config()
.isAvoidAutoVersion() ? empty() : getBrowserVersion();
if (optionalBrowserVersion.isPresent()) {
String browserVersion = optionalBrowserVersion.get();
preferenceKey = getDriverManagerType().name().toLowerCase()
+ browserVersion;
if (getLatest && !config.isOverride()
&& !config().isAvoidAutoVersion()
&& !config().isAvoidPreferences() && preferences
.checkKeyInPreferences(preferenceKey)) {
version = preferences
.getValueFromPreferences(preferenceKey);
} else {
version = getVersionForInstalledBrowser(
getDriverManagerType());
}
getLatest = version.isEmpty();
}
}
// For Edge
if (checkInsiderVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
Optional<String> driverInCache = handleCache(arch, version, os,
getLatest, cache);
String versionStr = getLatest ? "(latest version)" : version;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(version);
downloadedVersion = version;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
}
|
#vulnerable code
protected void reset() {
config().reset();
mirrorLog = false;
listVersions = null;
versionToDownload = null;
forcedArch = false;
useBeta = config().isUseBetaVersions();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected Optional<String> getDefaultBrowserVersion(String programFilesEnv,
String winBrowserName, String linuxBrowserName,
String macBrowserName, String versionFlag,
String browserNameInOutput) {
String browserBinaryPath = config().getBinaryPath();
if (IS_OS_WINDOWS) {
String programFiles = System.getenv(programFilesEnv)
.replaceAll("\\\\", "\\\\\\\\");
String browserPath = browserBinaryPath != null ? browserBinaryPath
: programFiles + winBrowserName;
String browserVersionOutput = runAndWait(getExecFile(), "wmic",
"datafile", "where", "name='" + browserPath + "'", "get",
"Version", "/value");
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional
.of(getVersionFromWmicOutput(browserVersionOutput));
}
} else if (IS_OS_LINUX || IS_OS_MAC) {
String browserPath;
if (browserBinaryPath != null) {
browserPath = browserBinaryPath;
} else {
browserPath = IS_OS_LINUX ? linuxBrowserName : macBrowserName;
}
String browserVersionOutput = runAndWait(browserPath, versionFlag);
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional.of(getVersionFromPosixOutput(
browserVersionOutput, browserNameInOutput));
}
}
return empty();
}
|
#vulnerable code
protected Optional<String> getDefaultBrowserVersion(String programFilesEnv,
String winBrowserName, String linuxBrowserName,
String macBrowserName, String versionFlag,
String browserNameInOutput) {
if (IS_OS_WINDOWS) {
String programFiles = System.getenv(programFilesEnv)
.replaceAll("\\\\", "\\\\\\\\");
String browserPath = browserBinaryPath != null ? browserBinaryPath
: programFiles + winBrowserName;
String browserVersionOutput = runAndWait(getExecFile(), "wmic",
"datafile", "where", "name='" + browserPath + "'", "get",
"Version", "/value");
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional
.of(getVersionFromWmicOutput(browserVersionOutput));
}
} else if (IS_OS_LINUX || IS_OS_MAC) {
String browserPath;
if (browserBinaryPath != null) {
browserPath = browserBinaryPath;
} else {
browserPath = IS_OS_LINUX ? linuxBrowserName : macBrowserName;
}
String browserVersionOutput = runAndWait(browserPath, versionFlag);
if (!isNullOrEmpty(browserVersionOutput)) {
return Optional.of(getVersionFromPosixOutput(
browserVersionOutput, browserNameInOutput));
}
}
return empty();
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void storeVersionToDownload(String driverVersion) {
if (!isUnknown(driverVersion)) {
if (driverVersion.startsWith(".")) {
driverVersion = driverVersion.substring(1);
}
driverVersionToDownload = driverVersion;
}
}
|
#vulnerable code
protected void storeVersionToDownload(String driverVersion) {
if (!isUnknown(driverVersion)) {
if (driverVersion.startsWith(".")) {
driverVersion = driverVersion.substring(1);
}
versionToDownload = driverVersion;
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(getDriverManagerType());
urlFilter = new UrlFilter();
boolean getLatest = isVersionLatest(version);
boolean cache = config().isForceCache();
if (getLatest) {
version = detectDriverVersionFromBrowser();
}
// Special case for Chromium snap packages
if (getDriverManagerType() == CHROMIUM && isSnap
&& ((ChromiumDriverManager) this).snapDriverExists()) {
return;
}
getLatest = isNullOrEmpty(version);
// Check latest version
if (getLatest && !config().isUseBetaVersions()) {
Optional<String> lastVersion = getLatestVersion();
getLatest = !lastVersion.isPresent();
if (!getLatest) {
version = lastVersion.get();
}
}
// Special case for Edge
if (checkPreInstalledVersion(version)) {
return;
}
String os = config().getOs();
log.trace("Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
if (getLatest && latestVersion != null) {
log.debug("Latest version of {} is {} (recently resolved)",
getDriverName(), latestVersion);
version = latestVersion;
cache = true;
}
// Manage driver
downloadAndExport(arch, version, getLatest, cache, os);
} catch (Exception e) {
handleException(e, arch, version);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void reset() {
useBetaVersions = false;
mirrorLog = false;
isForcingCache = false;
isForcingDownload = false;
listVersions = null;
architecture = null;
driverUrl = null;
version = null;
proxyValue = null;
proxyUser = null;
proxyPass = null;
ignoredVersions = null;
}
|
#vulnerable code
protected void reset() {
useBetaVersions = getBoolean("wdm.useBetaVersions");
mirrorLog = false;
isForcingCache = false;
isForcingDownload = false;
listVersions = null;
architecture = null;
driverUrl = null;
versionToDownload = null;
version = null;
proxyValue = null;
binaryPath = null;
proxyUser = null;
proxyPass = null;
ignoredVersions = null;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getProxyValue(),
config().getProxyUser(), config().getProxyPass());
httpClient.setTimeout(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = config().isForcingCache() || !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
version, driverInCache.get());
exportDriver(config().getExportParameter(exportParameterKey),
driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + config().getMyOsName() + arch.toString()
+ " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
handleException(e, arch, version);
}
}
|
#vulnerable code
protected void manage(Architecture arch, String version) {
httpClient = new HttpClient(config().getProxyValue(),
config().getProxyUser(), config().getProxyPass());
httpClient.setTimeout(config().getTimeout());
try (HttpClient wdmHttpClient = httpClient) {
downloader = new Downloader(driverManagerType);
urlFilter = new UrlFilter();
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(LATEST.name())
|| version.equalsIgnoreCase(NOT_SPECIFIED.name());
boolean cache = config().isForcingCache() || !isNetAvailable();
log.trace(">> Managing {} arch={} version={} getLatest={} cache={}",
getDriverName(), arch, version, getLatest, cache);
Optional<String> driverInCache = handleCache(arch, version,
getLatest, cache);
if (driverInCache.isPresent()) {
versionToDownload = version;
downloadedVersion = version;
log.debug("Driver for {} {} found in cache {}", getDriverName(),
version, driverInCache.get());
exportDriver(config().getExportParameter(exportParameterKey),
driverInCache.get());
} else {
List<URL> candidateUrls = filterCandidateUrls(arch, version,
getLatest);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errorMessage = getDriverName() + " " + versionStr
+ " for " + config().getMyOsName() + arch.toString()
+ " not found in "
+ config().getDriverUrl(driverUrlKey);
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
downloadCandidateUrls(candidateUrls);
}
} catch (Exception e) {
e.printStackTrace();
handleException(e, arch, version);
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void manage(Architecture arch, String version) {
try {
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(DriverVersion.LATEST.name())
|| version.equalsIgnoreCase(
DriverVersion.NOT_SPECIFIED.name());
String driverInCache = null;
if (!getLatest) {
versionToDownload = version;
driverInCache = existsDriverInCache(Downloader.getTargetPath(),
getDriverName(), version);
}
if (driverInCache != null) {
System.setProperty(VERSION_PROPERTY, version);
exportDriver(getExportParameter(), driverInCache);
} else {
// Get the complete list of URLs
List<URL> urls = getDrivers();
if (!urls.isEmpty()) {
List<URL> candidateUrls;
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
if (getLatest) {
candidateUrls = getLatest(urls, getDriverName());
} else {
candidateUrls = getVersion(urls, getDriverName(),
version);
}
if (versionToDownload == null) {
break;
}
log.trace("All URLS: {}", urls);
log.trace("Candidate URLS: {}", candidateUrls);
if (this.getClass().equals(EdgeDriverManager.class)) {
// Microsoft Edge binaries are different
continueSearchingVersion = false;
} else {
// Filter by architecture and OS
candidateUrls = filter(candidateUrls, arch);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty()
&& getLatest;
if (continueSearchingVersion) {
log.debug("No valid binary found for {} {}",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
}
} while (continueSearchingVersion);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errMessage = getDriverName() + " " + versionStr
+ " for " + MY_OS_NAME + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errMessage);
throw new RuntimeException(errMessage);
}
for (URL url : candidateUrls) {
String export = candidateUrls.contains(url)
? getExportParameter() : null;
System.setProperty(VERSION_PROPERTY, versionToDownload);
Downloader.download(url, versionToDownload, export,
getDriverName());
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
|
#vulnerable code
public void manage(Architecture arch, String version) {
try {
boolean getLatest = version == null || version.isEmpty()
|| version.equalsIgnoreCase(DriverVersion.LATEST.name())
|| version.equalsIgnoreCase(
DriverVersion.NOT_SPECIFIED.name());
String driverInCache = null;
if (!getLatest) {
driverInCache = existsDriverInCache(Downloader.getTargetPath(),
getDriverName(), version);
}
if (driverInCache != null) {
System.setProperty(VERSION_PROPERTY, version);
exportDriver(getExportParameter(), driverInCache);
} else {
// Get the complete list of URLs
List<URL> urls = getDrivers();
if (!urls.isEmpty()) {
List<URL> candidateUrls;
boolean continueSearchingVersion;
do {
// Get the latest or concrete version
if (getLatest) {
candidateUrls = getLatest(urls, getDriverName());
} else {
candidateUrls = getVersion(urls, getDriverName(),
version);
}
if (versionToDownload == null) {
break;
}
if (this.getClass().equals(EdgeDriverManager.class)) {
// Microsoft Edge binaries are different
continueSearchingVersion = false;
} else {
// Filter by architecture and OS
candidateUrls = filter(candidateUrls, arch);
// Find out if driver version has been found or not
continueSearchingVersion = candidateUrls.isEmpty()
&& getLatest;
if (continueSearchingVersion) {
log.debug("No valid binary found for {} {}",
getDriverName(), versionToDownload);
urls = removeFromList(urls, versionToDownload);
versionToDownload = null;
}
}
} while (continueSearchingVersion);
if (candidateUrls.isEmpty()) {
String versionStr = getLatest ? "(latest version)"
: version;
String errMessage = getDriverName() + " " + versionStr
+ " for " + MY_OS_NAME + arch.toString()
+ " not found in " + getDriverUrl();
log.error(errMessage);
throw new RuntimeException(errMessage);
}
for (URL url : candidateUrls) {
String export = candidateUrls.contains(url)
? getExportParameter() : null;
System.setProperty(VERSION_PROPERTY, versionToDownload);
Downloader.download(url, versionToDownload, export,
getDriverName());
}
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#location 72
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void exportDriver(String variableValue) {
downloadedDriverPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
}
|
#vulnerable code
protected void exportDriver(String variableValue) {
driverPath = variableValue;
Optional<String> exportParameter = getExportParameter();
if (!config.isAvoidExport() && exportParameter.isPresent()) {
String variableName = exportParameter.get();
log.info("Exporting {} as {}", variableName, variableValue);
System.setProperty(variableName, variableValue);
} else {
log.info("Driver location: {}", variableValue);
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected String getTargetPath() {
String path = null;
Object resolved = resolveConfigKey("wdm.targetPath", targetPath);
if (resolved != null) {
path = (String) resolved;
if (path.contains(HOME)) {
path = path.replace(HOME, System.getProperty("user.home"));
}
}
return path;
}
|
#vulnerable code
protected String getTargetPath() {
String path = (String) resolveConfigKey("wdm.targetPath", targetPath);
if (path.contains(HOME)) {
path = path.replace(HOME, System.getProperty("user.home"));
}
return path;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testServer() throws IOException {
String serverUrl = String.format("http://localhost:%s/%s", serverPort,
path);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(serverUrl).build();
// Assert response
Response response = client.newCall(request).execute();
assertTrue(response.isSuccessful());
// Assert attachment
String attachment = String.format("attachment; filename=\"%s\"",
driver);
assertTrue(response.headers().values("Content-Disposition")
.contains(attachment));
}
|
#vulnerable code
@Test
public void testServer() throws IOException {
String serverUrl = String.format("http://localhost:%s/%s", serverPort,
path);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url(serverUrl).build();
Response response = client.newCall(request).execute();
assertTrue(response.isSuccessful());
ResponseBody body = response.body();
log.debug("Content-Type {}", body.contentType());
log.debug("Content-Length {}", body.contentLength());
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void downloadAndExport(String driverVersion) throws IOException {
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String versionStr = isUnknown(driverVersion) ? "(latest version)"
: driverVersion;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(driverVersion);
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
String exportValue = downloader.download(url, versionToDownload,
getDriverName());
exportDriver(exportValue);
}
downloadedVersion = versionToDownload;
}
|
#vulnerable code
protected void downloadAndExport(String driverVersion) throws IOException {
Optional<String> driverInCache = searchDriverInCache(driverVersion);
String versionStr = isUnknown(driverVersion) ? "(latest version)"
: driverVersion;
if (driverInCache.isPresent() && !config().isOverride()) {
storeVersionToDownload(driverVersion);
downloadedVersion = driverVersion;
log.debug("Driver {} {} found in cache", getDriverName(),
versionStr);
exportDriver(driverInCache.get());
} else {
List<URL> candidateUrls = getCandidateUrls(driverVersion);
if (candidateUrls.isEmpty()) {
Architecture arch = config().getArchitecture();
String os = config().getOs();
String errorMessage = getDriverName() + " " + versionStr
+ " for " + os + arch.toString() + " not found in "
+ getDriverUrl();
log.error(errorMessage);
throw new WebDriverManagerException(errorMessage);
}
// Download first candidate URL
URL url = candidateUrls.iterator().next();
String exportValue = downloader.download(url, versionToDownload,
getDriverName());
exportDriver(exportValue);
downloadedVersion = versionToDownload;
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
try (final GeneratorScheduler scheduler = new GeneratorScheduler(Duration.ofSeconds(1))) {
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
apps.add(simpleDataApplication("data-1", scheduler, "sine", sine(100, 0, ofSeconds(120))));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
}
logger.info("Exiting...");
}
|
#vulnerable code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
logger.info("Exiting...");
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(final String... args) throws Throwable {
toInfinityAndBeyond();
final Options opts = new Options();
opts.addOption(
builder("n")
.longOpt("basename")
.hasArg().argName("BASENAME")
.desc("The base name of the simulator instance")
.build());
opts.addOption(
builder()
.longOpt("name-factory")
.hasArg().argName("FACTORY")
.desc("The name factory to use")
.build());
opts.addOption(
builder("c")
.longOpt("count")
.hasArg().argName("COUNT")
.type(Integer.class)
.desc("The number of instances to start")
.build());
opts.addOption(
builder("a")
.longOpt("account-name")
.hasArg().argName("NAME")
.desc("The name of the account (defaults to 'kapua-sys')")
.build());
opts.addOption(
builder("s")
.longOpt("seconds")
.hasArg().argName("SECONDS")
.type(Long.class)
.desc("Shutdown simulator after <SECONDS> seconds")
.build());
opts.addOption("?", "help", false, null);
{
final OptionGroup broker = new OptionGroup();
broker.setRequired(false);
broker.addOption(
builder("h")
.longOpt("broker-host")
.hasArg().argName("HOST")
.desc("Only the hostname of the broker, used for building the full URL")
.build());
broker.addOption(
builder("b")
.longOpt("broker")
.hasArg().argName("URL")
.desc("The full URL to the broker").build());
opts.addOptionGroup(broker);
}
{
final OptionGroup logging = new OptionGroup();
logging.setRequired(false);
logging.addOption(builder("q").longOpt("quiet").desc("Suppress output").build());
logging.addOption(builder("v").longOpt("verbose").desc("Show more output").build());
logging.addOption(builder("d").longOpt("debug").desc("Show debug output").build());
opts.addOptionGroup(logging);
}
final CommandLine cli;
try {
cli = new DefaultParser().parse(opts, args);
} catch (final ParseException e) {
System.err.println(e.getLocalizedMessage());
System.exit(-1);
return;
}
if (cli.hasOption('?')) {
showHelp(opts);
System.exit(0);
}
setupLogging(cli);
final String basename = replace(cli.getOptionValue('n', env("KSIM_BASE_NAME", "sim-")));
final String nameFactoryName = cli.getOptionValue("name-factory", env("KSIM_NAME_FACTORY", null));
final int count = Integer.parseInt(replace(cli.getOptionValue('c', env("KSIM_NUM_GATEWAYS", "1"))));
final String brokerHost = replace(cli.getOptionValue("bh"));
final String broker = replace(cli.getOptionValue('b', createBrokerUrl(Optional.ofNullable(brokerHost))));
final String accountName = replace(cli.getOptionValue('a', env("KSIM_ACCOUNT_NAME", "kapua-sys")));
final long shutdownAfter = Long
.parseLong(replace(cli.getOptionValue('s', Long.toString(Long.MAX_VALUE / 1_000L))));
dumpEnv();
logger.info("Starting simulation ...");
logger.info("\tbasename : {}", basename);
logger.info("\tname-factory : {}", nameFactoryName);
logger.info("\tcount: {}", count);
logger.info("\tbroker: {}", broker);
logger.info("\taccount-name: {}", accountName);
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final List<AutoCloseable> close = new LinkedList<>();
final NameFactory nameFactory = createNameFactory(nameFactoryName)
.orElseGet(() -> NameFactories.prefixed(basename));
try {
for (int i = 1; i <= count; i++) {
final String name = nameFactory.generateName(i);
logger.info("Creating instance #{} - {}", i, name);
final GatewayConfiguration configuration = new GatewayConfiguration(broker, accountName, name);
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
close.add(transport);
final Simulator simulator = new Simulator(configuration, transport, apps);
close.add(simulator);
}
Thread.sleep(shutdownAfter * 1_000L);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
closeAll(close);
}
logger.info("Exiting...");
}
|
#vulnerable code
public static void main(final String... args) throws Throwable {
toInfinityAndBeyond();
final Options opts = new Options();
opts.addOption("n", "basename", true, "The base name of the simulator instance");
opts.addOption(null, "name-factory", true, "The name factory to use");
opts.addOption("c", "count", true, "The number of instances to start");
opts.addOption("h", "broker-host", true, "The broker's host");
opts.addOption("b", "broker", true, "The URL to the broker");
opts.addOption("a", "account-name", true, "The name of the account");
opts.addOption("s", "shutdown", true, "Shutdown simulator after x seconds");
final CommandLine cli = new DefaultParser().parse(opts, args);
final String basename = replace(cli.getOptionValue('n', env("KSIM_BASE_NAME", "sim-")));
final String nameFactoryName = cli.getOptionValue("name-factory", env("KSIM_NAME_FACTORY", null));
final int count = Integer.parseInt(replace(cli.getOptionValue('c', env("KSIM_NUM_GATEWAYS", "1"))));
final String brokerHost = replace(cli.getOptionValue("bh"));
final String broker = replace(cli.getOptionValue('b', createBrokerUrl(Optional.ofNullable(brokerHost))));
final String accountName = replace(cli.getOptionValue('a', env("KSIM_ACCOUNT_NAME", "kapua-sys")));
final long shutdownAfter = Long
.parseLong(replace(cli.getOptionValue('s', Long.toString(Long.MAX_VALUE / 1_000L))));
dumpEnv();
logger.info("Starting simulation ...");
logger.info("\tbasename : {}", basename);
logger.info("\tname-factory : {}", nameFactoryName);
logger.info("\tcount: {}", count);
logger.info("\tbroker: {}", broker);
logger.info("\taccount-name: {}", accountName);
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final List<AutoCloseable> close = new LinkedList<>();
final NameFactory nameFactory = createNameFactory(nameFactoryName)
.orElseGet(() -> NameFactories.prefixed(basename));
try {
for (int i = 1; i <= count; i++) {
final String name = nameFactory.generateName(i);
logger.info("Creating instance #{} - {}", i, name);
final GatewayConfiguration configuration = new GatewayConfiguration(broker, accountName, name);
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
close.add(transport);
final Simulator simulator = new Simulator(configuration, transport, apps);
close.add(simulator);
}
Thread.sleep(shutdownAfter * 1_000L);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
closeAll(close);
}
logger.info("Exiting...");
}
#location 52
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ConsoleSetting settings = ConsoleSetting.getInstance();
String authCode = req.getParameter("code");
String uri = settings.getString(ConsoleSettingKeys.SSO_OPENID_SERVER_ENDPOINT_TOKEN);
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_CLIENT_ID) + "&redirect_uri=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_REDIRECT_URI);
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
String baseUri = settings.getString(ConsoleSettingKeys.SITE_HOME_URI);
String separator = baseUri.contains("?") ? "&" : "?";
resp.sendRedirect(baseUri + separator + "access_token=" + accessToken);
}
|
#vulnerable code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String authCode = req.getParameter("code");
String uri = "http://localhost:9090/auth/realms/master/protocol/openid-connect/token";
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=console&redirect_uri=" + callbackUrl;
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
resp.sendRedirect("http://localhost:8889/console.jsp?gwt.codesvr=127.0.0.1:9997&access_token=" + accessToken);
}
#location 23
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
try (final GeneratorScheduler scheduler = new GeneratorScheduler(Duration.ofSeconds(1))) {
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
apps.add(simpleDataApplication("data-1", scheduler, "sine", sine(100, 0, ofSeconds(120))));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
}
logger.info("Exiting...");
}
|
#vulnerable code
public static void main(final String[] args) throws Throwable {
toInfinityAndBeyond();
logger.info("Starting ...");
final ScheduledExecutorService downloadExecutor = Executors
.newSingleThreadScheduledExecutor(new NameThreadFactory("DownloadSimulator"));
final GatewayConfiguration configuration = new GatewayConfiguration(
"tcp://kapua-broker:kapua-password@localhost:1883", "kapua-sys", "sim-1");
final Set<Application> apps = new HashSet<>();
apps.add(new SimpleCommandApplication(s -> String.format("Command '%s' not found", s)));
apps.add(AnnotatedApplication.build(new SimpleDeployApplication(downloadExecutor)));
try (final MqttAsyncTransport transport = new MqttAsyncTransport(configuration);
final Simulator simulator = new Simulator(configuration, transport, apps);) {
Thread.sleep(Long.MAX_VALUE);
logger.info("Bye bye...");
} finally {
downloadExecutor.shutdown();
}
logger.info("Exiting...");
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
final InputStream is = urlConnection.getInputStream();
try {
byte[] buffer = new byte[4096];
final OutputStream os = new FileOutputStream(tmpFile);
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", maxLength, iconResource);
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
} finally {
is.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
|
#vulnerable code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
s_logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
s_logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
s_logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
s_logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
s_logger.warn("Cannot get Content-Length header!");
}
s_logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
try (OutputStream os = new FileOutputStream(tmpFile)) {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
s_logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
}
s_logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
s_logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
s_logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
s_logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
s_logger.info("Image validation passed for URL: {}", iconResource);
} else {
s_logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
s_logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
s_logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
#location 35
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
final InputStream is = urlConnection.getInputStream();
try {
byte[] buffer = new byte[4096];
final OutputStream os = new FileOutputStream(tmpFile);
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", maxLength, iconResource);
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
} finally {
is.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
|
#vulnerable code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
s_logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
s_logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
s_logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
s_logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
s_logger.warn("Cannot get Content-Length header!");
}
s_logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
try (OutputStream os = new FileOutputStream(tmpFile)) {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
s_logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
}
s_logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
s_logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
s_logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
s_logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
s_logger.info("Image validation passed for URL: {}", iconResource);
} else {
s_logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
s_logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
s_logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
#location 92
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
logger.warn("Content lenght exceeded ({}/{}) for URL: {}", contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
logger.warn("Cannot get Content-Length header!");
}
logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
final InputStream is = urlConnection.getInputStream();
try {
byte[] buffer = new byte[4096];
final OutputStream os = new FileOutputStream(tmpFile);
try {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
logger.warn("Maximum content lenght exceeded ({}) for URL: {}", maxLength, iconResource);
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
} finally {
os.close();
}
} finally {
is.close();
}
logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
logger.info("Image validation passed for URL: {}", iconResource);
} else {
logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
|
#vulnerable code
@SuppressWarnings("Duplicates")
private void checkIconResource(KapuaTicon icon) {
ConsoleSetting config = ConsoleSetting.getInstance();
String iconResource = icon.getResource();
//
// Check if the resource is an HTTP URL or not
if (iconResource != null &&
(iconResource.toLowerCase().startsWith("http://") ||
iconResource.toLowerCase().startsWith("https://"))) {
File tmpFile = null;
try {
s_logger.info("Got configuration component icon from URL: {}", iconResource);
//
// Tmp file name creation
String systemTmpDir = System.getProperty("java.io.tmpdir");
String iconResourcesTmpDir = config.getString(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_FOLDER);
String tmpFileName = Base64.encodeBase64String(MessageDigest.getInstance("MD5").digest(iconResource.getBytes(StandardCharsets.UTF_8)));
// Conversions needed got security reasons!
// On the file servlet we use the regex [0-9A-Za-z]{1,} to validate the given file id.
// This validation prevents the caller of the file servlet to try to move out of the directory where the icons are stored.
tmpFileName = tmpFileName.replaceAll("/", "a");
tmpFileName = tmpFileName.replaceAll("\\+", "m");
tmpFileName = tmpFileName.replaceAll("=", "z");
//
// Tmp dir check and creation
StringBuilder tmpDirPathSb = new StringBuilder().append(systemTmpDir);
if (!systemTmpDir.endsWith("/")) {
tmpDirPathSb.append("/");
}
tmpDirPathSb.append(iconResourcesTmpDir);
File tmpDir = new File(tmpDirPathSb.toString());
if (!tmpDir.exists()) {
s_logger.info("Creating tmp dir on path: {}", tmpDir.toString());
tmpDir.mkdir();
}
//
// Tmp file check and creation
tmpDirPathSb.append("/")
.append(tmpFileName);
tmpFile = new File(tmpDirPathSb.toString());
// Check date of modification to avoid caching forever
if (tmpFile.exists()) {
long lastModifiedDate = tmpFile.lastModified();
long maxCacheTime = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_CACHE_TIME);
if (System.currentTimeMillis() - lastModifiedDate > maxCacheTime) {
s_logger.info("Deleting old cached file: {}", tmpFile.toString());
tmpFile.delete();
}
}
// If file is not cached, download it.
if (!tmpFile.exists()) {
// Url connection
URL iconUrl = new URL(iconResource);
URLConnection urlConnection = iconUrl.openConnection();
urlConnection.setConnectTimeout(2000);
urlConnection.setReadTimeout(2000);
// Length check
String contentLengthString = urlConnection.getHeaderField("Content-Length");
long maxLength = config.getLong(ConsoleSettingKeys.DEVICE_CONFIGURATION_ICON_SIZE_MAX);
try {
Long contentLength = Long.parseLong(contentLengthString);
if (contentLength > maxLength) {
s_logger.warn("Content lenght exceeded ({}/{}) for URL: {}",
contentLength, maxLength, iconResource);
throw new IOException("Content-Length reported a length of " + contentLength + " which exceeds the maximum allowed size of " + maxLength);
}
} catch (NumberFormatException nfe) {
s_logger.warn("Cannot get Content-Length header!");
}
s_logger.info("Creating file: {}", tmpFile.toString());
tmpFile.createNewFile();
// Icon download
InputStream is = urlConnection.getInputStream();
byte[] buffer = new byte[4096];
try (OutputStream os = new FileOutputStream(tmpFile)) {
int len;
while ((len = is.read(buffer)) > 0) {
os.write(buffer, 0, len);
maxLength -= len;
if (maxLength < 0) {
s_logger.warn("Maximum content lenght exceeded ({}) for URL: {}",
new Object[] { maxLength, iconResource });
throw new IOException("Maximum content lenght exceeded (" + maxLength + ") for URL: " + iconResource);
}
}
}
s_logger.info("Downloaded file: {}", tmpFile.toString());
// Image metadata content checks
ImageFormat imgFormat = Sanselan.guessFormat(tmpFile);
if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_BMP) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_GIF) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_JPEG) ||
imgFormat.equals(ImageFormat.IMAGE_FORMAT_PNG)) {
s_logger.info("Detected image format: {}", imgFormat.name);
} else if (imgFormat.equals(ImageFormat.IMAGE_FORMAT_UNKNOWN)) {
s_logger.error("Unknown file format for URL: {}", iconResource);
throw new IOException("Unknown file format for URL: " + iconResource);
} else {
s_logger.error("Usupported file format ({}) for URL: {}", imgFormat, iconResource);
throw new IOException("Unknown file format for URL: {}" + iconResource);
}
s_logger.info("Image validation passed for URL: {}", iconResource);
} else {
s_logger.info("Using cached file: {}", tmpFile.toString());
}
//
// Injecting new URL for the icon resource
String newResourceURL = "img://console/file/icons?id=" +
tmpFileName;
s_logger.info("Injecting configuration component icon: {}", newResourceURL);
icon.setResource(newResourceURL);
} catch (Exception e) {
if (tmpFile != null &&
tmpFile.exists()) {
tmpFile.delete();
}
icon.setResource("Default");
s_logger.error("Error while checking component configuration icon. Using the default plugin icon.", e);
}
}
//
// If not, all is fine.
}
#location 137
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ConsoleSetting settings = ConsoleSetting.getInstance();
String authCode = req.getParameter("code");
String uri = settings.getString(ConsoleSettingKeys.SSO_OPENID_SERVER_ENDPOINT_TOKEN);
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_CLIENT_ID) + "&redirect_uri=" + settings.getString(ConsoleSettingKeys.SSO_OPENID_REDIRECT_URI);
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
String baseUri = settings.getString(ConsoleSettingKeys.SITE_HOME_URI);
String separator = baseUri.contains("?") ? "&" : "?";
resp.sendRedirect(baseUri + separator + "access_token=" + accessToken);
}
|
#vulnerable code
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String authCode = req.getParameter("code");
String uri = "http://localhost:9090/auth/realms/master/protocol/openid-connect/token";
URL url = new URL(uri);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
String urlParameters = "grant_type=authorization_code&code=" + authCode + "&client_id=console&redirect_uri=" + callbackUrl;
// Send post request
urlConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(urlConnection.getOutputStream());
outputStream.writeBytes(urlParameters);
outputStream.flush();
outputStream.close();
int responseCode = urlConnection.getResponseCode();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
// parse result
JsonReader jsonReader = Json.createReader(inputReader);
// Parse json response
JsonObject jsonObject = jsonReader.readObject();
inputReader.close();
// Get and clean jwks_uri property
String accessToken = jsonObject.getString("access_token");
resp.sendRedirect("http://localhost:8889/console.jsp?gwt.codesvr=127.0.0.1:9997&access_token=" + accessToken);
}
#location 36
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
int nblocks = blockIds.length;
if (modifiesInedges) {
int startStreamBlock = rangeStartEdgePtr / blocksize;
for(int i=0; i < nblocks; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
if (i >= startStreamBlock) {
// Synchronous write
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
} else {
// Asynchronous write (not implemented yet, so is same as synchronous)
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
} else if (modifiesOutedges) {
int last = streamingOffsetEdgePtr;
if (last == 0) {
last = edataFilesize;
}
int startblock = (int) (rangeStartEdgePtr / blocksize);
int endblock = (int) (last / blocksize);
for(int i=startblock; i <= endblock; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
/* Release all blocks */
for(Integer blockId : blockIds) {
dataBlockManager.release(blockId);
}
}
|
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
blocksize = ChiFilenames.getBlocksize(converter.sizeOf());
loadAdj();
loadEdata();
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
}
|
#vulnerable code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
loadAdj();
edataFilesize = (int) new File(edgeDataFilename).length();
blockId = dataBlockManager.allocateBlock(edataFilesize);
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockId, edataPtr, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockId, edataPtr, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
/* Load the edge data from file. Should be done asynchronously. */
if (!loaded) {
int read = 0;
FileInputStream fdis = new FileInputStream(new File(edgeDataFilename));
while (read < edataFilesize) {
read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read);
}
loaded = true;
}
}
#location 90
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
blocksize = ChiFilenames.getBlocksize(converter.sizeOf());
loadAdj();
loadEdata();
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockIds[edataPtr / blocksize], edataPtr % blocksize, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
}
|
#vulnerable code
public void loadVertices(int windowStart, int windowEnd, ChiVertex[] vertices)
throws FileNotFoundException, IOException {
if (adjData == null) {
loadAdj();
edataFilesize = (int) new File(edgeDataFilename).length();
blockId = dataBlockManager.allocateBlock(edataFilesize);
}
System.out.println("Load memory shard");
int vid = 0;
int edataPtr = 0;
int adjOffset = 0;
int sizeOf = converter.sizeOf();
DataInputStream adjInput = new DataInputStream(new ByteArrayInputStream(adjData));
while(adjInput.available() > 0) {
if (!hasSetOffset && vid > rangeEnd) {
streamingOffset = adjOffset;
streamingOffsetEdgePtr = edataPtr;
streamingOffsetVid = vid;
hasSetOffset = true;
}
if (!hasSetRangeOffset && vid >= rangeStart) {
rangeStartOffset = adjOffset;
rangeStartEdgePtr = edataPtr;
hasSetRangeOffset = true;
}
int n = 0;
int ns = adjInput.readUnsignedByte();
adjOffset += 1;
assert(ns >= 0);
if (ns == 0) {
// next value tells the number of vertices with zeros
vid++;
int nz = adjInput.readUnsignedByte();
adjOffset += 1;
vid += nz;
continue;
}
if (ns == 0xff) { // If 255 is not enough, then stores a 32-bit integer after.
n = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
} else {
n = ns;
}
ChiVertex vertex = null;
if (vid >= windowStart && vid <= windowEnd) {
vertex = vertices[vid - windowStart];
}
while (--n >= 0) {
int target = Integer.reverseBytes(adjInput.readInt());
adjOffset += 4;
if (!(target >= rangeStart && target <= rangeEnd))
throw new IllegalStateException("Target " + target + " not in range!");
if (vertex != null) {
vertex.addOutEdge(blockId, edataPtr, target);
}
if (target >= windowStart) {
if (target <= windowEnd) {
ChiVertex dstVertex = vertices[target - windowStart];
if (dstVertex != null) {
dstVertex.addInEdge(blockId, edataPtr, vid);
}
if (vertex != null && dstVertex != null) {
dstVertex.parallelSafe = false;
vertex.parallelSafe = false;
}
}
}
edataPtr += sizeOf;
// TODO: skip
}
vid++;
}
/* Load the edge data from file. Should be done asynchronously. */
if (!loaded) {
int read = 0;
FileInputStream fdis = new FileInputStream(new File(edgeDataFilename));
while (read < edataFilesize) {
read += fdis.read(dataBlockManager.getRawBlock(blockId), read, edataFilesize - read);
}
loaded = true;
}
}
#location 84
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.flush();
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.flush();
rFile.close();
}
dataBlockManager.release(blockId);
}
|
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.flush();
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.flush();
rFile.close();
}
dataBlockManager.release(blockId);
}
|
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
int nblocks = blockIds.length;
if (modifiesInedges) {
int startStreamBlock = rangeStartEdgePtr / blocksize;
for(int i=0; i < nblocks; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
if (i >= startStreamBlock) {
// Synchronous write
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
} else {
// Asynchronous write (not implemented yet, so is same as synchronous)
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
} else if (modifiesOutedges) {
int last = streamingOffsetEdgePtr;
if (last == 0) {
last = edataFilesize;
}
int startblock = (int) (rangeStartEdgePtr / blocksize);
int endblock = (int) (last / blocksize);
for(int i=startblock; i <= endblock; i++) {
String blockFilename = ChiFilenames.getFilenameShardEdataBlock(edgeDataFilename, i, blocksize);
CompressedIO.writeCompressed(new File(blockFilename),
dataBlockManager.getRawBlock(blockIds[i]),
blockSizes[i]);
}
}
/* Release all blocks */
for(Integer blockId : blockIds) {
dataBlockManager.release(blockId);
}
}
|
#vulnerable code
public void commitAndRelease(boolean modifiesInedges, boolean modifiesOutedges) throws IOException {
byte[] data = dataBlockManager.getRawBlock(blockId);
if (modifiesInedges) {
FileOutputStream fos = new FileOutputStream(new File(edgeDataFilename));
fos.write(data);
fos.close();
} else if (modifiesOutedges) {
ucar.unidata.io.RandomAccessFile rFile =
new ucar.unidata.io.RandomAccessFile(edgeDataFilename, "rwd");
rFile.seek(rangeStartEdgePtr);
int last = streamingOffsetEdgePtr;
if (last == 0) last = edataFilesize;
rFile.write(data, rangeStartEdgePtr, last - rangeStartEdgePtr);
rFile.close();
}
dataBlockManager.release(blockId);
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void send() throws Exception {
if ((message == null) || (endpoint == null)) {
logger.debug("event=send_http_request error_code=MissingParameters endpoint=" + endpoint + "\" message=\"" + message + "\"");
throw new Exception("Message and Endpoint must both be set");
}
HttpPost httpPost = new HttpPost(endpoint);
String msg = null;
if (message.getMessageStructure() == CNSMessageStructure.json) {
msg = message.getProtocolSpecificMessage(CnsSubscriptionProtocol.http);
} else {
msg = message.getMessage();
}
if (!rawMessageDelivery && message.getMessageType() == CNSMessageType.Notification) {
msg = com.comcast.cns.util.Util.generateMessageJson(message, CnsSubscriptionProtocol.http);
}
logger.info("event=send_sync_http_request endpoint=" + endpoint + "\" message=\"" + msg + "\"");
StringEntity stringEntity = new StringEntity(msg);
httpPost.setEntity(stringEntity);
composeHeader(httpPost);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// accept all 2xx status codes
if (statusCode > 200 || statusCode >= 300) {
if (entity != null) {
InputStream instream = entity.getContent();
InputStreamReader responseReader = new InputStreamReader(instream);
StringBuffer buffer = new StringBuffer();
char []arr = new char[1024];
int size = 0;
while ((size = responseReader.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, size);
}
instream.close();
}
logger.debug("event=http_post_error endpoint=" + endpoint + " error_code=" + statusCode);
throw new CMBException(new CMBErrorCodes(statusCode, "HttpError"), "Unreachable endpoint " + endpoint + " returns status code " + statusCode);
} else {
if (entity != null) {
EntityUtils.consume(entity);
}
}
}
|
#vulnerable code
@Override
public void send() throws Exception {
logger.debug("event=send_sync_http_request endpoint=" + endpoint + "\" message=\"" + message + "\"");
if ((message == null) || (endpoint == null)) {
logger.debug("event=send_http_request error_code=MissingParameters endpoint=" + endpoint + "\" message=\"" + message + "\"");
throw new Exception("Message and Endpoint must both be set");
}
HttpPost httpPost = new HttpPost(endpoint);
StringEntity stringEntity = new StringEntity(message);
httpPost.setEntity(stringEntity);
composeHeader(httpPost);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// accept all 2xx status codes
if (statusCode > 200 || statusCode >= 300) {
if (entity != null) {
InputStream instream = entity.getContent();
InputStreamReader responseReader = new InputStreamReader(instream);
StringBuffer buffer = new StringBuffer();
char []arr = new char[1024];
int size = 0;
while ((size = responseReader.read(arr, 0, arr.length)) != -1) {
buffer.append(arr, 0, size);
}
instream.close();
}
logger.debug("event=http_post_error endpoint=" + endpoint + " error_code=" + statusCode);
throw new CMBException(new CMBErrorCodes(statusCode, "HttpError"), "Unreachable endpoint " + endpoint + " returns status code " + statusCode);
} else {
if (entity != null) {
EntityUtils.consume(entity);
}
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String topicArn = request.getParameter("topicArn");
String userId = request.getParameter("userId");
Map<?, ?> params = request.getParameterMap();
connect(request);
out.println("<html>");
simpleHeader(request, out, "View/Edit Topic Delivery Policy");
if (params.containsKey("Update")) {
String numRetries = request.getParameter("numRetries");
String retriesNoDelay = request.getParameter("retriesNoDelay");
String minDelay = request.getParameter("minDelay");
String minDelayRetries = request.getParameter("minDelayRetries");
String maxDelay = request.getParameter("maxDelay");
String maxDelayRetries = request.getParameter("maxDelayRetries");
String maxReceiveRate = request.getParameter("maxReceiveRate");
String backoffFunc = request.getParameter("backoffFunc");
String ignoreOverride = request.getParameter("ignoreOverride");
CNSTopicDeliveryPolicy deliveryPolicy = new CNSTopicDeliveryPolicy();
CNSRetryPolicy defaultHealthyRetryPolicy = new CNSRetryPolicy();
if (maxDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMaxDelayTarget(Integer.parseInt(maxDelay));
}
if (minDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMinDelayTarget(Integer.parseInt(minDelay));
}
if (maxDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMaxDelayRetries(Integer.parseInt(maxDelayRetries));
}
if (minDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMinDelayRetries(Integer.parseInt(minDelayRetries));
}
if (retriesNoDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumNoDelayRetries(Integer.parseInt(retriesNoDelay));
}
if (numRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumRetries(Integer.parseInt(numRetries));
}
defaultHealthyRetryPolicy.setBackOffFunction(CnsBackoffFunction.valueOf(backoffFunc));
deliveryPolicy.setDefaultHealthyRetryPolicy(defaultHealthyRetryPolicy);
deliveryPolicy.setDisableSubscriptionOverrides(ignoreOverride != null ? true: false);
CNSThrottlePolicy defaultThrottle = new CNSThrottlePolicy();
if (maxReceiveRate.trim().length() > 0) {
defaultThrottle.setMaxReceivesPerSecond(Integer.parseInt(maxReceiveRate));
}
deliveryPolicy.setDefaultThrottlePolicy(defaultThrottle );
try {
SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest(topicArn, "DeliveryPolicy", deliveryPolicy.toString());
sns.setTopicAttributes(setTopicAttributesRequest);
logger.debug("event=set_delivery_policy topic_arn=" + topicArn + " userId= " + userId);
} catch (Exception ex) {
logger.error("event=set_delivery_policy user_id= " + userId, ex);
throw new ServletException(ex);
}
out.println("<body onload='javascript:window.opener.location.reload();window.close();'>");
} else {
int numRetries=0, retriesNoDelay = 0, minDelay = 0, minDelayRetries = 0, maxDelay = 0, maxDelayRetries = 0, maxReceiveRate = 0;
String retryBackoff = "linear";
boolean ignoreOverride = false;
if (topicArn != null) {
Map<String, String> attributes = null;
CNSTopicDeliveryPolicy deliveryPolicy = null;
try {
GetTopicAttributesRequest getTopicAttributesRequest = new GetTopicAttributesRequest(topicArn);
GetTopicAttributesResult getTopicAttributesResult = sns.getTopicAttributes(getTopicAttributesRequest);
attributes = getTopicAttributesResult.getAttributes();
deliveryPolicy = new CNSTopicDeliveryPolicy(new JSONObject(attributes.get("DeliveryPolicy")));
} catch (Exception ex) {
logger.error("event=failed_to_get_attributes arn=" + topicArn, ex);
throw new ServletException(ex);
}
if (deliveryPolicy != null) {
CNSRetryPolicy healPol = deliveryPolicy.getDefaultHealthyRetryPolicy();
if (healPol != null) {
numRetries= healPol.getNumRetries();
retriesNoDelay = healPol.getNumNoDelayRetries();
minDelay = healPol.getMinDelayTarget();
minDelayRetries = healPol.getNumMinDelayRetries();
maxDelay = healPol.getMaxDelayTarget();
maxDelayRetries = healPol.getNumMaxDelayRetries();
retryBackoff = healPol.getBackOffFunction().toString();
}
CNSThrottlePolicy throttlePol = deliveryPolicy.getDefaultThrottlePolicy();
if (throttlePol != null) {
if (throttlePol.getMaxReceivesPerSecond() != null) {
maxReceiveRate = throttlePol.getMaxReceivesPerSecond().intValue();
}
}
ignoreOverride = deliveryPolicy.isDisableSubscriptionOverrides();
}
}
out.println("<body>");
out.println("<h1>View/Edit Topic Delivery Policy</h1>");
out.println("<form action=\"/webui/cnsuser/editdeliverypolicy?topicArn="+topicArn+"\" method=POST>");
out.println("<input type='hidden' name='userId' value='"+ userId +"'>");
out.println("<table>");
out.println("<tr><td colspan=2><b><font color='orange'>Delivery Policy</font></b></td></tr>");
out.println("<tr><td colspan=2><b>Apply these delivery policies for the topic:</b></td></tr>");
out.println("<tr><td>Number of retries:</td><td><input type='text' name='numRetries' size='50' value='" + numRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between 0 - 100</font></I></td></tr>");
out.println("<tr><td>Retries with no delay:</td><td><input type='text' name='retriesNoDelay' size='50' value='" + retriesNoDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Minimum delay:</td><td><input type='text' name='minDelay' size='50' value='" + minDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds.Between 0 - maximum delay</font></I></td></tr>");
out.println("<tr><td>Minimum delay retries:</td><td><input type='text' name='minDelayRetries' size='50' value='" + minDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum delay:</td><td><input type='text' name='maxDelay' size='50' value='" + maxDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds. Between minimum delay - 3600</font></I></td></tr>");
out.println("<tr><td>Maximum delay retries:</td><td><input type='text' name='maxDelayRetries' size='50' value='" + maxDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum receive rate:</td><td><input type='text' name='maxReceiveRate' size='50' value='" + maxReceiveRate + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Receives per second. >= 1</font></I></td></tr>");
out.println("<tr><td> </td><td> </td></tr>");
if (retryBackoff.equals("linear")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear' selected>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("arithmetic")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic' selected>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("geometric")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric' selected>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("exponential")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential' selected>Exponential</option></select></td></tr>");
}
if (ignoreOverride) {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride' checked></td></tr>");
} else {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride'></td></tr>");
}
out.println("<tr><td colspan=2><hr/></td></tr>");
out.println("<tr><td colspan=2 align=right><input type='button' onclick='window.close()' value='Cancel'><input type='submit' name='Update' value='Update'></td></tr></table></form>");
}
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
|
#vulnerable code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String topicArn = request.getParameter("topicArn");
String userId = request.getParameter("userId");
Map<?, ?> params = request.getParameterMap();
connect(userId);
out.println("<html>");
simpleHeader(request, out, "View/Edit Topic Delivery Policy");
if (params.containsKey("Update")) {
String numRetries = request.getParameter("numRetries");
String retriesNoDelay = request.getParameter("retriesNoDelay");
String minDelay = request.getParameter("minDelay");
String minDelayRetries = request.getParameter("minDelayRetries");
String maxDelay = request.getParameter("maxDelay");
String maxDelayRetries = request.getParameter("maxDelayRetries");
String maxReceiveRate = request.getParameter("maxReceiveRate");
String backoffFunc = request.getParameter("backoffFunc");
String ignoreOverride = request.getParameter("ignoreOverride");
CNSTopicDeliveryPolicy deliveryPolicy = new CNSTopicDeliveryPolicy();
CNSRetryPolicy defaultHealthyRetryPolicy = new CNSRetryPolicy();
if (maxDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMaxDelayTarget(Integer.parseInt(maxDelay));
}
if (minDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setMinDelayTarget(Integer.parseInt(minDelay));
}
if (maxDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMaxDelayRetries(Integer.parseInt(maxDelayRetries));
}
if (minDelayRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumMinDelayRetries(Integer.parseInt(minDelayRetries));
}
if (retriesNoDelay.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumNoDelayRetries(Integer.parseInt(retriesNoDelay));
}
if (numRetries.trim().length() > 0) {
defaultHealthyRetryPolicy.setNumRetries(Integer.parseInt(numRetries));
}
defaultHealthyRetryPolicy.setBackOffFunction(CnsBackoffFunction.valueOf(backoffFunc));
deliveryPolicy.setDefaultHealthyRetryPolicy(defaultHealthyRetryPolicy);
deliveryPolicy.setDisableSubscriptionOverrides(ignoreOverride != null ? true: false);
CNSThrottlePolicy defaultThrottle = new CNSThrottlePolicy();
if (maxReceiveRate.trim().length() > 0) {
defaultThrottle.setMaxReceivesPerSecond(Integer.parseInt(maxReceiveRate));
}
deliveryPolicy.setDefaultThrottlePolicy(defaultThrottle );
try {
SetTopicAttributesRequest setTopicAttributesRequest = new SetTopicAttributesRequest(topicArn, "DeliveryPolicy", deliveryPolicy.toString());
sns.setTopicAttributes(setTopicAttributesRequest);
logger.debug("event=set_delivery_policy topic_arn=" + topicArn + " userId= " + userId);
} catch (Exception ex) {
logger.error("event=set_delivery_policy user_id= " + userId, ex);
throw new ServletException(ex);
}
out.println("<body onload='javascript:window.opener.location.reload();window.close();'>");
} else {
int numRetries=0, retriesNoDelay = 0, minDelay = 0, minDelayRetries = 0, maxDelay = 0, maxDelayRetries = 0, maxReceiveRate = 0;
String retryBackoff = "linear";
boolean ignoreOverride = false;
if (topicArn != null) {
Map<String, String> attributes = null;
CNSTopicDeliveryPolicy deliveryPolicy = null;
try {
GetTopicAttributesRequest getTopicAttributesRequest = new GetTopicAttributesRequest(topicArn);
GetTopicAttributesResult getTopicAttributesResult = sns.getTopicAttributes(getTopicAttributesRequest);
attributes = getTopicAttributesResult.getAttributes();
deliveryPolicy = new CNSTopicDeliveryPolicy(new JSONObject(attributes.get("DeliveryPolicy")));
} catch (Exception ex) {
logger.error("event=failed_to_get_attributes arn=" + topicArn, ex);
throw new ServletException(ex);
}
if (deliveryPolicy != null) {
CNSRetryPolicy healPol = deliveryPolicy.getDefaultHealthyRetryPolicy();
if (healPol != null) {
numRetries= healPol.getNumRetries();
retriesNoDelay = healPol.getNumNoDelayRetries();
minDelay = healPol.getMinDelayTarget();
minDelayRetries = healPol.getNumMinDelayRetries();
maxDelay = healPol.getMaxDelayTarget();
maxDelayRetries = healPol.getNumMaxDelayRetries();
retryBackoff = healPol.getBackOffFunction().toString();
}
CNSThrottlePolicy throttlePol = deliveryPolicy.getDefaultThrottlePolicy();
if (throttlePol != null) {
if (throttlePol.getMaxReceivesPerSecond() != null) {
maxReceiveRate = throttlePol.getMaxReceivesPerSecond().intValue();
}
}
ignoreOverride = deliveryPolicy.isDisableSubscriptionOverrides();
}
}
out.println("<body>");
out.println("<h1>View/Edit Topic Delivery Policy</h1>");
out.println("<form action=\"/webui/cnsuser/editdeliverypolicy?topicArn="+topicArn+"\" method=POST>");
out.println("<input type='hidden' name='userId' value='"+ userId +"'>");
out.println("<table>");
out.println("<tr><td colspan=2><b><font color='orange'>Delivery Policy</font></b></td></tr>");
out.println("<tr><td colspan=2><b>Apply these delivery policies for the topic:</b></td></tr>");
out.println("<tr><td>Number of retries:</td><td><input type='text' name='numRetries' size='50' value='" + numRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between 0 - 100</font></I></td></tr>");
out.println("<tr><td>Retries with no delay:</td><td><input type='text' name='retriesNoDelay' size='50' value='" + retriesNoDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Minimum delay:</td><td><input type='text' name='minDelay' size='50' value='" + minDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds.Between 0 - maximum delay</font></I></td></tr>");
out.println("<tr><td>Minimum delay retries:</td><td><input type='text' name='minDelayRetries' size='50' value='" + minDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum delay:</td><td><input type='text' name='maxDelay' size='50' value='" + maxDelay + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>In seconds. Between minimum delay - 3600</font></I></td></tr>");
out.println("<tr><td>Maximum delay retries:</td><td><input type='text' name='maxDelayRetries' size='50' value='" + maxDelayRetries + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Between (0 - number of retries)</font></I></td></tr>");
out.println("<tr><td>Maximum receive rate:</td><td><input type='text' name='maxReceiveRate' size='50' value='" + maxReceiveRate + "'></td></tr>");
out.println("<tr><td> </td><td><I><font color='grey'>Receives per second. >= 1</font></I></td></tr>");
out.println("<tr><td> </td><td> </td></tr>");
if (retryBackoff.equals("linear")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear' selected>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("arithmetic")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic' selected>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("geometric")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric' selected>Geometric</option><option value='exponential'>Exponential</option></select></td></tr>");
} else if (retryBackoff.equals("exponential")) {
out.println("<tr><td>Retry backoff function:</td><td><select name='backoffFunc'><option value='linear'>Linear</option><option value='arithmetic'>Arithmetic</option><option value='geometric'>Geometric</option><option value='exponential' selected>Exponential</option></select></td></tr>");
}
if (ignoreOverride) {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride' checked></td></tr>");
} else {
out.println("<tr><td>Ignore subscription override:</td><td><input type='checkbox' name='ignoreOverride'></td></tr>");
}
out.println("<tr><td colspan=2><hr/></td></tr>");
out.println("<tr><td colspan=2 align=right><input type='button' onclick='window.close()' value='Cancel'><input type='submit' name='Update' value='Update'></td></tr></table></form>");
}
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
#location 117
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Map<?, ?> parameters = request.getParameterMap();
String userId = request.getParameter("userId");
String topicArn = request.getParameter("topicArn");
String endPoint = request.getParameter("endPoint");
String protocol = request.getParameter("protocol");
String arn = request.getParameter("arn");
String nextToken = request.getParameter("nextToken");
connect(request);
if (parameters.containsKey("Subscribe")) {
try {
SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, protocol.toLowerCase(), endPoint);
sns.subscribe(subscribeRequest);
} catch (Exception ex) {
logger.error("event=subscribe", ex);
throw new ServletException(ex);
}
} else if (parameters.containsKey("Unsubscribe")) {
try {
UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(arn);
sns.unsubscribe(unsubscribeRequest);
} catch (Exception ex) {
logger.error("event=unsubscribe arn=" + arn , ex);
throw new ServletException(ex);
}
}
List<Subscription> subscriptions = new ArrayList<Subscription>();
ListSubscriptionsByTopicResult listSubscriptionsByTopicResult = null;
try {
listSubscriptionsByTopicResult = sns.listSubscriptionsByTopic(new ListSubscriptionsByTopicRequest(topicArn, nextToken));
subscriptions = listSubscriptionsByTopicResult.getSubscriptions();
} catch (Exception ex) {
logger.error("event=listAllSubscriptionsByTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
ICNSTopicPersistence topicHandler = PersistenceFactory.getTopicPersistence();
CNSTopic topic = null;
try {
topic = topicHandler.getTopic(topicArn);
} catch (Exception ex) {
logger.error("event=getTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
out.println("<html>");
out.println("<script type='text/javascript' language='javascript'>");
out.println("function changeEndpointHint(protocol){ ");
out.println(" if (protocol == 'HTTP' || protocol == 'HTTPS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. http://company.com'; }");
out.println(" else if (protocol == 'EMAIL' || protocol == 'EMAIL_JSON') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. user@domain.com'; }");
out.println(" else if (protocol == 'CQS' || protocol == 'SQS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. arn:aws:cqs:ccp:555555555555:my-queue'; } ");
out.println("}");
out.println("</script>");
header(request, out, "Subscriptions for Topic "+ ((topic != null) ? topic.getName():""));
out.println("<body>");
out.println("<h2>Subscriptions for Topic "+ ((topic != null) ? topic.getName():"") + "</h2>");
if (user != null) {
out.println("<table><tr><td><b>User Name:</b></td><td>"+ user.getUserName()+"</td></tr>");
out.println("<tr><td><b>User ID:</b></td><td>"+ user.getUserId()+"</td></tr>");
out.println("<tr><td><b>Access Key:</b></td><td>"+user.getAccessKey()+"</td></tr>");
out.println("<tr><td><b>Access Secret:</b></td><td>"+user.getAccessSecret()+"</td></tr>");
out.println("<tr><td><b>Topic Name:</b></td><td>"+ topic.getName()+"</td></tr>");
out.println("<tr><td><b>Topic Display Name:</b></td><td>" + topic.getDisplayName()+ "</td></tr>");
out.println("<tr><td><b>Topic Arn:</b></td><td>" + topic.getArn()+ "</td></tr>");
out.println("<tr><td><b>Num Subscriptions:</b></td><td>" + subscriptions.size()+ "</td></tr></table>");
}
out.println("<p><table><tr><td><b>Protocol</b></td><td><b>End Point</b></td><td> </td></tr>");
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td><select name='protocol' onchange='changeEndpointHint(this.value)'><option value='HTTP'>HTTP</option><option value='HTTPS'>HTTPS</option><option value='EMAIL'>EMAIL</option><option value='EMAIL_JSON'>EMAIL_JSON</option><option value='CQS'>CQS</option><option value='SQS'>SQS</option></select></td>");
out.println("<td><input type='text' name='endPoint' id = 'endPoint' size='65' placeholder='e.g. http://company.com'><input type='hidden' name='userId' value='"+ userId + "'></td><td><input type='submit' value='Subscribe' name='Subscribe' /></td></tr>");
out.println("</form></table>");
out.println("<p><hr width='100%' align='left' />");
out.println("<p><span class='content'><table border='1'>");
out.println("<tr><th>Row</th>");
out.println("<th>Arn</th>");
out.println("<th>Protocol</th>");
out.println("<th>End Point</th>");
out.println("<th> </th>");
out.println("<th> </th></tr>");
for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {
Subscription s = subscriptions.get(i);
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+user.getUserId()+"&arn="+s.getSubscriptionArn()+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td>"+i+"</td>");
out.println("<td>"+s.getSubscriptionArn() +"<input type='hidden' name='arn' value="+s.getSubscriptionArn()+"></td>");
out.println("<td>"+s.getProtocol()+"</td>");
out.println("<td>"+s.getEndpoint()+"</td>");
if (s.getProtocol().toString().equals("http") && !s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td><a href='' onclick=\"window.open('/webui/cnsuser/subscription/editdeliverypolicy?subscriptionArn="+ s.getSubscriptionArn() + "&userId=" + userId + "', 'EditDeliveryPolicy', 'height=630,width=580,toolbar=no')\">View/Edit Delivery Policy</a></td>");
} else {
out.println("<td> </td>");
}
if (s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td> </td>");
} else {
out.println("<td><input type='submit' value='Unsubscribe' name='Unsubscribe'/></td>");
}
out.println("</tr></form>");
}
out.println("</table></span></p>");
if (listSubscriptionsByTopicResult != null && listSubscriptionsByTopicResult.getNextToken() != null) {
out.println("<p><a href='/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"&nextToken="+response.encodeURL(listSubscriptionsByTopicResult.getNextToken())+"'>next ></a></p>");
}
out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a>");
out.println("<a href='/webui/cnsuser?userId="+userId+"&topicArn="+topicArn+"'>BACK TO TOPIC</a></h5>");
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
|
#vulnerable code
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (redirectUnauthenticatedUser(request, response)) {
return;
}
CMBControllerServlet.valueAccumulator.initializeAllCounters();
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Map<?, ?> parameters = request.getParameterMap();
String userId = request.getParameter("userId");
String topicArn = request.getParameter("topicArn");
String endPoint = request.getParameter("endPoint");
String protocol = request.getParameter("protocol");
String arn = request.getParameter("arn");
String nextToken = request.getParameter("nextToken");
connect(userId);
if (parameters.containsKey("Subscribe")) {
try {
SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, protocol.toLowerCase(), endPoint);
sns.subscribe(subscribeRequest);
} catch (Exception ex) {
logger.error("event=subscribe", ex);
throw new ServletException(ex);
}
} else if (parameters.containsKey("Unsubscribe")) {
try {
UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(arn);
sns.unsubscribe(unsubscribeRequest);
} catch (Exception ex) {
logger.error("event=unsubscribe arn=" + arn , ex);
throw new ServletException(ex);
}
}
List<Subscription> subscriptions = new ArrayList<Subscription>();
ListSubscriptionsByTopicResult listSubscriptionsByTopicResult = null;
try {
listSubscriptionsByTopicResult = sns.listSubscriptionsByTopic(new ListSubscriptionsByTopicRequest(topicArn, nextToken));
subscriptions = listSubscriptionsByTopicResult.getSubscriptions();
} catch (Exception ex) {
logger.error("event=listAllSubscriptionsByTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
ICNSTopicPersistence topicHandler = PersistenceFactory.getTopicPersistence();
CNSTopic topic = null;
try {
topic = topicHandler.getTopic(topicArn);
} catch (Exception ex) {
logger.error("event=getTopic topic_arn=" + topicArn, ex);
throw new ServletException(ex);
}
out.println("<html>");
out.println("<script type='text/javascript' language='javascript'>");
out.println("function changeEndpointHint(protocol){ ");
out.println(" if (protocol == 'HTTP' || protocol == 'HTTPS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. http://company.com'; }");
out.println(" else if (protocol == 'EMAIL' || protocol == 'EMAIL_JSON') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. user@domain.com'; }");
out.println(" else if (protocol == 'CQS' || protocol == 'SQS') { ");
out.println(" document.getElementById('endPoint').placeholder = 'e.g. arn:aws:cqs:ccp:555555555555:my-queue'; } ");
out.println("}");
out.println("</script>");
header(request, out, "Subscriptions for Topic "+ ((topic != null) ? topic.getName():""));
out.println("<body>");
out.println("<h2>Subscriptions for Topic "+ ((topic != null) ? topic.getName():"") + "</h2>");
if (user != null) {
out.println("<table><tr><td><b>User Name:</b></td><td>"+ user.getUserName()+"</td></tr>");
out.println("<tr><td><b>User ID:</b></td><td>"+ user.getUserId()+"</td></tr>");
out.println("<tr><td><b>Access Key:</b></td><td>"+user.getAccessKey()+"</td></tr>");
out.println("<tr><td><b>Access Secret:</b></td><td>"+user.getAccessSecret()+"</td></tr>");
out.println("<tr><td><b>Topic Name:</b></td><td>"+ topic.getName()+"</td></tr>");
out.println("<tr><td><b>Topic Display Name:</b></td><td>" + topic.getDisplayName()+ "</td></tr>");
out.println("<tr><td><b>Topic Arn:</b></td><td>" + topic.getArn()+ "</td></tr>");
out.println("<tr><td><b>Num Subscriptions:</b></td><td>" + subscriptions.size()+ "</td></tr></table>");
}
out.println("<p><table><tr><td><b>Protocol</b></td><td><b>End Point</b></td><td> </td></tr>");
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td><select name='protocol' onchange='changeEndpointHint(this.value)'><option value='HTTP'>HTTP</option><option value='HTTPS'>HTTPS</option><option value='EMAIL'>EMAIL</option><option value='EMAIL_JSON'>EMAIL_JSON</option><option value='CQS'>CQS</option><option value='SQS'>SQS</option></select></td>");
out.println("<td><input type='text' name='endPoint' id = 'endPoint' size='65' placeholder='e.g. http://company.com'><input type='hidden' name='userId' value='"+ userId + "'></td><td><input type='submit' value='Subscribe' name='Subscribe' /></td></tr>");
out.println("</form></table>");
out.println("<p><hr width='100%' align='left' />");
out.println("<p><span class='content'><table border='1'>");
out.println("<tr><th>Row</th>");
out.println("<th>Arn</th>");
out.println("<th>Protocol</th>");
out.println("<th>End Point</th>");
out.println("<th> </th>");
out.println("<th> </th></tr>");
for (int i = 0; subscriptions != null && i < subscriptions.size(); i++) {
Subscription s = subscriptions.get(i);
out.println("<form action=\"/webui/cnsuser/subscription/?userId="+user.getUserId()+"&arn="+s.getSubscriptionArn()+"&topicArn="+topicArn+"\" method=POST>");
out.println("<tr><td>"+i+"</td>");
out.println("<td>"+s.getSubscriptionArn() +"<input type='hidden' name='arn' value="+s.getSubscriptionArn()+"></td>");
out.println("<td>"+s.getProtocol()+"</td>");
out.println("<td>"+s.getEndpoint()+"</td>");
if (s.getProtocol().toString().equals("http") && !s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td><a href='' onclick=\"window.open('/webui/cnsuser/subscription/editdeliverypolicy?subscriptionArn="+ s.getSubscriptionArn() + "&userId=" + userId + "', 'EditDeliveryPolicy', 'height=630,width=580,toolbar=no')\">View/Edit Delivery Policy</a></td>");
} else {
out.println("<td> </td>");
}
if (s.getSubscriptionArn().equals("PendingConfirmation")) {
out.println("<td> </td>");
} else {
out.println("<td><input type='submit' value='Unsubscribe' name='Unsubscribe'/></td>");
}
out.println("</tr></form>");
}
out.println("</table></span></p>");
if (listSubscriptionsByTopicResult != null && listSubscriptionsByTopicResult.getNextToken() != null) {
out.println("<p><a href='/webui/cnsuser/subscription/?userId="+userId+"&topicArn="+topicArn+"&nextToken="+response.encodeURL(listSubscriptionsByTopicResult.getNextToken())+"'>next ></a></p>");
}
out.println("<h5 style='text-align:center;'><a href='/webui'>ADMIN HOME</a>");
out.println("<a href='/webui/cnsuser?userId="+userId+"&topicArn="+topicArn+"'>BACK TO TOPIC</a></h5>");
out.println("</body></html>");
CMBControllerServlet.valueAccumulator.deleteAllCounters();
}
#location 92
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
long timeoutMillis = unit.toMillis(timeout);
long endTime = System.currentTimeMillis() + timeoutMillis;
synchronized (this) {
if (done) return done;
if (timeoutMillis <= 0) return done;
waiters++;
try {
while (!done) {
wait(timeoutMillis);
if (endTime < System.currentTimeMillis() && !done) {
exception = new TimeoutException();
break;
}
}
} finally {
waiters--;
}
}
return done;
}
|
#vulnerable code
@Override
public boolean await(long timeout, TimeUnit unit) throws InterruptedException {
long timeoutMillis = unit.toMillis(timeout);
long endTime = System.currentTimeMillis() + timeoutMillis;
synchronized (this) {
if (ready) return ready;
if (timeoutMillis <= 0) return ready;
waiters++;
try {
while (!ready) {
wait(timeoutMillis);
if (endTime < System.currentTimeMillis() && !ready) {
exception = new TimeoutException();
break;
}
}
} finally {
waiters--;
}
}
return ready;
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static String readFileAsString(String filePath) throws IOException {
byte[] buffer = new byte[(int) getFile(filePath).length()];
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(new FileInputStream(getFile(filePath)));
bis.read(buffer);
} finally {
if (bis != null) {
bis.close();
}
}
return new String(buffer);
}
|
#vulnerable code
public static String readFileAsString(String filePath) throws IOException {
byte[] buffer = new byte[(int) getFile(filePath).length()];
BufferedInputStream inputStream = null;
try {
inputStream = new BufferedInputStream(new FileInputStream(getFile(filePath)));
inputStream.read(buffer);
} finally {
inputStream.close();
}
return new String(buffer);
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void state4ENTITY() throws ProtocolException {
boolean done = skip(CR, LF);
if (!done) {
return;
}
// content length
if (httpMessage.getFirstHeader(HttpHeaderType.CONTENT_LENGTH.getName()) != null) {
entity = new HttpEntity();
entity.setContentType(getContentType(httpMessage));
state = ENTITY_LENGTH;
}
// chunked
else if (TRANSFER_ENCODING_CHUNKED.equals(httpMessage.getFirstHeader(HttpHeaderType.TRANSFER_ENCODING.getName()).getValue())) {
entity = new HttpChunkEntity();
entity.setContentType(getContentType(httpMessage));
state = ENTITY_CHUNKED_SIZE;
}
// no entity
else {
state = END;
}
}
|
#vulnerable code
protected void state4ENTITY() throws ProtocolException {
boolean done = skip(CR, LF);
if (!done) {
return;
}
// content length
if (httpMessage.getFirstHeader(HttpHeaders.CONTENT_LENGTH.getName()) != null) {
entity = new HttpEntity();
entity.setCharset(getContentCharset(httpMessage));
state = ENTITY_LENGTH;
}
// chunked
else if (TRANSFER_ENCODING_CHUNKED.equals(httpMessage.getFirstHeader(HttpHeaders.TRANSFER_ENCODING.getName()).getValue())) {
entity = new HttpChunkEntity();
entity.setCharset(getContentCharset(httpMessage));
state = ENTITY_CHUNKED_SIZE;
}
// no entity
else {
state = END;
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@BeforeClass
public static void startElasticsearchRestClient() throws IOException {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
testClusterHost = System.getProperty("tests.cluster.host");
if (testClusterHost == null) {
ElasticsearchClient elasticsearchClientTemporary = null;
try {
testClusterHost = "localhost";
// We test if we have already something running at the testClusterHost address
elasticsearchClientTemporary = new ElasticsearchClient(getClientBuilder(
new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass));
elasticsearchClientTemporary.info();
staticLogger.debug("A node is already running locally. No need to start a Docker instance.");
} catch (ConnectException e) {
staticLogger.debug("No local node running. We need to start a Docker instance.");
// We start an elasticsearch Docker instance
Properties props = new Properties();
props.load(AbstractITCase.class.getResourceAsStream("/elasticsearch.version.properties"));
container = new ElasticsearchContainer().withVersion(props.getProperty("version"));
container.withEnv("ELASTIC_PASSWORD", testClusterPass);
container.setWaitStrategy(
new HttpWaitStrategy()
.forStatusCode(200)
.withBasicCredentials(testClusterUser, testClusterPass)
.withStartupTimeout(Duration.ofSeconds(90)));
container.start();
testClusterHost = container.getHost().getHostName();
testClusterPort = container.getFirstMappedPort();
} finally {
// We need to close the temporary client
if (elasticsearchClientTemporary != null) {
elasticsearchClientTemporary.shutdown();
}
}
} else {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
}
// We build the elasticsearch High Level Client based on the parameters
elasticsearchClient = new ElasticsearchClient(getClientBuilder(
new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass));
elasticsearchWithSecurity = Elasticsearch.builder()
.addNode(Elasticsearch.Node.builder()
.setHost(testClusterHost).setPort(testClusterPort).setScheme(testClusterScheme).build())
.setUsername(testClusterUser)
.setPassword(testClusterPass)
.build();
// We make sure the cluster is running
testClusterRunning();
// We set what will be elasticsearch behavior as it depends on the cluster version
elasticsearchClient.setElasticsearchBehavior();
}
|
#vulnerable code
@BeforeClass
public static void startElasticsearchRestClient() throws IOException {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
testClusterHost = System.getProperty("tests.cluster.host");
if (testClusterHost == null) {
// We start an elasticsearch Docker instance
Properties props = new Properties();
props.load(AbstractITCase.class.getResourceAsStream("/elasticsearch.version.properties"));
container = new ElasticsearchContainer().withVersion(props.getProperty("version"));
container.withEnv("ELASTIC_PASSWORD", testClusterPass);
container.setWaitStrategy(
new HttpWaitStrategy()
.forStatusCode(200)
.withBasicCredentials(testClusterUser, testClusterPass)
.withStartupTimeout(Duration.ofSeconds(90)));
container.start();
testClusterHost = container.getHost().getHostName();
testClusterPort = container.getFirstMappedPort();
} else {
testClusterPort = Integer.parseInt(System.getProperty("tests.cluster.port", DEFAULT_TEST_CLUSTER_PORT.toString()));
}
if (testClusterHost == null) {
Thread.dumpStack();
}
// We build the elasticsearch High Level Client based on the parameters
elasticsearchClient = new ElasticsearchClient(getClientBuilder(
new HttpHost(testClusterHost, testClusterPort), testClusterUser, testClusterPass));
elasticsearchWithSecurity = Elasticsearch.builder()
.addNode(Elasticsearch.Node.builder()
.setHost(testClusterHost).setPort(testClusterPort).setScheme(testClusterScheme).build())
.setUsername(testClusterUser)
.setPassword(testClusterPass)
.build();
// We make sure the cluster is running
testClusterRunning();
// We set what will be elasticsearch behavior as it depends on the cluster version
elasticsearchClient.setElasticsearchBehavior();
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Collection<FileAbstractModel> getFiles(String dir) {
logger.debug("Listing local files from {}", dir);
File[] files = new File(dir).listFiles();
Collection<FileAbstractModel> result;
if (files != null) {
result = new ArrayList<>(files.length);
// Iterate other files
for (File file : files) {
result.add(toFileAbstractModel(dir, file));
}
} else {
logger.debug("Symlink on windows gives null for listFiles(). Skipping [{}]", dir);
result = Collections.EMPTY_LIST;
}
logger.debug("{} local files found", result.size());
return result;
}
|
#vulnerable code
@Override
public Collection<FileAbstractModel> getFiles(String dir) {
if (logger.isDebugEnabled()) logger.debug("Listing local files from {}", dir);
File[] files = new File(dir).listFiles();
Collection<FileAbstractModel> result = new ArrayList<>(files.length);
// Iterate other files
for (File file : files) {
result.add(toFileAbstractModel(dir, file));
}
if (logger.isDebugEnabled()) logger.debug("{} local files found", result.size());
return result;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void start() throws Exception {
logger.info("Starting FS crawler");
if (loop < 0) {
logger.info("FS crawler started in watch mode. It will run unless you stop it with CTRL+C.");
}
if (loop == 0 && !rest) {
closed = true;
}
if (closed) {
logger.info("Fs crawler is closed. Exiting");
return;
}
esClientManager.start();
esClientManager.createIndices(settings);
// Start the crawler thread - but not if only in rest mode
if (loop != 0) {
fsCrawlerThread = new Thread(new FSParser(settings), "fs-crawler");
fsCrawlerThread.start();
}
}
|
#vulnerable code
public void start() throws Exception {
logger.info("Starting FS crawler");
if (loop < 0) {
logger.info("FS crawler started in watch mode. It will run unless you stop it with CTRL+C.");
}
if (loop == 0 && !rest) {
closed = true;
}
if (closed) {
logger.info("Fs crawler is closed. Exiting");
return;
}
esClientManager.start();
esClientManager.createIndices(settings);
// Start the REST Server if needed
if (rest) {
RestServer.start(settings, esClientManager);
logger.info("FS crawler Rest service started on [{}]", settings.getRest().url());
}
// Start the crawler thread - but not if only in rest mode
if (loop != 0) {
fsCrawlerThread = new Thread(new FSParser(settings), "fs-crawler");
fsCrawlerThread.start();
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected SuggestRefreshResponse newResponse(SuggestRefreshRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = Lists.newArrayList();
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
failedShards++;
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new SuggestRefreshResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
|
#vulnerable code
@Override
protected SuggestRefreshResponse newResponse(SuggestRefreshRequest request, AtomicReferenceArray shardsResponses, ClusterState clusterState) {
int successfulShards = 0;
int failedShards = 0;
List<ShardOperationFailedException> shardFailures = null;
for (int i = 0; i < shardsResponses.length(); i++) {
Object shardResponse = shardsResponses.get(i);
if (shardResponse == null) {
failedShards++;
} else if (shardResponse instanceof BroadcastShardOperationFailedException) {
failedShards++;
shardFailures.add(new DefaultShardOperationFailedException((BroadcastShardOperationFailedException) shardResponse));
} else {
successfulShards++;
}
}
return new SuggestRefreshResponse(shardsResponses.length(), successfulShards, failedShards, shardFailures);
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.