ENT-2847: Ent port: Make logging pluggable in NetworkRegistrationHelper. (#4477)

This commit is contained in:
Viktor Kolomeyko 2019-01-01 20:42:43 +00:00 committed by GitHub
parent b4c3fa1948
commit 5e16961fee
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -43,7 +43,9 @@ open class NetworkRegistrationHelper(
networkRootTrustStorePassword: String, networkRootTrustStorePassword: String,
private val nodeCaKeyAlias: String, private val nodeCaKeyAlias: String,
private val certRole: CertRole, private val certRole: CertRole,
private val nextIdleDuration: (Duration?) -> Duration? = FixedPeriodLimitedRetrialStrategy(10, Duration.ofMinutes(1)) private val nextIdleDuration: (Duration?) -> Duration? = FixedPeriodLimitedRetrialStrategy(10, Duration.ofMinutes(1)),
protected val logProgress: (String) -> Unit = ::println,
protected val logError: (String) -> Unit = System.err::println
) { ) {
companion object { companion object {
@ -86,7 +88,7 @@ open class NetworkRegistrationHelper(
// SELF_SIGNED_PRIVATE_KEY is used as progress indicator. // SELF_SIGNED_PRIVATE_KEY is used as progress indicator.
if (certStore.contains(nodeCaKeyAlias) && !certStore.contains(SELF_SIGNED_PRIVATE_KEY)) { if (certStore.contains(nodeCaKeyAlias) && !certStore.contains(SELF_SIGNED_PRIVATE_KEY)) {
println("Certificate already exists, Corda node will now terminate...") logProgress("Certificate already exists, Corda node will now terminate...")
return return
} }
@ -106,7 +108,7 @@ open class NetworkRegistrationHelper(
certStore.setCertPathOnly(nodeCaKeyAlias, nodeCaCertificates) certStore.setCertPathOnly(nodeCaKeyAlias, nodeCaCertificates)
certStore.value.internal.deleteEntry(SELF_SIGNED_PRIVATE_KEY) certStore.value.internal.deleteEntry(SELF_SIGNED_PRIVATE_KEY)
certStore.value.save() certStore.value.save()
println("Private key '$nodeCaKeyAlias' and its certificate-chain stored successfully.") logProgress("Private key '$nodeCaKeyAlias' and its certificate-chain stored successfully.")
onSuccess(nodeCaPublicKey, cryptoService.getSigner(nodeCaKeyAlias), nodeCaCertificates, tlsCrlIssuerCert?.subjectX500Principal?.toX500Name()) onSuccess(nodeCaPublicKey, cryptoService.getSigner(nodeCaKeyAlias), nodeCaCertificates, tlsCrlIssuerCert?.subjectX500Principal?.toX500Name())
// All done, clean up temp files. // All done, clean up temp files.
@ -124,9 +126,9 @@ open class NetworkRegistrationHelper(
private fun getTlsCrlIssuerCert(): X509Certificate? { private fun getTlsCrlIssuerCert(): X509Certificate? {
val tlsCrlIssuerCert = validateAndGetTlsCrlIssuerCert() val tlsCrlIssuerCert = validateAndGetTlsCrlIssuerCert()
if (tlsCrlIssuerCert == null && isTlsCrlIssuerCertRequired()) { if (tlsCrlIssuerCert == null && isTlsCrlIssuerCertRequired()) {
System.err.println("""tlsCrlIssuerCert config does not match the root certificate issuer and nor is there any other certificate in the trust store with a matching issuer. logError("""tlsCrlIssuerCert config does not match the root certificate issuer and nor is there any other certificate in the trust store with a matching issuer.
| Please make sure the config is correct or that the correct certificate for the CRL issuer is added to the node's trust store. | Please make sure the config is correct or that the correct certificate for the CRL issuer is added to the node's trust store.
| The node will now terminate.""".trimMargin()) | The node registration will now terminate.""".trimMargin())
throw IllegalArgumentException("TLS CRL issuer certificate not found in the trust store.") throw IllegalArgumentException("TLS CRL issuer certificate not found in the trust store.")
} }
return tlsCrlIssuerCert return tlsCrlIssuerCert
@ -161,7 +163,7 @@ open class NetworkRegistrationHelper(
// Validate certificate chain returned from the doorman with the root cert obtained via out-of-band process, to prevent MITM attack on doorman server. // Validate certificate chain returned from the doorman with the root cert obtained via out-of-band process, to prevent MITM attack on doorman server.
X509Utilities.validateCertificateChain(rootCert, certificates) X509Utilities.validateCertificateChain(rootCert, certificates)
println("Certificate signing request approved, storing private key with the certificate chain.") logProgress("Certificate signing request approved, storing private key with the certificate chain.")
} }
private fun CertificateStore.loadOrCreateKeyPair(alias: String, entryPassword: String = password): KeyPair { private fun CertificateStore.loadOrCreateKeyPair(alias: String, entryPassword: String = password): KeyPair {
@ -188,7 +190,7 @@ open class NetworkRegistrationHelper(
*/ */
private fun pollServerForCertificates(requestId: String): List<X509Certificate> { private fun pollServerForCertificates(requestId: String): List<X509Certificate> {
try { try {
println("Start polling server for certificate signing approval.") logProgress("Start polling server for certificate signing approval.")
// Poll server to download the signed certificate once request has been approved. // Poll server to download the signed certificate once request has been approved.
var idlePeriodDuration: Duration? = null var idlePeriodDuration: Duration? = null
while (true) { while (true) {
@ -209,9 +211,9 @@ open class NetworkRegistrationHelper(
} }
} }
} catch (certificateRequestException: CertificateRequestException) { } catch (certificateRequestException: CertificateRequestException) {
System.err.println(certificateRequestException.message) certificateRequestException.message?.let { logError(it) }
System.err.println("Please make sure the details in configuration file are correct and try again.") logError("Please make sure the details in configuration file are correct and try again.")
System.err.println("Corda node will now terminate.") logError("Corda node registration will now terminate.")
requestIdStore.deleteIfExists() requestIdStore.deleteIfExists()
throw certificateRequestException throw certificateRequestException
} }
@ -233,24 +235,21 @@ open class NetworkRegistrationHelper(
JcaPEMWriter(writer).use { JcaPEMWriter(writer).use {
it.writeObject(PemObject("CERTIFICATE REQUEST", request.encoded)) it.writeObject(PemObject("CERTIFICATE REQUEST", request.encoded))
} }
println("Certificate signing request with the following information will be submitted to the Corda certificate signing server.") logProgress("Certificate signing request with the following information will be submitted to the Corda certificate signing server.")
println() logProgress("Legal Name: $myLegalName")
println("Legal Name: $myLegalName") logProgress("Email: $emailAddress")
println("Email: $emailAddress") logProgress("Public Key: $publicKey")
println() logProgress("$writer")
println("Public Key: $publicKey")
println()
println("$writer")
// Post request to signing server via http. // Post request to signing server via http.
println("Submitting certificate signing request to Corda certificate signing server.") logProgress("Submitting certificate signing request to Corda certificate signing server.")
val requestId = certService.submitRequest(request) val requestId = certService.submitRequest(request)
// Persists request ID to file in case of node shutdown. // Persists request ID to file in case of node shutdown.
requestIdStore.writeLines(listOf(requestId)) requestIdStore.writeLines(listOf(requestId))
println("Successfully submitted request to Corda certificate signing server, request ID: $requestId.") logProgress("Successfully submitted request to Corda certificate signing server, request ID: $requestId.")
requestId requestId
} else { } else {
val requestId = requestIdStore.readLines { it.findFirst().get() } val requestId = requestIdStore.readLines { it.findFirst().get() }
println("Resuming from previous certificate signing request, request ID: $requestId.") logProgress("Resuming from previous certificate signing request, request ID: $requestId.")
requestId requestId
} }
} catch (e: Exception) { } catch (e: Exception) {
@ -274,7 +273,11 @@ class NodeRegistrationException(
class NodeRegistrationHelper( class NodeRegistrationHelper(
private val config: NodeConfiguration, private val config: NodeConfiguration,
certService: NetworkRegistrationService, regConfig: NodeRegistrationOption, computeNextIdleDoormanConnectionPollInterval: (Duration?) -> Duration? = FixedPeriodLimitedRetrialStrategy(10, Duration.ofMinutes(1))) : certService: NetworkRegistrationService,
regConfig: NodeRegistrationOption,
computeNextIdleDoormanConnectionPollInterval: (Duration?) -> Duration? = FixedPeriodLimitedRetrialStrategy(10, Duration.ofMinutes(1)),
logProgress: (String) -> Unit = ::println,
logError: (String) -> Unit = System.err::println) :
NetworkRegistrationHelper( NetworkRegistrationHelper(
config, config,
certService, certService,
@ -282,7 +285,7 @@ class NodeRegistrationHelper(
regConfig.networkRootTrustStorePassword, regConfig.networkRootTrustStorePassword,
CORDA_CLIENT_CA, CORDA_CLIENT_CA,
CertRole.NODE_CA, CertRole.NODE_CA,
computeNextIdleDoormanConnectionPollInterval) { computeNextIdleDoormanConnectionPollInterval, logProgress, logError) {
companion object { companion object {
val logger = contextLogger() val logger = contextLogger()
@ -297,7 +300,7 @@ class NodeRegistrationHelper(
val keyStore = config.p2pSslOptions.keyStore val keyStore = config.p2pSslOptions.keyStore
val certificateStore = keyStore.get(createNew = true) val certificateStore = keyStore.get(createNew = true)
certificateStore.update { certificateStore.update {
println("Generating SSL certificate for node messaging service.") logProgress("Generating SSL certificate for node messaging service.")
val sslKeyPair = Crypto.generateKeyPair(X509Utilities.DEFAULT_TLS_SIGNATURE_SCHEME) val sslKeyPair = Crypto.generateKeyPair(X509Utilities.DEFAULT_TLS_SIGNATURE_SCHEME)
val issuerCertificate = nodeCaCertificateChain.first() val issuerCertificate = nodeCaCertificateChain.first()
val validityWindow = X509Utilities.getCertificateValidityWindow(DEFAULT_VALIDITY_WINDOW.first, DEFAULT_VALIDITY_WINDOW.second, issuerCertificate) val validityWindow = X509Utilities.getCertificateValidityWindow(DEFAULT_VALIDITY_WINDOW.first, DEFAULT_VALIDITY_WINDOW.second, issuerCertificate)
@ -319,7 +322,7 @@ class NodeRegistrationHelper(
X509Utilities.validateCertificateChain(rootCert, sslCertificateChain) X509Utilities.validateCertificateChain(rootCert, sslCertificateChain)
setPrivateKey(CORDA_CLIENT_TLS, sslKeyPair.private, sslCertificateChain, keyStore.entryPassword) setPrivateKey(CORDA_CLIENT_TLS, sslKeyPair.private, sslCertificateChain, keyStore.entryPassword)
} }
println("SSL private key and certificate chain stored in ${keyStore.path}.") logProgress("SSL private key and certificate chain stored in ${keyStore.path}.")
} }
private fun createTruststore(rootCertificate: X509Certificate) { private fun createTruststore(rootCertificate: X509Certificate) {
@ -328,7 +331,7 @@ class NodeRegistrationHelper(
if (this.aliases().hasNext()) { if (this.aliases().hasNext()) {
logger.warn("The node's trust store already exists. The following certificates will be overridden: ${this.aliases().asSequence()}") logger.warn("The node's trust store already exists. The following certificates will be overridden: ${this.aliases().asSequence()}")
} }
println("Generating trust store for corda node.") logProgress("Generating trust store for corda node.")
// Assumes certificate chain always starts with client certificate and end with root certificate. // Assumes certificate chain always starts with client certificate and end with root certificate.
setCertificate(CORDA_ROOT_CA, rootCertificate) setCertificate(CORDA_ROOT_CA, rootCertificate)
// Copy remaining certificates from the network-trust-store // Copy remaining certificates from the network-trust-store
@ -338,7 +341,7 @@ class NodeRegistrationHelper(
setCertificate(it, certificate) setCertificate(it, certificate)
} }
} }
println("Node trust store stored in ${config.p2pSslOptions.trustStore.path}.") logProgress("Node trust store stored in ${config.p2pSslOptions.trustStore.path}.")
} }
override fun validateAndGetTlsCrlIssuerCert(): X509Certificate? { override fun validateAndGetTlsCrlIssuerCert(): X509Certificate? {