Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
3005143
Bump jenkins version
jmdesprez Nov 21, 2024
ab2914f
Add FIPS utility methods and messages
jmdesprez Nov 22, 2024
986fec8
Add FIPS compliance check for WinRM
jmdesprez Nov 22, 2024
986005e
Add FIPS compliance check for WinRMClient
jmdesprez Nov 22, 2024
066106e
Add FIPS compliance check for HostKey
jmdesprez Nov 22, 2024
89b9443
Add FIPS compliance check for EC2Cloud
jmdesprez Nov 25, 2024
dff8af1
Add FIPS compliance check for WinConnection
jmdesprez Nov 25, 2024
1729122
Add FIPS compliance check for WindowsData
jmdesprez Nov 25, 2024
6520e9f
Merge branch 'master' into JENKINS-74907
jmdesprez Nov 25, 2024
41419cc
Fix Jenkins security scan
jmdesprez Nov 25, 2024
2f073ac
Align BOM version with Jenkins version
jmdesprez Nov 26, 2024
5877f74
Bump Jenkins
jmdesprez Nov 26, 2024
1bb4a31
Fix tests
jmdesprez Nov 26, 2024
78a96b7
Make use of Common Lang instead of a private method
jmdesprez Nov 26, 2024
c16aeaf
Throw FormException instead of IllegalArgumentException
jmdesprez Nov 26, 2024
1fbb826
Make use of FIPS140Utils
jmdesprez Nov 26, 2024
e04e639
Move utility methods into FIPS140Utils
jmdesprez Nov 26, 2024
fcd7cd2
Add FIPS mention to messages keys
jmdesprez Nov 26, 2024
af72912
Merge branch 'master' into JENKINS-74907
jmdesprez Jan 22, 2025
8044460
Format repository with Spotless
jmdesprez Jan 22, 2025
fd76311
Update messages keys according to the properties file
jmdesprez Jan 22, 2025
126a1ef
Implement ensurePublicKeyInFipsMode using mina
jmdesprez Jan 22, 2025
da58504
Remove the RuntimeException catch
jmdesprez Jan 22, 2025
7e34b30
Add FIPS validation of decoded KeyPair
jmdesprez Jan 22, 2025
276ac81
Code cleanup
jmdesprez Jan 22, 2025
8d87877
Enable tests
jmdesprez Jan 22, 2025
8608cdc
Add Windows password length validation
jmdesprez Jan 22, 2025
bac89fb
Add password length validation in the constructor
jmdesprez Jan 29, 2025
93c5a3c
Only validate password when it is in use
jmdesprez Jan 29, 2025
bd6a541
Fix tests and add password length validation
jmdesprez Jan 29, 2025
ac3c0fc
Merge branch 'master' into JENKINS-74907
jmdesprez Jan 30, 2025
22bda8f
Code cleanup on tests
jmdesprez Jan 31, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ THE SOFTWARE.

<properties>
<changelist>999999-SNAPSHOT</changelist>
<jenkins.version>2.452.4</jenkins.version>
<jenkins.version>2.462.2</jenkins.version>
<gitHubRepo>jenkinsci/${project.artifactId}-plugin</gitHubRepo>
<hpi.compatibleSinceVersion>1626</hpi.compatibleSinceVersion>
</properties>
Expand Down
53 changes: 51 additions & 2 deletions src/main/java/hudson/plugins/ec2/EC2Cloud.java
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
import hudson.model.PeriodicWork;
import hudson.model.TaskListener;
import hudson.plugins.ec2.util.AmazonEC2Factory;
import hudson.plugins.ec2.util.FIPS140Utils;
import hudson.security.ACL;
import hudson.slaves.Cloud;
import hudson.slaves.NodeProvisioner.PlannedNode;
Expand All @@ -67,8 +68,10 @@
import hudson.util.ListBoxModel;
import hudson.util.Secret;
import hudson.util.StreamTaskListener;
import jenkins.bouncycastle.api.PEMEncodable;
import jenkins.model.Jenkins;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.security.FIPS140;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.HttpResponse;
Expand All @@ -87,6 +90,8 @@
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.security.Key;
import java.security.UnrecoverableKeyException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
Expand Down Expand Up @@ -206,7 +211,9 @@
LOGGER.fine(() -> "(resolvePrivateKey) Using jenkins ssh credential");
SSHUserPrivateKey privateKeyCredential = getSshCredential(sshKeysCredentialsId, Jenkins.get());
if (privateKeyCredential != null) {
return new EC2PrivateKey(privateKeyCredential.getPrivateKey());
String privateKey = privateKeyCredential.getPrivateKey();
ensurePrivateKeyInFipsMode(privateKey);
return new EC2PrivateKey(privateKey);
}
}
return null;
Expand Down Expand Up @@ -274,7 +281,9 @@
t.parent = this;

if (this.sshKeysCredentialsId == null && this.privateKey != null ){
migratePrivateSshKeyToCredential(this.privateKey.getPrivateKey());
String privateKey = this.privateKey.getPrivateKey();
ensurePrivateKeyInFipsMode(privateKey);
migratePrivateSshKeyToCredential(privateKey);
}
this.privateKey = null; // This enforces it not to be persisted and that CasC will never output privateKey on export

Expand Down Expand Up @@ -1106,6 +1115,33 @@
return credential;
}

/**
* Checks if the private key is allowed when FIPS mode is requested.
* Allowed private key with the following algorithms and sizes:
* <ul>
* <li>DSA with key size >= 2048</li>
* <li>RSA with key size >= 2048</li>
* <li>Elliptic curve (ED25519) with field size >= 224</li>
* </ul>
* If the private key is valid and allowed or not in FIPS mode method will just exit.
* If not it will throw an {@link IllegalArgumentException}.
* @param privateKeyString String containing the private key PEM.
*/
public static void ensurePrivateKeyInFipsMode(String privateKeyString) {
if (!FIPS140.useCompliantAlgorithms()) {
return;
}
if (StringUtils.isBlank(privateKeyString)) {

Check warning on line 1134 in src/main/java/hudson/plugins/ec2/EC2Cloud.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 1134 is only partially covered, one branch is missing
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_keyIsMandatory());

Check warning on line 1135 in src/main/java/hudson/plugins/ec2/EC2Cloud.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 1135 is not covered by tests
}
try {
Key privateKey = PEMEncodable.decode(privateKeyString).toPrivateKey();
FIPS140Utils.ensureKeyInFipsMode(privateKey);
} catch (RuntimeException | UnrecoverableKeyException | IOException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}

public static abstract class DescriptorImpl extends Descriptor<Cloud> {

public InstanceType[] getInstanceTypes() {
Expand Down Expand Up @@ -1197,78 +1233,91 @@
}
}

try {
ensurePrivateKeyInFipsMode(privateKey);
} catch (IllegalArgumentException ex) {
validations.add(FormValidation.error(ex, ex.getLocalizedMessage()));
}

validations.add(FormValidation.ok("SSH key validation successful"));
return FormValidation.aggregate(validations);
}

/**
* Tests the connection settings.
*
* Overriding needs to {@code @RequirePOST}
* @param ec2endpoint
* @param useInstanceProfileForCredentials
* @param credentialsId
* @param sshKeysCredentialsId
* @param roleArn
* @param roleSessionName
* @param region
* @return the validation result
* @throws IOException
* @throws ServletException
*/
@POST
protected FormValidation doTestConnection(@AncestorInPath ItemGroup context, URL ec2endpoint, boolean useInstanceProfileForCredentials, String credentialsId, String sshKeysCredentialsId, String roleArn, String roleSessionName, String region)
throws IOException, ServletException {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return FormValidation.ok();
}
try {
List<FormValidation> validations = new ArrayList<>();

LOGGER.fine(() -> "begin doTestConnection()");
String privateKey = "";
if (System.getProperty(SSH_PRIVATE_KEY_FILEPATH, "").isEmpty()) {
LOGGER.fine(() -> "static credential is in use");
SSHUserPrivateKey sshCredential = getSshCredential(sshKeysCredentialsId, context);
if (sshCredential != null) {
privateKey = sshCredential.getPrivateKey();
} else {
return FormValidation.error("Failed to find credential \"" + sshKeysCredentialsId + "\" in store.");
}
} else {
EC2PrivateKey k = EC2PrivateKey.fetchFromDisk();
if (k == null) {
validations.add(FormValidation.error("Failed to find private key file " + System.getProperty(SSH_PRIVATE_KEY_FILEPATH)));
if (!StringUtils.isEmpty(sshKeysCredentialsId)) {
validations.add(FormValidation.warning("Private key file path defined, selected credential will be ignored"));
}
return FormValidation.aggregate(validations);
}
privateKey = k.getPrivateKey();
}
LOGGER.fine(() -> "private key found ok");

AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, credentialsId, roleArn, roleSessionName, region);
AmazonEC2 ec2 = AmazonEC2Factory.getInstance().connect(credentialsProvider, ec2endpoint);
ec2.describeInstances();


if (privateKey.trim().length() > 0) {
// check if this key exists
EC2PrivateKey pk = new EC2PrivateKey(privateKey);
if (pk.find(ec2) == null)
validations.add(FormValidation
.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "
+ pk.getFingerprint() + ")"));
}

if (!System.getProperty(SSH_PRIVATE_KEY_FILEPATH, "").isEmpty()) {
if (!StringUtils.isEmpty(sshKeysCredentialsId)) {
validations.add(FormValidation.warning("Using private key file instead of selected credential"));
} else {
validations.add(FormValidation.ok("Using private key file"));
}
}

try {
ensurePrivateKeyInFipsMode(privateKey);
} catch (IllegalArgumentException ex) {
validations.add(FormValidation.error(ex, ex.getLocalizedMessage()));
}

Check warning on line 1319 in src/main/java/hudson/plugins/ec2/EC2Cloud.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 1237-1319 are not covered by tests

validations.add(FormValidation.ok(Messages.EC2Cloud_Success()));
return FormValidation.aggregate(validations);
} catch (AmazonClientException e) {
Expand Down
26 changes: 26 additions & 0 deletions src/main/java/hudson/plugins/ec2/WindowsData.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@
import hudson.Extension;
import hudson.model.Descriptor;

import hudson.plugins.ec2.util.FIPS140Utils;
import hudson.util.FormValidation;
import hudson.util.Secret;
import jenkins.security.FIPS140;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;


public class WindowsData extends AMITypeData {

Expand All @@ -19,6 +24,9 @@

@DataBoundConstructor
public WindowsData(String password, boolean useHTTPS, String bootDelay, boolean specifyPassword, boolean allowSelfSignedCertificate) {
FIPS140Utils.ensureNoPasswordLeak(useHTTPS, password);
FIPS140Utils.ensureNoSelfSignedCertificate(allowSelfSignedCertificate);

this.password = Secret.fromString(password);
this.useHTTPS = useHTTPS;
this.bootDelay = bootDelay;
Expand Down Expand Up @@ -89,6 +97,24 @@
public String getDisplayName() {
return "windows";
}

@SuppressWarnings("unused")
public FormValidation doCheckUseHTTPS(@QueryParameter boolean useHTTPS, @QueryParameter String password) {
try {
FIPS140Utils.ensureNoPasswordLeak(useHTTPS, password);
} catch (IllegalArgumentException ex) {
return FormValidation.error(ex, ex.getLocalizedMessage());
}
return FormValidation.ok();
}

@SuppressWarnings("unused")
public FormValidation doCheckAllowSelfSignedCertificate(@QueryParameter boolean allowSelfSignedCertificate) {
if (FIPS140.useCompliantAlgorithms() && allowSelfSignedCertificate) {
return FormValidation.error(Messages.AmazonEC2Cloud_selfSignedCertificateNotAllowedInFIPSMode());
}
return FormValidation.ok();
}
}

@Override
Expand Down
30 changes: 30 additions & 0 deletions src/main/java/hudson/plugins/ec2/ssh/verifiers/HostKey.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,18 @@
package hudson.plugins.ec2.ssh.verifiers;

import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.signature.KeyAlgorithm;
import com.trilead.ssh2.signature.KeyAlgorithmManager;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.plugins.ec2.Messages;
import hudson.plugins.ec2.util.FIPS140Utils;
import jenkins.security.FIPS140;

import java.io.IOException;
import java.io.Serializable;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Arrays;

/**
Expand All @@ -45,8 +54,29 @@ public final class HostKey implements Serializable {
private final String algorithm;
private final byte[] key;

public static void ensurePublicKeyInFipsMode(@NonNull String algorithm, @NonNull byte[] key) {
if (!FIPS140.useCompliantAlgorithms()) {
return;
}

KeyAlgorithm<PublicKey, PrivateKey> publicKeyPrivateKeyKeyAlgorithm = KeyAlgorithmManager
.getSupportedAlgorithms()
.stream()
.filter((keyAlgorithm) -> keyAlgorithm.getKeyFormat().equals(algorithm))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(Messages.AmazonEC2Cloud_keyIsNotApprovedInFIPSMode(algorithm)));
try {
Key publicKey = publicKeyPrivateKeyKeyAlgorithm.decodePublicKey(key);
FIPS140Utils.ensureKeyInFipsMode(publicKey);
} catch (RuntimeException | IOException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}

public HostKey(@NonNull String algorithm, @NonNull byte[] key) {
super();
ensurePublicKeyInFipsMode(algorithm, key);

this.algorithm = algorithm;
this.key = key.clone();
}
Expand Down
108 changes: 108 additions & 0 deletions src/main/java/hudson/plugins/ec2/util/FIPS140Utils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
package hudson.plugins.ec2.util;

import hudson.plugins.ec2.Messages;
import jenkins.security.FIPS140;

import java.net.URL;
import java.security.Key;
import java.security.interfaces.DSAKey;
import java.security.interfaces.ECKey;
import java.security.interfaces.RSAKey;

/**
* FIPS related utility methods (check Private and Public keys, ...)
*/
public class FIPS140Utils {

Check warning on line 15 in src/main/java/hudson/plugins/ec2/util/FIPS140Utils.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 15 is not covered by tests

/**
* Checks if the key is allowed when FIPS mode is requested.
* Allowed key with the following algorithms and sizes:
* <ul>
* <li>DSA with key size >= 2048</li>
* <li>RSA with key size >= 2048</li>
* <li>Elliptic curve (ED25519) with field size >= 224</li>
* </ul>
* If the key is valid and allowed or not in FIPS mode method will just exit.
* If not it will throw an {@link IllegalArgumentException}.
* @param key The key to check.
*/
public static void ensureKeyInFipsMode(Key key) {
if (!FIPS140.useCompliantAlgorithms()) {
return;
}
try {
if (key instanceof RSAKey) {
if (((RSAKey) key).getModulus().bitLength() < 2048) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_invalidKeySize());
}
} else if (key instanceof DSAKey) {
if (((DSAKey) key).getParams().getP().bitLength() < 2048) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_invalidKeySize());
}
} else if (key instanceof ECKey) {
if (((ECKey) key).getParams().getCurve().getField().getFieldSize() < 224) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_invalidKeySizeEC());
}
} else {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_keyIsNotApprovedInFIPSMode(key.getAlgorithm()));
}
} catch (RuntimeException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}

private static boolean isNotEmpty(String password) {
return password != null && !password.isEmpty();
}

/**
* Password leak prevention when FIPS mode is requested. If FIPS mode is not requested, this method does nothing.
* Otherwise, ensure that no password can be leaked
* @param url the requested URL
* @param password the password used
* @throws IllegalArgumentException if there is a risk that the password will leak
*/
public static void ensureNoPasswordLeak(URL url, String password) {
ensureNoPasswordLeak("https".equals(url.getProtocol()), password);
}

/**
* Password leak prevention when FIPS mode is requested. If FIPS mode is not requested, this method does nothing.
* Otherwise, ensure that no password can be leaked.
* @param useHTTPS is TLS used or not
* @param password the password used
* @throws IllegalArgumentException if there is a risk that the password will leak
*/
public static void ensureNoPasswordLeak(boolean useHTTPS, String password) {
ensureNoPasswordLeak(useHTTPS, isNotEmpty(password));
}

/**
* Password leak prevention when FIPS mode is requested. If FIPS mode is not requested, this method does nothing.
* Otherwise, ensure that no password can be leaked.
* @param useHTTPS is TLS used or not
* @param usePassword is a password used
* @throws IllegalArgumentException if there is a risk that the password will leak
*/
public static void ensureNoPasswordLeak(boolean useHTTPS, boolean usePassword) {
if (FIPS140.useCompliantAlgorithms()) {
if (!useHTTPS && usePassword) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_tlsIsRequiredInFIPSMode());
}
}
}

/**
* Password leak prevention when FIPS mode is requested. If FIPS mode is not requested, this method does nothing.
* Otherwise, ensure that no password can be leaked.
* @param allowSelfSignedCertificate is self-signed certificate allowed
* @throws IllegalArgumentException if FIPS mode is requested and a self-signed certificate is allowed
*/
public static void ensureNoSelfSignedCertificate(boolean allowSelfSignedCertificate) {
if (FIPS140.useCompliantAlgorithms()) {
if (allowSelfSignedCertificate) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_selfSignedCertificateNotAllowedInFIPSMode());
}
}
}
}
11 changes: 9 additions & 2 deletions src/main/java/hudson/plugins/ec2/win/WinConnection.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package hudson.plugins.ec2.win;

import com.hierynomus.protocol.transport.TransportException;
import com.hierynomus.security.bc.BCSecurityProvider;
import com.hierynomus.smbj.SmbConfig;
import hudson.plugins.ec2.Messages;
import hudson.plugins.ec2.util.FIPS140Utils;
import hudson.plugins.ec2.win.winrm.WinRM;
import hudson.plugins.ec2.win.winrm.WindowsProcess;

Expand All @@ -21,6 +21,7 @@
import com.hierynomus.msdtyp.AccessMask;
import com.hierynomus.mssmb2.SMB2ShareAccess;
import com.hierynomus.mssmb2.SMB2CreateDisposition;
import jenkins.security.FIPS140;

import javax.net.ssl.SSLException;
import java.util.logging.Level;
Expand Down Expand Up @@ -49,6 +50,8 @@ public WinConnection(String host, String username, String password) {
}

public WinConnection(String host, String username, String password, boolean allowSelfSignedCertificate) {
FIPS140Utils.ensureNoSelfSignedCertificate(allowSelfSignedCertificate);

this.host = host;
this.username = username;
this.password = password;
Expand All @@ -58,6 +61,9 @@ public WinConnection(String host, String username, String password, boolean allo
}

public WinRM winrm() {
FIPS140Utils.ensureNoPasswordLeak(useHTTPS, password);
FIPS140Utils.ensureNoSelfSignedCertificate(allowSelfSignedCertificate);

WinRM winrm = new WinRM(host, username, password, allowSelfSignedCertificate);
winrm.setUseHTTPS(useHTTPS);
return winrm;
Expand Down Expand Up @@ -178,6 +184,7 @@ public void close() {
}

public void setUseHTTPS(boolean useHTTPS) {
FIPS140Utils.ensureNoPasswordLeak(useHTTPS, password);
this.useHTTPS = useHTTPS;
}
}
Loading