tsig.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package dns
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "crypto/sha256"
  6. "crypto/sha512"
  7. "encoding/binary"
  8. "encoding/hex"
  9. "hash"
  10. "strconv"
  11. "strings"
  12. "time"
  13. )
  14. // HMAC hashing codes. These are transmitted as domain names.
  15. const (
  16. HmacSHA1 = "hmac-sha1."
  17. HmacSHA224 = "hmac-sha224."
  18. HmacSHA256 = "hmac-sha256."
  19. HmacSHA384 = "hmac-sha384."
  20. HmacSHA512 = "hmac-sha512."
  21. HmacMD5 = "hmac-md5.sig-alg.reg.int." // Deprecated: HmacMD5 is no longer supported.
  22. )
  23. // TsigProvider provides the API to plug-in a custom TSIG implementation.
  24. type TsigProvider interface {
  25. // Generate is passed the DNS message to be signed and the partial TSIG RR. It returns the signature and nil, otherwise an error.
  26. Generate(msg []byte, t *TSIG) ([]byte, error)
  27. // Verify is passed the DNS message to be verified and the TSIG RR. If the signature is valid it will return nil, otherwise an error.
  28. Verify(msg []byte, t *TSIG) error
  29. }
  30. type tsigHMACProvider string
  31. func (key tsigHMACProvider) Generate(msg []byte, t *TSIG) ([]byte, error) {
  32. // If we barf here, the caller is to blame
  33. rawsecret, err := fromBase64([]byte(key))
  34. if err != nil {
  35. return nil, err
  36. }
  37. var h hash.Hash
  38. switch CanonicalName(t.Algorithm) {
  39. case HmacSHA1:
  40. h = hmac.New(sha1.New, rawsecret)
  41. case HmacSHA224:
  42. h = hmac.New(sha256.New224, rawsecret)
  43. case HmacSHA256:
  44. h = hmac.New(sha256.New, rawsecret)
  45. case HmacSHA384:
  46. h = hmac.New(sha512.New384, rawsecret)
  47. case HmacSHA512:
  48. h = hmac.New(sha512.New, rawsecret)
  49. default:
  50. return nil, ErrKeyAlg
  51. }
  52. h.Write(msg)
  53. return h.Sum(nil), nil
  54. }
  55. func (key tsigHMACProvider) Verify(msg []byte, t *TSIG) error {
  56. b, err := key.Generate(msg, t)
  57. if err != nil {
  58. return err
  59. }
  60. mac, err := hex.DecodeString(t.MAC)
  61. if err != nil {
  62. return err
  63. }
  64. if !hmac.Equal(b, mac) {
  65. return ErrSig
  66. }
  67. return nil
  68. }
  69. type tsigSecretProvider map[string]string
  70. func (ts tsigSecretProvider) Generate(msg []byte, t *TSIG) ([]byte, error) {
  71. key, ok := ts[t.Hdr.Name]
  72. if !ok {
  73. return nil, ErrSecret
  74. }
  75. return tsigHMACProvider(key).Generate(msg, t)
  76. }
  77. func (ts tsigSecretProvider) Verify(msg []byte, t *TSIG) error {
  78. key, ok := ts[t.Hdr.Name]
  79. if !ok {
  80. return ErrSecret
  81. }
  82. return tsigHMACProvider(key).Verify(msg, t)
  83. }
  84. // TSIG is the RR the holds the transaction signature of a message.
  85. // See RFC 2845 and RFC 4635.
  86. type TSIG struct {
  87. Hdr RR_Header
  88. Algorithm string `dns:"domain-name"`
  89. TimeSigned uint64 `dns:"uint48"`
  90. Fudge uint16
  91. MACSize uint16
  92. MAC string `dns:"size-hex:MACSize"`
  93. OrigId uint16
  94. Error uint16
  95. OtherLen uint16
  96. OtherData string `dns:"size-hex:OtherLen"`
  97. }
  98. // TSIG has no official presentation format, but this will suffice.
  99. func (rr *TSIG) String() string {
  100. s := "\n;; TSIG PSEUDOSECTION:\n; " // add another semi-colon to signify TSIG does not have a presentation format
  101. s += rr.Hdr.String() +
  102. " " + rr.Algorithm +
  103. " " + tsigTimeToString(rr.TimeSigned) +
  104. " " + strconv.Itoa(int(rr.Fudge)) +
  105. " " + strconv.Itoa(int(rr.MACSize)) +
  106. " " + strings.ToUpper(rr.MAC) +
  107. " " + strconv.Itoa(int(rr.OrigId)) +
  108. " " + strconv.Itoa(int(rr.Error)) + // BIND prints NOERROR
  109. " " + strconv.Itoa(int(rr.OtherLen)) +
  110. " " + rr.OtherData
  111. return s
  112. }
  113. func (*TSIG) parse(c *zlexer, origin string) *ParseError {
  114. return &ParseError{err: "TSIG records do not have a presentation format"}
  115. }
  116. // The following values must be put in wireformat, so that the MAC can be calculated.
  117. // RFC 2845, section 3.4.2. TSIG Variables.
  118. type tsigWireFmt struct {
  119. // From RR_Header
  120. Name string `dns:"domain-name"`
  121. Class uint16
  122. Ttl uint32
  123. // Rdata of the TSIG
  124. Algorithm string `dns:"domain-name"`
  125. TimeSigned uint64 `dns:"uint48"`
  126. Fudge uint16
  127. // MACSize, MAC and OrigId excluded
  128. Error uint16
  129. OtherLen uint16
  130. OtherData string `dns:"size-hex:OtherLen"`
  131. }
  132. // If we have the MAC use this type to convert it to wiredata. Section 3.4.3. Request MAC
  133. type macWireFmt struct {
  134. MACSize uint16
  135. MAC string `dns:"size-hex:MACSize"`
  136. }
  137. // 3.3. Time values used in TSIG calculations
  138. type timerWireFmt struct {
  139. TimeSigned uint64 `dns:"uint48"`
  140. Fudge uint16
  141. }
  142. // TsigGenerate fills out the TSIG record attached to the message.
  143. // The message should contain a "stub" TSIG RR with the algorithm, key name
  144. // (owner name of the RR), time fudge (defaults to 300 seconds) and the current
  145. // time The TSIG MAC is saved in that Tsig RR. When TsigGenerate is called for
  146. // the first time requestMAC should be set to the empty string and timersOnly to
  147. // false.
  148. func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error) {
  149. return TsigGenerateWithProvider(m, tsigHMACProvider(secret), requestMAC, timersOnly)
  150. }
  151. // TsigGenerateWithProvider is similar to TsigGenerate, but allows for a custom TsigProvider.
  152. func TsigGenerateWithProvider(m *Msg, provider TsigProvider, requestMAC string, timersOnly bool) ([]byte, string, error) {
  153. if m.IsTsig() == nil {
  154. panic("dns: TSIG not last RR in additional")
  155. }
  156. rr := m.Extra[len(m.Extra)-1].(*TSIG)
  157. m.Extra = m.Extra[0 : len(m.Extra)-1] // kill the TSIG from the msg
  158. mbuf, err := m.Pack()
  159. if err != nil {
  160. return nil, "", err
  161. }
  162. buf, err := tsigBuffer(mbuf, rr, requestMAC, timersOnly)
  163. if err != nil {
  164. return nil, "", err
  165. }
  166. t := new(TSIG)
  167. // Copy all TSIG fields except MAC, its size, and time signed which are filled when signing.
  168. *t = *rr
  169. t.TimeSigned = 0
  170. t.MAC = ""
  171. t.MACSize = 0
  172. // Sign unless there is a key or MAC validation error (RFC 8945 5.3.2)
  173. if rr.Error != RcodeBadKey && rr.Error != RcodeBadSig {
  174. mac, err := provider.Generate(buf, rr)
  175. if err != nil {
  176. return nil, "", err
  177. }
  178. t.TimeSigned = rr.TimeSigned
  179. t.MAC = hex.EncodeToString(mac)
  180. t.MACSize = uint16(len(t.MAC) / 2) // Size is half!
  181. }
  182. tbuf := make([]byte, Len(t))
  183. off, err := PackRR(t, tbuf, 0, nil, false)
  184. if err != nil {
  185. return nil, "", err
  186. }
  187. mbuf = append(mbuf, tbuf[:off]...)
  188. // Update the ArCount directly in the buffer.
  189. binary.BigEndian.PutUint16(mbuf[10:], uint16(len(m.Extra)+1))
  190. return mbuf, t.MAC, nil
  191. }
  192. // TsigVerify verifies the TSIG on a message. If the signature does not
  193. // validate the returned error contains the cause. If the signature is OK, the
  194. // error is nil.
  195. func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
  196. return tsigVerify(msg, tsigHMACProvider(secret), requestMAC, timersOnly, uint64(time.Now().Unix()))
  197. }
  198. // TsigVerifyWithProvider is similar to TsigVerify, but allows for a custom TsigProvider.
  199. func TsigVerifyWithProvider(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool) error {
  200. return tsigVerify(msg, provider, requestMAC, timersOnly, uint64(time.Now().Unix()))
  201. }
  202. // actual implementation of TsigVerify, taking the current time ('now') as a parameter for the convenience of tests.
  203. func tsigVerify(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool, now uint64) error {
  204. // Strip the TSIG from the incoming msg
  205. stripped, tsig, err := stripTsig(msg)
  206. if err != nil {
  207. return err
  208. }
  209. buf, err := tsigBuffer(stripped, tsig, requestMAC, timersOnly)
  210. if err != nil {
  211. return err
  212. }
  213. if err := provider.Verify(buf, tsig); err != nil {
  214. return err
  215. }
  216. // Fudge factor works both ways. A message can arrive before it was signed because
  217. // of clock skew.
  218. // We check this after verifying the signature, following draft-ietf-dnsop-rfc2845bis
  219. // instead of RFC2845, in order to prevent a security vulnerability as reported in CVE-2017-3142/3143.
  220. ti := now - tsig.TimeSigned
  221. if now < tsig.TimeSigned {
  222. ti = tsig.TimeSigned - now
  223. }
  224. if uint64(tsig.Fudge) < ti {
  225. return ErrTime
  226. }
  227. return nil
  228. }
  229. // Create a wiredata buffer for the MAC calculation.
  230. func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) ([]byte, error) {
  231. var buf []byte
  232. if rr.TimeSigned == 0 {
  233. rr.TimeSigned = uint64(time.Now().Unix())
  234. }
  235. if rr.Fudge == 0 {
  236. rr.Fudge = 300 // Standard (RFC) default.
  237. }
  238. // Replace message ID in header with original ID from TSIG
  239. binary.BigEndian.PutUint16(msgbuf[0:2], rr.OrigId)
  240. if requestMAC != "" {
  241. m := new(macWireFmt)
  242. m.MACSize = uint16(len(requestMAC) / 2)
  243. m.MAC = requestMAC
  244. buf = make([]byte, len(requestMAC)) // long enough
  245. n, err := packMacWire(m, buf)
  246. if err != nil {
  247. return nil, err
  248. }
  249. buf = buf[:n]
  250. }
  251. tsigvar := make([]byte, DefaultMsgSize)
  252. if timersOnly {
  253. tsig := new(timerWireFmt)
  254. tsig.TimeSigned = rr.TimeSigned
  255. tsig.Fudge = rr.Fudge
  256. n, err := packTimerWire(tsig, tsigvar)
  257. if err != nil {
  258. return nil, err
  259. }
  260. tsigvar = tsigvar[:n]
  261. } else {
  262. tsig := new(tsigWireFmt)
  263. tsig.Name = CanonicalName(rr.Hdr.Name)
  264. tsig.Class = ClassANY
  265. tsig.Ttl = rr.Hdr.Ttl
  266. tsig.Algorithm = CanonicalName(rr.Algorithm)
  267. tsig.TimeSigned = rr.TimeSigned
  268. tsig.Fudge = rr.Fudge
  269. tsig.Error = rr.Error
  270. tsig.OtherLen = rr.OtherLen
  271. tsig.OtherData = rr.OtherData
  272. n, err := packTsigWire(tsig, tsigvar)
  273. if err != nil {
  274. return nil, err
  275. }
  276. tsigvar = tsigvar[:n]
  277. }
  278. if requestMAC != "" {
  279. x := append(buf, msgbuf...)
  280. buf = append(x, tsigvar...)
  281. } else {
  282. buf = append(msgbuf, tsigvar...)
  283. }
  284. return buf, nil
  285. }
  286. // Strip the TSIG from the raw message.
  287. func stripTsig(msg []byte) ([]byte, *TSIG, error) {
  288. // Copied from msg.go's Unpack() Header, but modified.
  289. var (
  290. dh Header
  291. err error
  292. )
  293. off, tsigoff := 0, 0
  294. if dh, off, err = unpackMsgHdr(msg, off); err != nil {
  295. return nil, nil, err
  296. }
  297. if dh.Arcount == 0 {
  298. return nil, nil, ErrNoSig
  299. }
  300. // Rcode, see msg.go Unpack()
  301. if int(dh.Bits&0xF) == RcodeNotAuth {
  302. return nil, nil, ErrAuth
  303. }
  304. for i := 0; i < int(dh.Qdcount); i++ {
  305. _, off, err = unpackQuestion(msg, off)
  306. if err != nil {
  307. return nil, nil, err
  308. }
  309. }
  310. _, off, err = unpackRRslice(int(dh.Ancount), msg, off)
  311. if err != nil {
  312. return nil, nil, err
  313. }
  314. _, off, err = unpackRRslice(int(dh.Nscount), msg, off)
  315. if err != nil {
  316. return nil, nil, err
  317. }
  318. rr := new(TSIG)
  319. var extra RR
  320. for i := 0; i < int(dh.Arcount); i++ {
  321. tsigoff = off
  322. extra, off, err = UnpackRR(msg, off)
  323. if err != nil {
  324. return nil, nil, err
  325. }
  326. if extra.Header().Rrtype == TypeTSIG {
  327. rr = extra.(*TSIG)
  328. // Adjust Arcount.
  329. arcount := binary.BigEndian.Uint16(msg[10:])
  330. binary.BigEndian.PutUint16(msg[10:], arcount-1)
  331. break
  332. }
  333. }
  334. if rr == nil {
  335. return nil, nil, ErrNoSig
  336. }
  337. return msg[:tsigoff], rr, nil
  338. }
  339. // Translate the TSIG time signed into a date. There is no
  340. // need for RFC1982 calculations as this date is 48 bits.
  341. func tsigTimeToString(t uint64) string {
  342. ti := time.Unix(int64(t), 0).UTC()
  343. return ti.Format("20060102150405")
  344. }
  345. func packTsigWire(tw *tsigWireFmt, msg []byte) (int, error) {
  346. // copied from zmsg.go TSIG packing
  347. // RR_Header
  348. off, err := PackDomainName(tw.Name, msg, 0, nil, false)
  349. if err != nil {
  350. return off, err
  351. }
  352. off, err = packUint16(tw.Class, msg, off)
  353. if err != nil {
  354. return off, err
  355. }
  356. off, err = packUint32(tw.Ttl, msg, off)
  357. if err != nil {
  358. return off, err
  359. }
  360. off, err = PackDomainName(tw.Algorithm, msg, off, nil, false)
  361. if err != nil {
  362. return off, err
  363. }
  364. off, err = packUint48(tw.TimeSigned, msg, off)
  365. if err != nil {
  366. return off, err
  367. }
  368. off, err = packUint16(tw.Fudge, msg, off)
  369. if err != nil {
  370. return off, err
  371. }
  372. off, err = packUint16(tw.Error, msg, off)
  373. if err != nil {
  374. return off, err
  375. }
  376. off, err = packUint16(tw.OtherLen, msg, off)
  377. if err != nil {
  378. return off, err
  379. }
  380. off, err = packStringHex(tw.OtherData, msg, off)
  381. if err != nil {
  382. return off, err
  383. }
  384. return off, nil
  385. }
  386. func packMacWire(mw *macWireFmt, msg []byte) (int, error) {
  387. off, err := packUint16(mw.MACSize, msg, 0)
  388. if err != nil {
  389. return off, err
  390. }
  391. off, err = packStringHex(mw.MAC, msg, off)
  392. if err != nil {
  393. return off, err
  394. }
  395. return off, nil
  396. }
  397. func packTimerWire(tw *timerWireFmt, msg []byte) (int, error) {
  398. off, err := packUint48(tw.TimeSigned, msg, 0)
  399. if err != nil {
  400. return off, err
  401. }
  402. off, err = packUint16(tw.Fudge, msg, off)
  403. if err != nil {
  404. return off, err
  405. }
  406. return off, nil
  407. }