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

Adding master password decrypting #4753

Merged
merged 13 commits into from
Dec 8, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ private Assertions() {
static void customizeExecutionContext(ExecutionContext ctx) {
if (MavenSettings.readFromDiskEnabled()) {
MavenExecutionContextView mctx = MavenExecutionContextView.view(ctx);
mctx.setMavenSettings(MavenSettings.readMavenSettingsFromDisk(mctx));
MavenSettings settings = MavenSettings.readMavenSettingsFromDisk(mctx);
if (settings != null) {
settings.updatePassword(mctx);
}
mctx.setMavenSettings(settings);
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
/*
* Copyright 2020 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.maven;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import lombok.*;
import lombok.experimental.FieldDefaults;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Parser;
import org.openrewrite.internal.PropertyPlaceholderHelper;
import org.openrewrite.maven.internal.MavenXmlMapper;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.UnaryOperator;

import static java.util.Collections.emptyList;

@FieldDefaults(makeFinal = true, level = AccessLevel.PRIVATE)
@ToString(onlyExplicitlyIncluded = true)
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Data
@AllArgsConstructor
@JacksonXmlRootElement(localName = "settingsSecurity")
public class MavenSecuritySettings {
@Nullable
String master;

public static @Nullable MavenSecuritySettings parse(Parser.Input source, ExecutionContext ctx) {
try {
return new Interpolator().interpolate(
MavenXmlMapper.readMapper().readValue(source.getSource(ctx), MavenSecuritySettings.class));
} catch (IOException e) {
ctx.getOnError().accept(new IOException("Failed to parse " + source.getPath(), e));
return null;
}
}

public static @Nullable MavenSecuritySettings parse(Path settingsPath, ExecutionContext ctx) {
return parse(new Parser.Input(settingsPath, () -> {
try {
return Files.newInputStream(settingsPath);
} catch (IOException e) {
ctx.getOnError().accept(new IOException("Failed to read settings-security.xml at " + settingsPath, e));
return null;
}
}), ctx);
}

public static @Nullable MavenSecuritySettings readMavenSecuritySettingsFromDisk(ExecutionContext ctx) {
final Optional<MavenSecuritySettings> userSettings = Optional.of(userSecuritySettingsPath())
.filter(MavenSecuritySettings::exists)
.map(path -> parse(path, ctx));
final MavenSecuritySettings installSettings = findMavenHomeSettings().map(path -> parse(path, ctx)).orElse(null);
return userSettings.map(mavenSecuritySettings -> mavenSecuritySettings.merge(installSettings))
.orElse(installSettings);
}

private static Path userSecuritySettingsPath() {
return Paths.get(System.getProperty("user.home")).resolve(".m2/settings-security.xml");
}

private static Optional<Path> findMavenHomeSettings() {
for (String envVariable : Arrays.asList("MVN_HOME", "M2_HOME", "MAVEN_HOME")) {
for (String s : Optional.ofNullable(System.getenv(envVariable)).map(Arrays::asList).orElse(emptyList())) {
Path resolve = Paths.get(s).resolve("conf/settings-security.xml");
if (exists(resolve)) {
return Optional.of(resolve);
}
}
}
return Optional.empty();
}

private static boolean exists(Path path) {
try {
return path.toFile().exists();
} catch (SecurityException e) {
return false;
}
}

public MavenSecuritySettings merge(@Nullable MavenSecuritySettings installSettings) {
return installSettings == null ? this : new MavenSecuritySettings(
master == null ? installSettings.master : master
);
}

/**
* Resolve all properties EXCEPT in the profiles section, which can be affected by
* the POM using the settings.
*/
private static class Interpolator {
private static final PropertyPlaceholderHelper propertyPlaceholders = new PropertyPlaceholderHelper(
"${", "}", null);

private static final UnaryOperator<String> propertyResolver = key -> {
String property = System.getProperty(key);
if (property != null) {
return property;
}
if (key.startsWith("env.")) {
return System.getenv().get(key.substring(4));
}
return System.getenv().get(key);
};

public MavenSecuritySettings interpolate(MavenSecuritySettings mavenSecuritySettings) {
return new MavenSecuritySettings(
interpolate(mavenSecuritySettings.master)
);
}

private @Nullable String interpolate(@Nullable String s) {
return s == null ? null : propertyPlaceholders.replacePlaceholders(s, propertyResolver);
}
}
}
107 changes: 107 additions & 0 deletions rewrite-maven/src/main/java/org/openrewrite/maven/MavenSettings.java
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import lombok.*;
import lombok.experimental.FieldDefaults;
import lombok.experimental.NonFinal;
import org.jetbrains.annotations.NotNull;
import org.jspecify.annotations.Nullable;
import org.openrewrite.ExecutionContext;
import org.openrewrite.Parser;
Expand All @@ -34,12 +35,25 @@
import org.openrewrite.maven.tree.MavenRepository;
import org.openrewrite.maven.tree.ProfileActivation;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.function.UnaryOperator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.Collections.emptyList;
import static org.openrewrite.maven.tree.MavenRepository.MAVEN_LOCAL_DEFAULT;
Expand Down Expand Up @@ -113,6 +127,99 @@ public MavenSettings(@Nullable String localRepository, @Nullable Profiles profil
.orElse(installSettings);
}

private byte[] extractPassword(@NotNull String pwd) {
svaningelgem marked this conversation as resolved.
Show resolved Hide resolved
Pattern pattern = Pattern.compile(".*?[^\\\\]?\\{(.*?)}.*");
Matcher matcher = pattern.matcher(pwd);
if (matcher.find()) {
return Base64.getDecoder().decode(matcher.group(1));
}
return pwd.getBytes(StandardCharsets.UTF_8);
}

private @Nullable String decrypt(@Nullable String fieldValue, @Nullable String password) {
if (fieldValue == null || fieldValue.isEmpty() || password == null) {
return null;
}

try {

byte[] encryptedText = extractPassword(fieldValue);

byte[] salt = new byte[8];
System.arraycopy(encryptedText, 0, salt, 0, 8);

int padLength = encryptedText[8];
byte[] encryptedBytes = new byte[encryptedText.length - 9 - padLength];
System.arraycopy(encryptedText, 9, encryptedBytes, 0, encryptedBytes.length);

byte[] keyAndIV = new byte[32];
byte[] pwdBytes = extractPassword(password);
int offset = 0;
while (offset < 32) {
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("SHA-256");
digest.update(pwdBytes);
digest.update(salt);
byte[] hash = digest.digest();
System.arraycopy(hash, 0, keyAndIV, offset, Math.min(hash.length, 32 - offset));
offset += hash.length;
}

Key key = new SecretKeySpec(keyAndIV, 0, 16, "AES");
IvParameterSpec iv = new IvParameterSpec(keyAndIV, 16, 16);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
byte[] clearBytes = cipher.doFinal(encryptedBytes);

int paddingLength = clearBytes[clearBytes.length - 1];
byte[] decryptedBytes = new byte[clearBytes.length - paddingLength];
System.arraycopy(clearBytes, 0, decryptedBytes, 0, decryptedBytes.length);
return new String(decryptedBytes, StandardCharsets.UTF_8);
} catch (NoSuchPaddingException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException |
InvalidKeyException | InvalidAlgorithmParameterException e) {
return null;
}
}

private void updateLocal(@Nullable String masterPassword) {
if (mavenLocal == null || masterPassword == null) {
return;
}

String password = decrypt(mavenLocal.getPassword(), masterPassword);
if (password != null) {
mavenLocal = mavenLocal.withPassword(password);
}
}

private void updateServers(@Nullable String masterPassword) {
if (servers == null || masterPassword == null) {
return;
}

List<Server> newServers = new ArrayList<>();
for (Server server : servers.servers ) {
String password = decrypt(server.getPassword(), masterPassword);
if (password != null) {
server = server.withPassword(password);
}
newServers.add(server);
}

servers.servers = newServers;
}

public void updatePassword(ExecutionContext ctx) {
MavenSecuritySettings security = MavenSecuritySettings.readMavenSecuritySettingsFromDisk(ctx);
if (security == null) {
return;
}

String decryptedMasterPassword = decrypt(security.getMaster(), "settings.security");

updateLocal(decryptedMasterPassword);
updateServers(decryptedMasterPassword);
}

public static boolean readFromDiskEnabled() {
final String propertyValue = System.getProperty("org.openrewrite.test.readMavenSettingsFromDisk");
return propertyValue != null && !propertyValue.equalsIgnoreCase("false");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright 2022 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.openrewrite.maven;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.maven.Assertions.pomXml;

class ChangeParentPom2Test implements RewriteTest {

@DocumentExample
@Test
void changeParent() {
rewriteRun(
spec -> spec.recipe(new ChangeParentPom(
"com.internal.fw1",
"com.internal.fw2",
"com-internal-fw1-pom",
"com-internal-fw2-pom",
"1.0.6",
null,
null,
null,
false
)),
pomXml(
"""
<project>
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.internal.fw1</groupId>
<artifactId>com-internal-fw1-pom</artifactId>
<version>1.7</version>
</parent>

<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
""",
"""
<project>
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>com.internal.fw2</groupId>
<artifactId>com-internal-fw2-pom</artifactId>
<version>1.0.6</version>
</parent>

<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
"""
)
);
}
}