dns/tlsa.go

78 lines
1.9 KiB
Go
Raw Normal View History

2012-09-14 17:48:52 +10:00
package dns
import (
"crypto/sha256"
"crypto/sha512"
"crypto/x509"
"encoding/hex"
"io"
"net"
"strconv"
)
// CertificateToDANE converts a certificate to a hex string as used in the TLSA record.
func CertificateToDANE(selector, matchingType uint8, cert *x509.Certificate) string {
2012-09-14 19:56:02 +10:00
switch matchingType {
case 0:
2012-09-14 19:56:02 +10:00
switch selector {
case 0:
2012-09-14 19:56:02 +10:00
return hex.EncodeToString(cert.Raw)
case 1:
2012-09-14 19:56:02 +10:00
return hex.EncodeToString(cert.RawSubjectPublicKeyInfo)
}
case 1:
h := sha256.New()
2012-09-14 19:56:02 +10:00
switch selector {
case 0:
2012-09-14 19:56:02 +10:00
return hex.EncodeToString(cert.Raw)
case 1:
io.WriteString(h, string(cert.RawSubjectPublicKeyInfo))
2012-09-14 19:56:02 +10:00
return hex.EncodeToString(h.Sum(nil))
}
case 2:
h := sha512.New()
2012-09-14 19:56:02 +10:00
switch selector {
case 0:
2012-09-14 19:56:02 +10:00
return hex.EncodeToString(cert.Raw)
case 1:
io.WriteString(h, string(cert.RawSubjectPublicKeyInfo))
2012-09-14 19:56:02 +10:00
return hex.EncodeToString(h.Sum(nil))
}
}
2012-09-14 19:56:02 +10:00
return ""
}
2012-09-15 01:11:14 +10:00
// Sign creates a TLSA record from an SSL certificate.
func (r *TLSA) Sign(usage, selector, matchingType int, cert *x509.Certificate) error {
2012-09-14 19:56:02 +10:00
r.Hdr.Rrtype = TypeTLSA
r.Usage = uint8(usage)
r.Selector = uint8(selector)
r.MatchingType = uint8(matchingType)
r.Certificate = CertificateToDANE(r.Selector, r.MatchingType, cert)
return nil
2012-09-14 17:48:52 +10:00
}
2012-09-15 01:11:14 +10:00
// Verify verifies a TLSA record against an SSL certificate. If it is OK
2012-09-14 19:45:48 +10:00
// a nil error is returned.
func (r *TLSA) Verify(cert *x509.Certificate) error {
if r.Certificate == CertificateToDANE(r.Selector, r.MatchingType, cert) {
2012-09-14 19:56:02 +10:00
return nil
}
2012-10-11 07:17:50 +11:00
return ErrSig // ErrSig, really?
}
2012-09-14 17:48:52 +10:00
2012-09-14 22:29:52 +10:00
// TLSAName returns the ownername of a TLSA resource record as per the
2012-09-15 01:11:14 +10:00
// rules specified in RFC 6698, Section 3. When an error occurs the
2012-09-14 22:29:52 +10:00
// empty string is returned.
func TLSAName(name, service, network string) string {
if !IsFqdn(name) {
2012-09-14 22:29:52 +10:00
return ""
}
p, e := net.LookupPort(network, service)
if e != nil {
2012-09-14 22:29:52 +10:00
return ""
}
2012-09-14 22:29:52 +10:00
return "_" + strconv.Itoa(p) + "_" + network + "." + name
2012-09-14 17:48:52 +10:00
}