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 API for generating SAML SP metadata #64517

Merged
merged 14 commits into from
Nov 6, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.core.security.action.saml;

import org.elasticsearch.action.ActionType;

public class SamlSPMetadataAction extends ActionType<SamlSPMetadataResponse> {
public static final String NAME = "cluster:admin/xpack/security/saml/metadata";
public static final SamlSPMetadataAction INSTANCE = new SamlSPMetadataAction();

private SamlSPMetadataAction() {
super(NAME, SamlSPMetadataResponse::new);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.core.security.action.saml;

import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

import static org.elasticsearch.action.ValidateActions.addValidationError;

public class SamlSPMetadataRequest extends ActionRequest {

String realmName;

public SamlSPMetadataRequest(StreamInput in) throws IOException {
super(in);
realmName = in.readOptionalString();
}

public SamlSPMetadataRequest() {
}

@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (Strings.hasText(realmName) == false) {
validationException = addValidationError("realm may not be empty", validationException);
}
return validationException;
}

public String getRealmName() {
return realmName;
}

public void setRealmName(String realmName) {
this.realmName = realmName;
}

@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"realmName=" + realmName +
'}';
}

@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeOptionalString(realmName);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.core.security.action.saml;

import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

/**
* Response containing a SAML SP metadata for a specific realm as XML.
*/
public class SamlSPMetadataResponse extends ActionResponse {
public String getXMLString() {
return XMLString;
}

private String XMLString;

public SamlSPMetadataResponse(StreamInput in) throws IOException {
super(in);
XMLString = in.readString();
}

public SamlSPMetadataResponse(String XMLString) {
this.XMLString = XMLString;
}

@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeString(XMLString);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.core.security.action.saml;

import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.test.ESTestCase;

import java.io.IOException;

import static org.hamcrest.Matchers.containsString;

public class SamlSPMetadataRequestTests extends ESTestCase {

public void testValidateFailsWhenRealmNotSet() {
final SamlSPMetadataRequest samlSPMetadataRequest = new SamlSPMetadataRequest();
final ActionRequestValidationException validationException = samlSPMetadataRequest.validate();
assertThat(validationException.getMessage(), containsString("realm may not be empty"));
}

public void testValidateSerialization() throws IOException {
final SamlSPMetadataRequest samlSPMetadataRequest = new SamlSPMetadataRequest();
samlSPMetadataRequest.setRealmName("saml1");
try (BytesStreamOutput out = new BytesStreamOutput()) {
samlSPMetadataRequest.writeTo(out);
try (StreamInput in = out.bytes().streamInput()) {
final SamlSPMetadataRequest serialized = new SamlSPMetadataRequest(in);
assertEquals(samlSPMetadataRequest.getRealmName(), serialized.getRealmName());
}
}
}

public void testValidateToString() {
final SamlSPMetadataRequest samlSPMetadataRequest = new SamlSPMetadataRequest();
samlSPMetadataRequest.setRealmName("saml1");
assertThat(samlSPMetadataRequest.toString(), containsString("{realmName=saml1}"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@
import org.elasticsearch.xpack.core.security.action.saml.SamlLogoutAction;
import org.elasticsearch.xpack.core.security.action.saml.SamlCompleteLogoutAction;
import org.elasticsearch.xpack.core.security.action.saml.SamlPrepareAuthenticationAction;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataAction;
import org.elasticsearch.xpack.core.security.action.token.CreateTokenAction;
import org.elasticsearch.xpack.core.security.action.token.InvalidateTokenAction;
import org.elasticsearch.xpack.core.security.action.token.RefreshTokenAction;
Expand Down Expand Up @@ -174,6 +175,7 @@
import org.elasticsearch.xpack.security.action.saml.TransportSamlLogoutAction;
import org.elasticsearch.xpack.security.action.saml.TransportSamlCompleteLogoutAction;
import org.elasticsearch.xpack.security.action.saml.TransportSamlPrepareAuthenticationAction;
import org.elasticsearch.xpack.security.action.saml.TransportSamlSPMetadataAction;
import org.elasticsearch.xpack.security.action.token.TransportCreateTokenAction;
import org.elasticsearch.xpack.security.action.token.TransportInvalidateTokenAction;
import org.elasticsearch.xpack.security.action.token.TransportRefreshTokenAction;
Expand Down Expand Up @@ -243,6 +245,7 @@
import org.elasticsearch.xpack.security.rest.action.saml.RestSamlLogoutAction;
import org.elasticsearch.xpack.security.rest.action.saml.RestSamlCompleteLogoutAction;
import org.elasticsearch.xpack.security.rest.action.saml.RestSamlPrepareAuthenticationAction;
import org.elasticsearch.xpack.security.rest.action.saml.RestSamlSPMetadataAction;
import org.elasticsearch.xpack.security.rest.action.user.RestChangePasswordAction;
import org.elasticsearch.xpack.security.rest.action.user.RestDeleteUserAction;
import org.elasticsearch.xpack.security.rest.action.user.RestGetUserPrivilegesAction;
Expand Down Expand Up @@ -781,6 +784,7 @@ public void onIndexModule(IndexModule module) {
new ActionHandler<>(SamlLogoutAction.INSTANCE, TransportSamlLogoutAction.class),
new ActionHandler<>(SamlInvalidateSessionAction.INSTANCE, TransportSamlInvalidateSessionAction.class),
new ActionHandler<>(SamlCompleteLogoutAction.INSTANCE, TransportSamlCompleteLogoutAction.class),
new ActionHandler<>(SamlSPMetadataAction.INSTANCE, TransportSamlSPMetadataAction.class),
new ActionHandler<>(OpenIdConnectPrepareAuthenticationAction.INSTANCE,
TransportOpenIdConnectPrepareAuthenticationAction.class),
new ActionHandler<>(OpenIdConnectAuthenticateAction.INSTANCE, TransportOpenIdConnectAuthenticateAction.class),
Expand Down Expand Up @@ -841,6 +845,7 @@ public List<RestHandler> getRestHandlers(Settings settings, RestController restC
new RestSamlLogoutAction(settings, getLicenseState()),
new RestSamlInvalidateSessionAction(settings, getLicenseState()),
new RestSamlCompleteLogoutAction(settings, getLicenseState()),
new RestSamlSPMetadataAction(settings, getLicenseState()),
new RestOpenIdConnectPrepareAuthenticationAction(settings, getLicenseState()),
new RestOpenIdConnectAuthenticateAction(settings, getLicenseState()),
new RestOpenIdConnectLogoutAction(settings, getLicenseState()),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.security.action.saml;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.HandledTransportAction;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.transport.TransportService;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataAction;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataRequest;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataResponse;
import org.elasticsearch.xpack.security.authc.Realms;
import org.elasticsearch.xpack.security.authc.saml.SamlMetadataCommand;
import org.elasticsearch.xpack.security.authc.saml.SamlRealm;
import org.elasticsearch.xpack.security.authc.saml.SamlUtils;
import org.opensaml.saml.saml2.metadata.EntityDescriptor;
import org.opensaml.saml.saml2.metadata.impl.EntityDescriptorMarshaller;
import org.w3c.dom.Element;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.util.List;

import static org.elasticsearch.xpack.security.authc.saml.SamlRealm.findSamlRealms;

/**
* Transport action responsible for generating a SAML SP Metadata.
*/
public class TransportSamlSPMetadataAction
extends HandledTransportAction<SamlSPMetadataRequest, SamlSPMetadataResponse> {

private final Realms realms;

@Inject
public TransportSamlSPMetadataAction(TransportService transportService, ActionFilters actionFilters, Realms realms) {
super(SamlSPMetadataAction.NAME, transportService, actionFilters, SamlSPMetadataRequest::new
);
this.realms = realms;
}

@Override
protected void doExecute(Task task, SamlSPMetadataRequest request,
ActionListener<SamlSPMetadataResponse> listener) {
List<SamlRealm> realms = findSamlRealms(this.realms, request.getRealmName(), null);
if (realms.isEmpty()) {
listener.onFailure(SamlUtils.samlException("Cannot find any matching realm for [{}]", request));
} else if (realms.size() > 1) {
listener.onFailure(SamlUtils.samlException("Found multiple matching realms [{}] for [{}]", realms, request));
} else {
prepareMetadata(realms.get(0), listener);
}
}

private void prepareMetadata(SamlRealm realm, ActionListener<SamlSPMetadataResponse> listener) {
try {
final EntityDescriptorMarshaller marshaller = new EntityDescriptorMarshaller();
final EntityDescriptor descriptor = SamlMetadataCommand.buildEntityDescriptorFromSamlRealm(realm);
final Element element = marshaller.marshall(descriptor);
final StringWriter writer = new StringWriter();
final Transformer serializer = SamlUtils.getHardenedXMLTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.transform(new DOMSource(element), new StreamResult(writer));
listener.onResponse(new SamlSPMetadataResponse(writer.toString()));
} catch (Exception e) {
logger.debug("Internal exception during SAML SP metadata generation", e);
listener.onFailure(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,18 @@ public static void main(String[] args) throws Exception {
exit(new SamlMetadataCommand().main(args, Terminal.DEFAULT));
}

public static EntityDescriptor buildEntityDescriptorFromSamlRealm(SamlRealm samlRealm) throws Exception {
final SpConfiguration spConfig = samlRealm.getLogoutHandler().getSpConfiguration();
final Locale locale = Locale.getDefault();
final SamlSpMetadataBuilder builder = new SamlSpMetadataBuilder(locale, spConfig.getEntityId())
.assertionConsumerServiceUrl(spConfig.getAscUrl())
.singleLogoutServiceUrl(spConfig.getLogoutUrl())
.encryptionCredentials(spConfig.getEncryptionCredentials())
.signingCredential(spConfig.getSigningConfiguration().getCredential())
.authnRequestsSigned(spConfig.getSigningConfiguration().shouldSign(AuthnRequest.DEFAULT_ELEMENT_LOCAL_NAME));
return builder.build();
}

public SamlMetadataCommand() {
this((environment) -> {
KeyStoreWrapper ksWrapper = KeyStoreWrapper.load(environment.configFile());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

package org.elasticsearch.xpack.security.rest.action.saml;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestResponse;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.rest.action.RestBuilderListener;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataAction;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataRequest;
import org.elasticsearch.xpack.core.security.action.saml.SamlSPMetadataResponse;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import static org.elasticsearch.rest.RestRequest.Method.GET;

public class RestSamlSPMetadataAction extends SamlBaseRestHandler {

static class Input {
String realm;
void setRealm(String realm) {
this.realm = realm;
}
}

static final ObjectParser<SamlSPMetadataRequest, Void> PARSER = new ObjectParser<>("security_saml_metadata",
SamlSPMetadataRequest::new);

static {
PARSER.declareStringOrNull(SamlSPMetadataRequest::setRealmName, new ParseField("realm"));
}

public RestSamlSPMetadataAction(Settings settings, XPackLicenseState licenseState) {
super(settings, licenseState);
}

@Override
public List<Route> routes() {
return Collections.singletonList(
new Route(GET, "/_security/saml/metadata"));
}

@Override
public String getName() {
return "security_saml_metadata_action";
}

@Override
public RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException {
try (XContentParser parser = request.contentParser()) {
final SamlSPMetadataRequest SamlSPRequest = PARSER.parse(parser, null);
return channel -> client.execute(SamlSPMetadataAction.INSTANCE, SamlSPRequest,
new RestBuilderListener<SamlSPMetadataResponse>(channel) {
@Override
public RestResponse buildResponse(SamlSPMetadataResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
builder.field("xml_metadata", response.getXMLString());
builder.endObject();
return new BytesRestResponse(RestStatus.OK, builder);
}
});
}
}
}