wrapToken.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. package gssapi
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "encoding/binary"
  6. "encoding/hex"
  7. "errors"
  8. "fmt"
  9. "gopkg.in/jcmturner/gokrb5.v7/crypto"
  10. "gopkg.in/jcmturner/gokrb5.v7/iana/keyusage"
  11. "gopkg.in/jcmturner/gokrb5.v7/types"
  12. )
  13. // RFC 4121, section 4.2.6.2
  14. const (
  15. HdrLen = 16 // Length of the Wrap Token's header
  16. FillerByte byte = 0xFF
  17. )
  18. // WrapToken represents a GSS API Wrap token, as defined in RFC 4121.
  19. // It contains the header fields, the payload and the checksum, and provides
  20. // the logic for converting to/from bytes plus computing and verifying checksums
  21. type WrapToken struct {
  22. // const GSS Token ID: 0x0504
  23. Flags byte // contains three flags: acceptor, sealed, acceptor subkey
  24. // const Filler: 0xFF
  25. EC uint16 // checksum length. big-endian
  26. RRC uint16 // right rotation count. big-endian
  27. SndSeqNum uint64 // sender's sequence number. big-endian
  28. Payload []byte // your data! :)
  29. CheckSum []byte // authenticated checksum of { payload | header }
  30. }
  31. // Return the 2 bytes identifying a GSS API Wrap token
  32. func getGssWrapTokenId() *[2]byte {
  33. return &[2]byte{0x05, 0x04}
  34. }
  35. // Marshal the WrapToken into a byte slice.
  36. // The payload should have been set and the checksum computed, otherwise an error is returned.
  37. func (wt *WrapToken) Marshal() ([]byte, error) {
  38. if wt.CheckSum == nil {
  39. return nil, errors.New("checksum has not been set")
  40. }
  41. if wt.Payload == nil {
  42. return nil, errors.New("payload has not been set")
  43. }
  44. pldOffset := HdrLen // Offset of the payload in the token
  45. chkSOffset := HdrLen + len(wt.Payload) // Offset of the checksum in the token
  46. bytes := make([]byte, chkSOffset+int(wt.EC))
  47. copy(bytes[0:], getGssWrapTokenId()[:])
  48. bytes[2] = wt.Flags
  49. bytes[3] = FillerByte
  50. binary.BigEndian.PutUint16(bytes[4:6], wt.EC)
  51. binary.BigEndian.PutUint16(bytes[6:8], wt.RRC)
  52. binary.BigEndian.PutUint64(bytes[8:16], wt.SndSeqNum)
  53. copy(bytes[pldOffset:], wt.Payload)
  54. copy(bytes[chkSOffset:], wt.CheckSum)
  55. return bytes, nil
  56. }
  57. // SetCheckSum uses the passed encryption key and key usage to compute the checksum over the payload and
  58. // the header, and sets the CheckSum field of this WrapToken.
  59. // If the payload has not been set or the checksum has already been set, an error is returned.
  60. func (wt *WrapToken) SetCheckSum(key types.EncryptionKey, keyUsage uint32) error {
  61. if wt.Payload == nil {
  62. return errors.New("payload has not been set")
  63. }
  64. if wt.CheckSum != nil {
  65. return errors.New("checksum has already been computed")
  66. }
  67. chkSum, cErr := wt.computeCheckSum(key, keyUsage)
  68. if cErr != nil {
  69. return cErr
  70. }
  71. wt.CheckSum = chkSum
  72. return nil
  73. }
  74. // ComputeCheckSum computes and returns the checksum of this token, computed using the passed key and key usage.
  75. // Note: This will NOT update the struct's Checksum field.
  76. func (wt *WrapToken) computeCheckSum(key types.EncryptionKey, keyUsage uint32) ([]byte, error) {
  77. if wt.Payload == nil {
  78. return nil, errors.New("cannot compute checksum with uninitialized payload")
  79. }
  80. // Build a slice containing { payload | header }
  81. checksumMe := make([]byte, HdrLen+len(wt.Payload))
  82. copy(checksumMe[0:], wt.Payload)
  83. copy(checksumMe[len(wt.Payload):], getChecksumHeader(wt.Flags, wt.SndSeqNum))
  84. encType, err := crypto.GetEtype(key.KeyType)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return encType.GetChecksumHash(key.KeyValue, checksumMe, keyUsage)
  89. }
  90. // Build a header suitable for a checksum computation
  91. func getChecksumHeader(flags byte, senderSeqNum uint64) []byte {
  92. header := make([]byte, 16)
  93. copy(header[0:], []byte{0x05, 0x04, flags, 0xFF, 0x00, 0x00, 0x00, 0x00})
  94. binary.BigEndian.PutUint64(header[8:], senderSeqNum)
  95. return header
  96. }
  97. // Verify computes the token's checksum with the provided key and usage,
  98. // and compares it to the checksum present in the token.
  99. // In case of any failure, (false, Err) is returned, with Err an explanatory error.
  100. func (wt *WrapToken) Verify(key types.EncryptionKey, keyUsage uint32) (bool, error) {
  101. computed, cErr := wt.computeCheckSum(key, keyUsage)
  102. if cErr != nil {
  103. return false, cErr
  104. }
  105. if !hmac.Equal(computed, wt.CheckSum) {
  106. return false, fmt.Errorf(
  107. "checksum mismatch. Computed: %s, Contained in token: %s",
  108. hex.EncodeToString(computed), hex.EncodeToString(wt.CheckSum))
  109. }
  110. return true, nil
  111. }
  112. // Unmarshal bytes into the corresponding WrapToken.
  113. // If expectFromAcceptor is true, we expect the token to have been emitted by the gss acceptor,
  114. // and will check the according flag, returning an error if the token does not match the expectation.
  115. func (wt *WrapToken) Unmarshal(b []byte, expectFromAcceptor bool) error {
  116. // Check if we can read a whole header
  117. if len(b) < 16 {
  118. return errors.New("bytes shorter than header length")
  119. }
  120. // Is the Token ID correct?
  121. if !bytes.Equal(getGssWrapTokenId()[:], b[0:2]) {
  122. return fmt.Errorf("wrong Token ID. Expected %s, was %s",
  123. hex.EncodeToString(getGssWrapTokenId()[:]),
  124. hex.EncodeToString(b[0:2]))
  125. }
  126. // Check the acceptor flag
  127. flags := b[2]
  128. isFromAcceptor := flags&0x01 == 1
  129. if isFromAcceptor && !expectFromAcceptor {
  130. return errors.New("unexpected acceptor flag is set: not expecting a token from the acceptor")
  131. }
  132. if !isFromAcceptor && expectFromAcceptor {
  133. return errors.New("expected acceptor flag is not set: expecting a token from the acceptor, not the initiator")
  134. }
  135. // Check the filler byte
  136. if b[3] != FillerByte {
  137. return fmt.Errorf("unexpected filler byte: expecting 0xFF, was %s ", hex.EncodeToString(b[3:4]))
  138. }
  139. checksumL := binary.BigEndian.Uint16(b[4:6])
  140. // Sanity check on the checksum length
  141. if int(checksumL) > len(b)-HdrLen {
  142. return fmt.Errorf("inconsistent checksum length: %d bytes to parse, checksum length is %d", len(b), checksumL)
  143. }
  144. wt.Flags = flags
  145. wt.EC = checksumL
  146. wt.RRC = binary.BigEndian.Uint16(b[6:8])
  147. wt.SndSeqNum = binary.BigEndian.Uint64(b[8:16])
  148. wt.Payload = b[16 : len(b)-int(checksumL)]
  149. wt.CheckSum = b[len(b)-int(checksumL):]
  150. return nil
  151. }
  152. // NewInitiatorWrapToken builds a new initiator token (acceptor flag will be set to 0) and computes the authenticated checksum.
  153. // Other flags are set to 0, and the RRC and sequence number are initialized to 0.
  154. // Note that in certain circumstances you may need to provide a sequence number that has been defined earlier.
  155. // This is currently not supported.
  156. func NewInitiatorWrapToken(payload []byte, key types.EncryptionKey) (*WrapToken, error) {
  157. encType, err := crypto.GetEtype(key.KeyType)
  158. if err != nil {
  159. return nil, err
  160. }
  161. token := WrapToken{
  162. Flags: 0x00, // all zeroed out (this is a token sent by the initiator)
  163. // Checksum size: length of output of the HMAC function, in bytes.
  164. EC: uint16(encType.GetHMACBitLength() / 8),
  165. RRC: 0,
  166. SndSeqNum: 0,
  167. Payload: payload,
  168. }
  169. if err := token.SetCheckSum(key, keyusage.GSSAPI_INITIATOR_SEAL); err != nil {
  170. return nil, err
  171. }
  172. return &token, nil
  173. }