From dfe957b0193cf2fd8b4f42205f0bcc164405b014 Mon Sep 17 00:00:00 2001 From: inoshperera Date: Sun, 9 Apr 2023 11:50:14 +0530 Subject: [PATCH 01/11] Add SCEP support fixes https://roadmap.entgra.net/issues/10042 --- .../mgt/core/impl/CertificateGenerator.java | 117 +++++++++++++++++- .../service/CertificateManagementService.java | 2 + .../CertificateManagementServiceImpl.java | 5 + .../util/CertificateManagementConstants.java | 1 + 4 files changed, 119 insertions(+), 6 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index 2cb6d4098f..20b4833d56 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -44,12 +44,17 @@ import org.bouncycastle.operator.OperatorCreationException; import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder; import org.bouncycastle.pkcs.PKCS10CertificationRequest; import org.bouncycastle.util.Store; -import org.jscep.message.*; +import org.jscep.message.CertRep; +import org.jscep.message.MessageDecodingException; +import org.jscep.message.MessageEncodingException; +import org.jscep.message.PkcsPkiEnvelopeDecoder; +import org.jscep.message.PkcsPkiEnvelopeEncoder; +import org.jscep.message.PkiMessage; +import org.jscep.message.PkiMessageDecoder; +import org.jscep.message.PkiMessageEncoder; import org.jscep.transaction.FailInfo; import org.jscep.transaction.Nonce; import org.jscep.transaction.TransactionId; -import org.wso2.carbon.certificate.mgt.core.cache.CertificateCacheManager; -import org.wso2.carbon.certificate.mgt.core.cache.impl.CertificateCacheManagerImpl; import org.wso2.carbon.certificate.mgt.core.dao.CertificateDAO; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOException; import org.wso2.carbon.certificate.mgt.core.dao.CertificateManagementDAOFactory; @@ -72,13 +77,31 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; -import java.security.*; +import java.security.InvalidKeyException; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Security; +import java.security.SignatureException; import java.security.cert.Certificate; -import java.security.cert.*; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateExpiredException; +import java.security.cert.CertificateFactory; +import java.security.cert.CertificateNotYetValidException; +import java.security.cert.X509Certificate; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; +import java.util.concurrent.TimeUnit; public class CertificateGenerator { @@ -757,4 +780,86 @@ public class CertificateGenerator { return generateCertificateFromCSR(privateKeyCA, certificationRequest, certCA.getIssuerX500Principal().getName()); } -} + + public X509Certificate generateAlteredCertificateFromCSR(String csr) + throws KeystoreException { + byte[] byteArrayBst = DatatypeConverter.parseBase64Binary(csr); + PKCS10CertificationRequest certificationRequest; + KeyStoreReader keyStoreReader = new KeyStoreReader(); + PrivateKey privateKeyCA = keyStoreReader.getCAPrivateKey(); + X509Certificate certCA = (X509Certificate) keyStoreReader.getCACertificate(); + + X509Certificate issuedCert; + try { + certificationRequest = new PKCS10CertificationRequest(byteArrayBst); + JcaContentSignerBuilder csBuilder = + new JcaContentSignerBuilder(CertificateManagementConstants.SIGNING_ALGORITHM); + ContentSigner signer = csBuilder.build(privateKeyCA); + + BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); + + X500Name issuerName = new X500Name(certCA.getSubjectDN().getName()); + + String commonName = certificationRequest.getSubject().getRDNs(BCStyle.CN)[0].getFirst() + .getValue().toString(); + X500Name subjectName = new X500Name("O=" + commonName + "O=AndroidDevice,CN=" + + serialNumber); + Date startDate = new Date(System.currentTimeMillis()); + Date endDate = new Date(System.currentTimeMillis() + + TimeUnit.DAYS.toMillis(365 * 100)); + PublicKey publicKey = getPublicKeyFromRequest(certificationRequest); + + X509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( + issuerName, serialNumber, startDate, endDate, + subjectName, publicKey); + + X509CertificateHolder certHolder = certBuilder.build(signer); + + CertificateFactory certificateFactory = CertificateFactory.getInstance + (CertificateManagementConstants.X_509); + byte[] encodedCertificate = certHolder.getEncoded(); + issuedCert = (X509Certificate) certificateFactory + .generateCertificate(new ByteArrayInputStream(encodedCertificate)); + + org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate = + new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); + List certificates = new ArrayList<>(); + certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + certificate.setCertificate(issuedCert); + certificates.add(certificate); + saveCertInKeyStore(certificates); + + } catch (OperatorCreationException e) { + String errorMsg = "Error creating the content signer"; + log.error(errorMsg); + throw new KeystoreException(errorMsg, e); + } catch (CertificateException e) { + String errorMsg = "Error when opening the newly created certificate"; + log.error(errorMsg); + throw new KeystoreException(errorMsg, e); + } catch (InvalidKeySpecException e) { + String errorMsg = "Public key is having invalid specification"; + log.error(errorMsg); + throw new KeystoreException(errorMsg, e); + } catch (NoSuchAlgorithmException e) { + String errorMsg = "Could not find RSA algorithm"; + log.error(errorMsg); + throw new KeystoreException(errorMsg, e); + } catch (IOException e) { + String errorMsg = "Error while reading the csr"; + log.error(errorMsg); + throw new KeystoreException(errorMsg, e); + } + return issuedCert; + } + + private static PublicKey getPublicKeyFromRequest(PKCS10CertificationRequest request) + throws InvalidKeySpecException, NoSuchAlgorithmException, IOException { + byte[] publicKeyBytes = request.getSubjectPublicKeyInfo().getEncoded(); + X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyBytes); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + PublicKey publicKey = keyFactory.generatePublic(publicKeySpec); + return publicKey; + } + +} \ No newline at end of file diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java index becd68720b..393dbdd0ed 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementService.java @@ -79,4 +79,6 @@ public interface CertificateManagementService { List searchCertificates(String serialNumber) throws CertificateManagementException; + X509Certificate generateAlteredCertificateFromCSR(String csr) throws KeystoreException; + } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java index c47472f35c..67cca297c4 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/service/CertificateManagementServiceImpl.java @@ -234,4 +234,9 @@ public class CertificateManagementServiceImpl implements CertificateManagementSe } } + @Override + public X509Certificate generateAlteredCertificateFromCSR(String csr) throws KeystoreException{ + return certificateGenerator.generateAlteredCertificateFromCSR(csr); + } + } diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java index 5e5f02c7f0..96c6cc2148 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/util/CertificateManagementConstants.java @@ -39,6 +39,7 @@ public final class CertificateManagementConstants { public static final String RSA_PRIVATE_KEY_END_TEXT = "-----END RSA PRIVATE KEY-----"; public static final String EMPTY_TEXT = ""; public static final int RSA_KEY_LENGTH = 2048; + public static final String SIGNING_ALGORITHM = "SHA256withRSA"; public static final class DataBaseTypes { private DataBaseTypes() { From d34adaae961a2c10eb9a23bb931b802eb2686e2c Mon Sep 17 00:00:00 2001 From: Pahansith Gunathilake Date: Wed, 19 Apr 2023 06:46:09 +0000 Subject: [PATCH 02/11] Fix issue with Nginx not recognizing the SCEP client certificate (#105) Co-authored-by: Pahansith Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/105 Co-authored-by: Pahansith Gunathilake Co-committed-by: Pahansith Gunathilake --- .../mgt/core/impl/CertificateGenerator.java | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index 20b4833d56..d686ff5115 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -97,10 +97,7 @@ import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.List; +import java.util.*; import java.util.concurrent.TimeUnit; public class CertificateGenerator { @@ -798,8 +795,16 @@ public class CertificateGenerator { BigInteger serialNumber = BigInteger.valueOf(System.currentTimeMillis()); - X500Name issuerName = new X500Name(certCA.getSubjectDN().getName()); - + //Reversing the order of components of the subject DN due to Nginx not verifying the client certificate + //generated by Java using this subject DN. + //Ref: https://stackoverflow.com/questions/33769978 & engineering mail SCEP implementation for Android + String[] dnParts = certCA.getSubjectDN().getName().split(","); + StringJoiner joiner = new StringJoiner(","); + for (int i = (dnParts.length - 1); i >= 0; i--) { + joiner.add(dnParts[i]); + } + String subjectDn = joiner.toString(); + X500Name issuerName = new X500Name(subjectDn); String commonName = certificationRequest.getSubject().getRDNs(BCStyle.CN)[0].getFirst() .getValue().toString(); X500Name subjectName = new X500Name("O=" + commonName + "O=AndroidDevice,CN=" + From 19ce7d6facd56640e010602f494c9982cda00248 Mon Sep 17 00:00:00 2001 From: Lasantha Dharmakeerthi Date: Mon, 10 Apr 2023 20:25:07 +0530 Subject: [PATCH 03/11] Add try it now feature (#99) Co-authored-by: Dharmakeerthi Lasantha Reviewed-on: https://repository.entgra.net/community/device-mgt-core/pulls/99 Co-authored-by: Lasantha Dharmakeerthi Co-committed-by: Lasantha Dharmakeerthi --- .../exception/StorageManagementException.java | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java index 38985716de..e69de29bb2 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java @@ -1,32 +0,0 @@ -/* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. - * - * Entgra (Pvt) Ltd. 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.wso2.carbon.device.mgt.core.common.exception; - -/** - * Represents the exception thrown during storing and retrieving the artifacts. - */ -public class StorageManagementException extends Exception { - public StorageManagementException(String message, Throwable ex) { - super(message, ex); - } - - public StorageManagementException(String message) { - super(message); - } -} - From 1aafd53d3e7f2a64ebb04369bad048bc796c30b7 Mon Sep 17 00:00:00 2001 From: inoshperera Date: Wed, 24 May 2023 13:54:10 +0530 Subject: [PATCH 04/11] OTP for enrollment with Mutual TLS Fixes https://roadmap.entgra.net/issues/10093 --- .../mgt/common/DeviceManagementConstants.java | 2 + .../common/general/QREnrollmentDetails.java | 9 ++++ .../mgt/common/otp/mgt/OTPEmailTypes.java | 2 +- .../mgt/common/spi/OTPManagementService.java | 6 +-- .../dao/impl/GenericOTPManagementDAOImpl.java | 6 ++- .../mgt/service/OTPManagementServiceImpl.java | 51 +++++++++---------- .../authenticator/BasicAuthAuthenticator.java | 31 +++++++++-- .../CertificateAuthenticator.java | 9 ++++ .../OneTimeTokenAuthenticator.java | 14 ++++- 9 files changed, 93 insertions(+), 37 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java index 154594678c..f95a78ed84 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/DeviceManagementConstants.java @@ -134,6 +134,8 @@ public final class DeviceManagementConstants { public static final String LAST_NAME = "last-name"; public static final String TENANT_ADMIN_USERNAME = "tenant-admin-username"; public static final String TENANT_ADMIN_PASSWORD = "tenant-admin-password"; + + public static final int OTP_DEFAULT_EXPIRY_SECONDS = 3600; } public static final class EventServices { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/general/QREnrollmentDetails.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/general/QREnrollmentDetails.java index 150fddef09..37e696c206 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/general/QREnrollmentDetails.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/general/QREnrollmentDetails.java @@ -22,6 +22,7 @@ public class QREnrollmentDetails { String ownershipType; String username; String enrollmentMode; + int tokenExpiry; public String getOwnershipType() { return ownershipType; } @@ -34,4 +35,12 @@ public class QREnrollmentDetails { public String getEnrollmentMode() { return enrollmentMode; } public void setEnrollmentMode(String enrollmentMode) { this.enrollmentMode = enrollmentMode; } + + public int getTokenExpiry() { + return tokenExpiry; + } + + public void setTokenExpiry(int tokenExpiry) { + this.tokenExpiry = tokenExpiry; + } } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java index 72bbea982e..9a182a0b14 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java @@ -18,5 +18,5 @@ package org.wso2.carbon.device.mgt.common.otp.mgt; public enum OTPEmailTypes { - USER_VERIFY, DEVICE_ENROLLMENT + USER_VERIFY, DEVICE_ENROLLMENT, USER_INVITE } diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java index bf1d112875..ed548499bf 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/spi/OTPManagementService.java @@ -34,7 +34,8 @@ public interface OTPManagementService { * @throws OTPManagementException if error occurred whle verifying validity of the OPT * @throws BadRequestException if found an null value for OTP */ - OneTimePinDTO isValidOTP(String oneTimeToken) throws OTPManagementException, BadRequestException; + OneTimePinDTO isValidOTP(String oneTimeToken, boolean requireRenewal) throws + OTPManagementException, BadRequestException; /** * Invalidate the OTP and send welcome mail @@ -58,8 +59,7 @@ public interface OTPManagementService { boolean hasEmailRegistered(String email, String emailDomain) throws OTPManagementException, DeviceManagementException; - OneTimePinDTO generateOneTimePin(String email, String emailType, String userName, Object metaDataObj, - int tenantId, boolean persistPin) throws OTPManagementException; + OneTimePinDTO generateOneTimePin(OneTimePinDTO oneTimePinData, boolean persistPin) throws OTPManagementException; OneTimePinDTO getRenewedOtpByEmailAndMailType(String email, String emailType) throws OTPManagementException; diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java index 574d6e7904..becea82ede 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java @@ -19,6 +19,7 @@ package org.wso2.carbon.device.mgt.core.otp.mgt.dao.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; import org.wso2.carbon.device.mgt.common.exceptions.DBConnectionException; import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OneTimePinDTO; import org.wso2.carbon.device.mgt.core.otp.mgt.dao.AbstractDAOImpl; @@ -55,7 +56,8 @@ public class GenericOTPManagementDAOImpl extends AbstractDAOImpl implements OTPM + "META_INFO, " + "CREATED_AT," + "TENANT_ID," - + "USERNAME) VALUES (?, ?, ?, ?, ?, ?, ?)"; + + "USERNAME, " + + "EXPIRY_TIME) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; try { Connection conn = this.getDBConnection(); Calendar calendar = Calendar.getInstance(); @@ -69,6 +71,8 @@ public class GenericOTPManagementDAOImpl extends AbstractDAOImpl implements OTPM stmt.setTimestamp(5, timestamp); stmt.setInt(6, oneTimePinDTO.getTenantId()); stmt.setString(7, oneTimePinDTO.getUsername()); + stmt.setInt(8, oneTimePinDTO.getExpiryTime() == 0 + ? DeviceManagementConstants.OTPProperties.OTP_DEFAULT_EXPIRY_SECONDS : oneTimePinDTO.getExpiryTime()); stmt.addBatch(); } stmt.executeBatch(); diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java index 4c8161e100..2d90dc5727 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/otp/mgt/service/OTPManagementServiceImpl.java @@ -126,7 +126,8 @@ public class OTPManagementServiceImpl implements OTPManagementService { } @Override - public OneTimePinDTO isValidOTP(String oneTimeToken) throws OTPManagementException, BadRequestException { + public OneTimePinDTO isValidOTP(String oneTimeToken, boolean requireRenewal) throws OTPManagementException, + BadRequestException { if (StringUtils.isBlank(oneTimeToken)){ String msg = "Received blank OTP to verify. OTP: " + oneTimeToken; log.error(msg); @@ -150,17 +151,19 @@ public class OTPManagementServiceImpl implements OTPManagementService { oneTimePinDTO.getCreatedAt().getTime() + oneTimePinDTO.getExpiryTime() * 1000L); if (currentTimestamp.after(expiredTimestamp)) { - String renewedOTP = UUID.randomUUID().toString(); - renewOTP(oneTimePinDTO, renewedOTP); - Gson gson = new Gson(); - Tenant tenant = gson.fromJson(oneTimePinDTO.getMetaInfo(), Tenant.class); + if (requireRenewal) { + String renewedOTP = UUID.randomUUID().toString(); + renewOTP(oneTimePinDTO, renewedOTP); + Gson gson = new Gson(); + Tenant tenant = gson.fromJson(oneTimePinDTO.getMetaInfo(), Tenant.class); - Properties props = new Properties(); - props.setProperty("first-name", tenant.getAdminFirstName()); - props.setProperty("otp-token", renewedOTP); - props.setProperty("email", oneTimePinDTO.getEmail()); - props.setProperty("type", oneTimePinDTO.getEmailType()); - sendMail(props, oneTimePinDTO.getEmail(), DeviceManagementConstants.EmailAttributes.USER_VERIFY_TEMPLATE); + Properties props = new Properties(); + props.setProperty("first-name", tenant.getAdminFirstName()); + props.setProperty("otp-token", renewedOTP); + props.setProperty("email", oneTimePinDTO.getEmail()); + props.setProperty("type", oneTimePinDTO.getEmailType()); + sendMail(props, oneTimePinDTO.getEmail(), DeviceManagementConstants.EmailAttributes.USER_VERIFY_TEMPLATE); + } return null; } return oneTimePinDTO; @@ -243,8 +246,14 @@ public class OTPManagementServiceImpl implements OTPManagementService { for (String username : deviceEnrollmentInvitation.getUsernames()) { String emailAddress = DeviceManagerUtil.getUserClaimValue( username, DeviceManagementConstants.User.CLAIM_EMAIL_ADDRESS); - oneTimePinDTO = generateOneTimePin(emailAddress, OTPEmailTypes.DEVICE_ENROLLMENT.toString(), username, - null, tenantId, false); + + OneTimePinDTO oneTimePinData = new OneTimePinDTO(); + oneTimePinData.setEmail(emailAddress); + oneTimePinData.setTenantId(tenantId); + oneTimePinData.setUsername(username); + oneTimePinData.setEmailType(OTPEmailTypes.USER_INVITE.toString()); + + oneTimePinDTO = generateOneTimePin(oneTimePinData, false); oneTimePinDTOList.add(oneTimePinDTO); props.setProperty("first-name", DeviceManagerUtil. getUserClaimValue(username, DeviceManagementConstants.User.CLAIM_FIRST_NAME)); @@ -278,27 +287,17 @@ public class OTPManagementServiceImpl implements OTPManagementService { /** * Create One Time Token - * @param email email - * @param emailType email type - * @param userName username - * @param metaDataObj meta data object - * @param tenantId tenant Id + * @param oneTimePinDTO Data related to the one time pin * @return {@link OneTimePinDTO} */ @Override - public OneTimePinDTO generateOneTimePin(String email, String emailType, String userName, Object metaDataObj, - int tenantId, boolean persistPin) throws OTPManagementException { + public OneTimePinDTO generateOneTimePin(OneTimePinDTO oneTimePinDTO, boolean persistPin) throws OTPManagementException { String otpValue = UUID.randomUUID().toString(); Gson gson = new Gson(); - String metaInfo = gson.toJson(metaDataObj); + String metaInfo = gson.toJson(oneTimePinDTO.getMetaInfo()); - OneTimePinDTO oneTimePinDTO = new OneTimePinDTO(); - oneTimePinDTO.setEmail(email); - oneTimePinDTO.setTenantId(tenantId); - oneTimePinDTO.setUsername(userName); - oneTimePinDTO.setEmailType(emailType); oneTimePinDTO.setMetaInfo(metaInfo); oneTimePinDTO.setOtpToken(otpValue); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java index 4bd7779dda..f1b0339994 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/BasicAuthAuthenticator.java @@ -36,6 +36,7 @@ import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils; import java.nio.charset.Charset; import java.util.Base64; import java.util.Properties; +import java.util.StringTokenizer; public class BasicAuthAuthenticator implements WebappAuthenticator { @@ -51,15 +52,23 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { @Override public boolean canHandle(Request request) { /* - This is done to avoid every endpoint being able to use basic auth. Add the following to - the required web.xml of the web app. + This is done to avoid every web app being able to use basic auth. Add the following to + the required web.xml of the web app. This is a global config for a web app to allow all + contexts of the web app to use basic auth basicAuth true + + Adding the basicAuthAllowList parameter allows to selectively allow some context paths in a + web app to use basic auth while all the other context remain unavailable with basic auth. + If this parameter is present, any context that requires basic auth must be specially + added as comma separated list to the param-value of basicAuthAllowList. */ - if (!isAuthenticationSupported(request)) { - return false; + if (!isAllowListedForBasicAuth(request)) { + if (!isAuthenticationSupported(request)) { + return false; + } } if (request.getCoyoteRequest() == null || request.getCoyoteRequest().getMimeHeaders() == null) { return false; @@ -76,6 +85,20 @@ public class BasicAuthAuthenticator implements WebappAuthenticator { return false; } + private boolean isAllowListedForBasicAuth(Request request) { + String param = request.getContext().findParameter("basicAuthAllowList"); + if (param != null && !param.isEmpty()) { + //Add the nonSecured end-points to cache + String[] basicAuthAllowList = param.split(","); + for (String contexPath : basicAuthAllowList) { + if (request.getRequestURI().toString().endsWith(contexPath.trim())) { + return true; + } + } + } + return false; + } + @Override public AuthenticationInfo authenticate(Request request, Response response) { AuthenticationInfo authenticationInfo = new AuthenticationInfo(); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index 4bead3ad4f..6bccefe7ec 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -75,21 +75,30 @@ public class CertificateAuthenticator implements WebappAuthenticator { // When there is a load balancer terminating mutual SSL, it should pass this header along and // as the value of this header, the client certificate subject dn should be passed. if (request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) { + log.info("PROXY_MUTUAL_AUTH_HEADER " + request.getHeader(PROXY_MUTUAL_AUTH_HEADER)); CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). getCertificateManagementService().verifySubjectDN(request.getHeader(PROXY_MUTUAL_AUTH_HEADER)); + log.info("clientCertificate" + certificateResponse.getSerialNumber()); + log.info("clientCertificate" + certificateResponse.getCommonName()); authenticationInfo = checkCertificateResponse(certificateResponse); + log.info("username" + authenticationInfo.getUsername()); } else if (request.getHeader(MUTUAL_AUTH_HEADER) != null) { + log.info("MUTUAL_AUTH_HEADER"); Object object = request.getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); X509Certificate[] clientCertificate = null; if (object instanceof X509Certificate[]) { + log.info("clientCertificate"); clientCertificate = (X509Certificate[]) request. getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); } if (clientCertificate != null && clientCertificate[0] != null) { CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). getCertificateManagementService().verifyPEMSignature(clientCertificate[0]); + log.info("clientCertificate" + certificateResponse.getSerialNumber()); + log.info("clientCertificate" + certificateResponse.getCommonName()); authenticationInfo = checkCertificateResponse(certificateResponse); + log.info("username" + authenticationInfo.getUsername()); } else { authenticationInfo.setStatus(Status.FAILURE); diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java index 9d290c51da..539e8be13d 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/OneTimeTokenAuthenticator.java @@ -49,8 +49,18 @@ public class OneTimeTokenAuthenticator implements WebappAuthenticator { try { OTPManagementService otpManagementService = AuthenticatorFrameworkDataHolder.getInstance() .getOtpManagementService(); - OneTimePinDTO validOTP = otpManagementService.isValidOTP(request.getHeader(Constants.HTTPHeaders - .ONE_TIME_TOKEN_HEADER)); + OneTimePinDTO validOTP; + if (request.getRequestURI().toString().endsWith("cloud/download-url") + || request.getRequestURI().toString().endsWith("cloud/tenant")) { + validOTP = otpManagementService.isValidOTP(request.getHeader(Constants.HTTPHeaders + .ONE_TIME_TOKEN_HEADER), true); + } else { + log.info("Validating OTP for enrollments PIN: " + request.getHeader(Constants + .HTTPHeaders.ONE_TIME_TOKEN_HEADER)); + validOTP = otpManagementService.isValidOTP(request.getHeader(Constants.HTTPHeaders + .ONE_TIME_TOKEN_HEADER), false); + } + if (validOTP != null) { authenticationInfo.setStatus(Status.CONTINUE); authenticationInfo.setTenantId(validOTP.getTenantId()); From 209f2b66c94cc64c361d19a35feb4b341c4b97b5 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Sat, 13 May 2023 12:56:56 +0530 Subject: [PATCH 05/11] Add tenant based storing and loading SCEP certificates --- .../mgt/core/dao/CertificateDAO.java | 10 +++++ .../dao/impl/AbstractCertificateDAOImpl.java | 36 +++++++++++++++++ .../mgt/core/impl/CertificateGenerator.java | 39 ++++++++++++++----- .../mgt/core/impl/KeyStoreReader.java | 37 ++++++++++++++++++ .../exception/StorageManagementException.java | 32 +++++++++++++++ 5 files changed, 145 insertions(+), 9 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java index cb97cf8892..fe1d829a82 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java @@ -51,6 +51,16 @@ public interface CertificateDAO { */ CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementDAOException; + /** + * Obtain a certificated stored in the database by providing the common name and the tenant ID + * + * @param serialNumber Serial number (Common name) of the certificate + * @param tenantId ID of the certificate owning tenant + * @return representation of the certificate. + * @throws CertificateManagementDAOException if fails to read the certificate from the database + */ + CertificateResponse retrieveCertificate(String serialNumber, int tenantId) throws CertificateManagementDAOException; + /** * Get all the certificates in a paginated manner. * diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index 4af136c987..e536eaf646 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -119,6 +119,42 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ return certificateResponse; } + @Override + public CertificateResponse retrieveCertificate(String serialNumber, int tenantId) throws CertificateManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + ResultSet resultSet = null; + CertificateResponse certificateResponse = null; + try { + conn = this.getConnection(); + String query = + "SELECT CERTIFICATE, SERIAL_NUMBER, TENANT_ID, USERNAME FROM" + + " DM_DEVICE_CERTIFICATE WHERE SERIAL_NUMBER = ? AND TENANT_ID = ? "; + stmt = conn.prepareStatement(query); + stmt.setString(1, serialNumber); + stmt.setInt(2, tenantId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + certificateResponse = new CertificateResponse(); + byte[] certificateBytes = resultSet.getBytes("CERTIFICATE"); + certificateResponse.setCertificate(certificateBytes); + certificateResponse.setSerialNumber(resultSet.getString("SERIAL_NUMBER")); + certificateResponse.setTenantId(resultSet.getInt("TENANT_ID")); + certificateResponse.setUsername(resultSet.getString("USERNAME")); + CertificateGenerator.extractCertificateDetails(certificateBytes, certificateResponse); + } + } catch (SQLException e) { + String errorMsg = + "Unable to get the read the certificate with serial" + serialNumber; + log.error(errorMsg, e); + throw new CertificateManagementDAOException(errorMsg, e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, resultSet); + } + return certificateResponse; + } + @Override public List searchCertificate(String serialNumber) throws CertificateManagementDAOException { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index d686ff5115..5c9bbfad45 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -358,15 +358,31 @@ public class CertificateGenerator { CertificateResponse lookUpCertificate = null; KeyStoreReader keyStoreReader = new KeyStoreReader(); if (distinguishedName != null && !distinguishedName.isEmpty()) { - if (distinguishedName.contains("/CN=")) { - String[] dnSplits = distinguishedName.split("/"); - for (String dnPart : dnSplits) { - if (dnPart.contains("CN=")) { - String commonNameExtracted = dnPart.replace("CN=", ""); - lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted); - break; + if (distinguishedName.contains("CN=")) { + String[] dnSplits = null; + if (distinguishedName.contains("/")) { + dnSplits = distinguishedName.split("/"); + } else if (distinguishedName.contains(",")) { + //some older versions of nginx will forward the client certificate subject dn separated with commas + dnSplits = distinguishedName.split(","); + } + String commonNameExtracted = null; + int tenantId = 0; + if (dnSplits != null && dnSplits.length >= 1) { + for (String dnPart : dnSplits) { + if (dnPart.contains("CN=")) { + commonNameExtracted = dnPart.replace("CN=", ""); + } else if (dnPart.contains("OU=")) { + //the OU of the certificate will be like OU=tenant_ ex: OU=tenant_-1234 + //splitting by underscore to extract the tenant domain + String[] orgUnitSplits = dnPart.split("_"); + tenantId = Integer.parseInt(orgUnitSplits[1]); + } } } + + lookUpCertificate = keyStoreReader.getCertificateBySerial(commonNameExtracted, tenantId); + } else { LdapName ldapName; try { @@ -807,8 +823,9 @@ public class CertificateGenerator { X500Name issuerName = new X500Name(subjectDn); String commonName = certificationRequest.getSubject().getRDNs(BCStyle.CN)[0].getFirst() .getValue().toString(); - X500Name subjectName = new X500Name("O=" + commonName + "O=AndroidDevice,CN=" + - serialNumber); + int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(); + X500Name subjectName = new X500Name("O=" + commonName + ",CN=" + + serialNumber + ", OU=tenant_"+tenantId); Date startDate = new Date(System.currentTimeMillis()); Date endDate = new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(365 * 100)); @@ -826,6 +843,10 @@ public class CertificateGenerator { issuedCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(encodedCertificate)); + io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate certificate = + new io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate(); + List certificates = new ArrayList<>(); + certificate.setTenantId(tenantId); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); List certificates = new ArrayList<>(); diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java index 60a7800863..921f11e794 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/KeyStoreReader.java @@ -275,6 +275,43 @@ public class KeyStoreReader { return raPrivateKey; } + public CertificateResponse getCertificateBySerial(String serialNumber, int tenantId) throws KeystoreException { + CertificateResponse certificateResponse = null; + try { + CertificateCacheManager cacheManager = CertificateCacheManagerImpl.getInstance(); + certificateResponse = cacheManager.getCertificateBySerial(serialNumber); + if (certificateResponse == null) { + try { + CertificateManagementDAOFactory.openConnection(); + certificateResponse = certDao.retrieveCertificate(serialNumber, tenantId); + } catch (SQLException e) { + String errorMsg = "Error when making a connection to the database."; + throw new KeystoreException(errorMsg, e); + } finally { + CertificateManagementDAOFactory.closeConnection(); + } + if (certificateResponse != null && certificateResponse.getCertificate() != null) { + Certificate certificate = (Certificate) Serializer.deserialize(certificateResponse.getCertificate()); + if (certificate instanceof X509Certificate) { + X509Certificate x509cert = (X509Certificate) certificate; + String commonName = CertificateGenerator.getCommonName(x509cert); + certificateResponse.setCommonName(commonName); + cacheManager.addCertificateBySerial(serialNumber, certificateResponse); + } + } + } + } catch (CertificateManagementDAOException e) { + String errorMsg = "Error when retrieving certificate from the the database for the serial number: " + + serialNumber; + throw new KeystoreException(errorMsg, e); + + } catch (ClassNotFoundException | IOException e) { + String errorMsg = "Error when de-serializing saved certificate."; + throw new KeystoreException(errorMsg, e); + } + return certificateResponse; + } + public CertificateResponse getCertificateBySerial(String serialNumber) throws KeystoreException { CertificateResponse certificateResponse = null; try { diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java index e69de29bb2..38985716de 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.core/src/main/java/org/wso2/carbon/device/mgt/core/common/exception/StorageManagementException.java @@ -0,0 +1,32 @@ +/* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved. + * + * Entgra (Pvt) Ltd. 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.wso2.carbon.device.mgt.core.common.exception; + +/** + * Represents the exception thrown during storing and retrieving the artifacts. + */ +public class StorageManagementException extends Exception { + public StorageManagementException(String message, Throwable ex) { + super(message, ex); + } + + public StorageManagementException(String message) { + super(message); + } +} + From 7100b36e35e0d0ce9f61e4a5dcd25452060a3cc2 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Mon, 29 May 2023 12:27:50 +0530 Subject: [PATCH 06/11] Fix package name issue --- .../certificate/mgt/core/impl/CertificateGenerator.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index 5c9bbfad45..e3973ed152 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -843,10 +843,6 @@ public class CertificateGenerator { issuedCert = (X509Certificate) certificateFactory .generateCertificate(new ByteArrayInputStream(encodedCertificate)); - io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate certificate = - new io.entgra.device.mgt.core.certificate.mgt.core.bean.Certificate(); - List certificates = new ArrayList<>(); - certificate.setTenantId(tenantId); org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); List certificates = new ArrayList<>(); From 48be39a96386b5726b6ff5a92b44ea7d76af964d Mon Sep 17 00:00:00 2001 From: inoshperera Date: Sun, 18 Jun 2023 12:22:01 +0530 Subject: [PATCH 07/11] Add the logic to save device id to certificate DB partialy fixes https://roadmap.entgra.net/issues/10145 --- .../mgt/core/bean/Certificate.java | 9 +++++ .../mgt/core/dao/CertificateDAO.java | 11 ++++++ .../dao/impl/AbstractCertificateDAOImpl.java | 34 +++++++++++++++++++ .../mgt/core/impl/CertificateGenerator.java | 29 ++++++++++++++-- 4 files changed, 80 insertions(+), 3 deletions(-) diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/bean/Certificate.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/bean/Certificate.java index 5ced778afa..40a9ef1c6c 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/bean/Certificate.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/bean/Certificate.java @@ -25,6 +25,15 @@ public class Certificate { X509Certificate certificate; int tenantId; String tenantDomain; + String deviceIdentifier; + + public String getDeviceIdentifier() { + return deviceIdentifier; + } + + public void setDeviceIdentifier(String deviceIdentifier) { + this.deviceIdentifier = deviceIdentifier; + } public int getTenantId() { return tenantId; diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java index fe1d829a82..3204b8e7b9 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/CertificateDAO.java @@ -41,6 +41,17 @@ public interface CertificateDAO { void addCertificate(List certificate) throws CertificateManagementDAOException; + /** + * This can be used to store a certificate in the database, where it will be stored against the serial number + * of the certificate. + * + * @param certificate Holds the certificate and relevant details. + * @throws CertificateManagementDAOException + * + */ + void addCertificate(Certificate certificate) + throws CertificateManagementDAOException; + /** * Usage is to obtain a certificate stored in the database by providing the common name. * diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java index e536eaf646..caa3bf1e19 100644 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/dao/impl/AbstractCertificateDAOImpl.java @@ -81,6 +81,40 @@ public abstract class AbstractCertificateDAOImpl implements CertificateDAO{ } } + @Override + public void addCertificate(Certificate certificate) + throws CertificateManagementDAOException { + Connection conn; + PreparedStatement stmt = null; + try { + conn = this.getConnection(); + stmt = conn.prepareStatement( + "INSERT INTO DM_DEVICE_CERTIFICATE (SERIAL_NUMBER, CERTIFICATE, TENANT_ID," + + " USERNAME, DEVICE_IDENTIFIER) VALUES (?,?,?,?,?)"); + PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext. + getThreadLocalCarbonContext(); + String username = threadLocalCarbonContext.getUsername(); + // the serial number of the certificate used for its creation is set as its alias. + String serialNumber = certificate.getSerial(); + if (serialNumber == null || serialNumber.isEmpty()) { + serialNumber = String.valueOf(certificate.getCertificate().getSerialNumber()); + } + byte[] bytes = Serializer.serialize(certificate.getCertificate()); + + stmt.setString(1, serialNumber); + stmt.setBytes(2, bytes); + stmt.setInt(3, certificate.getTenantId()); + stmt.setString(4, username); + stmt.setString(5, certificate.getDeviceIdentifier()); + stmt.executeUpdate(); + } catch (SQLException | IOException e) { + throw new CertificateManagementDAOException("Error occurred while saving the " + + "certificate. ", e); + } finally { + CertificateManagementDAOUtil.cleanupResources(stmt, null); + } + } + @Override public CertificateResponse retrieveCertificate(String serialNumber) throws CertificateManagementDAOException { diff --git a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java index e3973ed152..2a43704688 100755 --- a/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java +++ b/components/certificate-mgt/org.wso2.carbon.certificate.mgt.core/src/main/java/org/wso2/carbon/certificate/mgt/core/impl/CertificateGenerator.java @@ -710,6 +710,30 @@ public class CertificateGenerator { } } + public void saveCertificate(org.wso2.carbon.certificate.mgt.core.bean.Certificate + certificate) throws KeystoreException { + + if (certificate == null) { + return; + } + + try { + CertificateDAO certificateDAO = CertificateManagementDAOFactory.getCertificateDAO(); + CertificateManagementDAOFactory.beginTransaction(); + certificateDAO.addCertificate(certificate); + CertificateManagementDAOFactory.commitTransaction(); + } catch (CertificateManagementDAOException e) { + String errorMsg = "Error occurred when saving the generated certificate in database"; + log.error(errorMsg); + CertificateManagementDAOFactory.rollbackTransaction(); + throw new KeystoreException(errorMsg, e); + } catch (TransactionManagementException e) { + String errorMsg = "Error occurred when saving the generated certificate in database"; + log.error(errorMsg); + throw new KeystoreException(errorMsg, e); + } + } + public void saveCertInKeyStore(List certificate) throws KeystoreException { @@ -845,11 +869,10 @@ public class CertificateGenerator { org.wso2.carbon.certificate.mgt.core.bean.Certificate certificate = new org.wso2.carbon.certificate.mgt.core.bean.Certificate(); - List certificates = new ArrayList<>(); certificate.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); certificate.setCertificate(issuedCert); - certificates.add(certificate); - saveCertInKeyStore(certificates); + certificate.setDeviceIdentifier(commonName); + saveCertificate(certificate); } catch (OperatorCreationException e) { String errorMsg = "Error creating the content signer"; From 94408c7ce3f0f6fd4a97ec7bc6878fc147152e85 Mon Sep 17 00:00:00 2001 From: rajitha Date: Thu, 15 Jun 2023 14:08:46 +0530 Subject: [PATCH 08/11] Add otp token --- .../DeviceManagementConfigService.java | 7 +++- .../DeviceManagementConfigServiceImpl.java | 37 ++++++++++++++++++- .../config/jaxrs/util/DeviceMgtAPIUtils.java | 16 ++++++++ 3 files changed, 57 insertions(+), 3 deletions(-) diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/DeviceManagementConfigService.java b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/DeviceManagementConfigService.java index d5fe117a63..1adeb44f17 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/DeviceManagementConfigService.java +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/DeviceManagementConfigService.java @@ -156,7 +156,12 @@ public interface DeviceManagementConfigService { value = "The properties list using for query a device", required = true) @QueryParam("properties") - String properties); + String properties, + @ApiParam( + name = "withAccessToken", + value = "Whether to use access token or otp token for device configuration") + @QueryParam("withAccessToken") + boolean withAccessToken); @PUT @Path("/device/transfer") diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java index 8aea316c55..cf2fc9c83a 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/service/impl/DeviceManagementConfigServiceImpl.java @@ -35,8 +35,12 @@ import org.wso2.carbon.device.mgt.common.configuration.mgt.AmbiguousConfiguratio import org.wso2.carbon.device.mgt.common.configuration.mgt.DeviceConfiguration; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceNotFoundException; +import org.wso2.carbon.device.mgt.common.exceptions.OTPManagementException; import org.wso2.carbon.device.mgt.common.general.TenantDetail; +import org.wso2.carbon.device.mgt.common.otp.mgt.OTPEmailTypes; +import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OneTimePinDTO; import org.wso2.carbon.device.mgt.common.permission.mgt.PermissionManagementException; +import org.wso2.carbon.device.mgt.common.spi.OTPManagementService; import org.wso2.carbon.device.mgt.core.DeviceManagementConstants; import org.wso2.carbon.device.mgt.core.config.DeviceConfigurationManager; import org.wso2.carbon.device.mgt.core.config.DeviceManagementConfig; @@ -77,7 +81,8 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig @Path("/configurations") @Produces(MediaType.APPLICATION_JSON) public Response getConfiguration(@HeaderParam("token") String token, - @QueryParam("properties") String properties) { + @QueryParam("properties") String properties, + @QueryParam("withAccessToken") boolean withAccessToken) { DeviceManagementProviderService dms = DeviceMgtAPIUtils.getDeviceManagementService(); try { if (token == null || token.isEmpty()) { @@ -102,7 +107,8 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig deviceProps.put("token", token); DeviceConfiguration devicesConfiguration = dms.getDeviceConfiguration(deviceProps); - setAccessTokenToDeviceConfigurations(devicesConfiguration); + if (withAccessToken) setAccessTokenToDeviceConfigurations(devicesConfiguration); + else setOTPTokenToDeviceConfigurations(devicesConfiguration); return Response.status(Response.Status.OK).entity(devicesConfiguration).build(); } catch (DeviceManagementException e) { String msg = "Error occurred while retrieving configurations"; @@ -214,6 +220,33 @@ public class DeviceManagementConfigServiceImpl implements DeviceManagementConfig } } + private void setOTPTokenToDeviceConfigurations(DeviceConfiguration deviceConfiguration) + throws DeviceManagementException { + OneTimePinDTO oneTimePinData = new OneTimePinDTO(); + oneTimePinData.setEmail(OTPEmailTypes.DEVICE_ENROLLMENT.toString()); + oneTimePinData.setEmailType(OTPEmailTypes.DEVICE_ENROLLMENT.toString()); + oneTimePinData.setUsername(deviceConfiguration.getDeviceOwner()); + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( + deviceConfiguration.getTenantDomain(), true); + oneTimePinData.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()); + PrivilegedCarbonContext.endTenantFlow(); + OTPManagementService otpManagementService = DeviceMgtAPIUtils.getOtpManagementService(); + try { + OneTimePinDTO oneTimePinDTO = otpManagementService.generateOneTimePin(oneTimePinData, true); + if (oneTimePinDTO == null) { + String msg = "Null value returned when generating OTP token for " + oneTimePinData.getOtpToken(); + log.error(msg); + throw new DeviceManagementException(msg); + } + deviceConfiguration.setAccessToken(oneTimePinDTO.getOtpToken()); + } catch (OTPManagementException ex) { + String msg = "Error occurred while generating one time pin: " + ex.getMessage(); + log.error(msg, ex); + throw new DeviceManagementException(msg, ex); + } + } + @Override @Path("/tenants") @GET diff --git a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/util/DeviceMgtAPIUtils.java b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/util/DeviceMgtAPIUtils.java index cf098c6edc..7ad136cd7f 100644 --- a/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/util/DeviceMgtAPIUtils.java +++ b/components/device-mgt/io.entgra.carbon.device.mgt.config.api/src/main/java/io/entgra/carbon/device/mgt/config/jaxrs/util/DeviceMgtAPIUtils.java @@ -21,6 +21,7 @@ package io.entgra.carbon.device.mgt.config.jaxrs.util; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.spi.OTPManagementService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.user.core.service.RealmService; @@ -34,6 +35,8 @@ public class DeviceMgtAPIUtils { private static DeviceManagementProviderService deviceManagementProviderService = null; private static RealmService realmService = null; + private static OTPManagementService otpManagementService = null; + public static DeviceManagementProviderService getDeviceManagementService() { if (deviceManagementProviderService == null) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); @@ -48,6 +51,19 @@ public class DeviceMgtAPIUtils { return deviceManagementProviderService; } + public static OTPManagementService getOtpManagementService() { + if (otpManagementService == null) { + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + otpManagementService = (OTPManagementService) ctx.getOSGiService(OTPManagementService.class, null); + if (otpManagementService == null) { + String msg = "OTP Management Service has not initialized."; + log.error(msg); + throw new IllegalStateException(msg); + } + } + return otpManagementService; + } + public static RealmService getRealmService() { if (realmService == null) { PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); From b18003a1cdcbc84deef9bd6eabeabdb38a05c60a Mon Sep 17 00:00:00 2001 From: Pahansith Date: Wed, 21 Jun 2023 06:20:17 +0530 Subject: [PATCH 09/11] Add OTP based remote session implementation --- .../mgt/common/otp/mgt/OTPEmailTypes.java | 2 +- .../interceptor/DefaultTokenHandler.java | 100 +++++------------- .../ui/request/interceptor/UserHandler.java | 1 + .../interceptor/util/HandlerConstants.java | 1 + .../request/interceptor/util/HandlerUtil.java | 12 +++ 5 files changed, 44 insertions(+), 72 deletions(-) diff --git a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java index 9a182a0b14..ecfbc63905 100644 --- a/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java +++ b/components/device-mgt/org.wso2.carbon.device.mgt.common/src/main/java/org/wso2/carbon/device/mgt/common/otp/mgt/OTPEmailTypes.java @@ -18,5 +18,5 @@ package org.wso2.carbon.device.mgt.common.otp.mgt; public enum OTPEmailTypes { - USER_VERIFY, DEVICE_ENROLLMENT, USER_INVITE + USER_VERIFY, DEVICE_ENROLLMENT, USER_INVITE, REMOTE_SESSION } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java index b244a5ed67..661027d10e 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/DefaultTokenHandler.java @@ -18,21 +18,22 @@ package io.entgra.ui.request.interceptor; import com.google.gson.Gson; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import io.entgra.ui.request.interceptor.beans.AuthData; import io.entgra.ui.request.interceptor.util.HandlerConstants; import io.entgra.ui.request.interceptor.util.HandlerUtil; -import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.apache.http.HttpHeaders; import org.apache.http.HttpStatus; -import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; -import org.apache.http.entity.ContentType; import io.entgra.ui.request.interceptor.beans.ProxyResponse; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.DeviceManagementConstants; +import org.wso2.carbon.device.mgt.common.exceptions.OTPManagementException; +import org.wso2.carbon.device.mgt.common.otp.mgt.OTPEmailTypes; +import org.wso2.carbon.device.mgt.common.otp.mgt.dto.OneTimePinDTO; +import org.wso2.carbon.device.mgt.common.spi.OTPManagementService; +import org.wso2.carbon.user.api.UserStoreException; +import org.wso2.carbon.user.core.service.RealmService; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; @@ -54,71 +55,28 @@ public class DefaultTokenHandler extends HttpServlet { HttpSession httpSession = req.getSession(false); if (httpSession != null) { - AuthData authData = (AuthData) httpSession.getAttribute(HandlerConstants.SESSION_AUTH_DATA_KEY); - if (authData == null) { - HandlerUtil.sendUnAuthorizeResponse(resp); - return; + String userWithDomain = (String) httpSession.getAttribute(HandlerConstants.USERNAME_WITH_DOMAIN); + String[] userNameParts = userWithDomain.split("@"); + + OneTimePinDTO oneTimePinData = new OneTimePinDTO(); + oneTimePinData.setEmail(OTPEmailTypes.REMOTE_SESSION.toString()); + oneTimePinData.setEmailType(OTPEmailTypes.REMOTE_SESSION.toString()); + oneTimePinData.setUsername(userNameParts[0]); + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + RealmService realmService = (RealmService) ctx.getOSGiService(RealmService.class, null); + try { + oneTimePinData.setTenantId(realmService.getTenantManager().getTenantId(userNameParts[1])); + } catch (UserStoreException e) { + throw new RuntimeException(e); } - - AuthData defaultAuthData = (AuthData) httpSession - .getAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY); - if (defaultAuthData != null) { - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultAuthData.getAccessToken())); - return; - } - - String clientId = authData.getClientId(); - String clientSecret = authData.getClientSecret(); - - String queryString = req.getQueryString(); - String scopeString = ""; - if (StringUtils.isNotEmpty(queryString)) { - scopeString = req.getParameter("scopes"); - if (scopeString != null) { - scopeString = "?scopes=" + scopeString; - } - } - - String iotsCoreUrl = req.getScheme() + HandlerConstants.SCHEME_SEPARATOR - + System.getProperty(HandlerConstants.IOT_GW_HOST_ENV_VAR) - + HandlerConstants.COLON + HandlerUtil.getGatewayPort(req.getScheme()); - String tokenUrl = iotsCoreUrl + "/api/device-mgt/v1.0/devices/" + clientId - + "/" + clientSecret + "/default-token" + scopeString; - - HttpGet defaultTokenRequest = new HttpGet(tokenUrl); - defaultTokenRequest - .setHeader(HttpHeaders.AUTHORIZATION, HandlerConstants.BEARER + authData.getAccessToken()); - defaultTokenRequest - .setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED.toString()); - ProxyResponse tokenResultResponse = HandlerUtil.execute(defaultTokenRequest); - - if (tokenResultResponse.getExecutorResponse().contains(HandlerConstants.EXECUTOR_EXCEPTION_PREFIX)) { - log.error("Error occurred while invoking the API to get default token data."); - HandlerUtil.handleError(resp, tokenResultResponse); - return; - } - String tokenResult = tokenResultResponse.getData(); - if (tokenResult == null) { - log.error("Invalid default token response is received."); - HandlerUtil.handleError(resp, tokenResultResponse); - return; - } - - JsonParser jsonParser = new JsonParser(); - JsonElement jTokenResult = jsonParser.parse(tokenResult); - if (jTokenResult.isJsonObject()) { - JsonObject jTokenResultAsJsonObject = jTokenResult.getAsJsonObject(); - AuthData newDefaultAuthData = new AuthData(); - newDefaultAuthData.setClientId(clientId); - newDefaultAuthData.setClientSecret(clientSecret); - - String defaultToken = jTokenResultAsJsonObject.get("accessToken").getAsString(); - newDefaultAuthData.setAccessToken(defaultToken); - newDefaultAuthData.setRefreshToken(jTokenResultAsJsonObject.get("refreshToken").getAsString()); - newDefaultAuthData.setScope(jTokenResultAsJsonObject.get("scopes").getAsString()); - httpSession.setAttribute(HandlerConstants.SESSION_DEFAULT_AUTH_DATA_KEY, newDefaultAuthData); - - HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(defaultToken)); + oneTimePinData.setExpiryTime(DeviceManagementConstants.OTPProperties.OTP_DEFAULT_EXPIRY_SECONDS); + OTPManagementService otpManagementService = HandlerUtil.getOTPManagementService(); + try { + oneTimePinData = otpManagementService.generateOneTimePin(oneTimePinData, true); + HandlerUtil.handleSuccess(resp, constructSuccessProxyResponse(oneTimePinData.getOtpToken())); + } catch (OTPManagementException e) { + log.error("Failed while generating remote session OTP for user " + userWithDomain, e); + HandlerUtil.handleError(resp, HttpStatus.SC_INTERNAL_SERVER_ERROR); } } else { HandlerUtil.sendUnAuthorizeResponse(resp); diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java index 53be11141e..0061865583 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/UserHandler.java @@ -120,6 +120,7 @@ public class UserHandler extends HttpServlet { proxyResponse.setData( jTokenResultAsJsonObject.get("username").getAsString().replaceAll("@carbon.super", "")); HandlerUtil.handleSuccess(resp, proxyResponse); + httpSession.setAttribute(HandlerConstants.USERNAME_WITH_DOMAIN, jTokenResultAsJsonObject.get("username").getAsString()); log.info("Customer login", userLogContextBuilder.setUserName(proxyResponse.getData()).setUserRegistered(true).build()); } } catch (IOException e) { diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java index 27d6afaadc..a6aa8d6bff 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerConstants.java @@ -106,4 +106,5 @@ public class HandlerConstants { public static final String IOT_REPORTING_WEBAPP_HOST_ENV_VAR = "iot.reporting.webapp.host"; public static final String USER_SCOPES = "userScopes"; public static final String HUBSPOT_CHAT_URL = "api.hubapi.com"; + public static final String USERNAME_WITH_DOMAIN = "usernameWithDomain"; } diff --git a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java index b7376abddc..ab09718a04 100644 --- a/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java +++ b/components/ui-request-interceptor/io.entgra.ui.request.interceptor/src/main/java/io/entgra/ui/request/interceptor/util/HandlerUtil.java @@ -55,6 +55,8 @@ import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import io.entgra.ui.request.interceptor.beans.ProxyResponse; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.common.spi.OTPManagementService; import org.xml.sax.SAXException; import javax.servlet.http.HttpServletRequest; @@ -79,6 +81,8 @@ public class HandlerUtil { private static boolean isLoginCacheInitialized = false; private static AuthData authData; + private static OTPManagementService otpManagementService; + /*** * * @param httpRequest - httpMethod e.g:- HttpPost, HttpGet @@ -751,4 +755,12 @@ public class HandlerUtil { public static boolean isPropertyDefined(String property) { return StringUtils.isEmpty(System.getProperty(property)); } + + public static OTPManagementService getOTPManagementService() { + if (otpManagementService == null) { + otpManagementService = (OTPManagementService) PrivilegedCarbonContext + .getThreadLocalCarbonContext().getOSGiService(OTPManagementService.class, null); + } + return otpManagementService; + } } From 577e3e938414a1d9fe60680104d83e1e72f75cba Mon Sep 17 00:00:00 2001 From: Pahansith Date: Fri, 23 Jun 2023 20:39:12 +0530 Subject: [PATCH 10/11] Remove unnecessary logs --- .../CertificateAuthenticator.java | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java index 6bccefe7ec..031a195007 100644 --- a/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java +++ b/components/webapp-authenticator-framework/org.wso2.carbon.webapp.authenticator.framework/src/main/java/org/wso2/carbon/webapp/authenticator/framework/authenticator/CertificateAuthenticator.java @@ -75,31 +75,29 @@ public class CertificateAuthenticator implements WebappAuthenticator { // When there is a load balancer terminating mutual SSL, it should pass this header along and // as the value of this header, the client certificate subject dn should be passed. if (request.getHeader(PROXY_MUTUAL_AUTH_HEADER) != null) { - log.info("PROXY_MUTUAL_AUTH_HEADER " + request.getHeader(PROXY_MUTUAL_AUTH_HEADER)); + if (log.isDebugEnabled()) { + log.debug("PROXY_MUTUAL_AUTH_HEADER " + request.getHeader(PROXY_MUTUAL_AUTH_HEADER)); + } CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). getCertificateManagementService().verifySubjectDN(request.getHeader(PROXY_MUTUAL_AUTH_HEADER)); - log.info("clientCertificate" + certificateResponse.getSerialNumber()); - log.info("clientCertificate" + certificateResponse.getCommonName()); authenticationInfo = checkCertificateResponse(certificateResponse); - log.info("username" + authenticationInfo.getUsername()); + if (log.isDebugEnabled()) { + log.debug("Certificate Serial : " + certificateResponse.getSerialNumber() + + ", CN : " + certificateResponse.getCommonName() + + " , username" + authenticationInfo.getUsername()); + } } else if (request.getHeader(MUTUAL_AUTH_HEADER) != null) { - log.info("MUTUAL_AUTH_HEADER"); Object object = request.getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); X509Certificate[] clientCertificate = null; if (object instanceof X509Certificate[]) { - log.info("clientCertificate"); clientCertificate = (X509Certificate[]) request. getAttribute(CLIENT_CERTIFICATE_ATTRIBUTE); } if (clientCertificate != null && clientCertificate[0] != null) { CertificateResponse certificateResponse = AuthenticatorFrameworkDataHolder.getInstance(). getCertificateManagementService().verifyPEMSignature(clientCertificate[0]); - log.info("clientCertificate" + certificateResponse.getSerialNumber()); - log.info("clientCertificate" + certificateResponse.getCommonName()); authenticationInfo = checkCertificateResponse(certificateResponse); - log.info("username" + authenticationInfo.getUsername()); - } else { authenticationInfo.setStatus(Status.FAILURE); authenticationInfo.setMessage("No client certificate is present"); From 763cd7df25ed0b1c299a07056f3adfdb4cdfbf87 Mon Sep 17 00:00:00 2001 From: Pahansith Date: Mon, 26 Jun 2023 13:43:13 +0530 Subject: [PATCH 11/11] Fix missing imports --- .../api/service/impl/DeviceManagementConfigServiceImpl.java | 4 ++++ .../core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java | 1 + 2 files changed, 5 insertions(+) diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java index 556baf75e0..c7b191704e 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.config.api/src/main/java/io/entgra/device/mgt/core/device/mgt/config/api/service/impl/DeviceManagementConfigServiceImpl.java @@ -21,6 +21,10 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; +import io.entgra.device.mgt.core.device.mgt.common.exceptions.OTPManagementException; +import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.OTPEmailTypes; +import io.entgra.device.mgt.core.device.mgt.common.otp.mgt.dto.OneTimePinDTO; +import io.entgra.device.mgt.core.device.mgt.common.spi.OTPManagementService; import io.entgra.device.mgt.core.device.mgt.config.api.beans.ErrorResponse; import io.entgra.device.mgt.core.device.mgt.config.api.service.DeviceManagementConfigService; import io.entgra.device.mgt.core.device.mgt.config.api.util.DeviceMgtAPIUtils; diff --git a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java index 419a72549b..e5755cd999 100644 --- a/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java +++ b/components/device-mgt/io.entgra.device.mgt.core.device.mgt.core/src/main/java/io/entgra/device/mgt/core/device/mgt/core/otp/mgt/dao/impl/GenericOTPManagementDAOImpl.java @@ -18,6 +18,7 @@ package io.entgra.device.mgt.core.device.mgt.core.otp.mgt.dao.impl; +import io.entgra.device.mgt.core.device.mgt.common.DeviceManagementConstants; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import io.entgra.device.mgt.core.device.mgt.common.exceptions.DBConnectionException;