| 1 |
package dns |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/binary" |
| 6 |
"log" |
| 7 |
"net" |
| 8 |
"testing" |
| 9 |
) |
| 10 |
|
| 11 |
var tsigSecret = []byte("blaat") |
| 12 |
|
| 13 |
// ExampleTSIG_notify shows how to create a notify message with a TSIG signature. |
| 14 |
func ExampleTSIG_notify() { |
| 15 |
m := NewMsg("example.org.", TypeSOA) |
| 16 |
m.Authoritative = true |
| 17 |
m.Opcode = OpcodeNotify |
| 18 |
m.Pseudo = []RR{NewTSIG("key.example.com.", HmacSHA256, 0)} |
| 19 |
|
| 20 |
option := &TSIGOption{} |
| 21 |
hmac := HmacTSIG{Secret: tsigSecret} |
| 22 |
if err := TSIGSign(m, hmac, option); err != nil { |
| 23 |
log.Fatalf("Failed to sign: %s", err) |
| 24 |
} |
| 25 |
|
| 26 |
c := new(Client) |
| 27 |
// Use this if the notify must come from a particular source address. |
| 28 |
c.Transport = NewTransport() |
| 29 |
c.Dialer.LocalAddr = &net.UDPAddr{IP: net.ParseIP("198.51.100.1")} |
| 30 |
|
| 31 |
r, _, err := c.Exchange(context.TODO(), m, "udp", "8.8.4.4:53") |
| 32 |
if err != nil { |
| 33 |
log.Fatalf("Failed to sent notify: %s", err) |
| 34 |
} |
| 35 |
if r.Rcode == RcodeSuccess { |
| 36 |
log.Fatalf("Failed to sent notify: %s", err) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
func msgfn() *Msg { |
| 41 |
m := NewMsg("miek.nl.", TypeMX) |
| 42 |
m.ID = 3 |
| 43 |
m.Pseudo = []RR{NewTSIG("example.", HmacSHA256, 0)} |
| 44 |
return m |
| 45 |
} |
| 46 |
|
| 47 |
func TestTSIG(t *testing.T) { |
| 48 |
testcases := []struct { |
| 49 |
name string |
| 50 |
preFn func(m *Msg) // transform before signing |
| 51 |
postFn func(m *Msg) // transform before verifying |
| 52 |
err error |
| 53 |
}{ |
| 54 |
{"signverify", nil, nil, nil}, |
| 55 |
{"signverify-edns", func(m *Msg) { m.Security = true }, nil, nil}, |
| 56 |
{"signverify-changed-id", nil, func(m *Msg) { binary.BigEndian.PutUint16(m.Data[0:2], 42) }, nil}, |
| 57 |
} |
| 58 |
|
| 59 |
for _, tc := range testcases { |
| 60 |
t.Run(tc.name, func(t *testing.T) { |
| 61 |
m := msgfn() |
| 62 |
if tc.preFn != nil { |
| 63 |
tc.preFn(m) |
| 64 |
} |
| 65 |
|
| 66 |
option := TSIGOption{} |
| 67 |
hmac := HmacTSIG{Secret: tsigSecret} |
| 68 |
if err := TSIGSign(m, hmac, &option); err != nil { |
| 69 |
t.Fatalf("failed to sign: %s", err) |
| 70 |
} |
| 71 |
if tc.postFn != nil { |
| 72 |
tc.postFn(m) |
| 73 |
} |
| 74 |
|
| 75 |
option.RequestMAC = "" // Negate this from TSIGSign, as TSIGVerify is supposed to be running on a different machine normally. |
| 76 |
|
| 77 |
err := TSIGVerify(m, hmac, &option) |
| 78 |
if err != tc.err { |
| 79 |
t.Fatalf("expected %v error, got: %s", tc.err, err) |
| 80 |
} |
| 81 |
}) |
| 82 |
} |
| 83 |
} |