Skip to content

Commit

Permalink
Remove unnecessary (and faulty) logic from SSLValidator
Browse files Browse the repository at this point in the history
  • Loading branch information
adamkobor committed Oct 26, 2020
1 parent ebc8cfb commit 20b0928
Showing 1 changed file with 1 addition and 17 deletions.
18 changes: 1 addition & 17 deletions src/main/kotlin/com/kuvaszuptime/kuvasz/services/SSLValidator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import com.kuvaszuptime.kuvasz.models.CertificateInfo
import com.kuvaszuptime.kuvasz.models.SSLValidationError
import com.kuvaszuptime.kuvasz.util.toOffsetDateTime
import java.net.URL
import java.security.cert.Certificate
import java.security.cert.X509Certificate
import javax.inject.Singleton
import javax.net.ssl.HttpsURLConnection
Expand All @@ -19,26 +18,11 @@ class SSLValidator {
val conn = url.openConnection() as HttpsURLConnection
conn.connect()

getCertificateForHost(url, conn.serverCertificates)?.let { cert ->
conn.serverCertificates.filterIsInstance<X509Certificate>().firstOrNull()?.let { cert ->
Either.right(CertificateInfo(validTo = cert.notAfter.toOffsetDateTime()))
} ?: Either.left(SSLValidationError("There were no matching CN for the given host"))
} catch (e: Throwable) {
Either.left(SSLValidationError(e.message))
}
}

private fun getCertificateForHost(url: URL, certs: Array<Certificate>): X509Certificate? =
certs.filterIsInstance<X509Certificate>().firstOrNull { it.cnMatchesWithHost(url) }

private fun X509Certificate.cnMatchesWithHost(url: URL): Boolean {
val cn = subjectDN.name.split(",").first().trimEnd().removePrefix("CN=")

return if (cn.startsWith("*.")) {
val cnWithoutWildcard = cn.removePrefix("*.")
val subdomain = url.host.removeSuffix(cnWithoutWildcard)
val subdomainPattern = Regex("^(([A-Za-z0-9](?:[A-Za-z0-9\\-]{0,61}[A-Za-z0-9])?\\.)|(\\S{0}))\$")

subdomain.matches(subdomainPattern)
} else cn == url.host
}
}

0 comments on commit 20b0928

Please sign in to comment.