001/* 002 * Copyright 2015-2024 the original author or authors 003 * 004 * This software is licensed under the Apache License, Version 2.0, 005 * the GNU Lesser General Public License version 2 or later ("LGPL") 006 * and the WTFPL. 007 * You may choose either license to govern your use of this software only 008 * upon the condition that you accept all of the terms of either 009 * the Apache License 2.0, the LGPL 2.1+ or the WTFPL. 010 */ 011package org.minidns.dane; 012 013import org.minidns.dnsmessage.DnsMessage; 014import org.minidns.dnsname.DnsName; 015import org.minidns.dnssec.DnssecClient; 016import org.minidns.dnssec.DnssecQueryResult; 017import org.minidns.dnssec.DnssecUnverifiedReason; 018import org.minidns.record.Data; 019import org.minidns.record.Record; 020import org.minidns.record.TLSA; 021 022import javax.net.ssl.HttpsURLConnection; 023import javax.net.ssl.SSLContext; 024import javax.net.ssl.SSLPeerUnverifiedException; 025import javax.net.ssl.SSLSession; 026import javax.net.ssl.SSLSocket; 027import javax.net.ssl.TrustManager; 028import javax.net.ssl.X509TrustManager; 029 030import java.io.IOException; 031import java.security.KeyManagementException; 032import java.security.MessageDigest; 033import java.security.NoSuchAlgorithmException; 034import java.security.cert.Certificate; 035import java.security.cert.CertificateException; 036import java.security.cert.X509Certificate; 037import java.util.ArrayList; 038import java.util.List; 039import java.util.logging.Logger; 040 041/** 042 * A helper class to validate the usage of TLSA records. 043 */ 044public class DaneVerifier { 045 private static final Logger LOGGER = Logger.getLogger(DaneVerifier.class.getName()); 046 047 private final DnssecClient client; 048 049 public DaneVerifier() { 050 this(new DnssecClient()); 051 } 052 053 public DaneVerifier(DnssecClient client) { 054 this.client = client; 055 } 056 057 /** 058 * Verifies the certificate chain in an active {@link SSLSocket}. The socket must be connected. 059 * 060 * @param socket A connected {@link SSLSocket} whose certificate chain shall be verified using DANE. 061 * @return Whether the DANE verification is the only requirement according to the TLSA record. 062 * If this method returns {@code false}, additional PKIX validation is required. 063 * @throws CertificateException if the certificate chain provided differs from the one enforced using DANE. 064 */ 065 public boolean verify(SSLSocket socket) throws CertificateException { 066 if (!socket.isConnected()) { 067 throw new IllegalStateException("Socket not yet connected."); 068 } 069 return verify(socket.getSession()); 070 } 071 072 /** 073 * Verifies the certificate chain in an active {@link SSLSession}. 074 * 075 * @param session An active {@link SSLSession} whose certificate chain shall be verified using DANE. 076 * @return Whether the DANE verification is the only requirement according to the TLSA record. 077 * If this method returns {@code false}, additional PKIX validation is required. 078 * @throws CertificateException if the certificate chain provided differs from the one enforced using DANE. 079 */ 080 public boolean verify(SSLSession session) throws CertificateException { 081 try { 082 return verifyCertificateChain(convert(session.getPeerCertificates()), session.getPeerHost(), session.getPeerPort()); 083 } catch (SSLPeerUnverifiedException e) { 084 throw new CertificateException("Peer not verified", e); 085 } 086 } 087 088 /** 089 * Verifies a certificate chain to be valid when used with the given connection details using DANE. 090 * 091 * @param chain A certificate chain that should be verified using DANE. 092 * @param hostName The DNS name of the host this certificate chain belongs to. 093 * @param port The port number that was used to reach the server providing the certificate chain in question. 094 * @return Whether the DANE verification is the only requirement according to the TLSA record. 095 * If this method returns {@code false}, additional PKIX validation is required. 096 * @throws CertificateException if the certificate chain provided differs from the one enforced using DANE. 097 */ 098 public boolean verifyCertificateChain(X509Certificate[] chain, String hostName, int port) throws CertificateException { 099 DnsName req = DnsName.from("_" + port + "._tcp." + hostName); 100 DnssecQueryResult result; 101 try { 102 result = client.queryDnssec(req, Record.TYPE.TLSA); 103 } catch (IOException e) { 104 throw new RuntimeException(e); 105 } 106 DnsMessage res = result.dnsQueryResult.response; 107 // TODO: We previously used the AD bit here. This allowed non-DNSSEC aware clients to be plugged into 108 // DaneVerifier, which, in turn, allows to use a trusted forward as DNSSEC validator. Is this a good idea? 109 if (!result.isAuthenticData()) { 110 String msg = "Got TLSA response from DNS server, but was not signed properly."; 111 msg += " Reasons:"; 112 for (DnssecUnverifiedReason reason : result.getUnverifiedReasons()) { 113 msg += " " + reason; 114 } 115 LOGGER.info(msg); 116 return false; 117 } 118 119 List<DaneCertificateException.CertificateMismatch> certificateMismatchExceptions = new ArrayList<>(); 120 boolean verified = false; 121 for (Record<? extends Data> record : res.answerSection) { 122 if (record.type == Record.TYPE.TLSA && record.name.equals(req)) { 123 TLSA tlsa = (TLSA) record.payloadData; 124 try { 125 verified |= checkCertificateMatches(chain[0], tlsa, hostName); 126 } catch (DaneCertificateException.CertificateMismatch certificateMismatchException) { 127 // Record the mismatch and only throw an exception if no 128 // TLSA RR is able to verify the cert. This allows for TLSA 129 // certificate rollover. 130 certificateMismatchExceptions.add(certificateMismatchException); 131 } 132 if (verified) break; 133 } 134 } 135 136 if (!verified && !certificateMismatchExceptions.isEmpty()) { 137 throw new DaneCertificateException.MultipleCertificateMismatchExceptions(certificateMismatchExceptions); 138 } 139 140 return verified; 141 } 142 143 private static boolean checkCertificateMatches(X509Certificate cert, TLSA tlsa, String hostName) throws CertificateException { 144 if (tlsa.certUsage == null) { 145 LOGGER.warning("TLSA certificate usage byte " + tlsa.certUsageByte + " is not supported while verifying " + hostName); 146 return false; 147 } 148 149 switch (tlsa.certUsage) { 150 case serviceCertificateConstraint: // PKIX-EE 151 case domainIssuedCertificate: // DANE-EE 152 break; 153 case caConstraint: // PKIX-TA 154 case trustAnchorAssertion: // DANE-TA 155 default: 156 LOGGER.warning("TLSA certificate usage " + tlsa.certUsage + " (" + tlsa.certUsageByte + ") not supported while verifying " + hostName); 157 return false; 158 } 159 160 if (tlsa.selector == null) { 161 LOGGER.warning("TLSA selector byte " + tlsa.selectorByte + " is not supported while verifying " + hostName); 162 return false; 163 } 164 165 byte[] comp = null; 166 switch (tlsa.selector) { 167 case fullCertificate: 168 comp = cert.getEncoded(); 169 break; 170 case subjectPublicKeyInfo: 171 comp = cert.getPublicKey().getEncoded(); 172 break; 173 default: 174 LOGGER.warning("TLSA selector " + tlsa.selector + " (" + tlsa.selectorByte + ") not supported while verifying " + hostName); 175 return false; 176 } 177 178 if (tlsa.matchingType == null) { 179 LOGGER.warning("TLSA matching type byte " + tlsa.matchingTypeByte + " is not supported while verifying " + hostName); 180 return false; 181 } 182 183 switch (tlsa.matchingType) { 184 case noHash: 185 break; 186 case sha256: 187 try { 188 comp = MessageDigest.getInstance("SHA-256").digest(comp); 189 } catch (NoSuchAlgorithmException e) { 190 throw new CertificateException("Verification using TLSA failed: could not SHA-256 for matching", e); 191 } 192 break; 193 case sha512: 194 try { 195 comp = MessageDigest.getInstance("SHA-512").digest(comp); 196 } catch (NoSuchAlgorithmException e) { 197 throw new CertificateException("Verification using TLSA failed: could not SHA-512 for matching", e); 198 } 199 break; 200 default: 201 LOGGER.warning("TLSA matching type " + tlsa.matchingType + " not supported while verifying " + hostName); 202 return false; 203 } 204 205 boolean matches = tlsa.certificateAssociationEquals(comp); 206 if (!matches) { 207 throw new DaneCertificateException.CertificateMismatch(tlsa, comp); 208 } 209 210 // domain issued certificate does not require further verification, 211 // service certificate constraint does. 212 return tlsa.certUsage == TLSA.CertUsage.domainIssuedCertificate; 213 } 214 215 /** 216 * Invokes {@link HttpsURLConnection#connect()} in a DANE verified fashion. 217 * This method must be called before {@link HttpsURLConnection#connect()} is invoked. 218 * 219 * If a SSLSocketFactory was set on this HttpsURLConnection, it will be ignored. You can use 220 * {@link #verifiedConnect(HttpsURLConnection, X509TrustManager)} to inject a custom {@link TrustManager}. 221 * 222 * @param conn connection to be connected. 223 * @return The {@link HttpsURLConnection} after being connected. 224 * @throws IOException when the connection could not be established. 225 * @throws CertificateException if there was an exception while verifying the certificate. 226 */ 227 public HttpsURLConnection verifiedConnect(HttpsURLConnection conn) throws IOException, CertificateException { 228 return verifiedConnect(conn, null); 229 } 230 231 /** 232 * Invokes {@link HttpsURLConnection#connect()} in a DANE verified fashion. 233 * This method must be called before {@link HttpsURLConnection#connect()} is invoked. 234 * 235 * If a SSLSocketFactory was set on this HttpsURLConnection, it will be ignored. 236 * 237 * @param conn connection to be connected. 238 * @param trustManager A non-default {@link TrustManager} to be used. 239 * @return The {@link HttpsURLConnection} after being connected. 240 * @throws IOException when the connection could not be established. 241 * @throws CertificateException if there was an exception while verifying the certificate. 242 */ 243 public HttpsURLConnection verifiedConnect(HttpsURLConnection conn, X509TrustManager trustManager) throws IOException, CertificateException { 244 try { 245 SSLContext context = SSLContext.getInstance("TLS"); 246 ExpectingTrustManager expectingTrustManager = new ExpectingTrustManager(trustManager); 247 context.init(null, new TrustManager[] {expectingTrustManager}, null); 248 conn.setSSLSocketFactory(context.getSocketFactory()); 249 conn.connect(); 250 boolean fullyVerified = verifyCertificateChain(convert(conn.getServerCertificates()), conn.getURL().getHost(), 251 conn.getURL().getPort() < 0 ? conn.getURL().getDefaultPort() : conn.getURL().getPort()); 252 // If fullyVerified is true then it's the DANE verification performed by verifiyCertificateChain() is 253 // sufficient to verify the certificate and we ignore possible pending exceptions of ExpectingTrustManager. 254 if (!fullyVerified && expectingTrustManager.hasException()) { 255 throw new IOException("Peer verification failed using PKIX", expectingTrustManager.getException()); 256 } 257 return conn; 258 } catch (NoSuchAlgorithmException | KeyManagementException e) { 259 throw new RuntimeException(e); 260 } 261 } 262 263 private static X509Certificate[] convert(Certificate[] certificates) { 264 List<X509Certificate> certs = new ArrayList<>(); 265 for (Certificate certificate : certificates) { 266 if (certificate instanceof X509Certificate) { 267 certs.add((X509Certificate) certificate); 268 } 269 } 270 return certs.toArray(new X509Certificate[certs.size()]); 271 } 272}