KEYCLOAK-15238: Fix potential resource leak from not closing Stream/Reader

This commit is contained in:
testn 2020-08-21 19:29:11 +07:00 committed by Hynek Mlnařík
parent bd3840c606
commit 2cd03569d6
18 changed files with 90 additions and 68 deletions

View file

@ -286,12 +286,12 @@ public class KcinitDriver {
protected byte[] readFileRaw(File fp) throws IOException {
if (!fp.exists()) return null;
FileInputStream fis = new FileInputStream(fp);
try (FileInputStream fis = new FileInputStream(fp)) {
byte[] data = new byte[(int) fp.length()];
fis.read(data);
fis.close();
return data;
}
}
protected void writeFile(File fp, String payload) {
try {

View file

@ -113,8 +113,8 @@ public class PropertiesBasedRoleMapper implements RoleMappingsProvider {
if (path != null) {
File file = new File(path);
if (file.exists()) {
try {
this.roleMappings.load(new FileInputStream(file));
try (FileInputStream is = new FileInputStream(file)){
this.roleMappings.load(is);
logger.debugf("Successfully loaded role mappings from %s", path);
} catch (Exception e) {
logger.debugv(e, "Unable to load role mappings from %s", path);

View file

@ -284,7 +284,7 @@ public class DeploymentBuilder {
} catch (KeyStoreException e) {
throw new RuntimeException(e);
}
InputStream is = null;
InputStream is;
if (key.getKeystore().getFile() != null) {
File fp = new File(key.getKeystore().getFile());
if (!fp.exists()) {
@ -301,8 +301,8 @@ public class DeploymentBuilder {
throw new RuntimeException("KeyStore " + key.getKeystore().getResource() + " does not exist");
}
}
try {
keyStore.load(is, key.getKeystore().getPassword().toCharArray());
try (InputStream stream = is) {
keyStore.load(stream, key.getKeystore().getPassword().toCharArray());
} catch (Exception e) {
throw new RuntimeException(e);
}

View file

@ -207,7 +207,9 @@ public class Profile {
if (jbossServerConfigDir != null) {
File file = new File(jbossServerConfigDir, "profile.properties");
if (file.isFile()) {
properties.load(new FileInputStream(file));
try (FileInputStream is = new FileInputStream(file)) {
properties.load(is);
}
}
}
} catch (IOException e) {

View file

@ -58,8 +58,9 @@ public class KeystoreUtil {
} else {
trustStream = new FileInputStream(new File(filename));
}
trustStore.load(trustStream, password.toCharArray());
trustStream.close();
try (InputStream is = trustStream) {
trustStore.load(is, password.toCharArray());
}
return trustStore;
}

View file

@ -202,7 +202,9 @@ public class Debug {
*/
public static void loadConfig(File f) throws IOException {
prop = new Properties();
prop.load(new FileInputStream(f));
try (FileInputStream is = new FileInputStream((f))) {
prop.load(is);
}
}
/**

View file

@ -242,23 +242,23 @@ public class DBusConnection extends AbstractConnection {
if (null == display) throw new DBusException(getString("cannotResolveSessionBusAddress"));
File uuidfile = new File("/var/lib/dbus/machine-id");
if (!uuidfile.exists()) throw new DBusException(getString("cannotResolveSessionBusAddress"));
try {
BufferedReader r = new BufferedReader(new FileReader(uuidfile));
try (BufferedReader r = new BufferedReader(new FileReader(uuidfile))) {
String uuid = r.readLine();
String homedir = System.getProperty("user.home");
File addressfile = new File(homedir + "/.dbus/session-bus",
uuid + "-" + display.replaceAll(":([0-9]*)\\..*", "$1"));
if (!addressfile.exists())
throw new DBusException(getString("cannotResolveSessionBusAddress"));
r = new BufferedReader(new FileReader(addressfile));
try (BufferedReader r2 = new BufferedReader(new FileReader(addressfile))) {
String l;
while (null != (l = r.readLine())) {
while (null != (l = r2.readLine())) {
if (Debug.debug) Debug.print(Debug.VERBOSE, "Reading D-Bus session data: " + l);
if (l.matches("DBUS_SESSION_BUS_ADDRESS.*")) {
s = l.replaceAll("^[^=]*=", "");
if (Debug.debug) Debug.print(Debug.VERBOSE, "Parsing " + l + " to " + s);
}
}
}
if (null == s || "".equals(s))
throw new DBusException(getString("cannotResolveSessionBusAddress"));
if (Debug.debug)

View file

@ -232,7 +232,9 @@ public class FluentTestsHelper {
* @see #importTestRealm(InputStream)
*/
public FluentTestsHelper importTestRealm(String realmJsonPath) throws IOException {
return importTestRealm(FluentTestsHelper.class.getResourceAsStream(realmJsonPath));
try (InputStream fis = FluentTestsHelper.class.getResourceAsStream(realmJsonPath)) {
return importTestRealm(fis);
}
}
/**

View file

@ -158,8 +158,7 @@ public class TestsHelper {
public static boolean importTestRealm(String username, String password, String realmJsonPath) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ClassLoader classLoader = TestsHelper.class.getClassLoader();
InputStream stream = TestsHelper.class.getResourceAsStream(realmJsonPath);
try (InputStream stream = TestsHelper.class.getResourceAsStream(realmJsonPath)) {
RealmRepresentation realmRepresentation = mapper.readValue(stream, RealmRepresentation.class);
Keycloak keycloak = Keycloak.getInstance(
@ -172,6 +171,7 @@ public class TestsHelper {
testRealm = realmRepresentation.getRealm();
generateInitialAccessToken(keycloak);
return true;
}
}

View file

@ -345,8 +345,8 @@ public class SimpleHttp {
}
}
InputStreamReader reader = charset == null ? new InputStreamReader(is) :
new InputStreamReader(is, charset);
try (InputStreamReader reader = charset == null ? new InputStreamReader(is) :
new InputStreamReader(is, charset)) {
StringWriter writer = new StringWriter();
@ -356,6 +356,7 @@ public class SimpleHttp {
}
responseString = writer.toString();
}
} finally {
if (is != null) {
is.close();

View file

@ -339,11 +339,13 @@ public class CertificateValidator {
if (!f.canRead()) {
throw new IOException(String.format("Unable to read CRL from \"%s\"", f.getAbsolutePath()));
}
X509CRL crl = loadFromStream(cf, new FileInputStream(f.getAbsolutePath()));
try (FileInputStream is = new FileInputStream(f.getAbsolutePath())) {
X509CRL crl = loadFromStream(cf, is);
return Collections.singleton(crl);
}
}
}
}
catch(IOException ex) {
logger.errorf(ex.getMessage());
}

View file

@ -74,8 +74,9 @@ public class DirExportProvider extends MultipleStepsExportProvider {
@Override
public void writeRealm(String fileName, RealmRepresentation rep) throws IOException {
File file = new File(this.rootDirectory, fileName);
FileOutputStream stream = new FileOutputStream(file);
JsonSerialization.prettyMapper.writeValue(stream, rep);
try (FileOutputStream is = new FileOutputStream(file)) {
JsonSerialization.prettyMapper.writeValue(is, rep);
}
}
@Override

View file

@ -23,6 +23,7 @@ import org.keycloak.component.ComponentModel;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.models.RealmModel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
@ -47,9 +48,9 @@ public class JavaKeystoreKeyProvider extends AbstractRsaKeyProvider {
@Override
protected KeyWrapper loadKey(RealmModel realm, ComponentModel model) {
try {
try (FileInputStream is = new FileInputStream(model.get(JavaKeystoreKeyProviderFactory.KEYSTORE_KEY))) {
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream(model.get(JavaKeystoreKeyProviderFactory.KEYSTORE_KEY)), model.get(JavaKeystoreKeyProviderFactory.KEYSTORE_PASSWORD_KEY).toCharArray());
keyStore.load(is, model.get(JavaKeystoreKeyProviderFactory.KEYSTORE_PASSWORD_KEY).toCharArray());
PrivateKey privateKey = (PrivateKey) keyStore.getKey(model.get(JavaKeystoreKeyProviderFactory.KEY_ALIAS_KEY), model.get(JavaKeystoreKeyProviderFactory.KEY_PASSWORD_KEY).toCharArray());
PublicKey publicKey = KeyUtils.extractPublicKey(privateKey);

View file

@ -106,9 +106,11 @@ public class DockerComposeYamlInstallationProvider implements ClientInstallation
// Write README to .zip
zipOutput.putNextEntry(new ZipEntry(ROOT_DIR + "README.md"));
final String readmeContent = new BufferedReader(new InputStreamReader(DockerComposeYamlInstallationProvider.class.getResourceAsStream("/DockerComposeYamlReadme.md"))).lines().collect(Collectors.joining("\n"));
try (BufferedReader br = new BufferedReader(new InputStreamReader(DockerComposeYamlInstallationProvider.class.getResourceAsStream("/DockerComposeYamlReadme.md")))) {
final String readmeContent = br.lines().collect(Collectors.joining("\n"));
zipOutput.write(readmeContent.getBytes());
zipOutput.closeEntry();
}
zipOutput.close();
byteStream.close();

View file

@ -56,8 +56,8 @@ public class TestJavascriptResource {
}
private String resourceToString(String path) throws IOException {
InputStream is = TestingResourceProvider.class.getResourceAsStream(path);
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
try (InputStream is = TestingResourceProvider.class.getResourceAsStream(path);
BufferedReader buf = new BufferedReader(new InputStreamReader(is))) {
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while (line != null) {
@ -68,3 +68,4 @@ public class TestJavascriptResource {
return sb.toString().replace("${js-adapter.auth-server-url}", getAuthServerContextRoot() + "/auth");
}
}
}

View file

@ -64,11 +64,12 @@ public class TextFileChecker {
try (InputStream in = Files.newInputStream(path)) {
Long lastCheckedPosition = lastCheckedPositions.computeIfAbsent(path, p -> 0L);
in.skip(lastCheckedPosition);
BufferedReader b = new BufferedReader(new InputStreamReader(in));
try (BufferedReader b = new BufferedReader(new InputStreamReader(in))) {
lineChecker.accept(b.lines());
}
}
}
}
public void updateLastCheckedPositionsOfAllFilesToEndOfFile() throws IOException {
for (Path path : paths) {

View file

@ -36,7 +36,9 @@ public class TLSUtils {
}
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(new FileInputStream(keystorePath), "secret".toCharArray());
try (FileInputStream is = new FileInputStream(keystorePath)) {
keystore.load(is, "secret".toCharArray());
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, "secret".toCharArray());
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
@ -49,7 +51,9 @@ public class TLSUtils {
// Essentially, this is REQUEST CLIENT AUTH behavior. It doesn't fail if the client doesn't have a cert.
// However it will challenge him to send it.
KeyStore truststore = KeyStore.getInstance("jks");
truststore.load(new FileInputStream(truststorePath), "secret".toCharArray());
try (FileInputStream is = new FileInputStream(truststorePath)) {
truststore.load(is, "secret".toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);
TrustManager[] trustManagers = new TrustManager[trustManagerFactory.getTrustManagers().length + 1];

View file

@ -137,7 +137,9 @@ public class KeycloakServer {
File f = new File(System.getProperty("user.home"), ".keycloak-server.properties");
if (f.isFile()) {
Properties p = new Properties();
p.load(new FileInputStream(f));
try (FileInputStream is = new FileInputStream(f)) {
p.load(is);
}
System.getProperties().putAll(p);
}