wrapToken.go 6.8 KB

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