Skip to content

Commit

Permalink
Initiating the integration of the Argo CD weak credential tester plugin.
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesFoxxx committed Jun 13, 2024
1 parent e7cbb37 commit bcd35c2
Show file tree
Hide file tree
Showing 5 changed files with 353 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.grafana.GrafanaCredentialTester;
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.argocd.ArgoCdCredentialTester;
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.ncrack.NcrackCredentialTester;
Expand All @@ -65,6 +66,7 @@ protected void configurePlugin() {

Multibinder<CredentialTester> credentialTesterBinder =
Multibinder.newSetBinder(binder(), CredentialTester.class);
credentialTesterBinder.addBinding().to(ArgoCdCredentialTester.class);
credentialTesterBinder.addBinding().to(JenkinsCredentialTester.class);
credentialTesterBinder.addBinding().to(MlFlowCredentialTester.class);
credentialTesterBinder.addBinding().to(MysqlCredentialTester.class);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/*
* 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.argocd;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.tsunami.common.net.http.HttpRequest.get;
import static com.google.tsunami.common.net.http.HttpRequest.post;
import static java.nio.charset.StandardCharsets.UTF_8;

import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.flogger.GoogleLogger;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.protobuf.ByteString;
import com.google.tsunami.common.data.NetworkEndpointUtils;
import com.google.tsunami.common.data.NetworkServiceUtils;
import com.google.tsunami.common.net.http.HttpClient;
import com.google.tsunami.common.net.http.HttpHeaders;
import com.google.tsunami.common.net.http.HttpResponse;
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.util.Base64;
import java.util.List;
import javax.inject.Inject;

import jdk.jfr.ContentType;
import org.jsoup.Jsoup;
import org.jsoup.select.Elements;

/** Credential tester specifically for argocd. */
public final class ArgoCdCredentialTester extends CredentialTester {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private final HttpClient httpClient;

private static final String ARGOCD_SERVICE = "argocd";

@Inject
ArgoCdCredentialTester(HttpClient httpClient) {
this.httpClient = checkNotNull(httpClient);
}

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

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

@Override
public boolean canAccept(NetworkService networkService) {
return NetworkServiceUtils.getWebServiceName(networkService).equals(ARGOCD_SERVICE);
}

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

@Override
public ImmutableList<TestCredential> testValidCredentials(
NetworkService networkService, List<TestCredential> credentials) {
// Always return 1st weak credential to gracefully handle no auth configured case, where we
// return empty credential instead of all the weak credentials
return credentials.stream()
.filter(cred -> isArgoCdAccessible(networkService, cred))
.findFirst()
.map(ImmutableList::of)
.orElseGet(ImmutableList::of);
}

private boolean isArgoCdAccessible(NetworkService networkService, TestCredential credential) {
var uriAuthority = NetworkEndpointUtils.toUriAuthority(networkService.getNetworkEndpoint());
var url = String.format("http://%s/", uriAuthority) + "api/v1/session";
try {
logger.atInfo().log(
"url: %s, username: %s, password: %s",
url, credential.username(), credential.password().orElse(""));
HttpResponse response =
httpClient.send(
post(url)
.setHeaders(
HttpHeaders.builder().addHeader("Content-Type", "application/json").build())
.setRequestBody(
ByteString.copyFromUtf8(
String.format(
"{\"username\":\"%s\",\"password\":\"%s\"}",
credential.username(), credential.password().get())))
.build());
return response.status().isSuccess()
&& response.bodyString().isPresent()
&& bodyContainsToken(response.bodyString().get());
} catch (IOException e) {
logger.atWarning().withCause(e).log("Unable to query '%s'.", url);
return false;
}
}

private static boolean bodyContainsToken(String responseBody) {
try {
return JsonParser.parseString(responseBody).getAsJsonObject().has("token");
} catch (IllegalStateException | JsonSyntaxException e) {
return false;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,11 @@ service_default_credentials {
default_usernames: "username"
default_passwords: "password"
}

service_default_credentials {
service_name: "argocd"
default_usernames: "admin"
default_passwords: "Password1!"
default_passwords: "password"
default_passwords: "YOUR-PASSWORD-HERE"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
/*
* 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.argocd;

import static com.google.common.net.HttpHeaders.CONTENT_TYPE;
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.inject.Guice;
import com.google.tsunami.common.net.db.ConnectionProviderInterface;
import com.google.tsunami.common.net.http.HttpClientModule;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.provider.TestCredential;
import com.google.tsunami.plugins.detectors.credentials.genericweakcredentialdetector.testers.argocd.ArgoCdCredentialTester;
import com.google.tsunami.proto.NetworkService;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.util.Objects;
import java.util.Optional;
import javax.inject.Inject;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
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 ArgoCdCredentialTester}. */
@RunWith(JUnit4.class)
public class ArgoCdCredentialTesterTest {
@Rule public MockitoRule rule = MockitoJUnit.rule();
@Mock private ConnectionProviderInterface mockConnectionProvider;
@Mock private Connection mockConnection;
@Inject private ArgoCdCredentialTester tester;
private MockWebServer mockWebServer;
private static final TestCredential WEAK_CRED_1 =
TestCredential.create("admin", Optional.of("password"));
private static final TestCredential WEAK_CRED_2 =
TestCredential.create("admin", Optional.of("Password1!"));
private static final TestCredential WEAK_CRED_3 =
TestCredential.create("admin", Optional.of("YOUR-PASSWORD-HERE"));
private static final TestCredential WRONG_CRED_1 =
TestCredential.create("wrong", Optional.of("wrong"));

@Before
public void setup() {
mockWebServer = new MockWebServer();
Guice.createInjector(new HttpClientModule.Builder().build()).injectMembers(this);
}

@Test
public void detect_weakCredentialsExists_returnsWeakCredentials() throws Exception {
startMockWebServer();
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(
forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort()))
.setServiceName("argocd")
.build();

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

@Test
public void detect_weakCredentialsExist_returnsFirstWeakCredentials() throws Exception {
startMockWebServer();
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(
forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort()))
.setServiceName("argocd")
.build();

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

@Test
public void detect_argocdService_canAccept() throws Exception {
startMockWebServer();
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(
forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort()))
.setServiceName("argocd")
.build();

assertThat(tester.canAccept(targetNetworkService)).isTrue();
}

@Test
public void detect_noWeakCredentials_returnsNoCredentials() throws Exception {
startMockWebServer();
NetworkService targetNetworkService =
NetworkService.newBuilder()
.setNetworkEndpoint(
forHostnameAndPort(mockWebServer.getHostName(), mockWebServer.getPort()))
.setServiceName("argocd")
.build();
assertThat(tester.testValidCredentials(targetNetworkService, ImmutableList.of(WRONG_CRED_1)))
.isEmpty();
}

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

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

private void startMockWebServer() throws IOException {
final Dispatcher dispatcher =
new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) {
String authorizationRequestBody = request.getBody().readString(StandardCharsets.UTF_8);
if (request.getPath().equals("/api/v1/session")
&& Objects.equals(request.getMethod(), "POST")
&& Objects.equals(request.getHeader(CONTENT_TYPE), "application/json")) {
boolean isDefaultCredentials =
authorizationRequestBody.equals(
"{\"username\":\"admin\",\"password\":\"Password1!\"}")
|| authorizationRequestBody.equals(
"{\"username\":\"admin\",\"password\":\"password\"}")
|| authorizationRequestBody.equals(
"{\"username\":\"admin\",\"password\":\"YOUR-PASSWORD-HERE\"}");
if (isDefaultCredentials) {
return new MockResponse()
.setResponseCode(200)
.setBody("{\"token\": \"AToken\"\n" + "}");
} else {
return new MockResponse().setResponseCode(401);
}
}
return new MockResponse().setResponseCode(404);
}
};
mockWebServer.setDispatcher(dispatcher);
mockWebServer.start();
mockWebServer.url("/");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.tsunami.common.net.http.HttpRequest.get;
import static com.google.tsunami.common.net.http.HttpRequest.post;
import static java.util.stream.Collectors.joining;

import com.google.common.collect.ImmutableMap;
Expand All @@ -27,6 +28,7 @@
import com.google.tsunami.common.data.NetworkEndpointUtils;
import com.google.tsunami.common.data.NetworkServiceUtils;
import com.google.tsunami.common.net.http.HttpClient;
import com.google.tsunami.common.net.http.HttpHeaders;
import com.google.tsunami.common.net.http.HttpResponse;
import com.google.tsunami.common.net.http.HttpStatus;
import com.google.tsunami.plugin.PluginType;
Expand Down Expand Up @@ -277,6 +279,7 @@ private ImmutableSet<DetectedSoftware> detectSoftwareByCustomHeuristics(
HashSet<DetectedSoftware> detectedSoftware = new HashSet<>();

checkForMlflow(detectedSoftware, networkService, startingUrl);
checkForArgoCd(detectedSoftware, networkService, startingUrl);
return ImmutableSet.copyOf(detectedSoftware);
}

Expand Down Expand Up @@ -316,4 +319,42 @@ private void checkForMlflow(
logger.atWarning().withCause(e).log("Unable to query '%s'.", pingApiUrl);
}
}

private void checkForArgoCd(
Set<DetectedSoftware> software, NetworkService networkService, String startingUrl) {
logger.atInfo().log("probing Argo CD - custom fingerprint phase");

var uriAuthority = NetworkEndpointUtils.toUriAuthority(networkService.getNetworkEndpoint());
var applicationsApiUrl = String.format("http://%s/%s", uriAuthority, "api/v1/applications");
try {
HttpResponse apiApplicationsResponse =
httpClient.send(
post(applicationsApiUrl)
.setHeaders(
HttpHeaders.builder().addHeader("Content-Type", "application/json").build())
.build());

if (apiApplicationsResponse.status() != HttpStatus.INTERNAL_SERVER_ERROR
|| apiApplicationsResponse.bodyString().isEmpty()) {
return;
}

if (apiApplicationsResponse
.bodyString()
.get()
.contains(
"{\"error\":\"grpc: error while marshaling: proto: required field \\\"application\\\""
+ " not set\",\"code\":13,\"message\":\"grpc: error while marshaling: "
+ "proto: required field \\\"application\\\" not set\"}")) {
software.add(
DetectedSoftware.builder()
.setSoftwareIdentity(SoftwareIdentity.newBuilder().setSoftware("argocd").build())
.setRootPath(startingUrl)
.setContentHashes(ImmutableMap.of())
.build());
}
} catch (IOException e) {
logger.atWarning().withCause(e).log("Unable to query '%s'.", applicationsApiUrl);
}
}
}

0 comments on commit bcd35c2

Please sign in to comment.