+ int i, ret = LDAP_LOCAL_ERROR;
+ X509 *x;
+ const char *name;
+
+ if( ldap_int_hostname &&
+ ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
+ {
+ name = ldap_int_hostname;
+ } else {
+ name = name_in;
+ }
+
+ x = tls_get_cert((SSL *)s);
+ if (!x) {
+#ifdef NEW_LOGGING
+ LDAP_LOG ( TRANSPORT, ERR,
+ "ldap_pvt_tls_check_hostname: "
+ "TLS unable to get peer certificate.\n" , 0, 0, 0 );
+#else
+ Debug( LDAP_DEBUG_ANY,
+ "TLS: unable to get peer certificate.\n",
+ 0, 0, 0 );
+#endif
+ /* If this was a fatal condition, things would have
+ * aborted long before now.
+ */
+ return LDAP_SUCCESS;
+ }
+
+ i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
+ if (i >= 0) {
+ X509_EXTENSION *ex;
+ STACK_OF(GENERAL_NAME) *alt;
+
+ ex = X509_get_ext(x, i);
+ alt = X509V3_EXT_d2i(ex);
+ if (alt) {
+ int n, len1, len2 = 0;
+ char *domain;
+ GENERAL_NAME *gn;
+
+ len1 = strlen(name);
+ n = sk_GENERAL_NAME_num(alt);
+ domain = strchr(name, '.');
+ if (domain) {
+ len2 = len1 - (domain-name);
+ }
+ for (i=0; i<n; i++) {
+ gn = sk_GENERAL_NAME_value(alt, i);
+ if (gn->type == GEN_DNS) {
+ char *sn = ASN1_STRING_data(gn->d.ia5);
+ int sl = ASN1_STRING_length(gn->d.ia5);
+
+ /* Is this an exact match? */
+ if ((len1 == sl) && !strncasecmp(name, sn, len1)) {
+ break;
+ }
+
+ /* Is this a wildcard match? */
+ if ((*sn == '*') && domain && (len2 == sl-1) &&
+ !strncasecmp(domain, sn+1, len2))
+ {
+ break;
+ }
+
+#if 0
+ /* Is this a RFC 2549 style wildcard match? */
+ if ((*sn == '.') && domain && (len2 == sl) &&
+ !strncasecmp(domain, sn, len2))
+ {
+ break;
+ }
+#endif
+ }
+ }
+
+ GENERAL_NAMES_free(alt);
+ if (i < n) { /* Found a match */
+ ret = LDAP_SUCCESS;
+ }
+ }
+ }
+
+ if (ret != LDAP_SUCCESS) {
+ X509_NAME *xn;
+ char buf[2048];
+
+ xn = X509_get_subject_name(x);
+
+ if( X509_NAME_get_text_by_NID( xn, NID_commonName,
+ buf, sizeof(buf)) == -1)
+ {
+#ifdef NEW_LOGGING
+ LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_check_hostname: "
+ "TLS unable to get common name from peer certificate.\n",
+ 0, 0, 0 );
+#else
+ Debug( LDAP_DEBUG_ANY,
+ "TLS: unable to get common name from peer certificate.\n",
+ 0, 0, 0 );
+#endif
+ ld->ld_error = LDAP_STRDUP("TLS: unable to get CN from peer certificate");
+
+ } else if (strcasecmp(name, buf)) {
+#ifdef NEW_LOGGING
+ LDAP_LOG ( TRANSPORT, ERR, "ldap_pvt_tls_check_hostname: "
+ "TLS hostname (%s) does not match "
+ "common name in certificate (%s).\n", name, buf, 0 );
+#else
+ Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
+ "common name in certificate (%s).\n",
+ name, buf, 0 );
+#endif
+ ret = LDAP_CONNECT_ERROR;
+ ld->ld_error = LDAP_STRDUP("TLS: hostname does not match CN in peer certificate");
+
+ } else {
+ ret = LDAP_SUCCESS;
+ }
+ }
+ X509_free(x);
+ return ret;