tsig.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. // TSIG is the RR the holds the transaction signature of a message.
  70. // See RFC 2845 and RFC 4635.
  71. type TSIG struct {
  72. Hdr RR_Header
  73. Algorithm string `dns:"domain-name"`
  74. TimeSigned uint64 `dns:"uint48"`
  75. Fudge uint16
  76. MACSize uint16
  77. MAC string `dns:"size-hex:MACSize"`
  78. OrigId uint16
  79. Error uint16
  80. OtherLen uint16
  81. OtherData string `dns:"size-hex:OtherLen"`
  82. }
  83. // TSIG has no official presentation format, but this will suffice.
  84. func (rr *TSIG) String() string {
  85. s := "\n;; TSIG PSEUDOSECTION:\n; " // add another semi-colon to signify TSIG does not have a presentation format
  86. s += rr.Hdr.String() +
  87. " " + rr.Algorithm +
  88. " " + tsigTimeToString(rr.TimeSigned) +
  89. " " + strconv.Itoa(int(rr.Fudge)) +
  90. " " + strconv.Itoa(int(rr.MACSize)) +
  91. " " + strings.ToUpper(rr.MAC) +
  92. " " + strconv.Itoa(int(rr.OrigId)) +
  93. " " + strconv.Itoa(int(rr.Error)) + // BIND prints NOERROR
  94. " " + strconv.Itoa(int(rr.OtherLen)) +
  95. " " + rr.OtherData
  96. return s
  97. }
  98. func (*TSIG) parse(c *zlexer, origin string) *ParseError {
  99. return &ParseError{err: "TSIG records do not have a presentation format"}
  100. }
  101. // The following values must be put in wireformat, so that the MAC can be calculated.
  102. // RFC 2845, section 3.4.2. TSIG Variables.
  103. type tsigWireFmt struct {
  104. // From RR_Header
  105. Name string `dns:"domain-name"`
  106. Class uint16
  107. Ttl uint32
  108. // Rdata of the TSIG
  109. Algorithm string `dns:"domain-name"`
  110. TimeSigned uint64 `dns:"uint48"`
  111. Fudge uint16
  112. // MACSize, MAC and OrigId excluded
  113. Error uint16
  114. OtherLen uint16
  115. OtherData string `dns:"size-hex:OtherLen"`
  116. }
  117. // If we have the MAC use this type to convert it to wiredata. Section 3.4.3. Request MAC
  118. type macWireFmt struct {
  119. MACSize uint16
  120. MAC string `dns:"size-hex:MACSize"`
  121. }
  122. // 3.3. Time values used in TSIG calculations
  123. type timerWireFmt struct {
  124. TimeSigned uint64 `dns:"uint48"`
  125. Fudge uint16
  126. }
  127. // TsigGenerate fills out the TSIG record attached to the message.
  128. // The message should contain
  129. // a "stub" TSIG RR with the algorithm, key name (owner name of the RR),
  130. // time fudge (defaults to 300 seconds) and the current time
  131. // The TSIG MAC is saved in that Tsig RR.
  132. // When TsigGenerate is called for the first time requestMAC is set to the empty string and
  133. // timersOnly is false.
  134. // If something goes wrong an error is returned, otherwise it is nil.
  135. func TsigGenerate(m *Msg, secret, requestMAC string, timersOnly bool) ([]byte, string, error) {
  136. return tsigGenerateProvider(m, tsigHMACProvider(secret), requestMAC, timersOnly)
  137. }
  138. func tsigGenerateProvider(m *Msg, provider TsigProvider, requestMAC string, timersOnly bool) ([]byte, string, error) {
  139. if m.IsTsig() == nil {
  140. panic("dns: TSIG not last RR in additional")
  141. }
  142. rr := m.Extra[len(m.Extra)-1].(*TSIG)
  143. m.Extra = m.Extra[0 : len(m.Extra)-1] // kill the TSIG from the msg
  144. mbuf, err := m.Pack()
  145. if err != nil {
  146. return nil, "", err
  147. }
  148. buf, err := tsigBuffer(mbuf, rr, requestMAC, timersOnly)
  149. if err != nil {
  150. return nil, "", err
  151. }
  152. t := new(TSIG)
  153. // Copy all TSIG fields except MAC and its size, which are filled using the computed digest.
  154. *t = *rr
  155. mac, err := provider.Generate(buf, rr)
  156. if err != nil {
  157. return nil, "", err
  158. }
  159. t.MAC = hex.EncodeToString(mac)
  160. t.MACSize = uint16(len(t.MAC) / 2) // Size is half!
  161. tbuf := make([]byte, Len(t))
  162. off, err := PackRR(t, tbuf, 0, nil, false)
  163. if err != nil {
  164. return nil, "", err
  165. }
  166. mbuf = append(mbuf, tbuf[:off]...)
  167. // Update the ArCount directly in the buffer.
  168. binary.BigEndian.PutUint16(mbuf[10:], uint16(len(m.Extra)+1))
  169. return mbuf, t.MAC, nil
  170. }
  171. // TsigVerify verifies the TSIG on a message.
  172. // If the signature does not validate err contains the
  173. // error, otherwise it is nil.
  174. func TsigVerify(msg []byte, secret, requestMAC string, timersOnly bool) error {
  175. return tsigVerify(msg, tsigHMACProvider(secret), requestMAC, timersOnly, uint64(time.Now().Unix()))
  176. }
  177. func tsigVerifyProvider(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool) error {
  178. return tsigVerify(msg, provider, requestMAC, timersOnly, uint64(time.Now().Unix()))
  179. }
  180. // actual implementation of TsigVerify, taking the current time ('now') as a parameter for the convenience of tests.
  181. func tsigVerify(msg []byte, provider TsigProvider, requestMAC string, timersOnly bool, now uint64) error {
  182. // Strip the TSIG from the incoming msg
  183. stripped, tsig, err := stripTsig(msg)
  184. if err != nil {
  185. return err
  186. }
  187. buf, err := tsigBuffer(stripped, tsig, requestMAC, timersOnly)
  188. if err != nil {
  189. return err
  190. }
  191. if err := provider.Verify(buf, tsig); err != nil {
  192. return err
  193. }
  194. // Fudge factor works both ways. A message can arrive before it was signed because
  195. // of clock skew.
  196. // We check this after verifying the signature, following draft-ietf-dnsop-rfc2845bis
  197. // instead of RFC2845, in order to prevent a security vulnerability as reported in CVE-2017-3142/3143.
  198. ti := now - tsig.TimeSigned
  199. if now < tsig.TimeSigned {
  200. ti = tsig.TimeSigned - now
  201. }
  202. if uint64(tsig.Fudge) < ti {
  203. return ErrTime
  204. }
  205. return nil
  206. }
  207. // Create a wiredata buffer for the MAC calculation.
  208. func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) ([]byte, error) {
  209. var buf []byte
  210. if rr.TimeSigned == 0 {
  211. rr.TimeSigned = uint64(time.Now().Unix())
  212. }
  213. if rr.Fudge == 0 {
  214. rr.Fudge = 300 // Standard (RFC) default.
  215. }
  216. // Replace message ID in header with original ID from TSIG
  217. binary.BigEndian.PutUint16(msgbuf[0:2], rr.OrigId)
  218. if requestMAC != "" {
  219. m := new(macWireFmt)
  220. m.MACSize = uint16(len(requestMAC) / 2)
  221. m.MAC = requestMAC
  222. buf = make([]byte, len(requestMAC)) // long enough
  223. n, err := packMacWire(m, buf)
  224. if err != nil {
  225. return nil, err
  226. }
  227. buf = buf[:n]
  228. }
  229. tsigvar := make([]byte, DefaultMsgSize)
  230. if timersOnly {
  231. tsig := new(timerWireFmt)
  232. tsig.TimeSigned = rr.TimeSigned
  233. tsig.Fudge = rr.Fudge
  234. n, err := packTimerWire(tsig, tsigvar)
  235. if err != nil {
  236. return nil, err
  237. }
  238. tsigvar = tsigvar[:n]
  239. } else {
  240. tsig := new(tsigWireFmt)
  241. tsig.Name = CanonicalName(rr.Hdr.Name)
  242. tsig.Class = ClassANY
  243. tsig.Ttl = rr.Hdr.Ttl
  244. tsig.Algorithm = CanonicalName(rr.Algorithm)
  245. tsig.TimeSigned = rr.TimeSigned
  246. tsig.Fudge = rr.Fudge
  247. tsig.Error = rr.Error
  248. tsig.OtherLen = rr.OtherLen
  249. tsig.OtherData = rr.OtherData
  250. n, err := packTsigWire(tsig, tsigvar)
  251. if err != nil {
  252. return nil, err
  253. }
  254. tsigvar = tsigvar[:n]
  255. }
  256. if requestMAC != "" {
  257. x := append(buf, msgbuf...)
  258. buf = append(x, tsigvar...)
  259. } else {
  260. buf = append(msgbuf, tsigvar...)
  261. }
  262. return buf, nil
  263. }
  264. // Strip the TSIG from the raw message.
  265. func stripTsig(msg []byte) ([]byte, *TSIG, error) {
  266. // Copied from msg.go's Unpack() Header, but modified.
  267. var (
  268. dh Header
  269. err error
  270. )
  271. off, tsigoff := 0, 0
  272. if dh, off, err = unpackMsgHdr(msg, off); err != nil {
  273. return nil, nil, err
  274. }
  275. if dh.Arcount == 0 {
  276. return nil, nil, ErrNoSig
  277. }
  278. // Rcode, see msg.go Unpack()
  279. if int(dh.Bits&0xF) == RcodeNotAuth {
  280. return nil, nil, ErrAuth
  281. }
  282. for i := 0; i < int(dh.Qdcount); i++ {
  283. _, off, err = unpackQuestion(msg, off)
  284. if err != nil {
  285. return nil, nil, err
  286. }
  287. }
  288. _, off, err = unpackRRslice(int(dh.Ancount), msg, off)
  289. if err != nil {
  290. return nil, nil, err
  291. }
  292. _, off, err = unpackRRslice(int(dh.Nscount), msg, off)
  293. if err != nil {
  294. return nil, nil, err
  295. }
  296. rr := new(TSIG)
  297. var extra RR
  298. for i := 0; i < int(dh.Arcount); i++ {
  299. tsigoff = off
  300. extra, off, err = UnpackRR(msg, off)
  301. if err != nil {
  302. return nil, nil, err
  303. }
  304. if extra.Header().Rrtype == TypeTSIG {
  305. rr = extra.(*TSIG)
  306. // Adjust Arcount.
  307. arcount := binary.BigEndian.Uint16(msg[10:])
  308. binary.BigEndian.PutUint16(msg[10:], arcount-1)
  309. break
  310. }
  311. }
  312. if rr == nil {
  313. return nil, nil, ErrNoSig
  314. }
  315. return msg[:tsigoff], rr, nil
  316. }
  317. // Translate the TSIG time signed into a date. There is no
  318. // need for RFC1982 calculations as this date is 48 bits.
  319. func tsigTimeToString(t uint64) string {
  320. ti := time.Unix(int64(t), 0).UTC()
  321. return ti.Format("20060102150405")
  322. }
  323. func packTsigWire(tw *tsigWireFmt, msg []byte) (int, error) {
  324. // copied from zmsg.go TSIG packing
  325. // RR_Header
  326. off, err := PackDomainName(tw.Name, msg, 0, nil, false)
  327. if err != nil {
  328. return off, err
  329. }
  330. off, err = packUint16(tw.Class, msg, off)
  331. if err != nil {
  332. return off, err
  333. }
  334. off, err = packUint32(tw.Ttl, msg, off)
  335. if err != nil {
  336. return off, err
  337. }
  338. off, err = PackDomainName(tw.Algorithm, msg, off, nil, false)
  339. if err != nil {
  340. return off, err
  341. }
  342. off, err = packUint48(tw.TimeSigned, msg, off)
  343. if err != nil {
  344. return off, err
  345. }
  346. off, err = packUint16(tw.Fudge, msg, off)
  347. if err != nil {
  348. return off, err
  349. }
  350. off, err = packUint16(tw.Error, msg, off)
  351. if err != nil {
  352. return off, err
  353. }
  354. off, err = packUint16(tw.OtherLen, msg, off)
  355. if err != nil {
  356. return off, err
  357. }
  358. off, err = packStringHex(tw.OtherData, msg, off)
  359. if err != nil {
  360. return off, err
  361. }
  362. return off, nil
  363. }
  364. func packMacWire(mw *macWireFmt, msg []byte) (int, error) {
  365. off, err := packUint16(mw.MACSize, msg, 0)
  366. if err != nil {
  367. return off, err
  368. }
  369. off, err = packStringHex(mw.MAC, msg, off)
  370. if err != nil {
  371. return off, err
  372. }
  373. return off, nil
  374. }
  375. func packTimerWire(tw *timerWireFmt, msg []byte) (int, error) {
  376. off, err := packUint48(tw.TimeSigned, msg, 0)
  377. if err != nil {
  378. return off, err
  379. }
  380. off, err = packUint16(tw.Fudge, msg, off)
  381. if err != nil {
  382. return off, err
  383. }
  384. return off, nil
  385. }