Debian Codegraph @

handshake-messages.go

raw symbols SCIP
1 package mint
2
3 import (
4 "bytes"
5 "crypto"
6 "crypto/x509"
7 "encoding/binary"
8 "fmt"
9
10 "github.com/bifurcation/mint/syntax"
11 )
12
13 type HandshakeMessageBody interface {
14 Type() HandshakeType
15 Marshal() ([]byte, error)
16 Unmarshal(data []byte) (int, error)
17 }
18
19 // struct {
20 // ProtocolVersion legacy_version = 0x0303; /* TLS v1.2 */
21 // Random random;
22 // opaque legacy_session_id<0..32>;
23 // CipherSuite cipher_suites<2..2^16-2>;
24 // opaque legacy_compression_methods<1..2^8-1>;
25 // Extension extensions<0..2^16-1>;
26 // } ClientHello;
27 type ClientHelloBody struct {
28 LegacyVersion uint16
29 Random [32]byte
30 LegacySessionID []byte
31 CipherSuites []CipherSuite
32 Extensions ExtensionList
33 }
34
35 type clientHelloBodyInnerTLS struct {
36 LegacyVersion uint16
37 Random [32]byte
38 LegacySessionID []byte `tls:"head=1,max=32"`
39 CipherSuites []CipherSuite `tls:"head=2,min=2"`
40 LegacyCompressionMethods []byte `tls:"head=1,min=1"`
41 Extensions []Extension `tls:"head=2"`
42 }
43
44 type clientHelloBodyInnerDTLS struct {
45 LegacyVersion uint16
46 Random [32]byte
47 LegacySessionID []byte `tls:"head=1,max=32"`
48 EmptyCookie uint8
49 CipherSuites []CipherSuite `tls:"head=2,min=2"`
50 LegacyCompressionMethods []byte `tls:"head=1,min=1"`
51 Extensions []Extension `tls:"head=2"`
52 }
53
54 func (ch ClientHelloBody) Type() HandshakeType {
55 return HandshakeTypeClientHello
56 }
57
58 func (ch ClientHelloBody) Marshal() ([]byte, error) {
59 if ch.LegacyVersion == tls12Version {
60 return syntax.Marshal(clientHelloBodyInnerTLS{
61 LegacyVersion: ch.LegacyVersion,
62 Random: ch.Random,
63 LegacySessionID: []byte{},
64 CipherSuites: ch.CipherSuites,
65 LegacyCompressionMethods: []byte{0},
66 Extensions: ch.Extensions,
67 })
68 } else {
69 return syntax.Marshal(clientHelloBodyInnerDTLS{
70 LegacyVersion: ch.LegacyVersion,
71 Random: ch.Random,
72 LegacySessionID: []byte{},
73 CipherSuites: ch.CipherSuites,
74 LegacyCompressionMethods: []byte{0},
75 Extensions: ch.Extensions,
76 })
77 }
78
79 }
80
81 func (ch *ClientHelloBody) Unmarshal(data []byte) (int, error) {
82 var read int
83 var err error
84
85 // Note that this might be 0, in which case we do TLS. That
86 // makes the tests easier.
87 if ch.LegacyVersion != dtls12WireVersion {
88 var inner clientHelloBodyInnerTLS
89 read, err = syntax.Unmarshal(data, &inner)
90 if err != nil {
91 return 0, err
92 }
93
94 if len(inner.LegacyCompressionMethods) != 1 || inner.LegacyCompressionMethods[0] != 0 {
95 return 0, fmt.Errorf("tls.clienthello: Invalid compression method")
96 }
97
98 ch.LegacyVersion = inner.LegacyVersion
99 ch.Random = inner.Random
100 ch.LegacySessionID = inner.LegacySessionID
101 ch.CipherSuites = inner.CipherSuites
102 ch.Extensions = inner.Extensions
103 } else {
104 var inner clientHelloBodyInnerDTLS
105 read, err = syntax.Unmarshal(data, &inner)
106 if err != nil {
107 return 0, err
108 }
109
110 if inner.EmptyCookie != 0 {
111 return 0, fmt.Errorf("tls.clienthello: Invalid cookie")
112 }
113
114 if len(inner.LegacyCompressionMethods) != 1 || inner.LegacyCompressionMethods[0] != 0 {
115 return 0, fmt.Errorf("tls.clienthello: Invalid compression method")
116 }
117
118 ch.LegacyVersion = inner.LegacyVersion
119 ch.Random = inner.Random
120 ch.LegacySessionID = inner.LegacySessionID
121 ch.CipherSuites = inner.CipherSuites
122 ch.Extensions = inner.Extensions
123 }
124 return read, nil
125 }
126
127 // TODO: File a spec bug to clarify this
128 func (ch ClientHelloBody) Truncated() ([]byte, error) {
129 if len(ch.Extensions) == 0 {
130 return nil, fmt.Errorf("tls.clienthello.truncate: No extensions")
131 }
132
133 pskExt := ch.Extensions[len(ch.Extensions)-1]
134 if pskExt.ExtensionType != ExtensionTypePreSharedKey {
135 return nil, fmt.Errorf("tls.clienthello.truncate: Last extension is not PSK")
136 }
137
138 body, err := ch.Marshal()
139 if err != nil {
140 return nil, err
141 }
142 chm := &HandshakeMessage{
143 msgType: ch.Type(),
144 body: body,
145 length: uint32(len(body)),
146 }
147 chData := chm.Marshal()
148
149 psk := PreSharedKeyExtension{
150 HandshakeType: HandshakeTypeClientHello,
151 }
152 _, err = psk.Unmarshal(pskExt.ExtensionData)
153 if err != nil {
154 return nil, err
155 }
156
157 // Marshal just the binders so that we know how much to truncate
158 binders := struct {
159 Binders []PSKBinderEntry `tls:"head=2,min=33"`
160 }{Binders: psk.Binders}
161 binderData, _ := syntax.Marshal(binders)
162 binderLen := len(binderData)
163
164 chLen := len(chData)
165 return chData[:chLen-binderLen], nil
166 }
167
168 // struct {
169 // ProtocolVersion legacy_version = 0x0303; /* TLS v1.2 */
170 // Random random;
171 // opaque legacy_session_id_echo<0..32>;
172 // CipherSuite cipher_suite;
173 // uint8 legacy_compression_method = 0;
174 // Extension extensions<6..2^16-1>;
175 // } ServerHello;
176 type ServerHelloBody struct {
177 Version uint16
178 Random [32]byte
179 LegacySessionID []byte `tls:"head=1,max=32"`
180 CipherSuite CipherSuite
181 LegacyCompressionMethod uint8
182 Extensions ExtensionList `tls:"head=2"`
183 }
184
185 func (sh ServerHelloBody) Type() HandshakeType {
186 return HandshakeTypeServerHello
187 }
188
189 func (sh ServerHelloBody) Marshal() ([]byte, error) {
190 return syntax.Marshal(sh)
191 }
192
193 func (sh *ServerHelloBody) Unmarshal(data []byte) (int, error) {
194 return syntax.Unmarshal(data, sh)
195 }
196
197 // struct {
198 // opaque verify_data[verify_data_length];
199 // } Finished;
200 //
201 // verifyDataLen is not a field in the TLS struct, but we add it here so
202 // that calling code can tell us how much data to expect when we marshal /
203 // unmarshal. (We could add this to the marshal/unmarshal methods, but let's
204 // try to keep the signature consistent for now.)
205 //
206 // For similar reasons, we don't use the `syntax` module here, because this
207 // struct doesn't map well to standard TLS presentation language concepts.
208 //
209 // TODO: File a spec bug
210 type FinishedBody struct {
211 VerifyDataLen int
212 VerifyData []byte
213 }
214
215 func (fin FinishedBody) Type() HandshakeType {
216 return HandshakeTypeFinished
217 }
218
219 func (fin FinishedBody) Marshal() ([]byte, error) {
220 if len(fin.VerifyData) != fin.VerifyDataLen {
221 return nil, fmt.Errorf("tls.finished: data length mismatch")
222 }
223
224 body := make([]byte, len(fin.VerifyData))
225 copy(body, fin.VerifyData)
226 return body, nil
227 }
228
229 func (fin *FinishedBody) Unmarshal(data []byte) (int, error) {
230 if len(data) < fin.VerifyDataLen {
231 return 0, fmt.Errorf("tls.finished: Malformed finished; too short")
232 }
233
234 fin.VerifyData = make([]byte, fin.VerifyDataLen)
235 copy(fin.VerifyData, data[:fin.VerifyDataLen])
236 return fin.VerifyDataLen, nil
237 }
238
239 // struct {
240 // Extension extensions<0..2^16-1>;
241 // } EncryptedExtensions;
242 //
243 // Marshal() and Unmarshal() are handled by ExtensionList
244 type EncryptedExtensionsBody struct {
245 Extensions ExtensionList `tls:"head=2"`
246 }
247
248 func (ee EncryptedExtensionsBody) Type() HandshakeType {
249 return HandshakeTypeEncryptedExtensions
250 }
251
252 func (ee EncryptedExtensionsBody) Marshal() ([]byte, error) {
253 return syntax.Marshal(ee)
254 }
255
256 func (ee *EncryptedExtensionsBody) Unmarshal(data []byte) (int, error) {
257 return syntax.Unmarshal(data, ee)
258 }
259
260 // opaque ASN1Cert<1..2^24-1>;
261 //
262 // struct {
263 // ASN1Cert cert_data;
264 // Extension extensions<0..2^16-1>
265 // } CertificateEntry;
266 //
267 // struct {
268 // opaque certificate_request_context<0..2^8-1>;
269 // CertificateEntry certificate_list<0..2^24-1>;
270 // } Certificate;
271 type CertificateEntry struct {
272 CertData *x509.Certificate
273 Extensions ExtensionList
274 }
275
276 type CertificateBody struct {
277 CertificateRequestContext []byte
278 CertificateList []CertificateEntry
279 }
280
281 type certificateEntryInner struct {
282 CertData []byte `tls:"head=3,min=1"`
283 Extensions ExtensionList `tls:"head=2"`
284 }
285
286 type certificateBodyInner struct {
287 CertificateRequestContext []byte `tls:"head=1"`
288 CertificateList []certificateEntryInner `tls:"head=3"`
289 }
290
291 func (c CertificateBody) Type() HandshakeType {
292 return HandshakeTypeCertificate
293 }
294
295 func (c CertificateBody) Marshal() ([]byte, error) {
296 inner := certificateBodyInner{
297 CertificateRequestContext: c.CertificateRequestContext,
298 CertificateList: make([]certificateEntryInner, len(c.CertificateList)),
299 }
300
301 for i, entry := range c.CertificateList {
302 inner.CertificateList[i] = certificateEntryInner{
303 CertData: entry.CertData.Raw,
304 Extensions: entry.Extensions,
305 }
306 }
307
308 return syntax.Marshal(inner)
309 }
310
311 func (c *CertificateBody) Unmarshal(data []byte) (int, error) {
312 inner := certificateBodyInner{}
313 read, err := syntax.Unmarshal(data, &inner)
314 if err != nil {
315 return read, err
316 }
317
318 c.CertificateRequestContext = inner.CertificateRequestContext
319 c.CertificateList = make([]CertificateEntry, len(inner.CertificateList))
320
321 for i, entry := range inner.CertificateList {
322 c.CertificateList[i].CertData, err = x509.ParseCertificate(entry.CertData)
323 if err != nil {
324 return 0, fmt.Errorf("tls:certificate: Certificate failed to parse: %v", err)
325 }
326
327 c.CertificateList[i].Extensions = entry.Extensions
328 }
329
330 return read, nil
331 }
332
333 // struct {
334 // SignatureScheme algorithm;
335 // opaque signature<0..2^16-1>;
336 // } CertificateVerify;
337 type CertificateVerifyBody struct {
338 Algorithm SignatureScheme
339 Signature []byte `tls:"head=2"`
340 }
341
342 func (cv CertificateVerifyBody) Type() HandshakeType {
343 return HandshakeTypeCertificateVerify
344 }
345
346 func (cv CertificateVerifyBody) Marshal() ([]byte, error) {
347 return syntax.Marshal(cv)
348 }
349
350 func (cv *CertificateVerifyBody) Unmarshal(data []byte) (int, error) {
351 return syntax.Unmarshal(data, cv)
352 }
353
354 func (cv *CertificateVerifyBody) EncodeSignatureInput(data []byte) []byte {
355 // TODO: Change context for client auth
356 // TODO: Put this in a const
357 const context = "TLS 1.3, server CertificateVerify"
358 sigInput := bytes.Repeat([]byte{0x20}, 64)
359 sigInput = append(sigInput, []byte(context)...)
360 sigInput = append(sigInput, []byte{0}...)
361 sigInput = append(sigInput, data...)
362 return sigInput
363 }
364
365 func (cv *CertificateVerifyBody) Sign(privateKey crypto.Signer, handshakeHash []byte) (err error) {
366 sigInput := cv.EncodeSignatureInput(handshakeHash)
367 cv.Signature, err = sign(cv.Algorithm, privateKey, sigInput)
368 logf(logTypeHandshake, "Signed: alg=[%04x] sigInput=[%x], sig=[%x]", cv.Algorithm, sigInput, cv.Signature)
369 return
370 }
371
372 func (cv *CertificateVerifyBody) Verify(publicKey crypto.PublicKey, handshakeHash []byte) error {
373 sigInput := cv.EncodeSignatureInput(handshakeHash)
374 logf(logTypeHandshake, "About to verify: alg=[%04x] sigInput=[%x], sig=[%x]", cv.Algorithm, sigInput, cv.Signature)
375 return verify(cv.Algorithm, publicKey, sigInput, cv.Signature)
376 }
377
378 // struct {
379 // opaque certificate_request_context<0..2^8-1>;
380 // Extension extensions<2..2^16-1>;
381 // } CertificateRequest;
382 type CertificateRequestBody struct {
383 CertificateRequestContext []byte `tls:"head=1"`
384 Extensions ExtensionList `tls:"head=2"`
385 }
386
387 func (cr CertificateRequestBody) Type() HandshakeType {
388 return HandshakeTypeCertificateRequest
389 }
390
391 func (cr CertificateRequestBody) Marshal() ([]byte, error) {
392 return syntax.Marshal(cr)
393 }
394
395 func (cr *CertificateRequestBody) Unmarshal(data []byte) (int, error) {
396 return syntax.Unmarshal(data, cr)
397 }
398
399 // struct {
400 // uint32 ticket_lifetime;
401 // uint32 ticket_age_add;
402 // opaque ticket_nonce<1..255>;
403 // opaque ticket<1..2^16-1>;
404 // Extension extensions<0..2^16-2>;
405 // } NewSessionTicket;
406 type NewSessionTicketBody struct {
407 TicketLifetime uint32
408 TicketAgeAdd uint32
409 TicketNonce []byte `tls:"head=1"`
410 Ticket []byte `tls:"head=2,min=1"`
411 Extensions ExtensionList `tls:"head=2"`
412 }
413
414 const ticketNonceLen = 16
415
416 func NewSessionTicket(ticketLen int, ticketLifetime uint32) (*NewSessionTicketBody, error) {
417 buf := make([]byte, 4+ticketNonceLen+ticketLen)
418 _, err := prng.Read(buf)
419 if err != nil {
420 return nil, err
421 }
422
423 tkt := &NewSessionTicketBody{
424 TicketLifetime: ticketLifetime,
425 TicketAgeAdd: binary.BigEndian.Uint32(buf[:4]),
426 TicketNonce: buf[4 : 4+ticketNonceLen],
427 Ticket: buf[4+ticketNonceLen:],
428 }
429
430 return tkt, err
431 }
432
433 func (tkt NewSessionTicketBody) Type() HandshakeType {
434 return HandshakeTypeNewSessionTicket
435 }
436
437 func (tkt NewSessionTicketBody) Marshal() ([]byte, error) {
438 return syntax.Marshal(tkt)
439 }
440
441 func (tkt *NewSessionTicketBody) Unmarshal(data []byte) (int, error) {
442 return syntax.Unmarshal(data, tkt)
443 }
444
445 // enum {
446 // update_not_requested(0), update_requested(1), (255)
447 // } KeyUpdateRequest;
448 //
449 // struct {
450 // KeyUpdateRequest request_update;
451 // } KeyUpdate;
452 type KeyUpdateBody struct {
453 KeyUpdateRequest KeyUpdateRequest
454 }
455
456 func (ku KeyUpdateBody) Type() HandshakeType {
457 return HandshakeTypeKeyUpdate
458 }
459
460 func (ku KeyUpdateBody) Marshal() ([]byte, error) {
461 return syntax.Marshal(ku)
462 }
463
464 func (ku *KeyUpdateBody) Unmarshal(data []byte) (int, error) {
465 return syntax.Unmarshal(data, ku)
466 }
467
468 // struct {} EndOfEarlyData;
469 type EndOfEarlyDataBody struct{}
470
471 func (eoed EndOfEarlyDataBody) Type() HandshakeType {
472 return HandshakeTypeEndOfEarlyData
473 }
474
475 func (eoed EndOfEarlyDataBody) Marshal() ([]byte, error) {
476 return []byte{}, nil
477 }
478
479 func (eoed *EndOfEarlyDataBody) Unmarshal(data []byte) (int, error) {
480 return 0, nil
481 }