Debian Codegraph @

gssapi/WrapToken.go

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