You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@ozone.apache.org by GitBox <gi...@apache.org> on 2023/01/04 23:40:45 UTC

[GitHub] [ozone] fapifta commented on a diff in pull request #3982: HDDS-7339. Implement Certificate renewal task for services

fapifta commented on code in PR #3982:
URL: https://github.com/apache/ozone/pull/3982#discussion_r1061973055


##########
hadoop-hdds/framework/src/main/java/org/apache/hadoop/hdds/security/x509/certificate/client/DefaultCertificateClient.java:
##########
@@ -1095,4 +1112,332 @@ public synchronized void close() throws IOException {
       clientKeyStoresFactory.destroy();
     }
   }
+
+  /**
+   * Check how much time before certificate will enter expiry grace period.
+   * @return Duration, time before certificate enters the grace
+   *                   period defined by "hdds.x509.renew.grace.duration"
+   */
+  public Duration timeBeforeExpiryGracePeriod(X509Certificate certificate) {
+    Duration gracePeriod = securityConfig.getRenewalGracePeriod();
+    Date expireDate = certificate.getNotAfter();
+    LocalDateTime gracePeriodStart = expireDate.toInstant()
+        .atZone(ZoneId.systemDefault()).toLocalDateTime().minus(gracePeriod);
+    LocalDateTime currentTime = LocalDateTime.now();
+    if (gracePeriodStart.isBefore(currentTime)) {
+      // Cert is already in grace period time.
+      return Duration.ZERO;
+    } else {
+      return Duration.between(currentTime, gracePeriodStart);
+    }
+  }
+
+  /**
+   * Renew keys and certificate. Save the keys are certificate to disk in new
+   * directories, swap the current key directory and certs directory with the
+   * new directories.
+   * @param force, check certificate expiry time again if force is false.
+   * @return String, new certificate ID
+   * */
+  public String renewAndStoreKeyAndCertificate(boolean force)
+      throws CertificateException {
+    if (!force) {
+      synchronized (this) {
+        Preconditions.checkArgument(
+            timeBeforeExpiryGracePeriod(x509Certificate).isZero());
+      }
+    }
+
+    String newKeyPath = securityConfig.getKeyLocation(component)
+        .toString() + HDDS_NEW_KEY_CERT_DIR_NAME_SUFFIX;
+    String newCertPath = securityConfig.getCertificateLocation(component)
+        .toString() + HDDS_NEW_KEY_CERT_DIR_NAME_SUFFIX;
+    File newKeyDir = new File(newKeyPath);
+    File newCertDir = new File(newCertPath);
+    try {
+      FileUtils.deleteDirectory(newKeyDir);
+      FileUtils.deleteDirectory(newCertDir);
+      Files.createDirectories(newKeyDir.toPath());
+      Files.createDirectories(newCertDir.toPath());
+    } catch (IOException e) {
+      throw new CertificateException("Error while deleting/creating " +
+          newKeyPath + " or " + newCertPath + " directories to cleanup " +
+          " certificate storage. ", e, RENEW_ERROR);
+    }
+
+    // Generate key
+    KeyCodec newKeyCodec = new KeyCodec(securityConfig, newKeyDir.toPath());
+    KeyPair newKeyPair;
+    try {
+      newKeyPair = createKeyPair(newKeyCodec);
+    } catch (CertificateException e) {
+      throw new CertificateException("Error while creating new key pair.",
+          e, RENEW_ERROR);
+    }
+
+    // Get certificate signed
+    String newCertSerialId;
+    try {
+      CertificateSignRequest.Builder csrBuilder = getCSRBuilder(newKeyPair);
+      newCertSerialId = signAndStoreCertificate(csrBuilder.build(),
+          Paths.get(newCertPath));
+    } catch (Exception e) {
+      throw new CertificateException("Error while signing and storing new" +
+          " certificates.", e, RENEW_ERROR);
+    }
+
+    // switch Key and Certs directory on disk
+    File currentKeyDir = new File(
+        securityConfig.getKeyLocation(component).toString());
+    File currentCertDir = new File(
+        securityConfig.getCertificateLocation(component).toString());
+    File backupKeyDir = new File(
+        securityConfig.getKeyLocation(component).toString() +
+            HDDS_BACKUP_KEY_CERT_DIR_NAME_SUFFIX);
+    File backupCertDir = new File(
+        securityConfig.getCertificateLocation(component).toString() +
+            HDDS_BACKUP_KEY_CERT_DIR_NAME_SUFFIX);
+
+    try {
+      Files.move(currentKeyDir.toPath(), backupKeyDir.toPath(),
+          StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+    } catch (IOException e) {
+      // Cannot move current key dir to the backup dir
+      throw new CertificateException("Failed to move " +
+          currentKeyDir.getAbsolutePath() +
+          " to " + backupKeyDir.getAbsolutePath() + " during " +
+          "certificate renew.", RENEW_ERROR);
+    }
+
+    try {
+      Files.move(currentCertDir.toPath(), backupCertDir.toPath(),
+          StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+    } catch (IOException e) {
+      // Cannot move current cert dir to the backup dir
+      rollbackBackupDir(currentKeyDir, currentCertDir, backupKeyDir,
+          backupCertDir);
+      throw new CertificateException("Failed to move " +
+          currentCertDir.getAbsolutePath() +
+          " to " + backupCertDir.getAbsolutePath() + " during " +
+          "certificate renew.", RENEW_ERROR);
+    }
+
+    try {
+      Files.move(newKeyDir.toPath(), currentKeyDir.toPath(),
+          StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+    } catch (IOException e) {
+      // Cannot move new dir as the current dir
+      String msg = "Failed to move " + newKeyDir.getAbsolutePath() +
+          " to " + currentKeyDir.getAbsolutePath() +
+          " during certificate renew.";
+      // rollback
+      rollbackBackupDir(currentKeyDir, currentCertDir, backupKeyDir,
+          backupCertDir);
+      throw new CertificateException(msg, RENEW_ERROR);
+    }
+
+    try {
+      Files.move(newCertDir.toPath(), currentCertDir.toPath(),
+          StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
+    } catch (IOException e) {
+      // Cannot move new dir as the current dir
+      String msg = "Failed to move " + newCertDir.getAbsolutePath() +
+          " to " + currentCertDir.getAbsolutePath() +
+          " during certificate renew.";
+      // delete new key directory
+      try {
+        Files.createDirectories(currentKeyDir.toPath());

Review Comment:
   based on your explanation, and based on the comment 2 lines before this, shouldn't this be some form of delete operation instead of createDirectories?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@ozone.apache.org
For additional commands, e-mail: issues-help@ozone.apache.org