Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HyperSQL weak credential tester #582

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,18 @@
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.provider.Top100Passwords;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.tester.CredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.grafana.GrafanaCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.hive.HiveCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.hsqldb.HyperSQLCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.hydra.HydraCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.jenkins.JenkinsCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.mlflow.MlFlowCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.mysql.MysqlCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.hive.HiveCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.ncrack.NcrackCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.postgres.PostgresCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.rabbitmq.RabbitMQCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.wordpress.WordpressCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.rstudio.RStudioCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.wordpress.WordpressCredentialTester;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.zenml.ZenMlCredentialTester;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
Expand Down Expand Up @@ -80,6 +80,7 @@ protected void configurePlugin() {
credentialTesterBinder.addBinding().to(RStudioCredentialTester.class);
credentialTesterBinder.addBinding().to(RabbitMQCredentialTester.class);
credentialTesterBinder.addBinding().to(ZenMlCredentialTester.class);
credentialTesterBinder.addBinding().to(HyperSQLCredentialTester.class);

Multibinder<CredentialProvider> credentialProviderBinder =
Multibinder.newSetBinder(binder(), CredentialProvider.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.hsqldb;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.GoogleLogger;
import com.google.tsunami.common.data.NetworkEndpointUtils;
import com.google.tsunami.common.data.NetworkServiceUtils;
import com.google.tsunami.common.net.db.ConnectionProviderInterface;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.proto.TargetService;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.provider.TestCredential;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.tester.CredentialTester;
import com.google.tsunami.proto.NetworkService;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Import the necessary libraries

Suggested change
import java.util.List;
import java.util.HashSet;
import java.util.List;

import javax.inject.Inject;

/** Credential tester specifically for HyperSQL. */
public final class HyperSQLCredentialTester extends CredentialTester {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private final ConnectionProviderInterface connectionProvider;

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add error code constant

Suggested change
private static final int HSQL_INVALID_USER_ERROR = -4001;

private static final ImmutableMap<String, TargetService> SERVICE_MAP =
ImmutableMap.of("jdbc", TargetService.HSQLDB);

@Inject
HyperSQLCredentialTester(ConnectionProviderInterface connectionProvider) {
this.connectionProvider = checkNotNull(connectionProvider);
}

@Override
public String name() {
return "HyperSQLCredentialTester";
}

@Override
public String description() {
return "HyperSQL credential tester.";
}

@Override
public boolean canAccept(NetworkService networkService) {
String serviceName = NetworkServiceUtils.getServiceName(networkService);
return SERVICE_MAP.containsKey(serviceName);
}

@Override
public boolean batched() {
return true;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Disable batching to avoid unnecessary credential attempts

Suggested change
return true;
return false;

}

@Override
public ImmutableList<TestCredential> testValidCredentials(
NetworkService networkService, List<TestCredential> credentials) {
if (!canAccept(networkService)) {
return ImmutableList.of();
}

return credentials.stream()
.filter(cred -> isHsqlAccessible(networkService, cred))
.collect(toImmutableList());
}
Comment on lines +71 to +80
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The invalidUsernames variable will contain a set of all usernames that have been tried and have failed, so they should be removed from the list of valid credentials.

Suggested change
public ImmutableList<TestCredential> testValidCredentials(
NetworkService networkService, List<TestCredential> credentials) {
if (!canAccept(networkService)) {
return ImmutableList.of();
}
return credentials.stream()
.filter(cred -> isHsqlAccessible(networkService, cred))
.collect(toImmutableList());
}
public ImmutableList<TestCredential> testValidCredentials(
NetworkService networkService, List<TestCredential> credentials) {
HashSet<String> invalidUsernames = new HashSet<String>();
if (!canAccept(networkService)) {
return ImmutableList.of();
}
return credentials.stream()
.filter(cred -> !invalidUsernames.contains(cred.username()))
.filter(cred -> isHsqlAccessible(networkService, cred, invalidUsernames))
.collect(toImmutableList());
}


/**
* Using testdb as database name since hsqldb requires a database name in order to perform the
* connection However hsqldb does not create a default database during installation testdb is the
* database name used within the documentation
*/
private boolean isHsqlAccessible(NetworkService networkService, TestCredential credential) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method signature should be updated to accept the newly introduced variable.

Suggested change
private boolean isHsqlAccessible(NetworkService networkService, TestCredential credential) {
private boolean isHsqlAccessible(
NetworkService networkService, TestCredential credential, HashSet<String> invalidUsernames) {

try {
var url =
String.format(
"jdbc:hsqldb:hsql://%s/testdb",
NetworkEndpointUtils.toUriAuthority(networkService.getNetworkEndpoint()));
logger.atInfo().log(
"url: %s, username: %s, password: %s",
url, credential.username(), credential.password().orElse(""));
Connection conn =
connectionProvider.getConnection(
url, credential.username(), credential.password().orElse(""));

if (conn != null) {
logger.atInfo().log("Connected to the Hyper SQL server successfully.");
return true;
}
} catch (SQLException e) {
logger.atSevere().log(
"HyperSQLCredentialTester sql error: %s (%d)", e.getMessage(), e.getErrorCode());
}
Comment on lines +104 to +107
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error code -4001 is returned when the user is invalid.
Error code -4000 is returned when the user exists but the password is invalid.

This check optimizes testing by an order of magnitude, as it tries common passwords only on valid usernames.

Suggested change
} catch (SQLException e) {
logger.atSevere().log(
"HyperSQLCredentialTester sql error: %s (%d)", e.getMessage(), e.getErrorCode());
}
} catch (SQLException e) {
if (e.getErrorCode() == HSQL_INVALID_USER_ERROR) {
invalidUsernames.add(credential.username());
}
logger.atSevere().log(
"HyperSQLCredentialTester sql error: %s (%d)", e.getMessage(), e.getErrorCode());
}

return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,12 @@ service_default_credentials {
default_usernames: "default"
default_passwords: ""
}

service_default_credentials {
service_name: "jdbc"
# https://hsqldb.org/doc/guide/running-chapt.html
default_usernames: "sa"
default_passwords: ""
}


Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.hsqldb;

import static com.google.common.truth.Truth.assertThat;
import static com.google.tsunami.common.data.NetworkEndpointUtils.forHostnameAndPort;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

import com.google.common.collect.ImmutableList;
import com.google.tsunami.common.net.db.ConnectionProviderInterface;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.provider.TestCredential;
import com.google.tsunami.proto.NetworkService;
import java.sql.Connection;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;

/** Tests for {@link HyperSQLCredentialTester}. */
@RunWith(JUnit4.class)
public class HyperSQLCredentialTesterTest {
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock private ConnectionProviderInterface mockConnectionProvider;
@Mock private Connection mockConnection;
private HyperSQLCredentialTester tester;

private static final TestCredential WEAK_CRED_1 =
TestCredential.create("sa", Optional.of("test"));
private static final TestCredential WEAK_CRED_2 =
TestCredential.create("admin", Optional.of("weakpassword"));

@Before
public void setup() {
tester = new HyperSQLCredentialTester(mockConnectionProvider);
}

@Test
public void detect_weakCredExists_returnsWeakCred() throws Exception {
when(mockConnectionProvider.getConnection(
"jdbc:hsqldb:hsql://example.com:9001/testdb", "sa", "test"))
.thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 9001))
.setServiceName("jdbc")
.build();

assertThat(tester.testValidCredentials(targetNetworkService, ImmutableList.of(WEAK_CRED_1)))
.containsExactly(WEAK_CRED_1);
}

@Test
public void detect_weakCredsExist_returnsAllWeakCreds() throws Exception {
when(mockConnectionProvider.getConnection(
"jdbc:hsqldb:hsql://example.com:9001/testdb", "sa", "test"))
.thenReturn(mockConnection);
when(mockConnectionProvider.getConnection(
"jdbc:hsqldb:hsql://example.com:9001/testdb", "admin", "weakpassword"))
.thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 9001))
.setServiceName("jdbc")
.build();

assertThat(
tester.testValidCredentials(
targetNetworkService, ImmutableList.of(WEAK_CRED_1, WEAK_CRED_2)))
.containsExactly(WEAK_CRED_1, WEAK_CRED_2);
}

@Test
public void detect_noWeakCred_returnsNoCred() throws Exception {
when(mockConnectionProvider.getConnection(
"jdbc:hsqldb:hsql://example.com:9001/testdb", "hardtoguess", "hardtoguess"))
.thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 9001))
.setServiceName("jdbc")
.build();

assertThat(tester.testValidCredentials(targetNetworkService, ImmutableList.of(WEAK_CRED_1)))
.isEmpty();
}

@Test
public void detect_mySqlService_skips() throws Exception {
when(mockConnectionProvider.getConnection(any(), any(), any())).thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 9001))
.setServiceName("mysql")
.build();

assertThat(tester.testValidCredentials(targetNetworkService, ImmutableList.of(WEAK_CRED_1)))
.isEmpty();
verifyNoInteractions(mockConnectionProvider);
}
}
Loading