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

feat: add Weak Credential tester for Apache Hive #490

Merged
merged 13 commits into from
Oct 24, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
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;
Expand Down Expand Up @@ -68,6 +69,7 @@ protected void configurePlugin() {
credentialTesterBinder.addBinding().to(JenkinsCredentialTester.class);
credentialTesterBinder.addBinding().to(MlFlowCredentialTester.class);
credentialTesterBinder.addBinding().to(MysqlCredentialTester.class);
credentialTesterBinder.addBinding().to(HiveCredentialTester.class);
credentialTesterBinder.addBinding().to(HydraCredentialTester.class);
credentialTesterBinder.addBinding().to(NcrackCredentialTester.class);
credentialTesterBinder.addBinding().to(PostgresCredentialTester.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public final class Top100Passwords extends CredentialProvider {

private static final ImmutableList<String> TOP_USER_NAMES =
ImmutableList.of(
"",
"anonymous",
"root",
"admin",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Copyright 2023 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.hive;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.tsunami.common.net.http.HttpRequest.get;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.flogger.GoogleLogger;
import com.google.common.net.HostAndPort;
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.common.net.http.HttpResponse;
import com.google.tsunami.common.net.http.HttpClient;
import com.google.tsunami.common.net.http.HttpStatus;
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.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Optional;
import javax.inject.Inject;

/** Credential tester specifically for hive. */
public final class HiveCredentialTester extends CredentialTester {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private final ConnectionProviderInterface connectionProvider;
private final HttpClient httpClient;
private static final ImmutableMap<String, TargetService> SERVICE_MAP =
ImmutableMap.of("snet-sensor-mgmt", TargetService.HIVE);
private static final String HIVE_TITLE = "<title>HiveServer2</title>";

@Inject
HiveCredentialTester(ConnectionProviderInterface connectionProvider, HttpClient httpClient) {
this.connectionProvider = checkNotNull(connectionProvider);
this.httpClient = httpClient;
}

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

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

@Override
public boolean canAccept(NetworkService networkService) {
HostAndPort targetPage = NetworkEndpointUtils.toHostAndPort(networkService.getNetworkEndpoint());
String targetUri = String.format("http://%s:%d", targetPage.getHost(), 10002);

try {
HttpResponse response = httpClient.send(get(targetUri).withEmptyHeaders().build(), networkService);
if (response != null) {
Optional<String> body = response.bodyString();
if (response.status().code() == HttpStatus.OK.code()
&& body.isPresent() && body.get().contains(HIVE_TITLE)) {
logger.atWarning().log("Succeed to query hive http server '%s'.", targetUri);
} else {
logger.atWarning().log("Unable to query hive http server '%s'.", targetUri);
}
}
} catch (IOException e) {
logger.atWarning().withCause(e).log("Unable to query hive http server '%s'.", targetUri);
}
String serviceName = NetworkServiceUtils.getServiceName(networkService);
return SERVICE_MAP.containsKey(serviceName);
}

@Override
public boolean batched() {
return true;
}

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

return credentials.stream()
.filter(cred -> isHiveAccessible(networkService, cred))
.collect(toImmutableList());
}

private boolean isHiveAccessible(NetworkService networkService, TestCredential credential) {

try {
var url =
String.format(
"jdbc:hive2://%s/default",
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 Hive server successfully.");
return true;
}
} catch (SQLException e) {
logger.atSevere().log(
"HiveCredentialTester sql error: %s (%d)", e.getMessage(), e.getErrorCode());
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,5 @@ enum TargetService {
OWA = 23; // Outlook Web App (Web Application)
DICOM = 24; // Digital Imaging and Communications in Medicine (Healthcare
// Protocol)
HIVE = 25; // Apache Hive (SQL Database)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
* Copyright 2023 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.hive;

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.common.net.http.HttpClient;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.provider.TestCredential;
import com.google.tsunami.proto.NetworkService;
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;

import java.sql.Connection;
import java.util.Optional;

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

private static final TestCredential WEAK_CRED_1 =
TestCredential.create("user", Optional.of("1234"));
private static final TestCredential WEAK_CRED_2 =
TestCredential.create("root", Optional.of("pass"));

@Before
public void setup() {
tester = new HiveCredentialTester(mockConnectionProvider, httpClient);
}

@Test
public void detect_weakCredExists_returnsWeakCred() throws Exception {
when(mockConnectionProvider.getConnection(
"jdbc:hive2://example.com:10000/default", "user", "1234"))
.thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 10000))
.setServiceName("snet-sensor-mgmt")
.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:hive2://example.com:10000/default", "user", "1234"))
.thenReturn(mockConnection);
when(mockConnectionProvider.getConnection(
"jdbc:hive2://example.com:10000/default", "root", "pass"))
.thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 10000))
.setServiceName("snet-sensor-mgmt")
.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:hive2://example.com:10000/default", "hardtoguess", "hardtoguess"))
.thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 10000))
.setServiceName("snet-sensor-mgmt")
.build();

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

@Test
public void detect_hiveService_skips() throws Exception {
when(mockConnectionProvider.getConnection(any(), any(), any())).thenReturn(mockConnection);
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(forHostnameAndPort("example.com", 10000))
.setServiceName("snet-sensor-mgmt")
.build();

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