tsig.go 9.2 KB

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