Skip to content

Commit

Permalink
Ingest plexus-cipher (#78)
Browse files Browse the repository at this point in the history
Ingest plexus-cipher, add improvements to "detection" of encrypted strings.
  • Loading branch information
cstamas authored Oct 14, 2024
1 parent 85a46a6 commit f0183e1
Show file tree
Hide file tree
Showing 12 changed files with 429 additions and 119 deletions.
5 changes: 0 additions & 5 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,6 @@
<artifactId>slf4j-api</artifactId>
<version>${version.slf4j}</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-cipher</artifactId>
<version>3.0.0</version>
</dependency>

<dependency>
<groupId>javax.inject</groupId>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.codehaus.plexus.components.secdispatcher;

/**
* Cipher interface.
*
* @since 4.0.1
*/
public interface Cipher {
/**
* Encrypts the clear text data with password and returns result. No argument is allowed to be {@code null}.
*
* @throws CipherException if encryption failed (is unexpected to happen, as it would mean that Java Runtime
* lacks some Crypto elements).
*/
String encrypt(final String clearText, final String password) throws CipherException;

/**
* Decrypts the encrypted text with password and returns clear text result. No argument is allowed to be {@code null}.
*
* @throws CipherException if decryption failed. It may happen as with {@link #encrypt(String, String)} due Java
* Runtime lacking some Crypto elements (less likely). Most likely decrypt will fail due wrong provided password
* or maybe corrupted encrypted text.
*/
String decrypt(final String encryptedText, final String password) throws CipherException;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package org.codehaus.plexus.components.secdispatcher;

/**
* Exception thrown by {@link Cipher}.
*
* @since 4.0.1
*/
public class CipherException extends SecDispatcherException {
public CipherException(String message) {
super(message);
}

public CipherException(String message, Throwable cause) {
super(message, cause);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,23 @@ public interface SecDispatcher {
String decrypt(String str) throws SecDispatcherException, IOException;

/**
* Returns {@code true} if passed in string contains "legacy" password (Maven3 kind).
* Returns {@code true} if passed in string adheres to "encrypted string" format (current or legacy).
*
* @since 4.0.1
*/
default boolean isAnyEncryptedString(String str) {
return isEncryptedString(str) || isLegacyEncryptedString(str);
}

/**
* Returns {@code true} if passed in string adheres "encrypted string" format.
*/
boolean isEncryptedString(String str);

/**
* Returns {@code true} if passed in string adheres to "legacy encrypted string" format.
*/
boolean isLegacyPassword(String str);
boolean isLegacyEncryptedString(String str);

/**
* Reads the effective configuration, eventually creating new instance if not present.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
import java.util.StringTokenizer;
import java.util.stream.Collectors;

import org.codehaus.plexus.components.cipher.PlexusCipher;
import org.codehaus.plexus.components.cipher.PlexusCipherException;
import org.codehaus.plexus.components.secdispatcher.Dispatcher;
import org.codehaus.plexus.components.secdispatcher.DispatcherMeta;
import org.codehaus.plexus.components.secdispatcher.SecDispatcher;
Expand All @@ -48,15 +46,15 @@
* @author Oleg Gusakov
*/
public class DefaultSecDispatcher implements SecDispatcher {
public static final String SHIELD_BEGIN = "{";
public static final String SHIELD_END = "}";
public static final String ATTR_START = "[";
public static final String ATTR_STOP = "]";

protected final PlexusCipher cipher;
protected final Map<String, Dispatcher> dispatchers;
protected final Path configurationFile;

public DefaultSecDispatcher(PlexusCipher cipher, Map<String, Dispatcher> dispatchers, Path configurationFile) {
this.cipher = requireNonNull(cipher);
public DefaultSecDispatcher(Map<String, Dispatcher> dispatchers, Path configurationFile) {
this.dispatchers = requireNonNull(dispatchers);
this.configurationFile = requireNonNull(configurationFile);

Expand Down Expand Up @@ -100,66 +98,90 @@ public Collection<Field> fields() {
@Override
public String encrypt(String str, Map<String, String> attr) throws SecDispatcherException, IOException {
if (isEncryptedString(str)) return str;

try {
if (attr == null) {
attr = new HashMap<>();
} else {
attr = new HashMap<>(attr);
if (attr == null) {
attr = new HashMap<>();
} else {
attr = new HashMap<>(attr);
}
if (attr.get(DISPATCHER_NAME_ATTR) == null) {
SettingsSecurity conf = readConfiguration(false);
if (conf == null) {
throw new SecDispatcherException("No configuration found");
}
if (attr.get(DISPATCHER_NAME_ATTR) == null) {
SettingsSecurity conf = readConfiguration(false);
if (conf == null) {
throw new SecDispatcherException("No configuration found");
}
String defaultDispatcher = conf.getDefaultDispatcher();
if (defaultDispatcher == null) {
throw new SecDispatcherException("No defaultDispatcher set in configuration");
}
attr.put(DISPATCHER_NAME_ATTR, defaultDispatcher);
String defaultDispatcher = conf.getDefaultDispatcher();
if (defaultDispatcher == null) {
throw new SecDispatcherException("No defaultDispatcher set in configuration");
}
String name = attr.get(DISPATCHER_NAME_ATTR);
Dispatcher dispatcher = dispatchers.get(name);
if (dispatcher == null) throw new SecDispatcherException("No dispatcher exist with name " + name);
Dispatcher.EncryptPayload payload = dispatcher.encrypt(str, attr, prepareDispatcherConfig(name));
HashMap<String, String> resultAttributes = new HashMap<>(payload.getAttributes());
resultAttributes.put(SecDispatcher.DISPATCHER_NAME_ATTR, name);
resultAttributes.put(SecDispatcher.DISPATCHER_VERSION_ATTR, SecUtil.specVersion());
String res = ATTR_START
+ resultAttributes.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(","))
+ ATTR_STOP;
res += payload.getEncrypted();
return cipher.decorate(res);
} catch (PlexusCipherException e) {
throw new SecDispatcherException(e.getMessage(), e);
attr.put(DISPATCHER_NAME_ATTR, defaultDispatcher);
}
String name = attr.get(DISPATCHER_NAME_ATTR);
Dispatcher dispatcher = dispatchers.get(name);
if (dispatcher == null) throw new SecDispatcherException("No dispatcher exist with name " + name);
Dispatcher.EncryptPayload payload = dispatcher.encrypt(str, attr, prepareDispatcherConfig(name));
HashMap<String, String> resultAttributes = new HashMap<>(payload.getAttributes());
resultAttributes.put(SecDispatcher.DISPATCHER_NAME_ATTR, name);
resultAttributes.put(SecDispatcher.DISPATCHER_VERSION_ATTR, SecUtil.specVersion());
return SHIELD_BEGIN
+ ATTR_START
+ resultAttributes.entrySet().stream()
.map(e -> e.getKey() + "=" + e.getValue())
.collect(Collectors.joining(","))
+ ATTR_STOP
+ payload.getEncrypted()
+ SHIELD_END;
}

@Override
public String decrypt(String str) throws SecDispatcherException, IOException {
if (!isEncryptedString(str)) return str;
try {
String bare = cipher.unDecorate(str);
Map<String, String> attr = requireNonNull(stripAttributes(bare));
if (isLegacyPassword(str)) {
attr.put(DISPATCHER_NAME_ATTR, LegacyDispatcher.NAME);
}
String name = attr.get(DISPATCHER_NAME_ATTR);
Dispatcher dispatcher = dispatchers.get(name);
if (dispatcher == null) throw new SecDispatcherException("No dispatcher exist with name " + name);
return dispatcher.decrypt(strip(bare), attr, prepareDispatcherConfig(name));
} catch (PlexusCipherException e) {
throw new SecDispatcherException(e.getMessage(), e);
String bare = unDecorate(str);
Map<String, String> attr = requireNonNull(stripAttributes(bare));
if (isLegacyEncryptedString(str)) {
attr.put(DISPATCHER_NAME_ATTR, LegacyDispatcher.NAME);
}
String name = attr.get(DISPATCHER_NAME_ATTR);
Dispatcher dispatcher = dispatchers.get(name);
if (dispatcher == null) throw new SecDispatcherException("No dispatcher exist with name " + name);
return dispatcher.decrypt(strip(bare), attr, prepareDispatcherConfig(name));
}

/**
* <ul>
* <li>Current: {[name=master,cipher=AES/GCM/NoPadding,version=4.0]vvq66pZ7rkvzSPStGTI9q4QDnsmuDwo+LtjraRel2b0XpcGJFdXcYAHAS75HUA6GLpcVtEkmyQ==}</li>
* </ul>
*/
@Override
public boolean isLegacyPassword(String str) {
if (!isEncryptedString(str)) return false;
Map<String, String> attr = requireNonNull(stripAttributes(cipher.unDecorate(str)));
return !attr.containsKey(DISPATCHER_NAME_ATTR);
public boolean isEncryptedString(String str) {
boolean looksLike = str != null
&& !str.isBlank()
&& str.startsWith(SHIELD_BEGIN)
&& str.endsWith(SHIELD_END)
&& !unDecorate(str).contains(SHIELD_BEGIN)
&& !unDecorate(str).contains(SHIELD_END);
if (looksLike) {
Map<String, String> attributes = stripAttributes(unDecorate(str));
return attributes.containsKey(DISPATCHER_NAME_ATTR) && attributes.containsKey(DISPATCHER_VERSION_ATTR);
}
return false;
}

/**
* <ul>
* <li>Legacy: {jSMOWnoPFgsHVpMvz5VrIt5kRbzGpI8u+9EF1iFQyJQ=}</li>
* </ul>
*/
@Override
public boolean isLegacyEncryptedString(String str) {
boolean looksLike = str != null
&& !str.isBlank()
&& str.startsWith(SHIELD_BEGIN)
&& str.endsWith(SHIELD_END)
&& !unDecorate(str).contains(SHIELD_BEGIN)
&& !unDecorate(str).contains(SHIELD_END);
if (looksLike) {
return stripAttributes(unDecorate(str)).isEmpty();
}
return false;
}

@Override
Expand Down Expand Up @@ -284,7 +306,7 @@ protected Map<String, String> stripAttributes(String str) {
return result;
}

protected boolean isEncryptedString(String str) {
return cipher.isEncryptedString(str);
protected String unDecorate(String str) {
return str.substring(SHIELD_BEGIN.length(), str.length() - SHIELD_END.length());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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.codehaus.plexus.components.secdispatcher.internal.cipher;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.inject.Named;
import javax.inject.Singleton;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.util.Base64;

import org.codehaus.plexus.components.secdispatcher.CipherException;

@Singleton
@Named(AESGCMNoPadding.CIPHER_ALG)
public class AESGCMNoPadding implements org.codehaus.plexus.components.secdispatcher.Cipher {
public static final String CIPHER_ALG = "AES/GCM/NoPadding";

private static final int TAG_LENGTH_BIT = 128;
private static final int IV_LENGTH_BYTE = 12;
private static final int SALT_LENGTH_BYTE = 16;
private static final int PBE_ITERATIONS = 310000;
private static final int PBE_KEY_SIZE = SALT_LENGTH_BYTE * 16;
private static final String KEY_FACTORY = "PBKDF2WithHmacSHA512";
private static final String KEY_ALGORITHM = "AES";

@Override
public String encrypt(String clearText, String password) throws CipherException {
try {
byte[] salt = getRandomNonce(SALT_LENGTH_BYTE);
byte[] iv = getRandomNonce(IV_LENGTH_BYTE);
SecretKey secretKey = getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(CIPHER_ALG);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] cipherText = cipher.doFinal(clearText.getBytes(StandardCharsets.UTF_8));
byte[] cipherTextWithIvSalt = ByteBuffer.allocate(iv.length + salt.length + cipherText.length)
.put(iv)
.put(salt)
.put(cipherText)
.array();
return Base64.getEncoder().encodeToString(cipherTextWithIvSalt);
} catch (Exception e) {
throw new CipherException("Failed encrypting", e);
}
}

@Override
public String decrypt(String encryptedText, String password) throws CipherException {
try {
byte[] material = Base64.getDecoder().decode(encryptedText.getBytes(StandardCharsets.UTF_8));
ByteBuffer buffer = ByteBuffer.wrap(material);
byte[] iv = new byte[IV_LENGTH_BYTE];
buffer.get(iv);
byte[] salt = new byte[SALT_LENGTH_BYTE];
buffer.get(salt);
byte[] cipherText = new byte[buffer.remaining()];
buffer.get(cipherText);
SecretKey secretKey = getAESKeyFromPassword(password.toCharArray(), salt);
Cipher cipher = Cipher.getInstance(CIPHER_ALG);
cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
byte[] plainText = cipher.doFinal(cipherText);
return new String(plainText, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new CipherException("Failed decrypting", e);
}
}

private static byte[] getRandomNonce(int numBytes) throws NoSuchAlgorithmException {
byte[] nonce = new byte[numBytes];
SecureRandom.getInstanceStrong().nextBytes(nonce);
return nonce;
}

private static SecretKey getAESKeyFromPassword(char[] password, byte[] salt)
throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_FACTORY);
KeySpec spec = new PBEKeySpec(password, salt, PBE_ITERATIONS, PBE_KEY_SIZE);
return new SecretKeySpec(factory.generateSecret(spec).getEncoded(), KEY_ALGORITHM);
}
}
Loading

0 comments on commit f0183e1

Please sign in to comment.