use of org.wso2.carbon.identity.application.common.model.CertificateInfo in project carbon-identity-framework by wso2.
the class IdPManagementUIUtil method buildFederatedIdentityProvider.
/**
* Build a federated identity provider.
*
* @param request HttpServletRequest
* @param oldIdpName This value will be populated if there is an old IDP.
* @return IdentityProvider
* @throws Exception
*/
public static IdentityProvider buildFederatedIdentityProvider(HttpServletRequest request, StringBuilder oldIdpName) throws Exception {
IdentityProvider fedIdp = new IdentityProvider();
if (ServletFileUpload.isMultipartContent(request)) {
ServletRequestContext servletContext = new ServletRequestContext(request);
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(servletContext);
Map<String, String> paramMap = new HashMap<>();
List<String> idpClaims = new ArrayList<>();
List<String> idpRoles = new ArrayList<>();
List<String> customAuthenticatorNames = new ArrayList<>();
List<String> proConnectorNames = new ArrayList<>();
Map<String, List<Property>> customAuthenticatorProperties = new HashMap<>();
Map<String, List<Property>> customProProperties = new HashMap<>();
String idpUUID = StringUtils.EMPTY;
StringBuilder deletedCertificateValue = new StringBuilder();
for (Object item : items) {
DiskFileItem diskFileItem = (DiskFileItem) item;
if (diskFileItem != null) {
byte[] value = diskFileItem.get();
String key = diskFileItem.getFieldName();
if (StringUtils.equals(key, "idpUUID")) {
idpUUID = diskFileItem.getString();
}
if (IdPManagementUIUtil.META_DATA_SAML.equals(key)) {
if (StringUtils.isNotEmpty(diskFileItem.getName()) && !diskFileItem.getName().trim().endsWith(".xml")) {
throw new CarbonException("File not supported!");
} else {
paramMap.put(key, Base64.encode(value));
}
}
if ("certFile".equals(key)) {
paramMap.put(key, Base64.encode(value));
} else if (key.startsWith(IdentityApplicationConstants.CERTIFICATE_VAL)) {
deletedCertificateValue.append(new String(value, StandardCharsets.UTF_8));
} else if ("google_prov_private_key".equals(key)) {
paramMap.put(key, Base64.encode(value));
} else if (key.startsWith("claimrowname_")) {
String strValue = new String(value, StandardCharsets.UTF_8);
idpClaims.add(strValue);
paramMap.put(key, strValue);
} else if (key.startsWith("rolerowname_")) {
String strValue = new String(value, StandardCharsets.UTF_8);
idpRoles.add(strValue);
paramMap.put(key, strValue);
} else if (key.startsWith("custom_auth_name")) {
customAuthenticatorNames.add(new String(value, StandardCharsets.UTF_8));
} else if (key.startsWith("custom_pro_name")) {
proConnectorNames.add(new String(value, StandardCharsets.UTF_8));
} else if (key.startsWith("cust_auth_prop_")) {
int length = "cust_auth_prop_".length();
String authPropString = new String(key).substring(length);
if (authPropString.indexOf("#") > 0) {
String authName = authPropString.substring(0, authPropString.indexOf("#"));
String propName = authPropString.substring(authPropString.indexOf("#") + 1);
String propVal = new String(value, StandardCharsets.UTF_8);
Property prop = new Property();
prop.setName(propName);
prop.setValue(propVal);
List<Property> propList = null;
if (customAuthenticatorProperties.get(authName) == null) {
customAuthenticatorProperties.put(authName, new ArrayList<Property>());
}
propList = customAuthenticatorProperties.get(authName);
propList.add(prop);
customAuthenticatorProperties.put(authName, propList);
}
} else if (key.startsWith("cust_pro_prop_")) {
int length = "cust_pro_prop_".length();
String provPropString = new String(key).substring(length);
if (provPropString.indexOf("#") > 0) {
String proConName = provPropString.substring(0, provPropString.indexOf("#"));
String propName = provPropString.substring(provPropString.indexOf("#") + 1);
String propVal = new String(value, StandardCharsets.UTF_8);
Property prop = new Property();
prop.setName(propName);
prop.setValue(propVal);
List<Property> propList = null;
if (customProProperties.get(proConName) == null) {
customProProperties.put(proConName, new ArrayList<Property>());
}
propList = customProProperties.get(proConName);
propList.add(prop);
customProProperties.put(proConName, propList);
}
} else {
paramMap.put(key, new String(value, StandardCharsets.UTF_8));
}
String updatedValue = paramMap.get(key);
if (updatedValue != null && updatedValue.trim().length() == 0) {
paramMap.put(key, null);
}
}
}
paramMap.put(IdentityApplicationConstants.CERTIFICATE_VAL, deletedCertificateValue.toString());
IdentityProvider oldIdentityProvider = (IdentityProvider) request.getSession().getAttribute(idpUUID);
if (oldIdentityProvider != null) {
if (oldIdpName == null) {
oldIdpName = new StringBuilder();
}
oldIdpName.append(oldIdentityProvider.getIdentityProviderName());
}
if (oldIdentityProvider != null && oldIdentityProvider.getCertificate() != null) {
if (oldIdentityProvider.getCertificateInfoArray() != null && oldIdentityProvider.getCertificateInfoArray().length > 1) {
if (log.isDebugEnabled()) {
log.debug("Number of old certificate for the identity provider " + oldIdentityProvider.getDisplayName() + " is " + oldIdentityProvider.getCertificateInfoArray().length);
}
StringBuilder multipleCertificate = new StringBuilder();
for (CertificateInfo certificateInfo : oldIdentityProvider.getCertificateInfoArray()) {
multipleCertificate.append(new String(Base64.decode(certificateInfo.getCertValue()), StandardCharsets.UTF_8));
}
paramMap.put(IdentityApplicationConstants.OLD_CERT_FILE, Base64.encode(multipleCertificate.toString().getBytes(StandardCharsets.UTF_8)));
} else {
if (log.isDebugEnabled()) {
log.debug("Only one certificate has been found as old certificate.");
}
paramMap.put(IdentityApplicationConstants.OLD_CERT_FILE, oldIdentityProvider.getCertificate());
}
}
if (oldIdentityProvider != null && oldIdentityProvider.getProvisioningConnectorConfigs() != null) {
ProvisioningConnectorConfig[] provisioningConnectorConfig = oldIdentityProvider.getProvisioningConnectorConfigs();
for (ProvisioningConnectorConfig provisioningConnector : provisioningConnectorConfig) {
if (("googleapps").equals(provisioningConnector.getName())) {
Property[] googleProperties = provisioningConnector.getProvisioningProperties();
for (Property property : googleProperties) {
if (property.getName().equals("google_prov_private_key")) {
paramMap.put("old_google_prov_private_key", property.getValue());
}
}
}
}
}
// build identity provider basic information.
buildBasicInformation(fedIdp, paramMap);
// build out-bound authentication configuration.
buildOutboundAuthenticationConfiguration(fedIdp, paramMap);
// build custom authenticator configuration.
buildCustomAuthenticationConfiguration(fedIdp, customAuthenticatorNames, customAuthenticatorProperties, paramMap);
// build claim configuration.
if (oldIdentityProvider != null && oldIdentityProvider.getClaimConfig().getClaimMappings() != null) {
buildClaimConfiguration(fedIdp, paramMap, idpClaims, oldIdentityProvider.getClaimConfig().getClaimMappings());
} else {
buildClaimConfiguration(fedIdp, paramMap, idpClaims, null);
}
// build role configuration.
if (oldIdentityProvider != null && oldIdentityProvider.getPermissionAndRoleConfig() != null && oldIdentityProvider.getPermissionAndRoleConfig().getRoleMappings() != null) {
buildRoleConfiguration(fedIdp, paramMap, idpRoles, oldIdentityProvider.getPermissionAndRoleConfig().getRoleMappings());
} else {
buildRoleConfiguration(fedIdp, paramMap, idpRoles, null);
}
// build in-bound provisioning configuration.
buildInboundProvisioningConfiguration(fedIdp, paramMap);
// build out-bound provisioning configuration.
buildOutboundProvisioningConfiguration(fedIdp, paramMap);
// build custom provisioning connectors.
buildCustomProvisioningConfiguration(fedIdp, proConnectorNames, customProProperties, paramMap);
} else {
throw new Exception("Invalid Content Type: Not multipart/form-data");
}
return fedIdp;
}
use of org.wso2.carbon.identity.application.common.model.CertificateInfo in project carbon-identity-framework by wso2.
the class IdentityApplicationManagementUtil method getCertDataArray.
/**
* Generate CertData array
*
* @param certificateInfo array of certificate info
* @return CertData array
* @throws CertificateException
*/
public static List<CertData> getCertDataArray(CertificateInfo[] certificateInfo) throws CertificateException {
if (ArrayUtils.isNotEmpty(certificateInfo)) {
List<CertData> certDataList = new ArrayList<>();
HashMap<CertData, String> certDataMap = new HashMap<>();
int i = 0;
for (CertificateInfo certificateInfoVal : certificateInfo) {
String certVal = certificateInfoVal.getCertValue();
CertData certData = createCertData(certVal);
certDataList.add(certData);
certDataMap.put(certData, certVal);
i++;
}
setCertDataMap(certDataMap);
return certDataList;
} else {
String errorMsg = "Certificate info array is empty";
if (log.isDebugEnabled()) {
log.debug(errorMsg);
}
throw new IllegalArgumentException(errorMsg);
}
}
use of org.wso2.carbon.identity.application.common.model.CertificateInfo in project identity-inbound-auth-oauth by wso2-extensions.
the class SAML2BearerGrantHandler method validateSignatureAgainstIdpCertificate.
protected void validateSignatureAgainstIdpCertificate(Assertion assertion, String tenantDomain, IdentityProvider identityProvider) throws IdentityOAuth2Exception {
boolean isExceptionThrown = false;
SignatureException signatureException = null;
CertificateInfo[] certificateInfos = identityProvider.getCertificateInfoArray();
if (log.isDebugEnabled()) {
log.debug(certificateInfos.length + " certificates found for Identity Provider " + identityProvider.getIdentityProviderName());
}
if (ArrayUtils.isEmpty(certificateInfos)) {
// when signature validation was done only for one certificate.
throw new IdentityOAuth2Exception("No certificates found for Identity Provider " + identityProvider.getIdentityProviderName() + " of tenant domain " + tenantDomain);
}
try {
/*
The process mentioned below is done because OpenSAML3 does not support OSGi refer
https://shibboleth.1660669.n2.nabble.com/Null-Pointer-Exception-from-UnmarshallerFactory-while-migrating
-from-OpenSAML2-x-to-OpenSAML3-x-td7643903.html
and https://stackoverflow.com/questions/37948303/opensaml3-resource-not-found-default-config-xml-in-osgi
-container
*/
Thread thread = Thread.currentThread();
ClassLoader originalClassLoader = thread.getContextClassLoader();
thread.setContextClassLoader(SignatureValidationProvider.class.getClassLoader());
try {
int index = 0;
for (CertificateInfo certificateInfo : certificateInfos) {
X509Certificate x509Certificate = getIdpCertificate(tenantDomain, identityProvider, certificateInfo);
X509Credential x509Credential = new X509CredentialImpl(x509Certificate);
try {
if (log.isDebugEnabled()) {
log.debug("Validating the signature with certificate " + certificateInfo.getThumbPrint() + " at index: " + index);
}
SignatureValidator.validate(assertion.getSignature(), x509Credential);
isExceptionThrown = false;
break;
} catch (SignatureException e) {
if (log.isDebugEnabled()) {
log.debug("Signature validation failed with certificate " + certificateInfo.getThumbPrint() + " at index: " + index);
}
isExceptionThrown = true;
if (signatureException == null) {
signatureException = e;
} else {
signatureException.addSuppressed(e);
}
}
index++;
}
// If all the certification validation fails, then throw the exception.
if (isExceptionThrown) {
throw signatureException;
}
} finally {
thread.setContextClassLoader(originalClassLoader);
}
} catch (SignatureException e) {
throw new IdentityOAuth2Exception("Error while validating the signature.", e);
}
}
use of org.wso2.carbon.identity.application.common.model.CertificateInfo in project identity-api-server by wso2.
the class ServerIdpManagementService method processPatchRequest.
/**
* Evaluate the list of patch operations and update the root level attributes of the identity provider accordingly.
*
* @param patchRequest List of patch operations.
* @param idpToUpdate Identity Provider to be updated.
*/
private void processPatchRequest(List<Patch> patchRequest, IdentityProvider idpToUpdate) {
if (CollectionUtils.isEmpty(patchRequest)) {
return;
}
for (Patch patch : patchRequest) {
String path = patch.getPath();
Patch.OperationEnum operation = patch.getOperation();
String value = patch.getValue();
boolean isCertificateUpdateRequest = path.matches(Constants.CERTIFICATE_PATH_REGEX) && path.split(Constants.PATH_SEPERATOR).length == 4;
// 'ADD', 'REPLACE' and 'REMOVE' patch operations supported.
if (operation == Patch.OperationEnum.REPLACE) {
if (isCertificateUpdateRequest) {
List<String> certificates = new ArrayList<>();
int index = Integer.parseInt(path.split(Constants.PATH_SEPERATOR)[3]);
if (ArrayUtils.isNotEmpty(idpToUpdate.getCertificateInfoArray()) && (index >= 0) && (index < idpToUpdate.getCertificateInfoArray().length)) {
for (CertificateInfo certInfo : idpToUpdate.getCertificateInfoArray()) {
certificates.add(base64Decode(certInfo.getCertValue()));
}
if (!value.startsWith(IdentityUtil.PEM_BEGIN_CERTFICATE)) {
try {
value = base64Decode(value);
} catch (IllegalArgumentException e) {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_CERTIFICATE_FORMAT, null);
}
}
if (certificates.contains(value)) {
throw handleException(Response.Status.CONFLICT, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_IDP, "Cannot replace certificate as this certificate already exists.");
}
certificates.set(index, value);
idpToUpdate.setCertificate(base64Encode(StringUtils.join(certificates, "")));
} else if (ArrayUtils.isEmpty(idpToUpdate.getCertificateInfoArray()) || index >= idpToUpdate.getCertificateInfoArray().length) {
throw handleException(Response.Status.NOT_FOUND, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_IDP, "Cannot replace certificate as it does not exist.");
} else {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, null);
}
} else {
switch(path) {
case Constants.NAME_PATH:
idpToUpdate.setIdentityProviderName(value);
break;
case Constants.DESCRIPTION_PATH:
idpToUpdate.setIdentityProviderDescription(value);
break;
case Constants.IMAGE_PATH:
idpToUpdate.setImageUrl(value);
break;
case Constants.IS_PRIMARY_PATH:
idpToUpdate.setPrimary(Boolean.parseBoolean(value));
break;
case Constants.IS_ENABLED_PATH:
idpToUpdate.setEnable(Boolean.parseBoolean(value));
break;
case Constants.IS_FEDERATION_HUB_PATH:
idpToUpdate.setFederationHub(Boolean.parseBoolean(value));
break;
case Constants.HOME_REALM_PATH:
idpToUpdate.setHomeRealmId(value);
break;
case Constants.ALIAS_PATH:
idpToUpdate.setAlias(value);
break;
case Constants.IDP_ISSUER_NAME_PATH:
patchIdpProperties(idpToUpdate, Constants.IDP_ISSUER_NAME, value);
break;
case Constants.CERTIFICATE_JWKSURI_PATH:
patchIdpProperties(idpToUpdate, Constants.JWKS_URI, value);
break;
default:
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, null);
}
}
} else if (operation == Patch.OperationEnum.ADD) {
if (isCertificateUpdateRequest) {
List<String> certificates = new ArrayList<>();
int index = Integer.parseInt(path.split(Constants.PATH_SEPERATOR)[3]);
if (index != idpToUpdate.getCertificateInfoArray().length) {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Invalid index in 'path' attribute");
}
if (ArrayUtils.isNotEmpty(idpToUpdate.getCertificateInfoArray())) {
for (CertificateInfo certInfo : idpToUpdate.getCertificateInfoArray()) {
certificates.add(base64Decode(certInfo.getCertValue()));
}
}
if (!value.startsWith(IdentityUtil.PEM_BEGIN_CERTFICATE)) {
try {
value = base64Decode(value);
} catch (IllegalArgumentException e) {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_CERTIFICATE_FORMAT, null);
}
}
if (certificates.contains(value)) {
throw handleException(Response.Status.CONFLICT, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_IDP, "Cannot add certificate as it already exists.");
}
certificates.add(index, value);
idpToUpdate.setCertificate(base64Encode(StringUtils.join(certificates, "")));
// Need to remove the JWKS URI property, if it exists, when adding certificates as they are
// alternate options of the property Certificate Type.
IdentityProviderProperty[] propertyDTOS = idpToUpdate.getIdpProperties();
List<IdentityProviderProperty> idpNewProperties = new ArrayList<>();
for (IdentityProviderProperty propertyDTO : propertyDTOS) {
// Add properties to new list omitting the JWKS URI property.
if (!Constants.JWKS_URI.equals(propertyDTO.getName())) {
idpNewProperties.add(propertyDTO);
}
}
idpToUpdate.setIdpProperties(idpNewProperties.toArray(new IdentityProviderProperty[0]));
} else if (Constants.CERTIFICATE_JWKSURI_PATH.equals(path)) {
IdentityProviderProperty[] propertyDTOS = idpToUpdate.getIdpProperties();
for (IdentityProviderProperty propertyDTO : propertyDTOS) {
if (Constants.JWKS_URI.equals(propertyDTO.getName())) {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_IDP, "Cannot add JWKS URI as it already exists");
}
}
List<IdentityProviderProperty> idpProperties = new ArrayList<>(Arrays.asList(propertyDTOS));
IdentityProviderProperty jwksProperty = new IdentityProviderProperty();
jwksProperty.setName(Constants.JWKS_URI);
jwksProperty.setValue(value);
idpProperties.add(jwksProperty);
idpToUpdate.setIdpProperties(idpProperties.toArray(new IdentityProviderProperty[0]));
// property Certificate Type.
if (ArrayUtils.isNotEmpty(idpToUpdate.getCertificateInfoArray())) {
idpToUpdate.setCertificate(null);
}
} else {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, null);
}
} else if (operation == Patch.OperationEnum.REMOVE) {
if (isCertificateUpdateRequest) {
List<String> certificates = new ArrayList<>();
int index = Integer.parseInt(path.split(Constants.PATH_SEPERATOR)[3]);
if (ArrayUtils.isNotEmpty(idpToUpdate.getCertificateInfoArray()) && (index >= 0) && index < idpToUpdate.getCertificateInfoArray().length) {
for (CertificateInfo certInfo : idpToUpdate.getCertificateInfoArray()) {
certificates.add(base64Decode(certInfo.getCertValue()));
}
certificates.remove(index);
} else if (ArrayUtils.isEmpty(idpToUpdate.getCertificateInfoArray()) || index >= idpToUpdate.getCertificateInfoArray().length) {
throw handleException(Response.Status.NOT_FOUND, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_IDP, "Cannot replace certificate as it does not exist.");
} else {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, "Invalid index in 'path' attribute");
}
idpToUpdate.setCertificate(base64Encode(StringUtils.join(certificates, "")));
} else if (Constants.CERTIFICATE_JWKSURI_PATH.equals(path)) {
IdentityProviderProperty[] propertyDTOS = idpToUpdate.getIdpProperties();
List<IdentityProviderProperty> idpNewProperties = new ArrayList<>();
for (IdentityProviderProperty propertyDTO : propertyDTOS) {
// Add properties to new list omitting the JWKS URI property.
if (!Constants.JWKS_URI.equals(propertyDTO.getName())) {
idpNewProperties.add(propertyDTO);
}
}
// been available.
if (propertyDTOS.length == idpNewProperties.size()) {
throw handleException(Response.Status.NOT_FOUND, Constants.ErrorMessage.ERROR_CODE_ERROR_UPDATING_IDP, "Cannot remove JWKS URI as it does not exist.");
}
idpToUpdate.setIdpProperties(idpNewProperties.toArray(new IdentityProviderProperty[0]));
} else {
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, null);
}
} else {
// Throw an error if any other patch operations are sent in the request.
throw handleException(Response.Status.BAD_REQUEST, Constants.ErrorMessage.ERROR_CODE_INVALID_INPUT, null);
}
}
}
use of org.wso2.carbon.identity.application.common.model.CertificateInfo in project identity-api-server by wso2.
the class ServerIdpManagementService method createIDPCertificate.
private Certificate createIDPCertificate(IdentityProvider identityProvider) {
Certificate certificate = null;
IdentityProviderProperty[] idpProperties = identityProvider.getIdpProperties();
for (IdentityProviderProperty property : idpProperties) {
if (Constants.JWKS_URI.equals(property.getName())) {
certificate = new Certificate().jwksUri(property.getValue());
break;
}
}
if (certificate == null && ArrayUtils.isNotEmpty(identityProvider.getCertificateInfoArray())) {
List<String> certificates = new ArrayList<>();
for (CertificateInfo certInfo : identityProvider.getCertificateInfoArray()) {
certificates.add(certInfo.getCertValue());
}
certificate = new Certificate().certificates(certificates);
}
return certificate;
}
Aggregations