@ 69e3ad85cc0f4df2aca759df28acafb505578821 | history
package policy
import (
"crypto/x509"
"encoding/asn1"
"errors"
"fmt"
"strings"
"unicode/utf16"
)
var idQtUnotice = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 2, 2}
// policyInformation is one entry of certificatePolicies. The identifier is
// kept raw: encoding/asn1 holds OID arcs in an int, and the GOV root's
// 123-bit arc does not fit, so x509.OID decodes it instead.
type policyInformation struct {
ID asn1.RawValue
Qualifiers []policyQualifierInfo `asn1:"optional"`
}
type policyQualifierInfo struct {
ID asn1.ObjectIdentifier
Qualifier asn1.RawValue
}
// notesIn reads the user-notice text attached to each policy in a cert,
// keyed like byPolicy. Go parses certificatePolicies into bare OIDs and
// drops the qualifiers, so this reads the extension's bytes itself. Other
// qualifier kinds (CPS pointers) are skipped, as RFC 5280 allows.
func notesIn(c *x509.Certificate) (map[string]string, error) {
var raw []byte
for _, ext := range c.Extensions {
if ext.Id.Equal(oidCertificatePolicies) {
raw = ext.Value
}
}
if raw == nil {
return nil, nil
}
var infos []policyInformation
if rest, err := asn1.Unmarshal(raw, &infos); err != nil || len(rest) > 0 {
return nil, fmt.Errorf("certificatePolicies does not parse: %v", err)
}
notes := map[string]string{}
for _, info := range infos {
var id x509.OID
if err := id.UnmarshalBinary(info.ID.Bytes); err != nil {
return nil, err
}
var text strings.Builder
for _, q := range info.Qualifiers {
if !q.ID.Equal(idQtUnotice) {
continue
}
t, err := explicitText(q.Qualifier.FullBytes)
if err != nil {
return nil, err
}
text.WriteString(t)
}
if text.Len() > 0 {
notes[key(id)] = text.String()
}
}
return notes, nil
}
// explicitText reads a UserNotice ::= SEQUENCE { noticeRef OPTIONAL,
// explicitText OPTIONAL }. The two optional fields have different types, so
// it reads the elements and takes the one that is a string.
func explicitText(userNotice []byte) (string, error) {
var elems []asn1.RawValue
if rest, err := asn1.Unmarshal(userNotice, &elems); err != nil || len(rest) > 0 {
return "", errors.New("a user notice does not parse")
}
for _, e := range elems {
if e.Class != asn1.ClassUniversal {
continue
}
switch e.Tag {
case asn1.TagUTF8String, asn1.TagIA5String, 26: // 26 is VisibleString
return string(e.Bytes), nil
case asn1.TagBMPString:
if len(e.Bytes)%2 != 0 {
return "", errors.New("a BMPString has an odd length")
}
units := make([]uint16, len(e.Bytes)/2)
for i := range units {
units[i] = uint16(e.Bytes[2*i])<<8 | uint16(e.Bytes[2*i+1])
}
return string(utf16.Decode(units)), nil
}
}
return "", nil
}