From cea18eb6da34eda5e59ae42c006815567ade5a9a Mon Sep 17 00:00:00 2001 From: Oleksandra Matviienko Date: Wed, 13 May 2026 13:38:26 +0200 Subject: [PATCH 1/2] Fixed SSRF bypass in Version Control Git integration - Added RepositoryUriValidator invoked on save, access check, and every JGit network operation (clone, test, fetch, push) - Restricted repository URI schemes to http, https, ssh (rejects file://, git://, etc. regardless of SSRF flag) - Used URIish.getHost() for validation to match the parser JGit transport uses, preventing parser-disagreement bypasses - Added HostScopedCredentialsProvider that refuses credentials on cross-host redirects - Disabled JGit HTTP redirects globally via SystemReader override at VC service startup - Refactored SsrfProtectionValidator to expose validateHost(String) as public API --- .../DefaultEntitiesVersionControlService.java | 2 + .../common/util/SsrfProtectionValidator.java | 13 +- .../util/SsrfProtectionValidatorTest.java | 85 +++++++ .../sync/vc/DefaultGitRepositoryService.java | 70 ++++++ .../server/service/sync/vc/GitRepository.java | 19 +- .../vc/HostScopedCredentialsProvider.java | 43 ++++ .../sync/vc/RepositoryUriValidator.java | 67 ++++++ .../vc/HostScopedCredentialsProviderTest.java | 103 ++++++++ .../sync/vc/RepositoryUriValidatorTest.java | 227 ++++++++++++++++++ 9 files changed, 624 insertions(+), 5 deletions(-) create mode 100644 common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProvider.java create mode 100644 common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidator.java create mode 100644 common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProviderTest.java create mode 100644 common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidatorTest.java diff --git a/application/src/main/java/org/thingsboard/server/service/sync/vc/DefaultEntitiesVersionControlService.java b/application/src/main/java/org/thingsboard/server/service/sync/vc/DefaultEntitiesVersionControlService.java index 8c442ff09f..ad9662e78d 100644 --- a/application/src/main/java/org/thingsboard/server/service/sync/vc/DefaultEntitiesVersionControlService.java +++ b/application/src/main/java/org/thingsboard/server/service/sync/vc/DefaultEntitiesVersionControlService.java @@ -515,6 +515,7 @@ public class DefaultEntitiesVersionControlService implements EntitiesVersionCont @Override public ListenableFuture saveVersionControlSettings(TenantId tenantId, RepositorySettings versionControlSettings) { checkBranchName(versionControlSettings.getDefaultBranch()); + RepositoryUriValidator.validate(versionControlSettings); var restoredSettings = this.repositorySettingsService.restore(tenantId, versionControlSettings); try { var future = gitServiceQueue.initRepository(tenantId, restoredSettings); @@ -535,6 +536,7 @@ public class DefaultEntitiesVersionControlService implements EntitiesVersionCont @Override public ListenableFuture checkVersionControlAccess(TenantId tenantId, RepositorySettings settings) throws ThingsboardException { checkBranchName(settings.getDefaultBranch()); + RepositoryUriValidator.validate(settings); settings = this.repositorySettingsService.restore(tenantId, settings); try { return gitServiceQueue.testRepository(tenantId, settings); diff --git a/common/util/src/main/java/org/thingsboard/common/util/SsrfProtectionValidator.java b/common/util/src/main/java/org/thingsboard/common/util/SsrfProtectionValidator.java index 9132d117ae..d4822bdef4 100644 --- a/common/util/src/main/java/org/thingsboard/common/util/SsrfProtectionValidator.java +++ b/common/util/src/main/java/org/thingsboard/common/util/SsrfProtectionValidator.java @@ -61,7 +61,18 @@ public class SsrfProtectionValidator { throw new RuntimeException("URI is invalid: only HTTP and HTTPS schemes are allowed, got: " + scheme); } - String host = uri.getHost(); + validateHost(uri.getHost(), ssrfProtectionEnabled); + } + + public static void validateHost(String host) { + validateHost(host, enabled); + } + + static void validateHost(String host, boolean ssrfProtectionEnabled) { + if (!ssrfProtectionEnabled) { + return; + } + if (host == null || host.isEmpty()) { throw new RuntimeException("URI is invalid: hostname is missing"); } diff --git a/common/util/src/test/java/org/thingsboard/common/util/SsrfProtectionValidatorTest.java b/common/util/src/test/java/org/thingsboard/common/util/SsrfProtectionValidatorTest.java index 77f915c09c..a99c6abdf4 100644 --- a/common/util/src/test/java/org/thingsboard/common/util/SsrfProtectionValidatorTest.java +++ b/common/util/src/test/java/org/thingsboard/common/util/SsrfProtectionValidatorTest.java @@ -577,4 +577,89 @@ public class SsrfProtectionValidatorTest { } } + // --- validateHost(String) direct tests --- + + @ParameterizedTest + @ValueSource(strings = {"example.com", "8.8.8.8", "github.com"}) + void testValidateHostAllowsPublicHosts(String host) { + assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost(host, true)); + } + + @ParameterizedTest + @ValueSource(strings = {"127.0.0.1", "10.0.0.1", "192.168.1.1", "172.16.0.1", "169.254.169.254", "0.0.0.0"}) + void testValidateHostBlocksPrivateIps(String host) { + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost(host, true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + } + + @Test + void testValidateHostBlocksLocalhost() { + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("localhost", true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + } + + @Test + void testValidateHostBlocksIpv6Loopback() { + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("::1", true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("[::1]", true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + } + + @Test + void testValidateHostBlocksInternalSuffix() { + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("server.internal", true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("app.local", true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + } + + @Test + void testValidateHostRejectsNullOrEmpty() { + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost(null, true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("hostname is missing"); + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("", true)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("hostname is missing"); + } + + @Test + void testValidateHostDisabledSkipsAllChecks() { + // Even with private IP and null host, validation is a no-op when disabled + assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost("127.0.0.1", false)); + assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost(null, false)); + } + + @Test + void testValidateHostHonorsAllowList() { + try { + SsrfProtectionValidator.setAllowedHosts(List.of("10.0.0.0/8")); + assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost("10.1.2.3", true)); + } finally { + SsrfProtectionValidator.setAllowedHosts(Collections.emptyList()); + } + } + + @Test + void testValidateHostUsesStaticEnabledFlag() { + boolean original = SsrfProtectionValidator.isEnabled(); + try { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> SsrfProtectionValidator.validateHost("127.0.0.1")) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("URI is invalid"); + SsrfProtectionValidator.setEnabled(false); + assertThatNoException().isThrownBy(() -> SsrfProtectionValidator.validateHost("127.0.0.1")); + } finally { + SsrfProtectionValidator.setEnabled(original); + } + } + } diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java index 8653eb8804..ba52e64e5d 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java @@ -20,6 +20,12 @@ import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FileUtils; import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.errors.ConfigInvalidException; +import org.eclipse.jgit.lib.Config; +import org.eclipse.jgit.lib.StoredConfig; +import org.eclipse.jgit.storage.file.FileBasedConfig; +import org.eclipse.jgit.util.FS; +import org.eclipse.jgit.util.SystemReader; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Service; @@ -68,6 +74,70 @@ public class DefaultGitRepositoryService implements GitRepositoryService { if (StringUtils.isEmpty(repositoriesFolder)) { repositoriesFolder = defaultFolder; } + installRedirectHardeningSystemReader(); + } + + private static synchronized void installRedirectHardeningSystemReader() { + SystemReader current = SystemReader.getInstance(); + if (current instanceof RedirectHardeningSystemReader) { + return; + } + SystemReader.setInstance(new RedirectHardeningSystemReader(current)); + } + + private static final class RedirectHardeningSystemReader extends SystemReader { + private final SystemReader delegate; + + RedirectHardeningSystemReader(SystemReader delegate) { + this.delegate = delegate; + } + + @Override + public StoredConfig getUserConfig() throws ConfigInvalidException, IOException { + StoredConfig config = delegate.getUserConfig(); + config.setString("http", null, "followRedirects", "false"); + return config; + } + + @Override + public String getHostname() { + return delegate.getHostname(); + } + + @Override + public String getenv(String variable) { + return delegate.getenv(variable); + } + + @Override + public String getProperty(String key) { + return delegate.getProperty(key); + } + + @Override + public FileBasedConfig openUserConfig(Config parent, FS fs) { + return delegate.openUserConfig(parent, fs); + } + + @Override + public FileBasedConfig openSystemConfig(Config parent, FS fs) { + return delegate.openSystemConfig(parent, fs); + } + + @Override + public FileBasedConfig openJGitConfig(Config parent, FS fs) { + return delegate.openJGitConfig(parent, fs); + } + + @Override + public long getCurrentTime() { + return delegate.getCurrentTime(); + } + + @Override + public int getTimezone(long when) { + return delegate.getTimezone(when); + } } @Override diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java index 3602dd55ca..95d9804576 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java @@ -57,7 +57,6 @@ import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteRefUpdate; import org.eclipse.jgit.transport.SshTransport; import org.eclipse.jgit.transport.URIish; -import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import org.eclipse.jgit.transport.sshd.JGitKeyCache; import org.eclipse.jgit.transport.sshd.ServerKeyDatabase; import org.eclipse.jgit.transport.sshd.SshdSessionFactory; @@ -129,6 +128,7 @@ public class GitRepository { } public static GitRepository clone(RepositorySettings settings, File directory) throws GitAPIException { + RepositoryUriValidator.validate(settings); log.debug("Executing clone [{}]", settings.getRepositoryUri()); CloneCommand cloneCommand = Git.cloneRepository() .setURI(settings.getRepositoryUri()) @@ -179,6 +179,7 @@ public class GitRepository { if (settings.isLocalOnly()) { return; } + RepositoryUriValidator.validate(settings); log.debug("Executing test [{}]", settings.getRepositoryUri()); AuthHandler authHandler = AuthHandler.createFor(settings, directory); if (settings.isReadOnly()) { @@ -206,6 +207,7 @@ public class GitRepository { if (settings.isLocalOnly()) { return false; } + RepositoryUriValidator.validate(settings); log.debug("Executing fetch [{}]", settings.getRepositoryUri()); FetchResult result = execute(git.fetch() .setRemoveDeletedRefs(true)); @@ -374,6 +376,7 @@ public class GitRepository { if (settings.isLocalOnly()) { return; } + RepositoryUriValidator.validate(settings); log.debug("Executing push [{}][{}]", settings.getRepositoryUri(), remoteBranch); Iterable result = execute(git.push() .setRefSpecs(new RefSpec(localBranch + ":" + remoteBranch))); @@ -536,7 +539,7 @@ public class GitRepository { CredentialsProvider credentialsProvider = null; SshdSessionFactory sshSessionFactory = null; if (RepositoryAuthMethod.USERNAME_PASSWORD.equals(settings.getAuthMethod())) { - credentialsProvider = newCredentialsProvider(settings.getUsername(), settings.getPassword()); + credentialsProvider = newCredentialsProvider(settings.getUsername(), settings.getPassword(), extractHost(settings.getRepositoryUri())); } else if (RepositoryAuthMethod.PRIVATE_KEY.equals(settings.getAuthMethod())) { if (StringUtils.startsWith(settings.getRepositoryUri(), "https://")) { throw new IllegalArgumentException("Invalid URI format for private key authentication"); @@ -560,8 +563,16 @@ public class GitRepository { } } - private static CredentialsProvider newCredentialsProvider(String username, String password) { - return new UsernamePasswordCredentialsProvider(username, password == null ? "" : password); + private static CredentialsProvider newCredentialsProvider(String username, String password, String allowedHost) { + return new HostScopedCredentialsProvider(username, password, allowedHost); + } + + private static String extractHost(String repositoryUri) { + try { + return new URIish(repositoryUri).getHost(); + } catch (Exception e) { + return null; + } } private static SshdSessionFactory newSshdSessionFactory(String privateKey, String password, File directory) { diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProvider.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProvider.java new file mode 100644 index 0000000000..383a79dd36 --- /dev/null +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProvider.java @@ -0,0 +1,43 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * 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 org.thingsboard.server.service.sync.vc; + +import org.eclipse.jgit.errors.UnsupportedCredentialItem; +import org.eclipse.jgit.transport.CredentialItem; +import org.eclipse.jgit.transport.URIish; +import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; + +class HostScopedCredentialsProvider extends UsernamePasswordCredentialsProvider { + + private final String allowedHost; + + HostScopedCredentialsProvider(String username, String password, String allowedHost) { + super(username, password == null ? "" : password); + this.allowedHost = allowedHost; + } + + @Override + public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem { + if (uri == null || allowedHost == null) { + return false; + } + String requestedHost = uri.getHost(); + if (requestedHost == null || !allowedHost.equalsIgnoreCase(requestedHost)) { + return false; + } + return super.get(uri, items); + } +} diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidator.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidator.java new file mode 100644 index 0000000000..c4d8bdc310 --- /dev/null +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidator.java @@ -0,0 +1,67 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * 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 org.thingsboard.server.service.sync.vc; + +import org.eclipse.jgit.transport.URIish; +import org.thingsboard.common.util.SsrfProtectionValidator; +import org.thingsboard.server.common.data.sync.vc.RepositorySettings; + +import java.net.URISyntaxException; +import java.util.Set; + +public final class RepositoryUriValidator { + + private static final Set ALLOWED_SCHEMES = Set.of("http", "https", "ssh"); + + private RepositoryUriValidator() { + } + + public static void validate(RepositorySettings settings) { + if (settings == null || settings.isLocalOnly()) { + return; + } + String uri = settings.getRepositoryUri(); + if (uri == null || uri.isBlank()) { + throw new IllegalArgumentException("Repository URI is required"); + } + URIish parsed; + try { + parsed = new URIish(uri.trim()); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Repository URI is invalid: " + e.getMessage(), e); + } + // URIish returns null scheme for scp-style git@host:path; treat as ssh + String scheme = parsed.getScheme(); + String effectiveScheme = scheme == null ? "ssh" : scheme.toLowerCase(); + if (!ALLOWED_SCHEMES.contains(effectiveScheme)) { + throw new IllegalArgumentException("Repository URI scheme '" + effectiveScheme + "' is not allowed. " + + "Allowed schemes: http, https, ssh"); + } + String host = parsed.getHost(); + if (host == null || host.isEmpty()) { + throw new IllegalArgumentException("Repository URI is missing a hostname"); + } + // Validate the host extracted by URIish — the same parser JGit uses for transport. + // Using java.net.URI here would risk parser-disagreement SSRF bypasses + // (e.g. http://evil.com#@127.0.0.1/ where URI.getHost() and URIish.getHost() differ). + try { + SsrfProtectionValidator.validateHost(host); + } catch (RuntimeException e) { + throw new IllegalArgumentException("Repository URI is not allowed: " + e.getMessage() + + ". If this host should be accessible, contact the platform administrator about SSRF allow-list.", e); + } + } +} diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProviderTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProviderTest.java new file mode 100644 index 0000000000..e39179de2c --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/HostScopedCredentialsProviderTest.java @@ -0,0 +1,103 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * 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 org.thingsboard.server.service.sync.vc; + +import org.eclipse.jgit.transport.CredentialItem; +import org.eclipse.jgit.transport.URIish; +import org.junit.jupiter.api.Test; + +import java.net.URISyntaxException; + +import static org.assertj.core.api.Assertions.assertThat; + +class HostScopedCredentialsProviderTest { + + @Test + void sameHostReturnsCredentials() throws URISyntaxException { + HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "github.com"); + URIish uri = new URIish("https://github.com/owner/repo.git"); + CredentialItem.Username userItem = new CredentialItem.Username(); + CredentialItem.Password passItem = new CredentialItem.Password(); + + boolean result = provider.get(uri, userItem, passItem); + + assertThat(result).isTrue(); + assertThat(userItem.getValue()).isEqualTo("user"); + assertThat(new String(passItem.getValue())).isEqualTo("pass"); + } + + @Test + void crossHostReturnsFalseAndDoesNotPopulateItems() throws URISyntaxException { + HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "github.com"); + URIish redirectTarget = new URIish("https://attacker.example.com/owner/repo.git"); + CredentialItem.Username userItem = new CredentialItem.Username(); + CredentialItem.Password passItem = new CredentialItem.Password(); + + boolean result = provider.get(redirectTarget, userItem, passItem); + + assertThat(result).isFalse(); + assertThat(userItem.getValue()).isNull(); + assertThat(passItem.getValue()).isNull(); + } + + @Test + void hostComparisonIsCaseInsensitive() throws URISyntaxException { + HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "GitHub.COM"); + URIish uri = new URIish("https://github.com/owner/repo.git"); + CredentialItem.Username userItem = new CredentialItem.Username(); + + boolean result = provider.get(uri, userItem); + + assertThat(result).isTrue(); + assertThat(userItem.getValue()).isEqualTo("user"); + } + + @Test + void crossHostToPrivateIpIsRefused() throws URISyntaxException { + HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", "github.com"); + URIish internalRedirect = new URIish("http://10.0.0.5/owner/repo.git"); + CredentialItem.Username userItem = new CredentialItem.Username(); + + boolean result = provider.get(internalRedirect, userItem); + + assertThat(result).isFalse(); + assertThat(userItem.getValue()).isNull(); + } + + @Test + void nullAllowedHostRefuses() throws URISyntaxException { + HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", "pass", null); + URIish uri = new URIish("https://github.com/owner/repo.git"); + CredentialItem.Username userItem = new CredentialItem.Username(); + + boolean result = provider.get(uri, userItem); + + assertThat(result).isFalse(); + assertThat(userItem.getValue()).isNull(); + } + + @Test + void nullPasswordIsNormalizedToEmpty() throws URISyntaxException { + HostScopedCredentialsProvider provider = new HostScopedCredentialsProvider("user", null, "github.com"); + URIish uri = new URIish("https://github.com/owner/repo.git"); + CredentialItem.Password passItem = new CredentialItem.Password(); + + boolean result = provider.get(uri, passItem); + + assertThat(result).isTrue(); + assertThat(new String(passItem.getValue())).isEmpty(); + } +} diff --git a/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidatorTest.java b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidatorTest.java new file mode 100644 index 0000000000..71f9c62914 --- /dev/null +++ b/common/version-control/src/test/java/org/thingsboard/server/service/sync/vc/RepositoryUriValidatorTest.java @@ -0,0 +1,227 @@ +/** + * Copyright © 2016-2026 The Thingsboard Authors + * + * 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 org.thingsboard.server.service.sync.vc; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.thingsboard.common.util.SsrfProtectionValidator; +import org.thingsboard.server.common.data.sync.vc.RepositorySettings; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@ResourceLock("SsrfProtectionValidator") // shares static state with SsrfProtectionValidatorTest +class RepositoryUriValidatorTest { + + @AfterEach + void reset() { + SsrfProtectionValidator.setEnabled(false); + SsrfProtectionValidator.setAllowedHosts(Collections.emptyList()); + SsrfProtectionValidator.setAdditionalBlockedHosts(Collections.emptyList()); + } + + private static RepositorySettings settings(String uri) { + RepositorySettings s = new RepositorySettings(); + s.setRepositoryUri(uri); + return s; + } + + private static RepositorySettings localOnly(String uri) { + RepositorySettings s = settings(uri); + s.setLocalOnly(true); + return s; + } + + // --- localOnly skip --- + + @Test + void localOnlySkipsAllValidation() { + // Even file:// and unresolvable hosts pass when localOnly=true + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(localOnly("file:///etc/passwd"))); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(localOnly("anything-not-a-uri"))); + } + + @Test + void nullSettingsIsNoOp() { + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(null)); + } + + // --- null / blank URI --- + + @Test + void nullUriIsRejected() { + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings(null))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Repository URI is required"); + } + + @Test + void blankUriIsRejected() { + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings(" "))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Repository URI is required"); + } + + // --- scheme whitelist --- + + @ParameterizedTest + @ValueSource(strings = { + "file:///tmp/repo", + "git://github.com/foo/bar", + "ftp://server/repo" + }) + void disallowedSchemesAreRejected(String uri) { + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings(uri))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("scheme"); + } + + @ParameterizedTest + @ValueSource(strings = { + "http://example.com/foo.git", + "https://example.com/foo.git", + "ssh://git@example.com/foo.git", + "git@github.com:owner/repo.git" // scp-style → SSH inferred + }) + void allowedSchemesPassWhenSsrfDisabled(String uri) { + SsrfProtectionValidator.setEnabled(false); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings(uri))); + } + + // --- host checks --- + + @Test + void emptyHostIsRejected() { + // http:/// (no host) + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https:///path"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("hostname"); + } + + // --- SSRF integration: HTTP/HTTPS --- + + @Test + void httpPrivateIpRejectedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https://10.0.0.5/repo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void httpLocalhostRejectedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("http://localhost/repo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void httpPublicIpAllowedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("https://8.8.8.8/foo.git"))); + } + + // --- SSRF integration: SSH (uses validateHost) --- + + @Test + void sshPrivateIpRejectedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@192.168.1.10/foo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void scpStyleSshPrivateIpRejectedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("git@10.0.0.1:owner/repo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void sshInternalSuffixRejectedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@server.internal/foo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void sshPublicHostAllowedWhenSsrfEnabled() { + SsrfProtectionValidator.setEnabled(true); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@github.com/foo/bar.git"))); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("git@github.com:foo/bar.git"))); + } + + // --- allow-list interaction --- + + @Test + void sshHostInAllowListPassesEvenWhenPrivate() { + SsrfProtectionValidator.setEnabled(true); + SsrfProtectionValidator.setAllowedHosts(List.of("10.0.0.0/8")); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("ssh://git@10.1.2.3/foo.git"))); + } + + @Test + void httpHostInAllowListPassesEvenWhenPrivate() { + SsrfProtectionValidator.setEnabled(true); + SsrfProtectionValidator.setAllowedHosts(List.of("internal-git.corp")); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("https://internal-git.corp/foo.git"))); + } + + // --- Parser-consistency: host must come from URIish (the parser JGit transport uses) --- + + @Test + void userInfoBeforeInternalHostIsRejected() { + // http://github.com@127.0.0.1/ — URIish parses userinfo=github.com, host=127.0.0.1. + // JGit transport will connect to 127.0.0.1. Validator must see the same host. + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("http://github.com@127.0.0.1/repo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void userInfoBeforePrivateCidrHostIsRejected() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https://fake-user:fake-pass@10.0.0.5/repo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } + + @Test + void userInfoBeforePublicHostIsAllowed() { + // The userinfo is just credentials — host is what matters. + SsrfProtectionValidator.setEnabled(true); + assertThatNoException().isThrownBy(() -> RepositoryUriValidator.validate(settings("https://user:pass@github.com/repo.git"))); + } + + @Test + void ipv6LoopbackLiteralIsRejected() { + SsrfProtectionValidator.setEnabled(true); + assertThatThrownBy(() -> RepositoryUriValidator.validate(settings("https://[::1]/repo.git"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("not allowed"); + } +} From e57db098b75a6444966a1e3e2e9caafda1686869 Mon Sep 17 00:00:00 2001 From: Oleksandra Matviienko Date: Tue, 9 Jun 2026 22:39:13 +0200 Subject: [PATCH 2/2] Trim repository URI when scoping credentials so the credential host matches the validated host Clarify that forcing localOnly=false on the repository-settings API is part of the SSRF defense, not test-only scaffolding. --- .../org/thingsboard/server/controller/AdminController.java | 4 ++-- .../server/service/sync/vc/DefaultGitRepositoryService.java | 2 ++ .../org/thingsboard/server/service/sync/vc/GitRepository.java | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/thingsboard/server/controller/AdminController.java b/application/src/main/java/org/thingsboard/server/controller/AdminController.java index 0b04a6939f..21ffa0fc2a 100644 --- a/application/src/main/java/org/thingsboard/server/controller/AdminController.java +++ b/application/src/main/java/org/thingsboard/server/controller/AdminController.java @@ -304,7 +304,7 @@ public class AdminController extends BaseController { @PostMapping("/repositorySettings") public DeferredResult saveRepositorySettings(@RequestBody RepositorySettings settings) throws ThingsboardException { accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.WRITE); - settings.setLocalOnly(false); // only to be used in tests + settings.setLocalOnly(false); // force off for the tenant API: localOnly bypasses RepositoryUriValidator, so it must never be tenant-controlled (part of the SSRF defense) ListenableFuture future = versionControlService.saveVersionControlSettings(getTenantId(), settings); return wrapFuture(Futures.transform(future, savedSettings -> { savedSettings.setPassword(null); @@ -333,7 +333,7 @@ public class AdminController extends BaseController { @Parameter(description = "A JSON value representing the Repository Settings.") @RequestBody RepositorySettings settings) throws Exception { accessControlService.checkPermission(getCurrentUser(), Resource.VERSION_CONTROL, Operation.READ); - settings.setLocalOnly(false); // only to be used in tests + settings.setLocalOnly(false); // force off for the tenant API: localOnly bypasses RepositoryUriValidator, so it must never be tenant-controlled (part of the SSRF defense) return wrapFuture(versionControlService.checkVersionControlAccess(getTenantId(), settings), vcRequestTimeout); } diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java index ba52e64e5d..2098446152 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/DefaultGitRepositoryService.java @@ -95,6 +95,8 @@ public class DefaultGitRepositoryService implements GitRepositoryService { @Override public StoredConfig getUserConfig() throws ConfigInvalidException, IOException { StoredConfig config = delegate.getUserConfig(); + // SSRF hardening: keep http.followRedirects off — a followed + // redirect on the info/refs GET is itself the probe being closed. config.setString("http", null, "followRedirects", "false"); return config; } diff --git a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java index 95d9804576..b0ff55f6b9 100644 --- a/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java +++ b/common/version-control/src/main/java/org/thingsboard/server/service/sync/vc/GitRepository.java @@ -569,7 +569,7 @@ public class GitRepository { private static String extractHost(String repositoryUri) { try { - return new URIish(repositoryUri).getHost(); + return new URIish(repositoryUri.trim()).getHost(); } catch (Exception e) { return null; }