tsig.go 9.3 KB

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