diff --git a/dns.go b/dns.go new file mode 100644 index 0000000..d9e1790 --- /dev/null +++ b/dns.go @@ -0,0 +1,435 @@ +package dns_api + +import ( + "encoding/base64" + "errors" + "fmt" + "git.gammaspectra.live/givna.me/dns-api/ed25519" + "github.com/miekg/dns" + "math" + "net" + "strings" + "time" +) + +type RRSet []dns.RR + +func (l RRSet) Get(rrt uint16, name string) (rrset RRSet) { + for _, rr := range l { + if rr != nil && rr.Header().Rrtype == rrt && rr.Header().Name == name { + rrset = append(rrset, rr) + } + } + + return +} + +func (l RRSet) Delete(rrt uint16, name string) { + for i, rr := range l { + if rr != nil && rr.Header().Rrtype == rrt && rr.Header().Name == name { + l[i] = nil + } + } +} + +type Zone struct { + publicKey ed25519.PublicKey + privateKey ed25519.PrivateKey + + dnsKey *dns.DNSKEY + + rrset RRSet + + enforcedEntries RRSet +} + +func NewZoneFromPrivateKey(baseZone string, privateKey ed25519.PrivateKey) *Zone { + zone := NewZoneFromPublicKey(baseZone, privateKey.Public().(ed25519.PublicKey)) + if zone == nil { + return nil + } + + zone.privateKey = privateKey + + return zone +} + +func NewZoneFromPublicKey(baseZone string, publicKey ed25519.PublicKey) *Zone { + if len(baseZone) == 0 || baseZone[len(baseZone)-1] != '.' { + return nil + } + + zone := &Zone{ + publicKey: publicKey, + } + + zone.dnsKey = new(dns.DNSKEY) + zone.dnsKey.Hdr.Rrtype = dns.TypeDNSKEY + zone.dnsKey.Hdr.Name = PublicKeyToOnionV3(publicKey) + "." + baseZone + zone.dnsKey.Hdr.Class = dns.ClassINET + //public key cannot expire + zone.dnsKey.Hdr.Ttl = 2147483647 + zone.dnsKey.Flags = 257 //KSK + zone.dnsKey.Protocol = 3 + zone.dnsKey.Algorithm = dns.ED25519 + zone.dnsKey.PublicKey = base64.StdEncoding.EncodeToString(publicKey) + + return zone +} + +func (z *Zone) DeleteRR(rrtype string, name string) error { + rrt, ok := dns.StringToType[rrtype] + if !ok { + return fmt.Errorf("could not find record type for %s", rrtype) + } + + z.rrset.Delete(rrt, name) + return nil +} + +func (z *Zone) GetRR(rrtype string, name string) (rrset RRSet) { + rrt, ok := dns.StringToType[rrtype] + if !ok { + return nil + } + + return z.rrset.Get(rrt, name) +} + +func (z *Zone) AddRR(rr dns.RR) error { + if rr == nil { + return errors.New("no valid record found") + } + + if !strings.HasSuffix(rr.Header().Name, z.Name()) { + return fmt.Errorf("%s is not part of %s", rr.Header().Name, z.Name()) + } + + z.rrset = append(z.rrset, rr) + + return nil +} + +func (z *Zone) AddRecord(name string, ttl uint32, rr dns.RR) error { + if rr == nil { + return errors.New("no valid record found") + } + hdr := rr.Header() + hdr.Name = name + hdr.Class = dns.ClassINET + hdr.Ttl = ttl + + return z.AddRR(rr) +} + +func (z *Zone) AddRecordA(name string, ip net.IP, ttl uint32) error { + ip = ip.To4() + if ip == nil { + return errors.New("invalid ipv4") + } + + record := new(dns.A) + record.Hdr.Rrtype = dns.TypeA + record.A = ip + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordAAAA(name string, ip net.IP, ttl uint32) error { + ip = ip.To16() + if ip == nil { + return errors.New("invalid ipv6") + } + + record := new(dns.AAAA) + record.Hdr.Rrtype = dns.TypeAAAA + record.AAAA = ip + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordCNAME(name string, target string, ttl uint32) error { + record := new(dns.CNAME) + record.Hdr.Rrtype = dns.TypeCNAME + record.Target = target + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordTXT(name string, txt []string, ttl uint32) error { + record := new(dns.TXT) + record.Hdr.Rrtype = dns.TypeTXT + record.Txt = txt + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordCAA(name string, flag uint8, tag, value string, ttl uint32) error { + record := new(dns.CAA) + record.Hdr.Rrtype = dns.TypeCAA + record.Flag = flag + record.Tag = tag + record.Value = value + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordTLSA(name string, usage, selector, matchingType uint8, certificate string, ttl uint32) error { + record := new(dns.TLSA) + record.Hdr.Rrtype = dns.TypeTLSA + record.Usage = usage + record.Selector = selector + record.MatchingType = matchingType + record.Certificate = certificate + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordSVCB(name string, priority uint16, target string, value []dns.SVCBKeyValue, ttl uint32) error { + record := new(dns.SVCB) + record.Hdr.Rrtype = dns.TypeSVCB + record.Priority = priority + record.Target = target + record.Value = value + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordHTTPS(name string, priority uint16, target string, value []dns.SVCBKeyValue, ttl uint32) error { + record := new(dns.HTTPS) + record.Hdr.Rrtype = dns.TypeHTTPS + record.Priority = priority + record.Target = target + record.Value = value + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordSSHFP(name string, algorithm, ktype uint8, fingerprint string, ttl uint32) error { + record := new(dns.SSHFP) + record.Hdr.Rrtype = dns.TypeSSHFP + record.Algorithm = algorithm + record.Type = ktype + record.FingerPrint = fingerprint + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) AddRecordMX(name string, preference uint16, mx string, ttl uint32) error { + record := new(dns.MX) + record.Hdr.Rrtype = dns.TypeMX + record.Preference = preference + record.Mx = mx + return z.AddRecord(name, ttl, record) +} + +func (z *Zone) SetRR(rrtype string, name string, rrset RRSet) error { + + rrt, ok := dns.StringToType[rrtype] + if !ok { + return fmt.Errorf("could not find record type for %s", rrtype) + } + + z.rrset.Delete(rrt, name) + + for i, rr := range rrset { + if rr != nil && rr.Header().Rrtype != rrt { + return fmt.Errorf("expected %s, got record type %s at index %d", rrtype, dns.TypeToString[rr.Header().Rrtype], i) + } + } + + for _, rr := range rrset { + if rr != nil { + if err := z.AddRR(rr); err != nil { + return err + } + } + } + + return nil +} + +func (z *Zone) GetRRSet() RRSet { + + set := make(RRSet, 0, len(z.rrset)) + for _, rr := range z.rrset { + if rr != nil { + set = append(set, rr) + } + } + return set +} + +func (z *Zone) AddMissingRecords() { + func() { + for _, rr := range z.rrset.Get(dns.TypeDNSKEY, z.Name()) { + if k, ok := rr.(*dns.DNSKEY); ok { + if k.Flags == z.dnsKey.Flags && k.PublicKey == z.dnsKey.PublicKey && k.Algorithm == z.dnsKey.Algorithm { + return + } + } + } + z.AddRR(z.dnsKey) + }() + + func() { + for _, rr := range z.rrset.Get(dns.TypeCDNSKEY, z.Name()) { + if k, ok := rr.(*dns.CDNSKEY); ok { + if k.Flags == z.dnsKey.Flags && k.PublicKey == z.dnsKey.PublicKey && k.Algorithm == z.dnsKey.Algorithm { + return + } + } + } + cdnskey := dns.CDNSKEY{DNSKEY: *z.dnsKey} + cdnskey.Hdr.Rrtype = dns.TypeCDNSKEY + z.AddRR(&cdnskey) + }() + + func() { + ds := z.dnsKey.ToDS(dns.SHA256) + if ds == nil { + return + } + for _, rr := range z.rrset.Get(dns.TypeCDS, z.Name()) { + if k, ok := rr.(*dns.CDS); ok { + if k.KeyTag == ds.KeyTag && k.Digest == ds.Digest { + return + } + } + } + + cds := dns.CDS{DS: *ds} + cds.Hdr.Rrtype = dns.TypeCDS + z.AddRR(&cds) + }() +} + +func (z *Zone) Sign() (rrsigs []*dns.RRSIG, err error) { + + var types []uint16 + var names []string + + inTypes := func(i uint16) bool { + if i == dns.TypeRRSIG || + i == dns.TypeDS || + i == dns.TypeTA || + i == dns.TypeSOA || + i == dns.TypeRP { + return true + } + for _, j := range types { + if i == j { + return true + } + } + return false + } + + inNames := func(i string) bool { + for _, j := range names { + if i == j { + return true + } + } + return false + } + + z.AddMissingRecords() + + for _, rr := range z.rrset { + if rr == nil { + continue + } + h := rr.Header() + if !inTypes(h.Rrtype) { + types = append(types, h.Rrtype) + } + if !inNames(h.Name) { + names = append(names, h.Name) + } + } + + //TODO: do check, remove entries + /* + //TODO: make this an allowlist + if rrt == dns.TypeRRSIG || + rrt == dns.TypeDNSKEY || + rrt == dns.TypeCDNSKEY || + rrt == dns.TypeDS || + rrt == dns.TypeCDS || + rrt == dns.TypeNS || + rrt == dns.TypeTA || + rrt == dns.TypeRP || + rrt == dns.TypeSOA { //TODO: allow changing some but with verification of values + return fmt.Errorf("type %s not allowed", rrtype) + } + */ + + //Check if another ZSK key exists for zones, otherwise behave as CSK + + var isKSKOnly bool + for _, rr := range z.rrset.Get(dns.TypeDNSKEY, z.Name()) { + if k, ok := rr.(*dns.DNSKEY); ok { + //found ZSK key that is not ours + if k.Flags == 256 && k.PublicKey != z.dnsKey.PublicKey && k.Algorithm == z.dnsKey.Algorithm { + isKSKOnly = true + break + } + } + } + + //only sign DNSKEY, CDNSKEY, DS, CDS as KSK + if isKSKOnly { + types = []uint16{dns.TypeDS, dns.TypeCDS, dns.TypeDNSKEY, dns.TypeCDNSKEY} + } + + for _, rname := range names { + for _, rtype := range types { + rrset := z.rrset.Get(rtype, rname) + if len(rrset) > 0 { + rrsig, err := z.SignRRSet(rrset) + if err != nil { + return nil, err + } else { + rrsigs = append(rrsigs, rrsig) + } + } + } + } + + return rrsigs, nil +} + +//TODO: implement NSEC or similar + +func (z *Zone) SignRRSet(rrset RRSet) (*dns.RRSIG, error) { + if rrset == nil || len(rrset) == 0 { + return nil, errors.New("no records to sign") + } + + if z.privateKey == nil { + return nil, errors.New("nil private key") + } + + sig := new(dns.RRSIG) + //67 years or max uint32, RFC 4034 points to RFC1982 for max of 68y period + expirationTime := time.Now().UTC().AddDate(67, 0, 0).Unix() + if expirationTime > math.MaxUint32 { + expirationTime = math.MaxUint32 + } + + sig.Expiration = uint32(expirationTime) + sig.Inception = uint32(time.Now().UTC().Add(-time.Hour).Unix()) //add one hour in the past + sig.KeyTag = z.dnsKey.KeyTag() + sig.SignerName = z.dnsKey.Hdr.Name + sig.Algorithm = z.dnsKey.Algorithm + + if err := sig.Sign(z.privateKey, rrset); err != nil { + return nil, err + } + + return sig, nil +} + +func (z *Zone) Name() string { + return z.dnsKey.Hdr.Name +} + +func (z *Zone) DNSKEY() *dns.DNSKEY { + return z.dnsKey +} + +func (z *Zone) PubKey() ed25519.PublicKey { + return z.publicKey +} diff --git a/dns_test.go b/dns_test.go new file mode 100644 index 0000000..4a86b65 --- /dev/null +++ b/dns_test.go @@ -0,0 +1,32 @@ +package dns_api + +import ( + "net" + "testing" +) + +const testZone = "example.com." + +func TestRecordSign(t *testing.T) { + + zone := NewZoneFromPrivateKey(testZone, DecodeTorPrivateKey(testPrivateKey)) + t.Logf("zone name %s", zone.Name()) + + if err := zone.AddRecordA("test."+zone.Name(), net.IPv4(1, 2, 3, 4), 3600); err != nil { + t.Error(err) + } + + rrsigs, err := zone.Sign() + + if err != nil { + t.Error(err) + } + + for _, rr := range zone.GetRRSet() { + t.Logf(" %s\n", rr.String()) + } + + for _, rr := range rrsigs { + t.Logf(" %s\n", rr.String()) + } +} diff --git a/ed25519/key.go b/ed25519/key.go index 2eda9ae..2afebf2 100644 --- a/ed25519/key.go +++ b/ed25519/key.go @@ -5,6 +5,7 @@ import ( "crypto" goEd25519 "crypto/ed25519" "crypto/sha512" + "errors" "filippo.io/edwards25519" "io" "strconv" @@ -33,6 +34,19 @@ func Sign(privateKey PrivateKey, message []byte) []byte { return signature } +// Sign signs the given message with priv. +// Ed25519 performs two passes over messages to be signed and therefore cannot +// handle pre-hashed messages. Thus opts.HashFunc() must return zero to +// indicate the message hasn't been hashed. This can be achieved by passing +// crypto.Hash(0) as the value for opts. +func (priv PrivateKey) Sign(rand io.Reader, message []byte, opts crypto.SignerOpts) (signature []byte, err error) { + if opts.HashFunc() != crypto.Hash(0) { + return nil, errors.New("ed25519: cannot sign hashed message") + } + + return Sign(priv, message), nil +} + func sign(signature, privateKey, message []byte) { if l := len(privateKey); l != PrivateKeySize { panic("ed25519: bad private key length: " + strconv.Itoa(l)) diff --git a/go.mod b/go.mod index 30b23cf..dcda304 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,13 @@ go 1.18 require ( filippo.io/edwards25519 v1.0.0 + github.com/miekg/dns v1.1.49 golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e ) -require golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect +require ( + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect + golang.org/x/net v0.0.0-20220607020251-c690dde0001d // indirect + golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098 // indirect + golang.org/x/tools v0.1.11 // indirect +) diff --git a/go.sum b/go.sum index 13c5efd..aaa8683 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,42 @@ filippo.io/edwards25519 v1.0.0 h1:0wAIcmJUqRdI8IJ/3eGi5/HwXZWPujYXXlkrQogz0Ek= filippo.io/edwards25519 v1.0.0/go.mod h1:N1IkdkCkiLB6tki+MYJoSx2JTY9NUlxZE7eHn5EwJns= +github.com/miekg/dns v1.1.49 h1:qe0mQU3Z/XpFeE+AEBo2rqaS1IPBJ3anmqZ4XiZJVG8= +github.com/miekg/dns v1.1.49/go.mod h1:e3IlAVfNqAllflbibAZEWOXOQ+Ynzk/dDozDxY7XnME= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e h1:T8NU3HyQ8ClP4SEE+KbFlg6n0NhuTsN4MyznaarGsZM= golang.org/x/crypto v0.0.0-20220525230936-793ad666bf5e/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210726213435-c6fcb2dbf985/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d h1:4SFsTMi4UahlKoloni7L4eYzhFRifURQLw+yv0QDCx8= +golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c h1:5KslGYwFpkhGh+Q16bwMP3cOontH8FOep7tGV86Y7SQ= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098 h1:PgOr27OhUx2IRqGJ2RxAWI4dJQ7bi9cSrB82uzFzfUA= +golang.org/x/sys v0.0.0-20220614162138-6c1b26c55098/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.6-0.20210726203631-07bc1bf47fb2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.11 h1:loJ25fNOEhSXfHrpoGj91eCUThwdNX6u24rO1xnNteY= +golang.org/x/tools v0.1.11/go.mod h1:SgwaegtQh8clINPpECJMqnxLv9I09HLqnW3RMqW0CA4= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=