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

[JENKINS-74907] Add validations when Jenkins is in FIPS mode #1010

Draft
wants to merge 18 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
6 changes: 3 additions & 3 deletions 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.3</jenkins.version>
<gitHubRepo>jenkinsci/${project.artifactId}-plugin</gitHubRepo>
<hpi.compatibleSinceVersion>1626</hpi.compatibleSinceVersion>
</properties>
Expand Down Expand Up @@ -201,8 +201,8 @@ THE SOFTWARE.
<dependencies>
<dependency>
<groupId>io.jenkins.tools.bom</groupId>
<artifactId>bom-2.452.x</artifactId>
<version>3654.v237e4a_f2d8da_</version>
<artifactId>bom-2.462.x</artifactId>
<version>3722.vcc62e7311580</version>
<scope>import</scope>
<type>pom</type>
</dependency>
Expand Down
22 changes: 20 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 Down Expand Up @@ -206,7 +207,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();
FIPS140Utils.ensurePrivateKeyInFipsMode(privateKey);
return new EC2PrivateKey(privateKey);
}
}
return null;
Expand Down Expand Up @@ -274,7 +277,9 @@
t.parent = this;

if (this.sshKeysCredentialsId == null && this.privateKey != null ){
migratePrivateSshKeyToCredential(this.privateKey.getPrivateKey());
String privateKey = this.privateKey.getPrivateKey();
FIPS140Utils.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 @@ -1197,78 +1202,91 @@
}
}

try {
FIPS140Utils.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 {
FIPS140Utils.ensurePrivateKeyInFipsMode(privateKey);
} catch (IllegalArgumentException ex) {
validations.add(FormValidation.error(ex, ex.getLocalizedMessage()));
}

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

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 1206-1288 are not covered by tests

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

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


public class WindowsData extends AMITypeData {

Expand All @@ -18,7 +25,19 @@
private final Boolean allowSelfSignedCertificate; //Boolean to allow nulls when the saved template doesn't have the field

@DataBoundConstructor
public WindowsData(String password, boolean useHTTPS, String bootDelay, boolean specifyPassword, boolean allowSelfSignedCertificate) {
public WindowsData(String password, boolean useHTTPS, String bootDelay, boolean specifyPassword, boolean allowSelfSignedCertificate)
throws Descriptor.FormException {
try {
FIPS140Utils.ensureNoPasswordLeak(useHTTPS, password);
} catch (IllegalArgumentException e) {
throw new Descriptor.FormException(e, "password");
}
try {
FIPS140Utils.ensureNoSelfSignedCertificate(allowSelfSignedCertificate);
} catch (IllegalArgumentException e) {
throw new Descriptor.FormException(e, "allowSelfSignedCertificate");
}

this.password = Secret.fromString(password);
this.useHTTPS = useHTTPS;
this.bootDelay = bootDelay;
Expand All @@ -32,11 +51,12 @@
}

@Deprecated
public WindowsData(String password, boolean useHTTPS, String bootDelay, boolean specifyPassword) {
public WindowsData(String password, boolean useHTTPS, String bootDelay, boolean specifyPassword)
throws Descriptor.FormException {
this(password, useHTTPS, bootDelay, specifyPassword, true);
}

public WindowsData(String password, boolean useHTTPS, String bootDelay) {
public WindowsData(String password, boolean useHTTPS, String bootDelay) throws Descriptor.FormException {
this(password, useHTTPS, bootDelay, false);
}

Expand Down Expand Up @@ -89,6 +109,36 @@
public String getDisplayName() {
return "windows";
}

@POST
@SuppressWarnings("unused")
public FormValidation doCheckUseHTTPS(@QueryParameter boolean useHTTPS, @QueryParameter String password) {
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {

Check warning on line 116 in src/main/java/hudson/plugins/ec2/WindowsData.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 116 is only partially covered, one branch is missing
// for security reasons, do not perform any check if the user is not an admin
return FormValidation.ok();

Check warning on line 118 in src/main/java/hudson/plugins/ec2/WindowsData.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 118 is not covered by tests
}
try {
FIPS140Utils.ensureNoPasswordLeak(useHTTPS, password);
jmdesprez marked this conversation as resolved.
Show resolved Hide resolved
} catch (IllegalArgumentException ex) {
return FormValidation.error(ex, ex.getLocalizedMessage());

Check warning on line 123 in src/main/java/hudson/plugins/ec2/WindowsData.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 122-123 are not covered by tests
}
return FormValidation.ok();
}

@POST
@SuppressWarnings("unused")
public FormValidation doCheckAllowSelfSignedCertificate(@QueryParameter boolean allowSelfSignedCertificate) {
Fixed Show fixed Hide fixed
Fixed Show fixed Hide fixed
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {

Check warning on line 131 in src/main/java/hudson/plugins/ec2/WindowsData.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 131 is only partially covered, one branch is missing
// for security reasons, do not perform any check if the user is not an admin
return FormValidation.ok();

Check warning on line 133 in src/main/java/hudson/plugins/ec2/WindowsData.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 133 is not covered by tests
}
try {
FIPS140Utils.ensureNoSelfSignedCertificate(allowSelfSignedCertificate);
} catch (IllegalArgumentException ex) {
return FormValidation.error(ex, ex.getLocalizedMessage());

Check warning on line 138 in src/main/java/hudson/plugins/ec2/WindowsData.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 137-138 are not covered by tests
}
return FormValidation.ok();
}
}

@Override
Expand Down
3 changes: 3 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 @@ -28,6 +28,7 @@

import com.trilead.ssh2.KnownHosts;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.plugins.ec2.util.FIPS140Utils;

import java.io.Serializable;
import java.util.Arrays;
Expand All @@ -47,6 +48,8 @@ public final class HostKey implements Serializable {

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

this.algorithm = algorithm;
this.key = key.clone();
}
Expand Down
161 changes: 161 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,161 @@
package hudson.plugins.ec2.util;

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 jenkins.bouncycastle.api.PEMEncodable;
import jenkins.security.FIPS140;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.security.Key;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.UnrecoverableKeyException;
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 24 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 24 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_invalidKeySizeInFIPSMode());
}
} else if (key instanceof DSAKey) {
if (((DSAKey) key).getParams().getP().bitLength() < 2048) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_invalidKeySizeInFIPSMode());
}
} else if (key instanceof ECKey) {
if (((ECKey) key).getParams().getCurve().getField().getFieldSize() < 224) {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_invalidKeySizeECInFIPSMode());
}
} else {
throw new IllegalArgumentException(Messages.AmazonEC2Cloud_keyIsNotApprovedInFIPSMode(key.getAlgorithm()));
}
} catch (RuntimeException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}


/**
* 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, !StringUtils.isEmpty(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());
}
}
}

/**
* 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 131 in src/main/java/hudson/plugins/ec2/util/FIPS140Utils.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

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

Check warning on line 132 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 132 is not covered by tests
}
try {
Key privateKey = PEMEncodable.decode(privateKeyString).toPrivateKey();
ensureKeyInFipsMode(privateKey);
} catch (RuntimeException | UnrecoverableKeyException | IOException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}

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);
ensureKeyInFipsMode(publicKey);
} catch (RuntimeException | IOException e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
}
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
Loading