heimdal - fix various warnings
[sfrench/samba-autobuild/.git] / source4 / heimdal / lib / hx509 / cert.c
index 3194526e3456ef36094a57ff2b0b6c9c400d1268..7eda0eba48689926d591e8aef194ffcf39d2eade 100644 (file)
@@ -1,38 +1,37 @@
 /*
- * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
- * (Royal Institute of Technology, Stockholm, Sweden). 
- * All rights reserved. 
- *
- * Redistribution and use in source and binary forms, with or without 
- * modification, are permitted provided that the following conditions 
- * are met: 
- *
- * 1. Redistributions of source code must retain the above copyright 
- *    notice, this list of conditions and the following disclaimer. 
- *
- * 2. Redistributions in binary form must reproduce the above copyright 
- *    notice, this list of conditions and the following disclaimer in the 
- *    documentation and/or other materials provided with the distribution. 
- *
- * 3. Neither the name of the Institute nor the names of its contributors 
- *    may be used to endorse or promote products derived from this software 
- *    without specific prior written permission. 
- *
- * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND 
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
- * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE 
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 
- * SUCH DAMAGE. 
+ * Copyright (c) 2004 - 2007 Kungliga Tekniska Högskolan
+ * (Royal Institute of Technology, Stockholm, Sweden).
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * 3. Neither the name of the Institute nor the names of its contributors
+ *    may be used to endorse or promote products derived from this software
+ *    without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
  */
 
 #include "hx_locl.h"
-RCSID("$Id: cert.c 23457 2008-07-27 12:12:56Z lha $");
 #include "crypto-headers.h"
 #include <rtbl.h>
 
@@ -59,6 +58,7 @@ struct hx509_verify_ctx_data {
 #define HX509_VERIFY_CTX_F_REQUIRE_RFC3280             4
 #define HX509_VERIFY_CTX_F_CHECK_TRUST_ANCHORS         8
 #define HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS          16
+#define HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK                32
     time_t time_now;
     unsigned int max_depth;
 #define HX509_VERIFY_MAX_DEPTH 30
@@ -141,7 +141,7 @@ hx509_context_init(hx509_context *context)
  * the existans of a revokation method (OCSP, CRL) or not. Note that
  * hx509_verify_path(), hx509_cms_verify_signed(), and other function
  * call hx509_revoke_verify().
- * 
+ *
  * @param context hx509 context to change the flag for.
  * @param flag zero, revokation method required, non zero missing
  * revokation method ok
@@ -160,7 +160,7 @@ hx509_context_set_missing_revoke(hx509_context context, int flag)
 
 /**
  * Free the context allocated by hx509_context_init().
- * 
+ *
  * @param context context to be freed.
  *
  * @ingroup hx509
@@ -205,7 +205,7 @@ _hx509_cert_get_version(const Certificate *t)
 
 /**
  * Allocate and init an hx509 certificate object from the decoded
- * certificate `c´.
+ * certificate `c´.
  *
  * @param context A hx509 context.
  * @param c
@@ -268,7 +268,7 @@ hx509_cert_init(hx509_context context, const Certificate *c, hx509_cert *cert)
  */
 
 int
-hx509_cert_init_data(hx509_context context, 
+hx509_cert_init_data(hx509_context context,
                     const void *ptr,
                     size_t len,
                     hx509_cert *cert)
@@ -294,7 +294,7 @@ hx509_cert_init_data(hx509_context context,
 }
 
 void
-_hx509_cert_set_release(hx509_cert cert, 
+_hx509_cert_set_release(hx509_cert cert,
                        _hx509_cert_release_func release,
                        void *ctx)
 {
@@ -383,7 +383,7 @@ hx509_cert_ref(hx509_cert cert)
 
 /**
  * Allocate an verification context that is used fo control the
- * verification process. 
+ * verification process.
  *
  * @param context A hx509 context.
  * @param ctx returns a pointer to a hx509_verify_ctx object.
@@ -405,7 +405,7 @@ hx509_verify_init_ctx(hx509_context context, hx509_verify_ctx *ctx)
     c->max_depth = HX509_VERIFY_MAX_DEPTH;
 
     *ctx = c;
-    
+
     return 0;
 }
 
@@ -432,6 +432,7 @@ hx509_verify_destroy_ctx(hx509_verify_ctx ctx)
  * Set the trust anchors in the verification context, makes an
  * reference to the keyset, so the consumer can free the keyset
  * independent of the destruction of the verification context (ctx).
+ * If there already is a keyset attached, it's released.
  *
  * @param ctx a verification context
  * @param set a keyset containing the trust anchors.
@@ -442,6 +443,8 @@ hx509_verify_destroy_ctx(hx509_verify_ctx ctx)
 void
 hx509_verify_attach_anchors(hx509_verify_ctx ctx, hx509_certs set)
 {
+    if (ctx->trust_anchors)
+       hx509_certs_free(&ctx->trust_anchors);
     ctx->trust_anchors = _hx509_certs_ref(set);
 }
 
@@ -569,6 +572,16 @@ hx509_verify_ctx_f_allow_default_trustanchors(hx509_verify_ctx ctx, int boolean)
        ctx->flags |= HX509_VERIFY_CTX_F_NO_DEFAULT_ANCHORS;
 }
 
+void
+hx509_verify_ctx_f_allow_best_before_signature_algs(hx509_context ctx, 
+                                                   int boolean)
+{
+    if (boolean)
+       ctx->flags &= ~HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK;
+    else
+       ctx->flags |= HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK;
+}
+
 static const Extension *
 find_extension(const Certificate *cert, const heim_oid *oid, int *idx)
 {
@@ -576,7 +589,7 @@ find_extension(const Certificate *cert, const heim_oid *oid, int *idx)
 
     if (c->version == NULL || *c->version < 2 || c->extensions == NULL)
        return NULL;
-    
+
     for (;*idx < c->extensions->len; (*idx)++) {
        if (der_heim_oid_cmp(&c->extensions->val[*idx].extnID, oid) == 0)
            return &c->extensions->val[(*idx)++];
@@ -585,7 +598,7 @@ find_extension(const Certificate *cert, const heim_oid *oid, int *idx)
 }
 
 static int
-find_extension_auth_key_id(const Certificate *subject, 
+find_extension_auth_key_id(const Certificate *subject,
                           AuthorityKeyIdentifier *ai)
 {
     const Extension *e;
@@ -594,12 +607,12 @@ find_extension_auth_key_id(const Certificate *subject,
 
     memset(ai, 0, sizeof(*ai));
 
-    e = find_extension(subject, oid_id_x509_ce_authorityKeyIdentifier(), &i);
+    e = find_extension(subject, &asn1_oid_id_x509_ce_authorityKeyIdentifier, &i);
     if (e == NULL)
        return HX509_EXTENSION_NOT_FOUND;
-    
-    return decode_AuthorityKeyIdentifier(e->extnValue.data, 
-                                        e->extnValue.length, 
+
+    return decode_AuthorityKeyIdentifier(e->extnValue.data,
+                                        e->extnValue.length,
                                         ai, &size);
 }
 
@@ -613,17 +626,17 @@ _hx509_find_extension_subject_key_id(const Certificate *issuer,
 
     memset(si, 0, sizeof(*si));
 
-    e = find_extension(issuer, oid_id_x509_ce_subjectKeyIdentifier(), &i);
+    e = find_extension(issuer, &asn1_oid_id_x509_ce_subjectKeyIdentifier, &i);
     if (e == NULL)
        return HX509_EXTENSION_NOT_FOUND;
-    
-    return decode_SubjectKeyIdentifier(e->extnValue.data, 
+
+    return decode_SubjectKeyIdentifier(e->extnValue.data,
                                       e->extnValue.length,
                                       si, &size);
 }
 
 static int
-find_extension_name_constraints(const Certificate *subject, 
+find_extension_name_constraints(const Certificate *subject,
                                NameConstraints *nc)
 {
     const Extension *e;
@@ -632,12 +645,12 @@ find_extension_name_constraints(const Certificate *subject,
 
     memset(nc, 0, sizeof(*nc));
 
-    e = find_extension(subject, oid_id_x509_ce_nameConstraints(), &i);
+    e = find_extension(subject, &asn1_oid_id_x509_ce_nameConstraints, &i);
     if (e == NULL)
        return HX509_EXTENSION_NOT_FOUND;
-    
-    return decode_NameConstraints(e->extnValue.data, 
-                                 e->extnValue.length, 
+
+    return decode_NameConstraints(e->extnValue.data,
+                                 e->extnValue.length,
                                  nc, &size);
 }
 
@@ -650,11 +663,11 @@ find_extension_subject_alt_name(const Certificate *cert, int *i,
 
     memset(sa, 0, sizeof(*sa));
 
-    e = find_extension(cert, oid_id_x509_ce_subjectAltName(), i);
+    e = find_extension(cert, &asn1_oid_id_x509_ce_subjectAltName, i);
     if (e == NULL)
        return HX509_EXTENSION_NOT_FOUND;
-    
-    return decode_GeneralNames(e->extnValue.data, 
+
+    return decode_GeneralNames(e->extnValue.data,
                               e->extnValue.length,
                               sa, &size);
 }
@@ -668,11 +681,11 @@ find_extension_eku(const Certificate *cert, ExtKeyUsage *eku)
 
     memset(eku, 0, sizeof(*eku));
 
-    e = find_extension(cert, oid_id_x509_ce_extKeyUsage(), &i);
+    e = find_extension(cert, &asn1_oid_id_x509_ce_extKeyUsage, &i);
     if (e == NULL)
        return HX509_EXTENSION_NOT_FOUND;
-    
-    return decode_ExtKeyUsage(e->extnValue.data, 
+
+    return decode_ExtKeyUsage(e->extnValue.data,
                              e->extnValue.length,
                              eku, &size);
 }
@@ -716,7 +729,7 @@ hx509_free_octet_string_list(hx509_octet_string_list *list)
 
 /**
  * Return a list of subjectAltNames specified by oid in the
- * certificate. On error the 
+ * certificate. On error the
  *
  * The returned list of octet string should be freed with
  * hx509_free_octet_string_list().
@@ -748,8 +761,7 @@ hx509_cert_find_subjectAltName_otherName(hx509_context context,
        ret = find_extension_subject_alt_name(_hx509_get_cert(cert), &i, &sa);
        i++;
        if (ret == HX509_EXTENSION_NOT_FOUND) {
-           ret = 0;
-           break;
+           return 0;
        } else if (ret != 0) {
            hx509_set_error_string(context, 0, ret, "Error searching for SAN");
            hx509_free_octet_string_list(list);
@@ -758,11 +770,11 @@ hx509_cert_find_subjectAltName_otherName(hx509_context context,
 
        for (j = 0; j < sa.len; j++) {
            if (sa.val[j].element == choice_GeneralName_otherName &&
-               der_heim_oid_cmp(&sa.val[j].u.otherName.type_id, oid) == 0) 
+               der_heim_oid_cmp(&sa.val[j].u.otherName.type_id, oid) == 0)
            {
                ret = add_to_list(list, &sa.val[j].u.otherName.value);
                if (ret) {
-                   hx509_set_error_string(context, 0, ret, 
+                   hx509_set_error_string(context, 0, ret,
                                           "Error adding an exra SAN to "
                                           "return list");
                    hx509_free_octet_string_list(list);
@@ -773,12 +785,11 @@ hx509_cert_find_subjectAltName_otherName(hx509_context context,
        }
        free_GeneralNames(&sa);
     }
-    return 0;
 }
 
 
 static int
-check_key_usage(hx509_context context, const Certificate *cert, 
+check_key_usage(hx509_context context, const Certificate *cert,
                unsigned flags, int req_present)
 {
     const Extension *e;
@@ -790,7 +801,7 @@ check_key_usage(hx509_context context, const Certificate *cert,
     if (_hx509_cert_get_version(cert) < 3)
        return 0;
 
-    e = find_extension(cert, oid_id_x509_ce_keyUsage(), &i);
+    e = find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i);
     if (e == NULL) {
        if (req_present) {
            hx509_set_error_string(context, 0, HX509_KU_CERT_MISSING,
@@ -800,7 +811,7 @@ check_key_usage(hx509_context context, const Certificate *cert,
        }
        return 0;
     }
-    
+
     ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, &ku, &size);
     if (ret)
        return ret;
@@ -827,7 +838,7 @@ check_key_usage(hx509_context context, const Certificate *cert,
  */
 
 int
-_hx509_check_key_usage(hx509_context context, hx509_cert cert, 
+_hx509_check_key_usage(hx509_context context, hx509_cert cert,
                       unsigned flags, int req_present)
 {
     return check_key_usage(context, _hx509_get_cert(cert), flags, req_present);
@@ -836,7 +847,7 @@ _hx509_check_key_usage(hx509_context context, hx509_cert cert,
 enum certtype { PROXY_CERT, EE_CERT, CA_CERT };
 
 static int
-check_basic_constraints(hx509_context context, const Certificate *cert, 
+check_basic_constraints(hx509_context context, const Certificate *cert,
                        enum certtype type, int depth)
 {
     BasicConstraints bc;
@@ -847,7 +858,7 @@ check_basic_constraints(hx509_context context, const Certificate *cert,
     if (_hx509_cert_get_version(cert) < 3)
        return 0;
 
-    e = find_extension(cert, oid_id_x509_ce_basicConstraints(), &i);
+    e = find_extension(cert, &asn1_oid_id_x509_ce_basicConstraints, &i);
     if (e == NULL) {
        switch(type) {
        case PROXY_CERT:
@@ -865,8 +876,8 @@ check_basic_constraints(hx509_context context, const Certificate *cert,
        }
        }
     }
-    
-    ret = decode_BasicConstraints(e->extnValue.data, 
+
+    ret = decode_BasicConstraints(e->extnValue.data,
                                  e->extnValue.length, &bc,
                                  &size);
     if (ret)
@@ -901,14 +912,14 @@ _hx509_cert_is_parent_cmp(const Certificate *subject,
     SubjectKeyIdentifier si;
     int ret_ai, ret_si, ret;
 
-    ret = _hx509_name_cmp(&issuer->tbsCertificate.subject, 
+    ret = _hx509_name_cmp(&issuer->tbsCertificate.subject,
                          &subject->tbsCertificate.issuer,
                          &diff);
     if (ret)
        return ret;
     if (diff)
        return diff;
-    
+
     memset(&ai, 0, sizeof(ai));
     memset(&si, 0, sizeof(si));
 
@@ -937,7 +948,7 @@ _hx509_cert_is_parent_cmp(const Certificate *subject,
            goto out;
        }
     }
-    
+
     if (ai.keyIdentifier == NULL) {
        Name name;
 
@@ -946,7 +957,7 @@ _hx509_cert_is_parent_cmp(const Certificate *subject,
        if (ai.authorityCertSerialNumber == NULL)
            return -1;
 
-       diff = der_heim_integer_cmp(ai.authorityCertSerialNumber, 
+       diff = der_heim_integer_cmp(ai.authorityCertSerialNumber,
                                    &issuer->tbsCertificate.serialNumber);
        if (diff)
            return diff;
@@ -955,12 +966,12 @@ _hx509_cert_is_parent_cmp(const Certificate *subject,
        if (ai.authorityCertIssuer->val[0].element != choice_GeneralName_directoryName)
            return -1;
        
-       name.element = 
+       name.element =
            ai.authorityCertIssuer->val[0].u.directoryName.element;
-       name.u.rdnSequence = 
+       name.u.rdnSequence =
            ai.authorityCertIssuer->val[0].u.directoryName.u.rdnSequence;
 
-       ret = _hx509_name_cmp(&issuer->tbsCertificate.subject, 
+       ret = _hx509_name_cmp(&issuer->tbsCertificate.subject,
                              &name,
                              &diff);
        if (ret)
@@ -1008,7 +1019,7 @@ certificate_is_self_signed(hx509_context context,
                           int *self_signed)
 {
     int ret, diff;
-    ret = _hx509_name_cmp(&cert->tbsCertificate.subject, 
+    ret = _hx509_name_cmp(&cert->tbsCertificate.subject,
                          &cert->tbsCertificate.issuer, &diff);
     *self_signed = (diff == 0);
     if (ret)
@@ -1033,7 +1044,7 @@ find_parent(hx509_context context,
            time_t time_now,
            hx509_certs trust_anchors,
            hx509_path *path,
-           hx509_certs pool, 
+           hx509_certs pool,
            hx509_cert current,
            hx509_cert *parent)
 {
@@ -1043,7 +1054,7 @@ find_parent(hx509_context context,
 
     *parent = NULL;
     memset(&ai, 0, sizeof(ai));
-    
+
     _hx509_query_clear(&q);
 
     if (!subject_null_p(current->data)) {
@@ -1122,8 +1133,8 @@ find_parent(hx509_context context,
  */
 
 static int
-is_proxy_cert(hx509_context context, 
-             const Certificate *cert, 
+is_proxy_cert(hx509_context context,
+             const Certificate *cert,
              ProxyCertInfo *rinfo)
 {
     ProxyCertInfo info;
@@ -1134,14 +1145,14 @@ is_proxy_cert(hx509_context context,
     if (rinfo)
        memset(rinfo, 0, sizeof(*rinfo));
 
-    e = find_extension(cert, oid_id_pkix_pe_proxyCertInfo(), &i);
+    e = find_extension(cert, &asn1_oid_id_pkix_pe_proxyCertInfo, &i);
     if (e == NULL) {
        hx509_clear_error_string(context);
        return HX509_EXTENSION_NOT_FOUND;
     }
 
-    ret = decode_ProxyCertInfo(e->extnValue.data, 
-                              e->extnValue.length, 
+    ret = decode_ProxyCertInfo(e->extnValue.data,
+                              e->extnValue.length,
                               &info,
                               &size);
     if (ret) {
@@ -1151,7 +1162,7 @@ is_proxy_cert(hx509_context context,
     if (size != e->extnValue.length) {
        free_ProxyCertInfo(&info);
        hx509_clear_error_string(context);
-       return HX509_EXTRA_DATA_AFTER_STRUCTURE; 
+       return HX509_EXTRA_DATA_AFTER_STRUCTURE;
     }
     if (rinfo == NULL)
        free_ProxyCertInfo(&info);
@@ -1187,7 +1198,7 @@ void
 _hx509_path_free(hx509_path *path)
 {
     unsigned i;
-    
+
     for (i = 0; i < path->len; i++)
        hx509_cert_free(path->val[i]);
     free(path->val);
@@ -1208,7 +1219,7 @@ _hx509_path_free(hx509_path *path)
  * The path includes a path from the top certificate to the anchor
  * certificate.
  *
- * The caller needs to free `path´ both on successful built path and
+ * The caller needs to free `path´ both on successful built path and
  * failure.
  */
 
@@ -1236,7 +1247,7 @@ _hx509_calculate_path(hx509_context context,
 
     while (!certificate_is_anchor(context, anchors, current)) {
 
-       ret = find_parent(context, time_now, anchors, path, 
+       ret = find_parent(context, time_now, anchors, path,
                          pool, current, &parent);
        hx509_cert_free(current);
        if (ret)
@@ -1256,8 +1267,8 @@ _hx509_calculate_path(hx509_context context,
        }
     }
 
-    if ((flags & HX509_CALCULATE_PATH_NO_ANCHOR) && 
-       path->len > 0 && 
+    if ((flags & HX509_CALCULATE_PATH_NO_ANCHOR) &&
+       path->len > 0 &&
        certificate_is_anchor(context, anchors, path->val[path->len - 1]))
     {
        hx509_cert_free(path->val[path->len - 1]);
@@ -1297,7 +1308,7 @@ _hx509_Certificate_cmp(const Certificate *p, const Certificate *q)
     diff = der_heim_bit_string_cmp(&p->signatureValue, &q->signatureValue);
     if (diff)
        return diff;
-    diff = _hx509_AlgorithmIdentifier_cmp(&p->signatureAlgorithm, 
+    diff = _hx509_AlgorithmIdentifier_cmp(&p->signatureAlgorithm,
                                          &q->signatureAlgorithm);
     if (diff)
        return diff;
@@ -1472,7 +1483,9 @@ hx509_cert_get_SPKI(hx509_context context, hx509_cert p, SubjectPublicKeyInfo *s
  * @param context a hx509 context.
  * @param p a hx509 certificate object.
  * @param alg AlgorithmIdentifier, should be freed with
- * free_AlgorithmIdentifier().
+ *            free_AlgorithmIdentifier(). The algorithmidentifier is
+ *            typicly rsaEncryption, or id-ecPublicKey, or some other
+ *            public key mechanism.
  *
  * @return An hx509 error code, see hx509_get_error_string().
  *
@@ -1481,7 +1494,7 @@ hx509_cert_get_SPKI(hx509_context context, hx509_cert p, SubjectPublicKeyInfo *s
 
 int
 hx509_cert_get_SPKI_AlgorithmIdentifier(hx509_context context,
-                                       hx509_cert p, 
+                                       hx509_cert p,
                                        AlgorithmIdentifier *alg)
 {
     int ret;
@@ -1534,7 +1547,7 @@ _hx509_cert_private_decrypt(hx509_context context,
     return _hx509_private_key_private_decrypt(context,
                                              ciphertext,
                                              encryption_oid,
-                                             p->private_key, 
+                                             p->private_key,
                                              cleartext);
 }
 
@@ -1623,7 +1636,7 @@ match_RDN(const RelativeDistinguishedName *c,
 
     if (c->len != n->len)
        return HX509_NAME_CONSTRAINT_ERROR;
-    
+
     for (i = 0; i < n->len; i++) {
        int diff, ret;
 
@@ -1654,13 +1667,13 @@ match_X501Name(const Name *c, const Name *n)
            return ret;
     }
     return 0;
-} 
+}
 
 
 static int
 match_general_name(const GeneralName *c, const GeneralName *n, int *match)
 {
-    /* 
+    /*
      * Name constraints only apply to the same name type, see RFC3280,
      * 4.2.1.11.
      */
@@ -1741,7 +1754,7 @@ match_general_name(const GeneralName *c, const GeneralName *n, int *match)
 }
 
 static int
-match_alt_name(const GeneralName *n, const Certificate *c, 
+match_alt_name(const GeneralName *n, const Certificate *c,
               int *same, int *match)
 {
     GeneralNames sa;
@@ -1790,14 +1803,14 @@ match_tree(const GeneralSubtrees *t, const Certificate *c, int *match)
            && !subject_null_p(c))
        {
            GeneralName certname;
-           
+       
            memset(&certname, 0, sizeof(certname));
            certname.element = choice_GeneralName_directoryName;
-           certname.u.directoryName.element = 
+           certname.u.directoryName.element =
                c->tbsCertificate.subject.element;
-           certname.u.directoryName.u.rdnSequence = 
+           certname.u.directoryName.u.rdnSequence =
                c->tbsCertificate.subject.u.rdnSequence;
-    
+
            ret = match_general_name(&t->val[i].base, &certname, &name);
        }
 
@@ -1814,7 +1827,7 @@ match_tree(const GeneralSubtrees *t, const Certificate *c, int *match)
 }
 
 static int
-check_name_constraints(hx509_context context, 
+check_name_constraints(hx509_context context,
                       const hx509_name_constraints *nc,
                       const Certificate *c)
 {
@@ -1978,13 +1991,13 @@ hx509_verify_path(hx509_context context,
                ret = certificate_is_self_signed(context, c, &selfsigned);
                if (ret)
                    goto out;
-               if (selfsigned) 
+               if (selfsigned)
                    selfsigned_depth++;
            }
 
            break;
        case PROXY_CERT: {
-           ProxyCertInfo info;     
+           ProxyCertInfo info; 
 
            if (is_proxy_cert(context, c, &info) == 0) {
                int j;
@@ -2003,24 +2016,24 @@ hx509_verify_path(hx509_context context,
                free_ProxyCertInfo(&info);
                
                j = 0;
-               if (find_extension(c, oid_id_x509_ce_subjectAltName(), &j)) {
+               if (find_extension(c, &asn1_oid_id_x509_ce_subjectAltName, &j)) {
                    ret = HX509_PROXY_CERT_INVALID;
-                   hx509_set_error_string(context, 0, ret, 
+                   hx509_set_error_string(context, 0, ret,
                                           "Proxy certificate have explicity "
                                           "forbidden subjectAltName");
                    goto out;
                }
 
                j = 0;
-               if (find_extension(c, oid_id_x509_ce_issuerAltName(), &j)) {
+               if (find_extension(c, &asn1_oid_id_x509_ce_issuerAltName, &j)) {
                    ret = HX509_PROXY_CERT_INVALID;
-                   hx509_set_error_string(context, 0, ret, 
+                   hx509_set_error_string(context, 0, ret,
                                           "Proxy certificate have explicity "
                                           "forbidden issuerAltName");
                    goto out;
                }
                        
-               /* 
+               /*
                 * The subject name of the proxy certificate should be
                 * CN=XXX,<proxy issuer>, prune of CN and check if its
                 * the same over the whole chain of proxy certs and
@@ -2050,10 +2063,10 @@ hx509_verify_path(hx509_context context,
                }
 
                j = proxy_issuer.u.rdnSequence.len;
-               if (proxy_issuer.u.rdnSequence.len < 2 
+               if (proxy_issuer.u.rdnSequence.len < 2
                    || proxy_issuer.u.rdnSequence.val[j - 1].len > 1
                    || der_heim_oid_cmp(&proxy_issuer.u.rdnSequence.val[j - 1].val[0].type,
-                                       oid_id_at_commonName()))
+                                       &asn1_oid_id_at_commonName))
                {
                    ret = HX509_PROXY_CERT_NAME_WRONG;
                    hx509_set_error_string(context, 0, ret,
@@ -2080,7 +2093,7 @@ hx509_verify_path(hx509_context context,
 
                break;
            } else {
-               /* 
+               /*
                 * Now we are done with the proxy certificates, this
                 * cert was an EE cert and we we will fall though to
                 * EE checking below.
@@ -2097,7 +2110,7 @@ hx509_verify_path(hx509_context context,
             */
            if (proxy_cert_depth) {
 
-               ret = _hx509_name_cmp(&proxy_issuer, 
+               ret = _hx509_name_cmp(&proxy_issuer,
                                      &c->tbsCertificate.subject, &diff);
                if (ret) {
                    hx509_set_error_string(context, 0, ret, "out of memory");
@@ -2121,11 +2134,11 @@ hx509_verify_path(hx509_context context,
            break;
        }
 
-       ret = check_basic_constraints(context, c, type, 
+       ret = check_basic_constraints(context, c, type,
                                      i - proxy_cert_depth - selfsigned_depth);
        if (ret)
            goto out;
-           
+       
        /*
         * Don't check the trust anchors expiration time since they
         * are transported out of band, from RFC3820.
@@ -2211,7 +2224,7 @@ hx509_verify_path(hx509_context context,
            int parent = (i < path.len - 1) ? i + 1 : i;
 
            ret = hx509_revoke_verify(context,
-                                     ctx->revoke_ctx, 
+                                     ctx->revoke_ctx,
                                      certs,
                                      ctx->time_now,
                                      path.val[i],
@@ -2263,6 +2276,24 @@ hx509_verify_path(hx509_context context,
                                   "Failed to verify signature of certificate");
            goto out;
        }
+       /* 
+        * Verify that the sigature algorithm "best-before" date is
+        * before the creation date of the certificate, do this for
+        * trust anchors too, since any trust anchor that is created
+        * after a algorithm is known to be bad deserved to be invalid.
+        *
+        * Skip the leaf certificate for now...
+        */
+
+       if (i != 0 && (ctx->flags & HX509_VERIFY_CTX_F_NO_BEST_BEFORE_CHECK) == 0) {
+           time_t notBefore = 
+               _hx509_Time2time_t(&c->tbsCertificate.validity.notBefore);
+           ret = _hx509_signature_best_before(context,
+                                              &c->signatureAlgorithm,
+                                              notBefore);
+           if (ret)
+               goto out;
+       }
     }
 
 out:
@@ -2326,9 +2357,10 @@ hx509_verify_hostname(hx509_context context,
                      hx509_hostname_type type,
                      const char *hostname,
                      const struct sockaddr *sa,
-                     /* XXX krb5_socklen_t */ int sa_size) 
+                     /* XXX krb5_socklen_t */ int sa_size)
 {
     GeneralNames san;
+    const Name *name;
     int ret, i, j;
 
     if (sa && sa_size <= 0)
@@ -2339,11 +2371,10 @@ hx509_verify_hostname(hx509_context context,
     i = 0;
     do {
        ret = find_extension_subject_alt_name(cert->data, &i, &san);
-       if (ret == HX509_EXTENSION_NOT_FOUND) {
-           ret = 0;
-           break;
-       } else if (ret != 0)
+       if (ret == HX509_EXTENSION_NOT_FOUND)
            break;
+       else if (ret != 0)
+           return HX509_PARSING_NAME_FAILED;
 
        for (j = 0; j < san.len; j++) {
            switch (san.val[j].element) {
@@ -2360,31 +2391,31 @@ hx509_verify_hostname(hx509_context context,
        free_GeneralNames(&san);
     } while (1);
 
-    {
-       const Name *name = &cert->data->tbsCertificate.subject;
-
-       /* match if first component is a CN= */
-       if (name->u.rdnSequence.len > 0
-           && name->u.rdnSequence.val[0].len == 1
-           && der_heim_oid_cmp(&name->u.rdnSequence.val[0].val[0].type,
-                               oid_id_at_commonName()) == 0)
-       {
-           DirectoryString *ds = &name->u.rdnSequence.val[0].val[0].value;
-
-           switch (ds->element) {
-           case choice_DirectoryString_printableString:
-               if (strcasecmp(ds->u.printableString, hostname) == 0)
+    name = &cert->data->tbsCertificate.subject;
+
+    /* Find first CN= in the name, and try to match the hostname on that */
+    for (ret = 0, i = name->u.rdnSequence.len - 1; ret == 0 && i >= 0; i--) {
+       for (j = 0; ret == 0 && j < name->u.rdnSequence.val[i].len; j++) {
+           AttributeTypeAndValue *n = &name->u.rdnSequence.val[i].val[j];
+
+           if (der_heim_oid_cmp(&n->type, &asn1_oid_id_at_commonName) == 0) {
+               DirectoryString *ds = &n->value;
+               switch (ds->element) {
+               case choice_DirectoryString_printableString:
+                   if (strcasecmp(ds->u.printableString, hostname) == 0)
+                       return 0;
+                   break;
+               case choice_DirectoryString_ia5String:
+                   if (strcasecmp(ds->u.ia5String, hostname) == 0)
                    return 0;
-               break;
-           case choice_DirectoryString_ia5String:
-               if (strcasecmp(ds->u.ia5String, hostname) == 0)
-                   return 0;
-               break;
-           case choice_DirectoryString_utf8String:
-               if (strcasecmp(ds->u.utf8String, hostname) == 0)
-                   return 0;
-           default:
-               break;
+                   break;
+               case choice_DirectoryString_utf8String:
+                   if (strcasecmp(ds->u.utf8String, hostname) == 0)
+                       return 0;
+               default:
+                   break;
+               }
+               ret = HX509_NAME_CONSTRAINT_ERROR;
            }
        }
     }
@@ -2397,8 +2428,8 @@ hx509_verify_hostname(hx509_context context,
 
 int
 _hx509_set_cert_attribute(hx509_context context,
-                         hx509_cert cert, 
-                         const heim_oid *oid, 
+                         hx509_cert cert,
+                         const heim_oid *oid,
                          const heim_octet_string *attr)
 {
     hx509_cert_attribute a;
@@ -2407,7 +2438,7 @@ _hx509_set_cert_attribute(hx509_context context,
     if (hx509_cert_get_attribute(cert, oid) != NULL)
        return 0;
 
-    d = realloc(cert->attrs.val, 
+    d = realloc(cert->attrs.val,
                sizeof(cert->attrs.val[0]) * (cert->attrs.len + 1));
     if (d == NULL) {
        hx509_clear_error_string(context);
@@ -2421,7 +2452,7 @@ _hx509_set_cert_attribute(hx509_context context,
 
     der_copy_octet_string(attr, &a->data);
     der_copy_oid(oid, &a->oid);
-    
+
     cert->attrs.val[cert->attrs.len] = a;
     cert->attrs.len++;
 
@@ -2495,7 +2526,7 @@ hx509_cert_get_friendly_name(hx509_cert cert)
     if (cert->friendlyname)
        return cert->friendlyname;
 
-    a = hx509_cert_get_attribute(cert, oid_id_pkcs_9_at_friendlyName());
+    a = hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_friendlyName);
     if (a == NULL) {
        hx509_name name;
 
@@ -2517,13 +2548,13 @@ hx509_cert_get_friendly_name(hx509_cert cert)
        free_PKCS9_friendlyName(&n);
        return NULL;
     }
-    
+
     cert->friendlyname = malloc(n.val[0].length + 1);
     if (cert->friendlyname == NULL) {
        free_PKCS9_friendlyName(&n);
        return NULL;
     }
-    
+
     for (i = 0; i < n.val[0].length; i++) {
        if (n.val[0].data[i] <= 0xff)
            cert->friendlyname[i] = n.val[0].data[i] & 0xff;
@@ -2611,7 +2642,7 @@ hx509_query_match_option(hx509_query *q, hx509_query_option option)
 
 int
 hx509_query_match_issuer_serial(hx509_query *q,
-                               const Name *issuer, 
+                               const Name *issuer,
                                const heim_integer *serialNumber)
 {
     int ret;
@@ -2746,7 +2777,7 @@ hx509_query_match_expr(hx509_context context, hx509_query *q, const char *expr)
 
 int
 hx509_query_match_cmp_func(hx509_query *q,
-                          int (*func)(void *, hx509_cert),
+                          int (*func)(hx509_context, hx509_cert, void *),
                           void *ctx)
 {
     if (func)
@@ -2840,7 +2871,7 @@ _hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509_cert
     }
     if ((q->match & HX509_QUERY_MATCH_ISSUER_ID))
        return 0;
-    if ((q->match & HX509_QUERY_PRIVATE_KEY) && 
+    if ((q->match & HX509_QUERY_PRIVATE_KEY) &&
        _hx509_cert_private_key(cert) == NULL)
        return 0;
 
@@ -2869,7 +2900,7 @@ _hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509_cert
     if (q->match & HX509_QUERY_MATCH_LOCAL_KEY_ID) {
        hx509_cert_attribute a;
 
-       a = hx509_cert_get_attribute(cert, oid_id_pkcs_9_at_localKeyId());
+       a = hx509_cert_get_attribute(cert, &asn1_oid_id_pkcs_9_at_localKeyId);
        if (a == NULL)
            return 0;
        if (der_heim_octet_string_cmp(&a->data, q->local_key_id) != 0)
@@ -2891,7 +2922,7 @@ _hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509_cert
            return 0;
     }
     if (q->match & HX509_QUERY_MATCH_FUNCTION) {
-       ret = (*q->cmp_func)(q->cmp_func_ctx, cert);
+       ret = (*q->cmp_func)(context, cert, q->cmp_func_ctx);
        if (ret != 0)
            return 0;
     }
@@ -2900,7 +2931,7 @@ _hx509_query_match_cert(hx509_context context, const hx509_query *q, hx509_cert
        heim_octet_string os;
 
        os.data = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
-       os.length = 
+       os.length =
            c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
 
        ret = _hx509_verify_signature(context,
@@ -3039,12 +3070,12 @@ hx509_query_unparse_stats(hx509_context context, int printtype, FILE *out)
        return;
     f = fopen(context->querystat, "r");
     if (f == NULL) {
-       fprintf(out, "No statistic file %s: %s.\n", 
+       fprintf(out, "No statistic file %s: %s.\n",
                context->querystat, strerror(errno));
        return;
     }
     rk_cloexec_file(f);
-    
+
     for (i = 0; i < sizeof(stats)/sizeof(stats[0]); i++) {
        stats[i].index = i;
        stats[i].stats = 0;
@@ -3075,7 +3106,7 @@ hx509_query_unparse_stats(hx509_context context, int printtype, FILE *out)
        errx(1, "out of memory");
 
     rtbl_set_separator (t, "  ");
-    
+
     rtbl_add_column_by_id (t, 0, "Name", 0);
     rtbl_add_column_by_id (t, 1, "Counter", 0);
 
@@ -3083,7 +3114,7 @@ hx509_query_unparse_stats(hx509_context context, int printtype, FILE *out)
     for (i = 0; i < sizeof(stats)/sizeof(stats[0]); i++) {
        char str[10];
 
-       if (stats[i].index < sizeof(statname)/sizeof(statname[0])) 
+       if (stats[i].index < sizeof(statname)/sizeof(statname[0]))
            rtbl_add_column_entry_by_id (t, 0, statname[stats[i].index]);
        else {
            snprintf(str, sizeof(str), "%d", stats[i].index);
@@ -3096,7 +3127,7 @@ hx509_query_unparse_stats(hx509_context context, int printtype, FILE *out)
     rtbl_format(t, out);
     rtbl_destroy(t);
 
-    fprintf(out, "\nQueries: multi %lu total %lu\n", 
+    fprintf(out, "\nQueries: multi %lu total %lu\n",
            multiqueries, totalqueries);
 }
 
@@ -3163,10 +3194,10 @@ _hx509_cert_get_keyusage(hx509_context context,
     if (_hx509_cert_get_version(cert) < 3)
        return 0;
 
-    e = find_extension(cert, oid_id_x509_ce_keyUsage(), &i);
+    e = find_extension(cert, &asn1_oid_id_x509_ce_keyUsage, &i);
     if (e == NULL)
        return HX509_KU_CERT_MISSING;
-    
+
     ret = decode_KeyUsage(e->extnValue.data, e->extnValue.length, ku, &size);
     if (ret)
        return ret;
@@ -3212,7 +3243,7 @@ hx509_cert_binary(hx509_context context, hx509_cert c, heim_octet_string *os)
     os->data = NULL;
     os->length = 0;
 
-    ASN1_MALLOC_ENCODE(Certificate, os->data, os->length, 
+    ASN1_MALLOC_ENCODE(Certificate, os->data, os->length,
                       _hx509_get_cert(c), &size, ret);
     if (ret) {
        os->data = NULL;
@@ -3348,6 +3379,45 @@ _hx509_cert_to_env(hx509_context context, hx509_cert cert, hx509_env *env)
        }
     }
 
+    {
+       Certificate *c = _hx509_get_cert(cert);
+        heim_octet_string os, sig;
+       hx509_env envhash = NULL;
+
+       os.data = c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.data;
+       os.length =
+         c->tbsCertificate.subjectPublicKeyInfo.subjectPublicKey.length / 8;
+
+       ret = _hx509_create_signature(context,
+                                     NULL,
+                                     hx509_signature_sha1(),
+                                     &os,
+                                     NULL,
+                                     &sig);
+       if (ret != 0)
+           goto out;
+
+       ret = hex_encode(sig.data, sig.length, &buf);
+       der_free_octet_string(&sig);
+       if (ret < 0) {
+           ret = ENOMEM;
+           hx509_set_error_string(context, 0, ret,
+                                  "Out of memory");
+           goto out;
+       }
+       
+       ret = hx509_env_add(context, &envhash, "sha1", buf);
+       free(buf);
+       if (ret) 
+           goto out;
+
+       ret = hx509_env_add_binding(context, &envcert, "hash", envhash);
+       if (ret) {
+         hx509_env_free(&envhash);
+         goto out;
+       }
+    }
+
     ret = hx509_env_add_binding(context, env, "certificate", envcert);
     if (ret)
        goto out;