github.com/3andne/restls-client-go@v0.1.6/u_tls_extensions.go (about) 1 // Copyright 2017 Google Inc. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package tls 6 7 import ( 8 "encoding/json" 9 "errors" 10 "fmt" 11 "io" 12 "strings" 13 14 "github.com/gaukas/godicttls" 15 "golang.org/x/crypto/cryptobyte" 16 ) 17 18 // ExtensionFromID returns a TLSExtension for the given extension ID. 19 func ExtensionFromID(id uint16) TLSExtension { 20 // deep copy 21 switch id { 22 case extensionServerName: 23 return &SNIExtension{} 24 case extensionStatusRequest: 25 return &StatusRequestExtension{} 26 case extensionSupportedCurves: 27 return &SupportedCurvesExtension{} 28 case extensionSupportedPoints: 29 return &SupportedPointsExtension{} 30 case extensionSignatureAlgorithms: 31 return &SignatureAlgorithmsExtension{} 32 case extensionALPN: 33 return &ALPNExtension{} 34 case extensionStatusRequestV2: 35 return &StatusRequestV2Extension{} 36 case extensionSCT: 37 return &SCTExtension{} 38 case utlsExtensionPadding: 39 return &UtlsPaddingExtension{} 40 case extensionExtendedMasterSecret: 41 return &ExtendedMasterSecretExtension{} 42 case fakeExtensionTokenBinding: 43 return &FakeTokenBindingExtension{} 44 case utlsExtensionCompressCertificate: 45 return &UtlsCompressCertExtension{} 46 case fakeExtensionDelegatedCredentials: 47 return &FakeDelegatedCredentialsExtension{} 48 case extensionSessionTicket: 49 return &SessionTicketExtension{} 50 case extensionPreSharedKey: 51 return &FakePreSharedKeyExtension{} 52 // case extensionEarlyData: 53 // return &EarlyDataExtension{} 54 case extensionSupportedVersions: 55 return &SupportedVersionsExtension{} 56 // case extensionCookie: 57 // return &CookieExtension{} 58 case extensionPSKModes: 59 return &PSKKeyExchangeModesExtension{} 60 // case extensionCertificateAuthorities: 61 // return &CertificateAuthoritiesExtension{} 62 case extensionSignatureAlgorithmsCert: 63 return &SignatureAlgorithmsCertExtension{} 64 case extensionKeyShare: 65 return &KeyShareExtension{} 66 case extensionQUICTransportParameters: 67 return &QUICTransportParametersExtension{} 68 case extensionNextProtoNeg: 69 return &NPNExtension{} 70 case utlsExtensionApplicationSettings: 71 return &ApplicationSettingsExtension{} 72 case fakeOldExtensionChannelID: 73 return &FakeChannelIDExtension{true} 74 case fakeExtensionChannelID: 75 return &FakeChannelIDExtension{} 76 case fakeRecordSizeLimit: 77 return &FakeRecordSizeLimitExtension{} 78 case extensionRenegotiationInfo: 79 return &RenegotiationInfoExtension{} 80 default: 81 if isGREASEUint16(id) { 82 return &UtlsGREASEExtension{} 83 } 84 return nil // not returning GenericExtension, it should be handled by caller 85 } 86 } 87 88 type TLSExtension interface { 89 writeToUConn(*UConn) error 90 91 Len() int // includes header 92 93 // Read reads up to len(p) bytes into p. 94 // It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. 95 Read(p []byte) (n int, err error) // implements io.Reader 96 } 97 98 // TLSExtensionWriter is an interface allowing a TLS extension to be 99 // auto-constucted/recovered by reading in a byte stream. 100 type TLSExtensionWriter interface { 101 TLSExtension 102 103 // Write writes the extension data as a byte slice, up to len(b) bytes from b. 104 // It returns the number of bytes written (0 <= n <= len(b)) and any error encountered. 105 // 106 // The implementation MUST NOT silently drop data if consumed less than len(b) bytes, 107 // instead, it MUST return an error. 108 Write(b []byte) (n int, err error) 109 } 110 111 type TLSExtensionJSON interface { 112 TLSExtension 113 114 // UnmarshalJSON unmarshals the JSON-encoded data into the extension. 115 UnmarshalJSON([]byte) error 116 } 117 118 // SNIExtension implements server_name (0) 119 type SNIExtension struct { 120 ServerName string // not an array because go crypto/tls doesn't support multiple SNIs 121 } 122 123 func (e *SNIExtension) Len() int { 124 // Literal IP addresses, absolute FQDNs, and empty strings are not permitted as SNI values. 125 // See RFC 6066, Section 3. 126 hostName := hostnameInSNI(e.ServerName) 127 if len(hostName) == 0 { 128 return 0 129 } 130 return 4 + 2 + 1 + 2 + len(hostName) 131 } 132 133 func (e *SNIExtension) Read(b []byte) (int, error) { 134 // Literal IP addresses, absolute FQDNs, and empty strings are not permitted as SNI values. 135 // See RFC 6066, Section 3. 136 hostName := hostnameInSNI(e.ServerName) 137 if len(hostName) == 0 { 138 return 0, io.EOF 139 } 140 if len(b) < e.Len() { 141 return 0, io.ErrShortBuffer 142 } 143 // RFC 3546, section 3.1 144 b[0] = byte(extensionServerName >> 8) 145 b[1] = byte(extensionServerName) 146 b[2] = byte((len(hostName) + 5) >> 8) 147 b[3] = byte(len(hostName) + 5) 148 b[4] = byte((len(hostName) + 3) >> 8) 149 b[5] = byte(len(hostName) + 3) 150 // b[6] Server Name Type: host_name (0) 151 b[7] = byte(len(hostName) >> 8) 152 b[8] = byte(len(hostName)) 153 copy(b[9:], []byte(hostName)) 154 return e.Len(), io.EOF 155 } 156 157 func (e *SNIExtension) UnmarshalJSON(_ []byte) error { 158 return nil // no-op 159 } 160 161 // Write is a no-op for StatusRequestExtension. 162 // SNI should not be fingerprinted and is user controlled. 163 func (e *SNIExtension) Write(b []byte) (int, error) { 164 fullLen := len(b) 165 extData := cryptobyte.String(b) 166 // RFC 6066, Section 3 167 var nameList cryptobyte.String 168 if !extData.ReadUint16LengthPrefixed(&nameList) || nameList.Empty() { 169 return fullLen, errors.New("unable to read server name extension data") 170 } 171 var serverName string 172 for !nameList.Empty() { 173 var nameType uint8 174 var serverNameBytes cryptobyte.String 175 if !nameList.ReadUint8(&nameType) || 176 !nameList.ReadUint16LengthPrefixed(&serverNameBytes) || 177 serverNameBytes.Empty() { 178 return fullLen, errors.New("unable to read server name extension data") 179 } 180 if nameType != 0 { 181 continue 182 } 183 if len(serverName) != 0 { 184 return fullLen, errors.New("multiple names of the same name_type in server name extension are prohibited") 185 } 186 serverName = string(serverNameBytes) 187 if strings.HasSuffix(serverName, ".") { 188 return fullLen, errors.New("SNI value may not include a trailing dot") 189 } 190 } 191 // clientHelloSpec.Extensions = append(clientHelloSpec.Extensions, &SNIExtension{}) // gaukas moved this line out from the loop. 192 193 // don't copy SNI from ClientHello to ClientHelloSpec! 194 return fullLen, nil 195 } 196 197 func (e *SNIExtension) writeToUConn(uc *UConn) error { 198 uc.config.ServerName = e.ServerName 199 hostName := hostnameInSNI(e.ServerName) 200 uc.HandshakeState.Hello.ServerName = hostName 201 202 return nil 203 } 204 205 // StatusRequestExtension implements status_request (5) 206 type StatusRequestExtension struct { 207 } 208 209 func (e *StatusRequestExtension) Len() int { 210 return 9 211 } 212 213 func (e *StatusRequestExtension) Read(b []byte) (int, error) { 214 if len(b) < e.Len() { 215 return 0, io.ErrShortBuffer 216 } 217 // RFC 4366, section 3.6 218 b[0] = byte(extensionStatusRequest >> 8) 219 b[1] = byte(extensionStatusRequest) 220 b[2] = 0 221 b[3] = 5 222 b[4] = 1 // OCSP type 223 // Two zero valued uint16s for the two lengths. 224 return e.Len(), io.EOF 225 } 226 227 func (e *StatusRequestExtension) UnmarshalJSON(_ []byte) error { 228 return nil // no-op 229 } 230 231 // Write is a no-op for StatusRequestExtension. No data for this extension. 232 func (e *StatusRequestExtension) Write(b []byte) (int, error) { 233 fullLen := len(b) 234 extData := cryptobyte.String(b) 235 // RFC 4366, Section 3.6 236 var statusType uint8 237 var ignored cryptobyte.String 238 if !extData.ReadUint8(&statusType) || 239 !extData.ReadUint16LengthPrefixed(&ignored) || 240 !extData.ReadUint16LengthPrefixed(&ignored) { 241 return fullLen, errors.New("unable to read status request extension data") 242 } 243 244 if statusType != statusTypeOCSP { 245 return fullLen, errors.New("status request extension statusType is not statusTypeOCSP(1)") 246 } 247 248 return fullLen, nil 249 } 250 251 func (e *StatusRequestExtension) writeToUConn(uc *UConn) error { 252 uc.HandshakeState.Hello.OcspStapling = true 253 return nil 254 } 255 256 // SupportedCurvesExtension implements supported_groups (renamed from "elliptic_curves") (10) 257 type SupportedCurvesExtension struct { 258 Curves []CurveID 259 } 260 261 func (e *SupportedCurvesExtension) Len() int { 262 return 6 + 2*len(e.Curves) 263 } 264 265 func (e *SupportedCurvesExtension) Read(b []byte) (int, error) { 266 if len(b) < e.Len() { 267 return 0, io.ErrShortBuffer 268 } 269 // http://tools.ietf.org/html/rfc4492#section-5.5.1 270 b[0] = byte(extensionSupportedCurves >> 8) 271 b[1] = byte(extensionSupportedCurves) 272 b[2] = byte((2 + 2*len(e.Curves)) >> 8) 273 b[3] = byte(2 + 2*len(e.Curves)) 274 b[4] = byte((2 * len(e.Curves)) >> 8) 275 b[5] = byte(2 * len(e.Curves)) 276 for i, curve := range e.Curves { 277 b[6+2*i] = byte(curve >> 8) 278 b[7+2*i] = byte(curve) 279 } 280 return e.Len(), io.EOF 281 } 282 283 func (e *SupportedCurvesExtension) UnmarshalJSON(data []byte) error { 284 var namedGroups struct { 285 NamedGroupList []string `json:"named_group_list"` 286 } 287 if err := json.Unmarshal(data, &namedGroups); err != nil { 288 return err 289 } 290 291 for _, namedGroup := range namedGroups.NamedGroupList { 292 if namedGroup == "GREASE" { 293 e.Curves = append(e.Curves, GREASE_PLACEHOLDER) 294 continue 295 } 296 297 if group, ok := godicttls.DictSupportedGroupsNameIndexed[namedGroup]; ok { 298 e.Curves = append(e.Curves, CurveID(group)) 299 } else { 300 return fmt.Errorf("unknown named group: %s", namedGroup) 301 } 302 } 303 return nil 304 } 305 306 func (e *SupportedCurvesExtension) Write(b []byte) (int, error) { 307 fullLen := len(b) 308 extData := cryptobyte.String(b) 309 // RFC 4492, sections 5.1.1 and RFC 8446, Section 4.2.7 310 var curvesBytes cryptobyte.String 311 if !extData.ReadUint16LengthPrefixed(&curvesBytes) || curvesBytes.Empty() { 312 return 0, errors.New("unable to read supported curves extension data") 313 } 314 curves := []CurveID{} 315 for !curvesBytes.Empty() { 316 var curve uint16 317 if !curvesBytes.ReadUint16(&curve) { 318 return 0, errors.New("unable to read supported curves extension data") 319 } 320 curves = append(curves, CurveID(unGREASEUint16(curve))) 321 } 322 e.Curves = curves 323 return fullLen, nil 324 } 325 326 func (e *SupportedCurvesExtension) writeToUConn(uc *UConn) error { 327 // uc.config.CurvePreferences = e.Curves // #Restls# Remove 328 uc.HandshakeState.Hello.SupportedCurves = e.Curves 329 return nil 330 } 331 332 // SupportedPointsExtension implements ec_point_formats (11) 333 type SupportedPointsExtension struct { 334 SupportedPoints []uint8 335 } 336 337 func (e *SupportedPointsExtension) Len() int { 338 return 5 + len(e.SupportedPoints) 339 } 340 341 func (e *SupportedPointsExtension) Read(b []byte) (int, error) { 342 if len(b) < e.Len() { 343 return 0, io.ErrShortBuffer 344 } 345 // http://tools.ietf.org/html/rfc4492#section-5.5.2 346 b[0] = byte(extensionSupportedPoints >> 8) 347 b[1] = byte(extensionSupportedPoints) 348 b[2] = byte((1 + len(e.SupportedPoints)) >> 8) 349 b[3] = byte(1 + len(e.SupportedPoints)) 350 b[4] = byte(len(e.SupportedPoints)) 351 for i, pointFormat := range e.SupportedPoints { 352 b[5+i] = pointFormat 353 } 354 return e.Len(), io.EOF 355 } 356 357 func (e *SupportedPointsExtension) UnmarshalJSON(data []byte) error { 358 var pointFormatList struct { 359 ECPointFormatList []string `json:"ec_point_format_list"` 360 } 361 if err := json.Unmarshal(data, &pointFormatList); err != nil { 362 return err 363 } 364 365 for _, pointFormat := range pointFormatList.ECPointFormatList { 366 if format, ok := godicttls.DictECPointFormatNameIndexed[pointFormat]; ok { 367 e.SupportedPoints = append(e.SupportedPoints, format) 368 } else { 369 return fmt.Errorf("unknown point format: %s", pointFormat) 370 } 371 } 372 return nil 373 } 374 375 func (e *SupportedPointsExtension) Write(b []byte) (int, error) { 376 fullLen := len(b) 377 extData := cryptobyte.String(b) 378 // RFC 4492, Section 5.1.2 379 supportedPoints := []uint8{} 380 if !readUint8LengthPrefixed(&extData, &supportedPoints) || 381 len(supportedPoints) == 0 { 382 return 0, errors.New("unable to read supported points extension data") 383 } 384 e.SupportedPoints = supportedPoints 385 return fullLen, nil 386 } 387 388 func (e *SupportedPointsExtension) writeToUConn(uc *UConn) error { 389 uc.HandshakeState.Hello.SupportedPoints = e.SupportedPoints 390 return nil 391 } 392 393 // SignatureAlgorithmsExtension implements signature_algorithms (13) 394 type SignatureAlgorithmsExtension struct { 395 SupportedSignatureAlgorithms []SignatureScheme 396 } 397 398 func (e *SignatureAlgorithmsExtension) Len() int { 399 return 6 + 2*len(e.SupportedSignatureAlgorithms) 400 } 401 402 func (e *SignatureAlgorithmsExtension) Read(b []byte) (int, error) { 403 if len(b) < e.Len() { 404 return 0, io.ErrShortBuffer 405 } 406 // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 407 b[0] = byte(extensionSignatureAlgorithms >> 8) 408 b[1] = byte(extensionSignatureAlgorithms) 409 b[2] = byte((2 + 2*len(e.SupportedSignatureAlgorithms)) >> 8) 410 b[3] = byte(2 + 2*len(e.SupportedSignatureAlgorithms)) 411 b[4] = byte((2 * len(e.SupportedSignatureAlgorithms)) >> 8) 412 b[5] = byte(2 * len(e.SupportedSignatureAlgorithms)) 413 for i, sigScheme := range e.SupportedSignatureAlgorithms { 414 b[6+2*i] = byte(sigScheme >> 8) 415 b[7+2*i] = byte(sigScheme) 416 } 417 return e.Len(), io.EOF 418 } 419 420 func (e *SignatureAlgorithmsExtension) UnmarshalJSON(data []byte) error { 421 var signatureAlgorithms struct { 422 Algorithms []string `json:"supported_signature_algorithms"` 423 } 424 if err := json.Unmarshal(data, &signatureAlgorithms); err != nil { 425 return err 426 } 427 428 for _, sigScheme := range signatureAlgorithms.Algorithms { 429 if sigScheme == "GREASE" { 430 e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, GREASE_PLACEHOLDER) 431 continue 432 } 433 434 if scheme, ok := godicttls.DictSignatureSchemeNameIndexed[sigScheme]; ok { 435 e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, SignatureScheme(scheme)) 436 } else { 437 return fmt.Errorf("unknown signature scheme: %s", sigScheme) 438 } 439 } 440 return nil 441 } 442 443 func (e *SignatureAlgorithmsExtension) Write(b []byte) (int, error) { 444 fullLen := len(b) 445 extData := cryptobyte.String(b) 446 // RFC 5246, Section 7.4.1.4.1 447 var sigAndAlgs cryptobyte.String 448 if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { 449 return 0, errors.New("unable to read signature algorithms extension data") 450 } 451 supportedSignatureAlgorithms := []SignatureScheme{} 452 for !sigAndAlgs.Empty() { 453 var sigAndAlg uint16 454 if !sigAndAlgs.ReadUint16(&sigAndAlg) { 455 return 0, errors.New("unable to read signature algorithms extension data") 456 } 457 supportedSignatureAlgorithms = append( 458 supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) 459 } 460 e.SupportedSignatureAlgorithms = supportedSignatureAlgorithms 461 return fullLen, nil 462 } 463 464 func (e *SignatureAlgorithmsExtension) writeToUConn(uc *UConn) error { 465 uc.HandshakeState.Hello.SupportedSignatureAlgorithms = e.SupportedSignatureAlgorithms 466 return nil 467 } 468 469 // StatusRequestV2Extension implements status_request_v2 (17) 470 type StatusRequestV2Extension struct { 471 } 472 473 func (e *StatusRequestV2Extension) writeToUConn(uc *UConn) error { 474 uc.HandshakeState.Hello.OcspStapling = true 475 return nil 476 } 477 478 func (e *StatusRequestV2Extension) Len() int { 479 return 13 480 } 481 482 func (e *StatusRequestV2Extension) Read(b []byte) (int, error) { 483 if len(b) < e.Len() { 484 return 0, io.ErrShortBuffer 485 } 486 // RFC 4366, section 3.6 487 b[0] = byte(extensionStatusRequestV2 >> 8) 488 b[1] = byte(extensionStatusRequestV2) 489 b[2] = 0 490 b[3] = 9 491 b[4] = 0 492 b[5] = 7 493 b[6] = 2 // OCSP type 494 b[7] = 0 495 b[8] = 4 496 // Two zero valued uint16s for the two lengths. 497 return e.Len(), io.EOF 498 } 499 500 // Write is a no-op for StatusRequestV2Extension. No data for this extension. 501 func (e *StatusRequestV2Extension) Write(b []byte) (int, error) { 502 fullLen := len(b) 503 extData := cryptobyte.String(b) 504 // RFC 4366, Section 3.6 505 var statusType uint8 506 var ignored cryptobyte.String 507 if !extData.ReadUint16LengthPrefixed(&ignored) || 508 !extData.ReadUint8(&statusType) || 509 !extData.ReadUint16LengthPrefixed(&ignored) || 510 !extData.ReadUint16LengthPrefixed(&ignored) || 511 !extData.ReadUint16LengthPrefixed(&ignored) { 512 return fullLen, errors.New("unable to read status request v2 extension data") 513 } 514 515 if statusType != statusV2TypeOCSP { 516 return fullLen, errors.New("status request v2 extension statusType is not statusV2TypeOCSP(2)") 517 } 518 519 return fullLen, nil 520 } 521 522 func (e *StatusRequestV2Extension) UnmarshalJSON(_ []byte) error { 523 return nil // no-op 524 } 525 526 // SignatureAlgorithmsCertExtension implements signature_algorithms_cert (50) 527 type SignatureAlgorithmsCertExtension struct { 528 SupportedSignatureAlgorithms []SignatureScheme 529 } 530 531 func (e *SignatureAlgorithmsCertExtension) Len() int { 532 return 6 + 2*len(e.SupportedSignatureAlgorithms) 533 } 534 535 func (e *SignatureAlgorithmsCertExtension) Read(b []byte) (int, error) { 536 if len(b) < e.Len() { 537 return 0, io.ErrShortBuffer 538 } 539 // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 540 b[0] = byte(extensionSignatureAlgorithmsCert >> 8) 541 b[1] = byte(extensionSignatureAlgorithmsCert) 542 b[2] = byte((2 + 2*len(e.SupportedSignatureAlgorithms)) >> 8) 543 b[3] = byte(2 + 2*len(e.SupportedSignatureAlgorithms)) 544 b[4] = byte((2 * len(e.SupportedSignatureAlgorithms)) >> 8) 545 b[5] = byte(2 * len(e.SupportedSignatureAlgorithms)) 546 for i, sigAndHash := range e.SupportedSignatureAlgorithms { 547 b[6+2*i] = byte(sigAndHash >> 8) 548 b[7+2*i] = byte(sigAndHash) 549 } 550 return e.Len(), io.EOF 551 } 552 553 // Copied from SignatureAlgorithmsExtension.UnmarshalJSON 554 func (e *SignatureAlgorithmsCertExtension) UnmarshalJSON(data []byte) error { 555 var signatureAlgorithms struct { 556 Algorithms []string `json:"supported_signature_algorithms"` 557 } 558 if err := json.Unmarshal(data, &signatureAlgorithms); err != nil { 559 return err 560 } 561 562 for _, sigScheme := range signatureAlgorithms.Algorithms { 563 if sigScheme == "GREASE" { 564 e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, GREASE_PLACEHOLDER) 565 continue 566 } 567 568 if scheme, ok := godicttls.DictSignatureSchemeNameIndexed[sigScheme]; ok { 569 e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, SignatureScheme(scheme)) 570 } else { 571 return fmt.Errorf("unknown cert signature scheme: %s", sigScheme) 572 } 573 } 574 return nil 575 } 576 577 // Write implementation copied from SignatureAlgorithmsExtension.Write 578 // 579 // Warning: not tested. 580 func (e *SignatureAlgorithmsCertExtension) Write(b []byte) (int, error) { 581 fullLen := len(b) 582 extData := cryptobyte.String(b) 583 // RFC 8446, Section 4.2.3 584 var sigAndAlgs cryptobyte.String 585 if !extData.ReadUint16LengthPrefixed(&sigAndAlgs) || sigAndAlgs.Empty() { 586 return 0, errors.New("unable to read signature algorithms extension data") 587 } 588 supportedSignatureAlgorithms := []SignatureScheme{} 589 for !sigAndAlgs.Empty() { 590 var sigAndAlg uint16 591 if !sigAndAlgs.ReadUint16(&sigAndAlg) { 592 return 0, errors.New("unable to read signature algorithms extension data") 593 } 594 supportedSignatureAlgorithms = append( 595 supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) 596 } 597 e.SupportedSignatureAlgorithms = supportedSignatureAlgorithms 598 return fullLen, nil 599 } 600 601 func (e *SignatureAlgorithmsCertExtension) writeToUConn(uc *UConn) error { 602 uc.HandshakeState.Hello.SupportedSignatureAlgorithms = e.SupportedSignatureAlgorithms 603 return nil 604 } 605 606 // ALPNExtension implements application_layer_protocol_negotiation (16) 607 type ALPNExtension struct { 608 AlpnProtocols []string 609 } 610 611 func (e *ALPNExtension) writeToUConn(uc *UConn) error { 612 uc.config.NextProtos = e.AlpnProtocols 613 uc.HandshakeState.Hello.AlpnProtocols = e.AlpnProtocols 614 return nil 615 } 616 617 func (e *ALPNExtension) Len() int { 618 bLen := 2 + 2 + 2 619 for _, s := range e.AlpnProtocols { 620 bLen += 1 + len(s) 621 } 622 return bLen 623 } 624 625 func (e *ALPNExtension) Read(b []byte) (int, error) { 626 if len(b) < e.Len() { 627 return 0, io.ErrShortBuffer 628 } 629 630 b[0] = byte(extensionALPN >> 8) 631 b[1] = byte(extensionALPN & 0xff) 632 lengths := b[2:] 633 b = b[6:] 634 635 stringsLength := 0 636 for _, s := range e.AlpnProtocols { 637 l := len(s) 638 b[0] = byte(l) 639 copy(b[1:], s) 640 b = b[1+l:] 641 stringsLength += 1 + l 642 } 643 644 lengths[2] = byte(stringsLength >> 8) 645 lengths[3] = byte(stringsLength) 646 stringsLength += 2 647 lengths[0] = byte(stringsLength >> 8) 648 lengths[1] = byte(stringsLength) 649 650 return e.Len(), io.EOF 651 } 652 653 func (e *ALPNExtension) UnmarshalJSON(b []byte) error { 654 var protocolNames struct { 655 ProtocolNameList []string `json:"protocol_name_list"` 656 } 657 658 if err := json.Unmarshal(b, &protocolNames); err != nil { 659 return err 660 } 661 662 e.AlpnProtocols = protocolNames.ProtocolNameList 663 return nil 664 } 665 666 func (e *ALPNExtension) Write(b []byte) (int, error) { 667 fullLen := len(b) 668 extData := cryptobyte.String(b) 669 // RFC 7301, Section 3.1 670 var protoList cryptobyte.String 671 if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { 672 return 0, errors.New("unable to read ALPN extension data") 673 } 674 alpnProtocols := []string{} 675 for !protoList.Empty() { 676 var proto cryptobyte.String 677 if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() { 678 return 0, errors.New("unable to read ALPN extension data") 679 } 680 alpnProtocols = append(alpnProtocols, string(proto)) 681 682 } 683 e.AlpnProtocols = alpnProtocols 684 return fullLen, nil 685 } 686 687 // ApplicationSettingsExtension represents the TLS ALPS extension. 688 // At the time of this writing, this extension is currently a draft: 689 // https://datatracker.ietf.org/doc/html/draft-vvv-tls-alps-01 690 type ApplicationSettingsExtension struct { 691 SupportedProtocols []string 692 } 693 694 func (e *ApplicationSettingsExtension) writeToUConn(uc *UConn) error { 695 return nil 696 } 697 698 func (e *ApplicationSettingsExtension) Len() int { 699 bLen := 2 + 2 + 2 // Type + Length + ALPS Extension length 700 for _, s := range e.SupportedProtocols { 701 bLen += 1 + len(s) // Supported ALPN Length + actual length of protocol 702 } 703 return bLen 704 } 705 706 func (e *ApplicationSettingsExtension) Read(b []byte) (int, error) { 707 if len(b) < e.Len() { 708 return 0, io.ErrShortBuffer 709 } 710 711 // Read Type. 712 b[0] = byte(utlsExtensionApplicationSettings >> 8) // hex: 44 dec: 68 713 b[1] = byte(utlsExtensionApplicationSettings & 0xff) // hex: 69 dec: 105 714 715 lengths := b[2:] // get the remaining buffer without Type 716 b = b[6:] // set the buffer to the buffer without Type, Length and ALPS Extension Length (so only the Supported ALPN list remains) 717 718 stringsLength := 0 719 for _, s := range e.SupportedProtocols { 720 l := len(s) // Supported ALPN Length 721 b[0] = byte(l) // Supported ALPN Length in bytes hex: 02 dec: 2 722 copy(b[1:], s) // copy the Supported ALPN as bytes to the buffer 723 b = b[1+l:] // set the buffer to the buffer without the Supported ALPN Length and Supported ALPN (so we can continue to the next protocol in this loop) 724 stringsLength += 1 + l // Supported ALPN Length (the field itself) + Supported ALPN Length (the value) 725 } 726 727 lengths[2] = byte(stringsLength >> 8) // ALPS Extension Length hex: 00 dec: 0 728 lengths[3] = byte(stringsLength) // ALPS Extension Length hex: 03 dec: 3 729 stringsLength += 2 // plus ALPS Extension Length field length 730 lengths[0] = byte(stringsLength >> 8) // Length hex:00 dec: 0 731 lengths[1] = byte(stringsLength) // Length hex: 05 dec: 5 732 733 return e.Len(), io.EOF 734 } 735 736 func (e *ApplicationSettingsExtension) UnmarshalJSON(b []byte) error { 737 var applicationSettingsSupport struct { 738 SupportedProtocols []string `json:"supported_protocols"` 739 } 740 741 if err := json.Unmarshal(b, &applicationSettingsSupport); err != nil { 742 return err 743 } 744 745 e.SupportedProtocols = applicationSettingsSupport.SupportedProtocols 746 return nil 747 } 748 749 // Write implementation copied from ALPNExtension.Write 750 func (e *ApplicationSettingsExtension) Write(b []byte) (int, error) { 751 fullLen := len(b) 752 extData := cryptobyte.String(b) 753 // https://datatracker.ietf.org/doc/html/draft-vvv-tls-alps-01 754 var protoList cryptobyte.String 755 if !extData.ReadUint16LengthPrefixed(&protoList) || protoList.Empty() { 756 return 0, errors.New("unable to read ALPN extension data") 757 } 758 alpnProtocols := []string{} 759 for !protoList.Empty() { 760 var proto cryptobyte.String 761 if !protoList.ReadUint8LengthPrefixed(&proto) || proto.Empty() { 762 return 0, errors.New("unable to read ALPN extension data") 763 } 764 alpnProtocols = append(alpnProtocols, string(proto)) 765 766 } 767 e.SupportedProtocols = alpnProtocols 768 return fullLen, nil 769 } 770 771 // SCTExtension implements signed_certificate_timestamp (18) 772 type SCTExtension struct { 773 } 774 775 func (e *SCTExtension) writeToUConn(uc *UConn) error { 776 uc.HandshakeState.Hello.Scts = true 777 return nil 778 } 779 780 func (e *SCTExtension) Len() int { 781 return 4 782 } 783 784 func (e *SCTExtension) Read(b []byte) (int, error) { 785 if len(b) < e.Len() { 786 return 0, io.ErrShortBuffer 787 } 788 // https://tools.ietf.org/html/rfc6962#section-3.3.1 789 b[0] = byte(extensionSCT >> 8) 790 b[1] = byte(extensionSCT) 791 // zero uint16 for the zero-length extension_data 792 return e.Len(), io.EOF 793 } 794 795 func (e *SCTExtension) UnmarshalJSON(_ []byte) error { 796 return nil // no-op 797 } 798 799 func (e *SCTExtension) Write(_ []byte) (int, error) { 800 return 0, nil 801 } 802 803 // SessionTicketExtension implements session_ticket (35) 804 type SessionTicketExtension struct { 805 Session *ClientSessionState 806 } 807 808 func (e *SessionTicketExtension) writeToUConn(uc *UConn) error { 809 if e.Session != nil { 810 uc.HandshakeState.Session = e.Session.session 811 uc.HandshakeState.Hello.SessionTicket = e.Session.ticket 812 } 813 return nil 814 } 815 816 func (e *SessionTicketExtension) Len() int { 817 if e.Session != nil { 818 return 4 + len(e.Session.ticket) 819 } 820 return 4 821 } 822 823 func (e *SessionTicketExtension) Read(b []byte) (int, error) { 824 if len(b) < e.Len() { 825 return 0, io.ErrShortBuffer 826 } 827 828 extBodyLen := e.Len() - 4 829 830 b[0] = byte(extensionSessionTicket >> 8) 831 b[1] = byte(extensionSessionTicket) 832 b[2] = byte(extBodyLen >> 8) 833 b[3] = byte(extBodyLen) 834 if extBodyLen > 0 { 835 copy(b[4:], e.Session.ticket) 836 } 837 return e.Len(), io.EOF 838 } 839 840 func (e *SessionTicketExtension) UnmarshalJSON(_ []byte) error { 841 return nil // no-op 842 } 843 844 func (e *SessionTicketExtension) Write(_ []byte) (int, error) { 845 // RFC 5077, Section 3.2 846 return 0, nil 847 } 848 849 // GenericExtension allows to include in ClientHello arbitrary unsupported extensions. 850 // It is not defined in TLS RFCs nor by IANA. 851 // If a server echoes this extension back, the handshake will likely fail due to no further support. 852 type GenericExtension struct { 853 Id uint16 854 Data []byte 855 } 856 857 func (e *GenericExtension) writeToUConn(uc *UConn) error { 858 return nil 859 } 860 861 func (e *GenericExtension) Len() int { 862 return 4 + len(e.Data) 863 } 864 865 func (e *GenericExtension) Read(b []byte) (int, error) { 866 if len(b) < e.Len() { 867 return 0, io.ErrShortBuffer 868 } 869 870 b[0] = byte(e.Id >> 8) 871 b[1] = byte(e.Id) 872 b[2] = byte(len(e.Data) >> 8) 873 b[3] = byte(len(e.Data)) 874 if len(e.Data) > 0 { 875 copy(b[4:], e.Data) 876 } 877 return e.Len(), io.EOF 878 } 879 880 func (e *GenericExtension) UnmarshalJSON(b []byte) error { 881 var genericExtension struct { 882 Name string `json:"name"` 883 Data []byte `json:"data"` 884 } 885 if err := json.Unmarshal(b, &genericExtension); err != nil { 886 return err 887 } 888 889 // lookup extension ID by name 890 if id, ok := godicttls.DictExtTypeNameIndexed[genericExtension.Name]; ok { 891 e.Id = id 892 } else { 893 return fmt.Errorf("unknown extension name %s", genericExtension.Name) 894 } 895 e.Data = genericExtension.Data 896 return nil 897 } 898 899 // ExtendedMasterSecretExtension implements extended_master_secret (23) 900 // 901 // Was named as ExtendedMasterSecretExtension, renamed due to crypto/tls 902 // implemented this extension's support. 903 type ExtendedMasterSecretExtension struct { 904 } 905 906 // TODO: update when this extension is implemented in crypto/tls 907 // but we probably won't have to enable it in Config 908 func (e *ExtendedMasterSecretExtension) writeToUConn(uc *UConn) error { 909 uc.HandshakeState.Hello.Ems = true 910 return nil 911 } 912 913 func (e *ExtendedMasterSecretExtension) Len() int { 914 return 4 915 } 916 917 func (e *ExtendedMasterSecretExtension) Read(b []byte) (int, error) { 918 if len(b) < e.Len() { 919 return 0, io.ErrShortBuffer 920 } 921 // https://tools.ietf.org/html/rfc7627 922 b[0] = byte(extensionExtendedMasterSecret >> 8) 923 b[1] = byte(extensionExtendedMasterSecret) 924 // The length is 0 925 return e.Len(), io.EOF 926 } 927 928 func (e *ExtendedMasterSecretExtension) UnmarshalJSON(_ []byte) error { 929 return nil // no-op 930 } 931 932 func (e *ExtendedMasterSecretExtension) Write(_ []byte) (int, error) { 933 // https://tools.ietf.org/html/rfc7627 934 return 0, nil 935 } 936 937 // var extendedMasterSecretLabel = []byte("extended master secret") 938 939 // extendedMasterFromPreMasterSecret generates the master secret from the pre-master 940 // secret and session hash. See https://tools.ietf.org/html/rfc7627#section-4 941 func extendedMasterFromPreMasterSecret(version uint16, suite *cipherSuite, preMasterSecret []byte, sessionHash []byte) []byte { 942 masterSecret := make([]byte, masterSecretLength) 943 prfForVersion(version, suite)(masterSecret, preMasterSecret, extendedMasterSecretLabel, sessionHash) 944 return masterSecret 945 } 946 947 // GREASE stinks with dead parrots, have to be super careful, and, if possible, not include GREASE 948 // https://github.com/google/boringssl/blob/1c68fa2350936ca5897a66b430ebaf333a0e43f5/ssl/internal.h 949 const ( 950 ssl_grease_cipher = iota 951 ssl_grease_group 952 ssl_grease_extension1 953 ssl_grease_extension2 954 ssl_grease_version 955 ssl_grease_ticket_extension 956 ssl_grease_last_index = ssl_grease_ticket_extension 957 ) 958 959 // it is responsibility of user not to generate multiple grease extensions with same value 960 type UtlsGREASEExtension struct { 961 Value uint16 962 Body []byte // in Chrome first grease has empty body, second grease has a single zero byte 963 } 964 965 func (e *UtlsGREASEExtension) writeToUConn(uc *UConn) error { 966 return nil 967 } 968 969 // will panic if ssl_grease_last_index[index] is out of bounds. 970 func GetBoringGREASEValue(greaseSeed [ssl_grease_last_index]uint16, index int) uint16 { 971 // GREASE value is back from deterministic to random. 972 // https://github.com/google/boringssl/blob/a365138ac60f38b64bfc608b493e0f879845cb88/ssl/handshake_client.c#L530 973 ret := uint16(greaseSeed[index]) 974 /* This generates a random value of the form 0xωaωa, for all 0 ≤ ω < 16. */ 975 ret = (ret & 0xf0) | 0x0a 976 ret |= ret << 8 977 return ret 978 } 979 980 func (e *UtlsGREASEExtension) Len() int { 981 return 4 + len(e.Body) 982 } 983 984 func (e *UtlsGREASEExtension) Read(b []byte) (int, error) { 985 if len(b) < e.Len() { 986 return 0, io.ErrShortBuffer 987 } 988 989 b[0] = byte(e.Value >> 8) 990 b[1] = byte(e.Value) 991 b[2] = byte(len(e.Body) >> 8) 992 b[3] = byte(len(e.Body)) 993 if len(e.Body) > 0 { 994 copy(b[4:], e.Body) 995 } 996 return e.Len(), io.EOF 997 } 998 999 func (e *UtlsGREASEExtension) Write(b []byte) (int, error) { 1000 e.Value = GREASE_PLACEHOLDER 1001 e.Body = make([]byte, len(b)) 1002 n := copy(e.Body, b) 1003 return n, nil 1004 } 1005 1006 func (e *UtlsGREASEExtension) UnmarshalJSON(b []byte) error { 1007 var jsonObj struct { 1008 Id uint16 `json:"id"` 1009 Data []byte `json:"data"` 1010 KeepID bool `json:"keep_id"` 1011 KeepData bool `json:"keep_data"` 1012 } 1013 1014 if err := json.Unmarshal(b, &jsonObj); err != nil { 1015 return err 1016 } 1017 1018 if jsonObj.Id == 0 { 1019 return nil 1020 } 1021 1022 if isGREASEUint16(jsonObj.Id) { 1023 if jsonObj.KeepID { 1024 e.Value = jsonObj.Id 1025 } 1026 if jsonObj.KeepData { 1027 e.Body = jsonObj.Data 1028 } 1029 return nil 1030 } else { 1031 return errors.New("GREASE extension id must be a GREASE value") 1032 } 1033 } 1034 1035 // UtlsPaddingExtension implements padding (21) 1036 type UtlsPaddingExtension struct { 1037 PaddingLen int 1038 WillPad bool // set to false to disable extension 1039 1040 // Functor for deciding on padding length based on unpadded ClientHello length. 1041 // If willPad is false, then this extension should not be included. 1042 GetPaddingLen func(clientHelloUnpaddedLen int) (paddingLen int, willPad bool) 1043 } 1044 1045 func (e *UtlsPaddingExtension) writeToUConn(uc *UConn) error { 1046 return nil 1047 } 1048 1049 func (e *UtlsPaddingExtension) Len() int { 1050 if e.WillPad { 1051 return 4 + e.PaddingLen 1052 } else { 1053 return 0 1054 } 1055 } 1056 1057 func (e *UtlsPaddingExtension) Update(clientHelloUnpaddedLen int) { 1058 if e.GetPaddingLen != nil { 1059 e.PaddingLen, e.WillPad = e.GetPaddingLen(clientHelloUnpaddedLen) 1060 } 1061 } 1062 1063 func (e *UtlsPaddingExtension) Read(b []byte) (int, error) { 1064 if !e.WillPad { 1065 return 0, io.EOF 1066 } 1067 if len(b) < e.Len() { 1068 return 0, io.ErrShortBuffer 1069 } 1070 // https://tools.ietf.org/html/rfc7627 1071 b[0] = byte(utlsExtensionPadding >> 8) 1072 b[1] = byte(utlsExtensionPadding) 1073 b[2] = byte(e.PaddingLen >> 8) 1074 b[3] = byte(e.PaddingLen) 1075 return e.Len(), io.EOF 1076 } 1077 1078 func (e *UtlsPaddingExtension) UnmarshalJSON(b []byte) error { 1079 var jsonObj struct { 1080 Length uint `json:"len"` 1081 } 1082 if err := json.Unmarshal(b, &jsonObj); err != nil { 1083 return err 1084 } 1085 1086 if jsonObj.Length == 0 { 1087 e.GetPaddingLen = BoringPaddingStyle 1088 } else { 1089 e.PaddingLen = int(jsonObj.Length) 1090 e.WillPad = true 1091 } 1092 1093 return nil 1094 } 1095 1096 func (e *UtlsPaddingExtension) Write(_ []byte) (int, error) { 1097 e.GetPaddingLen = BoringPaddingStyle 1098 return 0, nil 1099 } 1100 1101 // https://github.com/google/boringssl/blob/7d7554b6b3c79e707e25521e61e066ce2b996e4c/ssl/t1_lib.c#L2803 1102 func BoringPaddingStyle(unpaddedLen int) (int, bool) { 1103 if unpaddedLen > 0xff && unpaddedLen < 0x200 { 1104 paddingLen := 0x200 - unpaddedLen 1105 if paddingLen >= 4+1 { 1106 paddingLen -= 4 1107 } else { 1108 paddingLen = 1 1109 } 1110 return paddingLen, true 1111 } 1112 return 0, false 1113 } 1114 1115 // UtlsCompressCertExtension implements compress_certificate (27) and is only implemented client-side 1116 // for server certificates. Alternate certificate message formats 1117 // (https://datatracker.ietf.org/doc/html/rfc7250) are not supported. 1118 // 1119 // See https://datatracker.ietf.org/doc/html/rfc8879#section-3 1120 type UtlsCompressCertExtension struct { 1121 Algorithms []CertCompressionAlgo 1122 } 1123 1124 func (e *UtlsCompressCertExtension) writeToUConn(uc *UConn) error { 1125 uc.certCompressionAlgs = e.Algorithms 1126 return nil 1127 } 1128 1129 func (e *UtlsCompressCertExtension) Len() int { 1130 return 4 + 1 + (2 * len(e.Algorithms)) 1131 } 1132 1133 func (e *UtlsCompressCertExtension) Read(b []byte) (int, error) { 1134 if len(b) < e.Len() { 1135 return 0, io.ErrShortBuffer 1136 } 1137 b[0] = byte(utlsExtensionCompressCertificate >> 8) 1138 b[1] = byte(utlsExtensionCompressCertificate & 0xff) 1139 1140 extLen := 2 * len(e.Algorithms) 1141 if extLen > 255 { 1142 return 0, errors.New("too many certificate compression methods") 1143 } 1144 1145 // Extension data length. 1146 b[2] = byte((extLen + 1) >> 8) 1147 b[3] = byte((extLen + 1) & 0xff) 1148 1149 // Methods length. 1150 b[4] = byte(extLen) 1151 1152 i := 5 1153 for _, compMethod := range e.Algorithms { 1154 b[i] = byte(compMethod >> 8) 1155 b[i+1] = byte(compMethod) 1156 i += 2 1157 } 1158 return e.Len(), io.EOF 1159 } 1160 1161 func (e *UtlsCompressCertExtension) Write(b []byte) (int, error) { 1162 fullLen := len(b) 1163 extData := cryptobyte.String(b) 1164 methods := []CertCompressionAlgo{} 1165 methodsRaw := new(cryptobyte.String) 1166 if !extData.ReadUint8LengthPrefixed(methodsRaw) { 1167 return 0, errors.New("unable to read cert compression algorithms extension data") 1168 } 1169 for !methodsRaw.Empty() { 1170 var method uint16 1171 if !methodsRaw.ReadUint16(&method) { 1172 return 0, errors.New("unable to read cert compression algorithms extension data") 1173 } 1174 methods = append(methods, CertCompressionAlgo(method)) 1175 } 1176 1177 e.Algorithms = methods 1178 return fullLen, nil 1179 } 1180 1181 func (e *UtlsCompressCertExtension) UnmarshalJSON(b []byte) error { 1182 var certificateCompressionAlgorithms struct { 1183 Algorithms []string `json:"algorithms"` 1184 } 1185 if err := json.Unmarshal(b, &certificateCompressionAlgorithms); err != nil { 1186 return err 1187 } 1188 1189 for _, algorithm := range certificateCompressionAlgorithms.Algorithms { 1190 if alg, ok := godicttls.DictCertificateCompressionAlgorithmNameIndexed[algorithm]; ok { 1191 e.Algorithms = append(e.Algorithms, CertCompressionAlgo(alg)) 1192 } else { 1193 return fmt.Errorf("unknown certificate compression algorithm %s", algorithm) 1194 } 1195 } 1196 return nil 1197 } 1198 1199 // KeyShareExtension implements key_share (51) and is for TLS 1.3 only. 1200 type KeyShareExtension struct { 1201 KeyShares []KeyShare 1202 } 1203 1204 func (e *KeyShareExtension) Len() int { 1205 return 4 + 2 + e.keySharesLen() 1206 } 1207 1208 func (e *KeyShareExtension) keySharesLen() int { 1209 extLen := 0 1210 for _, ks := range e.KeyShares { 1211 extLen += 4 + len(ks.Data) 1212 } 1213 return extLen 1214 } 1215 1216 func (e *KeyShareExtension) Read(b []byte) (int, error) { 1217 if len(b) < e.Len() { 1218 return 0, io.ErrShortBuffer 1219 } 1220 1221 b[0] = byte(extensionKeyShare >> 8) 1222 b[1] = byte(extensionKeyShare) 1223 keySharesLen := e.keySharesLen() 1224 b[2] = byte((keySharesLen + 2) >> 8) 1225 b[3] = byte(keySharesLen + 2) 1226 b[4] = byte((keySharesLen) >> 8) 1227 b[5] = byte(keySharesLen) 1228 1229 i := 6 1230 for _, ks := range e.KeyShares { 1231 b[i] = byte(ks.Group >> 8) 1232 b[i+1] = byte(ks.Group) 1233 b[i+2] = byte(len(ks.Data) >> 8) 1234 b[i+3] = byte(len(ks.Data)) 1235 copy(b[i+4:], ks.Data) 1236 i += 4 + len(ks.Data) 1237 } 1238 1239 return e.Len(), io.EOF 1240 } 1241 1242 func (e *KeyShareExtension) Write(b []byte) (int, error) { 1243 fullLen := len(b) 1244 extData := cryptobyte.String(b) 1245 // RFC 8446, Section 4.2.8 1246 var clientShares cryptobyte.String 1247 if !extData.ReadUint16LengthPrefixed(&clientShares) { 1248 return 0, errors.New("unable to read key share extension data") 1249 } 1250 keyShares := []KeyShare{} 1251 for !clientShares.Empty() { 1252 var ks KeyShare 1253 var group uint16 1254 if !clientShares.ReadUint16(&group) || 1255 !readUint16LengthPrefixed(&clientShares, &ks.Data) || 1256 len(ks.Data) == 0 { 1257 return 0, errors.New("unable to read key share extension data") 1258 } 1259 ks.Group = CurveID(unGREASEUint16(group)) 1260 // if not GREASE, key share data will be discarded as it should 1261 // be generated per connection 1262 if ks.Group != GREASE_PLACEHOLDER { 1263 ks.Data = nil 1264 } 1265 keyShares = append(keyShares, ks) 1266 } 1267 e.KeyShares = keyShares 1268 return fullLen, nil 1269 } 1270 1271 func (e *KeyShareExtension) writeToUConn(uc *UConn) error { 1272 uc.HandshakeState.Hello.KeyShares = e.KeyShares 1273 return nil 1274 } 1275 1276 func (e *KeyShareExtension) UnmarshalJSON(b []byte) error { 1277 var keyShareClientHello struct { 1278 ClientShares []struct { 1279 Group string `json:"group"` 1280 KeyExchange []uint8 `json:"key_exchange"` 1281 } `json:"client_shares"` 1282 } 1283 if err := json.Unmarshal(b, &keyShareClientHello); err != nil { 1284 return err 1285 } 1286 1287 for _, clientShare := range keyShareClientHello.ClientShares { 1288 if clientShare.Group == "GREASE" { 1289 e.KeyShares = append(e.KeyShares, KeyShare{ 1290 Group: GREASE_PLACEHOLDER, 1291 Data: clientShare.KeyExchange, 1292 }) 1293 continue 1294 } 1295 1296 if groupID, ok := godicttls.DictSupportedGroupsNameIndexed[clientShare.Group]; ok { 1297 ks := KeyShare{ 1298 Group: CurveID(groupID), 1299 Data: clientShare.KeyExchange, 1300 } 1301 e.KeyShares = append(e.KeyShares, ks) 1302 } else { 1303 return fmt.Errorf("unknown group %s", clientShare.Group) 1304 } 1305 } 1306 return nil 1307 } 1308 1309 // QUICTransportParametersExtension implements quic_transport_parameters (57). 1310 // 1311 // Currently, it works as a fake extension and does not support parsing, since 1312 // the QUICConn provided by this package does not really understand these 1313 // parameters. 1314 type QUICTransportParametersExtension struct { 1315 TransportParameters TransportParameters 1316 1317 marshalResult []byte // TransportParameters will be marshaled into this slice 1318 } 1319 1320 func (e *QUICTransportParametersExtension) Len() int { 1321 if e.marshalResult == nil { 1322 e.marshalResult = e.TransportParameters.Marshal() 1323 } 1324 return 4 + len(e.marshalResult) 1325 } 1326 1327 func (e *QUICTransportParametersExtension) Read(b []byte) (int, error) { 1328 if len(b) < e.Len() { 1329 return 0, io.ErrShortBuffer 1330 } 1331 1332 b[0] = byte(extensionQUICTransportParameters >> 8) 1333 b[1] = byte(extensionQUICTransportParameters) 1334 // e.Len() is called before so that e.marshalResult is set 1335 b[2] = byte((len(e.marshalResult)) >> 8) 1336 b[3] = byte(len(e.marshalResult)) 1337 copy(b[4:], e.marshalResult) 1338 1339 return e.Len(), io.EOF 1340 } 1341 1342 func (e *QUICTransportParametersExtension) writeToUConn(*UConn) error { 1343 // no need to set *UConn.quic.transportParams, since it is unused 1344 return nil 1345 } 1346 1347 // PSKKeyExchangeModesExtension implements psk_key_exchange_modes (45). 1348 type PSKKeyExchangeModesExtension struct { 1349 Modes []uint8 1350 } 1351 1352 func (e *PSKKeyExchangeModesExtension) Len() int { 1353 return 4 + 1 + len(e.Modes) 1354 } 1355 1356 func (e *PSKKeyExchangeModesExtension) Read(b []byte) (int, error) { 1357 if len(b) < e.Len() { 1358 return 0, io.ErrShortBuffer 1359 } 1360 1361 if len(e.Modes) > 255 { 1362 return 0, errors.New("too many PSK Key Exchange modes") 1363 } 1364 1365 b[0] = byte(extensionPSKModes >> 8) 1366 b[1] = byte(extensionPSKModes) 1367 1368 modesLen := len(e.Modes) 1369 b[2] = byte((modesLen + 1) >> 8) 1370 b[3] = byte(modesLen + 1) 1371 b[4] = byte(modesLen) 1372 1373 if len(e.Modes) > 0 { 1374 copy(b[5:], e.Modes) 1375 } 1376 1377 return e.Len(), io.EOF 1378 } 1379 1380 func (e *PSKKeyExchangeModesExtension) Write(b []byte) (int, error) { 1381 fullLen := len(b) 1382 extData := cryptobyte.String(b) 1383 // RFC 8446, Section 4.2.9 1384 // TODO: PSK Modes have their own form of GREASE-ing which is not currently implemented 1385 // the current functionality will NOT re-GREASE/re-randomize these values when using a fingerprinted spec 1386 // https://github.com/refraction-networking/utls/pull/58#discussion_r522354105 1387 // https://tools.ietf.org/html/draft-ietf-tls-grease-01#section-2 1388 pskModes := []uint8{} 1389 if !readUint8LengthPrefixed(&extData, &pskModes) { 1390 return 0, errors.New("unable to read PSK extension data") 1391 } 1392 e.Modes = pskModes 1393 return fullLen, nil 1394 } 1395 1396 func (e *PSKKeyExchangeModesExtension) writeToUConn(uc *UConn) error { 1397 uc.HandshakeState.Hello.PskModes = e.Modes 1398 return nil 1399 } 1400 1401 func (e *PSKKeyExchangeModesExtension) UnmarshalJSON(b []byte) error { 1402 var pskKeyExchangeModes struct { 1403 Modes []string `json:"ke_modes"` 1404 } 1405 if err := json.Unmarshal(b, &pskKeyExchangeModes); err != nil { 1406 return err 1407 } 1408 1409 for _, mode := range pskKeyExchangeModes.Modes { 1410 if modeID, ok := godicttls.DictPSKKeyExchangeModeNameIndexed[mode]; ok { 1411 e.Modes = append(e.Modes, modeID) 1412 } else { 1413 return fmt.Errorf("unknown PSK Key Exchange Mode %s", mode) 1414 } 1415 } 1416 return nil 1417 } 1418 1419 // SupportedVersionsExtension implements supported_versions (43). 1420 type SupportedVersionsExtension struct { 1421 Versions []uint16 1422 } 1423 1424 func (e *SupportedVersionsExtension) writeToUConn(uc *UConn) error { 1425 uc.HandshakeState.Hello.SupportedVersions = e.Versions 1426 return nil 1427 } 1428 1429 func (e *SupportedVersionsExtension) Len() int { 1430 return 4 + 1 + (2 * len(e.Versions)) 1431 } 1432 1433 func (e *SupportedVersionsExtension) Read(b []byte) (int, error) { 1434 if len(b) < e.Len() { 1435 return 0, io.ErrShortBuffer 1436 } 1437 extLen := 2 * len(e.Versions) 1438 if extLen > 255 { 1439 return 0, errors.New("too many supported versions") 1440 } 1441 1442 b[0] = byte(extensionSupportedVersions >> 8) 1443 b[1] = byte(extensionSupportedVersions) 1444 b[2] = byte((extLen + 1) >> 8) 1445 b[3] = byte(extLen + 1) 1446 b[4] = byte(extLen) 1447 1448 i := 5 1449 for _, sv := range e.Versions { 1450 b[i] = byte(sv >> 8) 1451 b[i+1] = byte(sv) 1452 i += 2 1453 } 1454 return e.Len(), io.EOF 1455 } 1456 1457 func (e *SupportedVersionsExtension) Write(b []byte) (int, error) { 1458 fullLen := len(b) 1459 extData := cryptobyte.String(b) 1460 // RFC 8446, Section 4.2.1 1461 var versList cryptobyte.String 1462 if !extData.ReadUint8LengthPrefixed(&versList) || versList.Empty() { 1463 return 0, errors.New("unable to read supported versions extension data") 1464 } 1465 supportedVersions := []uint16{} 1466 for !versList.Empty() { 1467 var vers uint16 1468 if !versList.ReadUint16(&vers) { 1469 return 0, errors.New("unable to read supported versions extension data") 1470 } 1471 supportedVersions = append(supportedVersions, unGREASEUint16(vers)) 1472 } 1473 e.Versions = supportedVersions 1474 return fullLen, nil 1475 } 1476 1477 func (e *SupportedVersionsExtension) UnmarshalJSON(b []byte) error { 1478 var supportedVersions struct { 1479 Versions []string `json:"versions"` 1480 } 1481 if err := json.Unmarshal(b, &supportedVersions); err != nil { 1482 return err 1483 } 1484 1485 for _, version := range supportedVersions.Versions { 1486 switch version { 1487 case "GREASE": 1488 e.Versions = append(e.Versions, GREASE_PLACEHOLDER) 1489 case "TLS 1.3": 1490 e.Versions = append(e.Versions, VersionTLS13) 1491 case "TLS 1.2": 1492 e.Versions = append(e.Versions, VersionTLS12) 1493 case "TLS 1.1": 1494 e.Versions = append(e.Versions, VersionTLS11) 1495 case "TLS 1.0": 1496 e.Versions = append(e.Versions, VersionTLS10) 1497 case "SSL 3.0": // deprecated 1498 // e.Versions = append(e.Versions, VersionSSL30) 1499 return fmt.Errorf("SSL 3.0 is deprecated") 1500 default: 1501 return fmt.Errorf("unknown version %s", version) 1502 } 1503 } 1504 return nil 1505 } 1506 1507 // CookieExtension implements cookie (44). 1508 // MUST NOT be part of initial ClientHello 1509 type CookieExtension struct { 1510 Cookie []byte 1511 } 1512 1513 func (e *CookieExtension) writeToUConn(uc *UConn) error { 1514 return nil 1515 } 1516 1517 func (e *CookieExtension) Len() int { 1518 return 4 + len(e.Cookie) 1519 } 1520 1521 func (e *CookieExtension) Read(b []byte) (int, error) { 1522 if len(b) < e.Len() { 1523 return 0, io.ErrShortBuffer 1524 } 1525 1526 b[0] = byte(extensionCookie >> 8) 1527 b[1] = byte(extensionCookie) 1528 b[2] = byte(len(e.Cookie) >> 8) 1529 b[3] = byte(len(e.Cookie)) 1530 if len(e.Cookie) > 0 { 1531 copy(b[4:], e.Cookie) 1532 } 1533 return e.Len(), io.EOF 1534 } 1535 1536 func (e *CookieExtension) UnmarshalJSON(data []byte) error { 1537 var cookie struct { 1538 Cookie []uint8 `json:"cookie"` 1539 } 1540 if err := json.Unmarshal(data, &cookie); err != nil { 1541 return err 1542 } 1543 e.Cookie = []byte(cookie.Cookie) 1544 return nil 1545 } 1546 1547 // NPNExtension implements next_protocol_negotiation (Not IANA assigned) 1548 type NPNExtension struct { 1549 NextProtos []string 1550 } 1551 1552 func (e *NPNExtension) writeToUConn(uc *UConn) error { 1553 uc.config.NextProtos = e.NextProtos 1554 uc.HandshakeState.Hello.NextProtoNeg = true 1555 return nil 1556 } 1557 1558 func (e *NPNExtension) Len() int { 1559 return 4 1560 } 1561 1562 func (e *NPNExtension) Read(b []byte) (int, error) { 1563 if len(b) < e.Len() { 1564 return 0, io.ErrShortBuffer 1565 } 1566 b[0] = byte(extensionNextProtoNeg >> 8) 1567 b[1] = byte(extensionNextProtoNeg & 0xff) 1568 // The length is always 0 1569 return e.Len(), io.EOF 1570 } 1571 1572 // Write is a no-op for NPNExtension. NextProtos are not included in the 1573 // ClientHello. 1574 func (e *NPNExtension) Write(_ []byte) (int, error) { 1575 return 0, nil 1576 } 1577 1578 // draft-agl-tls-nextprotoneg-04: 1579 // The "extension_data" field of a "next_protocol_negotiation" extension 1580 // in a "ClientHello" MUST be empty. 1581 func (e *NPNExtension) UnmarshalJSON(_ []byte) error { 1582 return nil 1583 } 1584 1585 // RenegotiationInfoExtension implements renegotiation_info (65281) 1586 type RenegotiationInfoExtension struct { 1587 // Renegotiation field limits how many times client will perform renegotiation: no limit, once, or never. 1588 // The extension still will be sent, even if Renegotiation is set to RenegotiateNever. 1589 Renegotiation RenegotiationSupport // [UTLS] added for internal use only 1590 1591 // RenegotiatedConnection is not yet properly handled, now we 1592 // are just copying it to the client hello. 1593 // 1594 // If this is the initial handshake for a connection, then the 1595 // "renegotiated_connection" field is of zero length in both the 1596 // ClientHello and the ServerHello. 1597 // RenegotiatedConnection []byte 1598 } 1599 1600 func (e *RenegotiationInfoExtension) Len() int { 1601 return 5 // + len(e.RenegotiatedConnection) 1602 } 1603 1604 func (e *RenegotiationInfoExtension) Read(b []byte) (int, error) { 1605 if len(b) < e.Len() { 1606 return 0, io.ErrShortBuffer 1607 } 1608 1609 // dataLen := len(e.RenegotiatedConnection) 1610 extBodyLen := 1 // + len(dataLen) 1611 1612 b[0] = byte(extensionRenegotiationInfo >> 8) 1613 b[1] = byte(extensionRenegotiationInfo & 0xff) 1614 b[2] = byte(extBodyLen >> 8) 1615 b[3] = byte(extBodyLen) 1616 // b[4] = byte(dataLen) 1617 // copy(b[5:], e.RenegotiatedConnection) 1618 1619 return e.Len(), io.EOF 1620 } 1621 1622 func (e *RenegotiationInfoExtension) UnmarshalJSON(_ []byte) error { 1623 e.Renegotiation = RenegotiateOnceAsClient 1624 return nil 1625 } 1626 1627 func (e *RenegotiationInfoExtension) Write(_ []byte) (int, error) { 1628 e.Renegotiation = RenegotiateOnceAsClient // none empty or other modes are unsupported 1629 // extData := cryptobyte.String(b) 1630 // var renegotiatedConnection cryptobyte.String 1631 // if !extData.ReadUint8LengthPrefixed(&renegotiatedConnection) || !extData.Empty() { 1632 // return 0, errors.New("unable to read renegotiation info extension data") 1633 // } 1634 // e.RenegotiatedConnection = make([]byte, len(renegotiatedConnection)) 1635 // copy(e.RenegotiatedConnection, renegotiatedConnection) 1636 return 0, nil 1637 } 1638 1639 func (e *RenegotiationInfoExtension) writeToUConn(uc *UConn) error { 1640 uc.config.Renegotiation = e.Renegotiation 1641 switch e.Renegotiation { 1642 case RenegotiateOnceAsClient: 1643 fallthrough 1644 case RenegotiateFreelyAsClient: 1645 uc.HandshakeState.Hello.SecureRenegotiationSupported = true 1646 case RenegotiateNever: 1647 default: 1648 } 1649 return nil 1650 } 1651 1652 /* 1653 FAKE EXTENSIONS 1654 */ 1655 1656 type FakeChannelIDExtension struct { 1657 // The extension ID changed from 30031 to 30032. Set to true to use the old extension ID. 1658 OldExtensionID bool 1659 } 1660 1661 func (e *FakeChannelIDExtension) writeToUConn(uc *UConn) error { 1662 return nil 1663 } 1664 1665 func (e *FakeChannelIDExtension) Len() int { 1666 return 4 1667 } 1668 1669 func (e *FakeChannelIDExtension) Read(b []byte) (int, error) { 1670 if len(b) < e.Len() { 1671 return 0, io.ErrShortBuffer 1672 } 1673 extensionID := fakeExtensionChannelID 1674 if e.OldExtensionID { 1675 extensionID = fakeOldExtensionChannelID 1676 } 1677 // https://tools.ietf.org/html/draft-balfanz-tls-channelid-00 1678 b[0] = byte(extensionID >> 8) 1679 b[1] = byte(extensionID & 0xff) 1680 // The length is 0 1681 return e.Len(), io.EOF 1682 } 1683 1684 func (e *FakeChannelIDExtension) Write(_ []byte) (int, error) { 1685 return 0, nil 1686 } 1687 1688 func (e *FakeChannelIDExtension) UnmarshalJSON(_ []byte) error { 1689 return nil 1690 } 1691 1692 // FakeRecordSizeLimitExtension implements record_size_limit (28) 1693 // but with no support. 1694 type FakeRecordSizeLimitExtension struct { 1695 Limit uint16 1696 } 1697 1698 func (e *FakeRecordSizeLimitExtension) writeToUConn(uc *UConn) error { 1699 return nil 1700 } 1701 1702 func (e *FakeRecordSizeLimitExtension) Len() int { 1703 return 6 1704 } 1705 1706 func (e *FakeRecordSizeLimitExtension) Read(b []byte) (int, error) { 1707 if len(b) < e.Len() { 1708 return 0, io.ErrShortBuffer 1709 } 1710 // https://tools.ietf.org/html/draft-balfanz-tls-channelid-00 1711 b[0] = byte(fakeRecordSizeLimit >> 8) 1712 b[1] = byte(fakeRecordSizeLimit & 0xff) 1713 1714 b[2] = byte(0) 1715 b[3] = byte(2) 1716 1717 b[4] = byte(e.Limit >> 8) 1718 b[5] = byte(e.Limit & 0xff) 1719 return e.Len(), io.EOF 1720 } 1721 1722 func (e *FakeRecordSizeLimitExtension) Write(b []byte) (int, error) { 1723 fullLen := len(b) 1724 extData := cryptobyte.String(b) 1725 if !extData.ReadUint16(&e.Limit) { 1726 return 0, errors.New("unable to read record size limit extension data") 1727 } 1728 return fullLen, nil 1729 } 1730 1731 func (e *FakeRecordSizeLimitExtension) UnmarshalJSON(data []byte) error { 1732 var limitAccepter struct { 1733 Limit uint16 `json:"record_size_limit"` 1734 } 1735 if err := json.Unmarshal(data, &limitAccepter); err != nil { 1736 return err 1737 } 1738 1739 e.Limit = limitAccepter.Limit 1740 return nil 1741 } 1742 1743 type DelegatedCredentialsExtension = FakeDelegatedCredentialsExtension 1744 1745 // https://tools.ietf.org/html/rfc8472#section-2 1746 type FakeTokenBindingExtension struct { 1747 MajorVersion, MinorVersion uint8 1748 KeyParameters []uint8 1749 } 1750 1751 func (e *FakeTokenBindingExtension) writeToUConn(uc *UConn) error { 1752 return nil 1753 } 1754 1755 func (e *FakeTokenBindingExtension) Len() int { 1756 // extension ID + data length + versions + key parameters length + key parameters 1757 return 2 + 2 + 2 + 1 + len(e.KeyParameters) 1758 } 1759 1760 func (e *FakeTokenBindingExtension) Read(b []byte) (int, error) { 1761 if len(b) < e.Len() { 1762 return 0, io.ErrShortBuffer 1763 } 1764 dataLen := e.Len() - 4 1765 b[0] = byte(fakeExtensionTokenBinding >> 8) 1766 b[1] = byte(fakeExtensionTokenBinding & 0xff) 1767 b[2] = byte(dataLen >> 8) 1768 b[3] = byte(dataLen & 0xff) 1769 b[4] = e.MajorVersion 1770 b[5] = e.MinorVersion 1771 b[6] = byte(len(e.KeyParameters)) 1772 if len(e.KeyParameters) > 0 { 1773 copy(b[7:], e.KeyParameters) 1774 } 1775 return e.Len(), io.EOF 1776 } 1777 1778 func (e *FakeTokenBindingExtension) Write(b []byte) (int, error) { 1779 fullLen := len(b) 1780 extData := cryptobyte.String(b) 1781 var keyParameters cryptobyte.String 1782 if !extData.ReadUint8(&e.MajorVersion) || 1783 !extData.ReadUint8(&e.MinorVersion) || 1784 !extData.ReadUint8LengthPrefixed(&keyParameters) { 1785 return 0, errors.New("unable to read token binding extension data") 1786 } 1787 e.KeyParameters = keyParameters 1788 return fullLen, nil 1789 } 1790 1791 func (e *FakeTokenBindingExtension) UnmarshalJSON(data []byte) error { 1792 var tokenBindingAccepter struct { 1793 TB_ProtocolVersion struct { 1794 Major uint8 `json:"major"` 1795 Minor uint8 `json:"minor"` 1796 } `json:"token_binding_version"` 1797 TokenBindingKeyParameters []string `json:"key_parameters_list"` 1798 } 1799 if err := json.Unmarshal(data, &tokenBindingAccepter); err != nil { 1800 return err 1801 } 1802 1803 e.MajorVersion = tokenBindingAccepter.TB_ProtocolVersion.Major 1804 e.MinorVersion = tokenBindingAccepter.TB_ProtocolVersion.Minor 1805 for _, param := range tokenBindingAccepter.TokenBindingKeyParameters { 1806 switch param { 1807 case "rsa2048_pkcs1.5": 1808 e.KeyParameters = append(e.KeyParameters, 0) 1809 case "rsa2048_pss": 1810 e.KeyParameters = append(e.KeyParameters, 1) 1811 case "ecdsap256": 1812 e.KeyParameters = append(e.KeyParameters, 2) 1813 default: 1814 return fmt.Errorf("unknown token binding key parameter: %s", param) 1815 } 1816 } 1817 return nil 1818 } 1819 1820 // https://datatracker.ietf.org/doc/html/draft-ietf-tls-subcerts-15#section-4.1.1 1821 1822 type FakeDelegatedCredentialsExtension struct { 1823 SupportedSignatureAlgorithms []SignatureScheme 1824 } 1825 1826 func (e *FakeDelegatedCredentialsExtension) writeToUConn(uc *UConn) error { 1827 return nil 1828 } 1829 1830 func (e *FakeDelegatedCredentialsExtension) Len() int { 1831 return 6 + 2*len(e.SupportedSignatureAlgorithms) 1832 } 1833 1834 func (e *FakeDelegatedCredentialsExtension) Read(b []byte) (int, error) { 1835 if len(b) < e.Len() { 1836 return 0, io.ErrShortBuffer 1837 } 1838 // https://datatracker.ietf.org/doc/html/draft-ietf-tls-subcerts-15#section-4.1.1 1839 b[0] = byte(fakeExtensionDelegatedCredentials >> 8) 1840 b[1] = byte(fakeExtensionDelegatedCredentials) 1841 b[2] = byte((2 + 2*len(e.SupportedSignatureAlgorithms)) >> 8) 1842 b[3] = byte((2 + 2*len(e.SupportedSignatureAlgorithms))) 1843 b[4] = byte((2 * len(e.SupportedSignatureAlgorithms)) >> 8) 1844 b[5] = byte((2 * len(e.SupportedSignatureAlgorithms))) 1845 for i, sigAndHash := range e.SupportedSignatureAlgorithms { 1846 b[6+2*i] = byte(sigAndHash >> 8) 1847 b[7+2*i] = byte(sigAndHash) 1848 } 1849 return e.Len(), io.EOF 1850 } 1851 1852 func (e *FakeDelegatedCredentialsExtension) Write(b []byte) (int, error) { 1853 fullLen := len(b) 1854 extData := cryptobyte.String(b) 1855 //https://datatracker.ietf.org/doc/html/draft-ietf-tls-subcerts-15#section-4.1.1 1856 var supportedAlgs cryptobyte.String 1857 if !extData.ReadUint16LengthPrefixed(&supportedAlgs) || supportedAlgs.Empty() { 1858 return 0, errors.New("unable to read signature algorithms extension data") 1859 } 1860 supportedSignatureAlgorithms := []SignatureScheme{} 1861 for !supportedAlgs.Empty() { 1862 var sigAndAlg uint16 1863 if !supportedAlgs.ReadUint16(&sigAndAlg) { 1864 return 0, errors.New("unable to read signature algorithms extension data") 1865 } 1866 supportedSignatureAlgorithms = append( 1867 supportedSignatureAlgorithms, SignatureScheme(sigAndAlg)) 1868 } 1869 e.SupportedSignatureAlgorithms = supportedSignatureAlgorithms 1870 return fullLen, nil 1871 } 1872 1873 // Implementation copied from SignatureAlgorithmsExtension.UnmarshalJSON 1874 func (e *FakeDelegatedCredentialsExtension) UnmarshalJSON(data []byte) error { 1875 var signatureAlgorithms struct { 1876 Algorithms []string `json:"supported_signature_algorithms"` 1877 } 1878 if err := json.Unmarshal(data, &signatureAlgorithms); err != nil { 1879 return err 1880 } 1881 1882 for _, sigScheme := range signatureAlgorithms.Algorithms { 1883 if sigScheme == "GREASE" { 1884 e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, GREASE_PLACEHOLDER) 1885 continue 1886 } 1887 1888 if scheme, ok := godicttls.DictSignatureSchemeNameIndexed[sigScheme]; ok { 1889 e.SupportedSignatureAlgorithms = append(e.SupportedSignatureAlgorithms, SignatureScheme(scheme)) 1890 } else { 1891 return fmt.Errorf("unknown delegated credentials signature scheme: %s", sigScheme) 1892 } 1893 } 1894 return nil 1895 } 1896 1897 // FakePreSharedKeyExtension is an extension used to set the PSK extension in the 1898 // ClientHello. 1899 // 1900 // Unfortunately, even when the PSK extension is set, there will be no PSK-based 1901 // resumption since crypto/tls does not implement PSK. 1902 type FakePreSharedKeyExtension struct { 1903 PskIdentities []PskIdentity `json:"identities"` 1904 PskBinders [][]byte `json:"binders"` 1905 } 1906 1907 func (e *FakePreSharedKeyExtension) writeToUConn(uc *UConn) error { 1908 if uc.config.ClientSessionCache == nil { 1909 return nil // don't write the extension if there is no session cache 1910 } 1911 if session, ok := uc.config.ClientSessionCache.Get(uc.clientSessionCacheKey()); !ok || session == nil { 1912 return nil // don't write the extension if there is no session cache available for this session 1913 } 1914 uc.HandshakeState.Hello.PskIdentities = e.PskIdentities 1915 uc.HandshakeState.Hello.PskBinders = e.PskBinders 1916 return nil 1917 } 1918 1919 func (e *FakePreSharedKeyExtension) Len() int { 1920 length := 4 // extension type + extension length 1921 length += 2 // identities length 1922 for _, identity := range e.PskIdentities { 1923 length += 2 + len(identity.Label) + 4 // identity length + identity + obfuscated ticket age 1924 } 1925 length += 2 // binders length 1926 for _, binder := range e.PskBinders { 1927 length += len(binder) 1928 } 1929 return length 1930 } 1931 1932 func (e *FakePreSharedKeyExtension) Read(b []byte) (int, error) { 1933 if len(b) < e.Len() { 1934 return 0, io.ErrShortBuffer 1935 } 1936 1937 b[0] = byte(extensionPreSharedKey >> 8) 1938 b[1] = byte(extensionPreSharedKey) 1939 b[2] = byte((e.Len() - 4) >> 8) 1940 b[3] = byte(e.Len() - 4) 1941 1942 // identities length 1943 identitiesLength := 0 1944 for _, identity := range e.PskIdentities { 1945 identitiesLength += 2 + len(identity.Label) + 4 // identity length + identity + obfuscated ticket age 1946 } 1947 b[4] = byte(identitiesLength >> 8) 1948 b[5] = byte(identitiesLength) 1949 1950 // identities 1951 offset := 6 1952 for _, identity := range e.PskIdentities { 1953 b[offset] = byte(len(identity.Label) >> 8) 1954 b[offset+1] = byte(len(identity.Label)) 1955 offset += 2 1956 copy(b[offset:], identity.Label) 1957 offset += len(identity.Label) 1958 b[offset] = byte(identity.ObfuscatedTicketAge >> 24) 1959 b[offset+1] = byte(identity.ObfuscatedTicketAge >> 16) 1960 b[offset+2] = byte(identity.ObfuscatedTicketAge >> 8) 1961 b[offset+3] = byte(identity.ObfuscatedTicketAge) 1962 offset += 4 1963 } 1964 1965 // binders length 1966 bindersLength := 0 1967 for _, binder := range e.PskBinders { 1968 bindersLength += len(binder) 1969 } 1970 b[offset] = byte(bindersLength >> 8) 1971 b[offset+1] = byte(bindersLength) 1972 offset += 2 1973 1974 // binders 1975 for _, binder := range e.PskBinders { 1976 copy(b[offset:], binder) 1977 offset += len(binder) 1978 } 1979 1980 return e.Len(), io.EOF 1981 } 1982 1983 func (e *FakePreSharedKeyExtension) Write(b []byte) (n int, err error) { 1984 fullLen := len(b) 1985 s := cryptobyte.String(b) 1986 1987 var identitiesLength uint16 1988 if !s.ReadUint16(&identitiesLength) { 1989 return 0, errors.New("tls: invalid PSK extension") 1990 } 1991 1992 // identities 1993 for identitiesLength > 0 { 1994 var identityLength uint16 1995 if !s.ReadUint16(&identityLength) { 1996 return 0, errors.New("tls: invalid PSK extension") 1997 } 1998 identitiesLength -= 2 1999 2000 if identityLength > identitiesLength { 2001 return 0, errors.New("tls: invalid PSK extension") 2002 } 2003 2004 var identity []byte 2005 if !s.ReadBytes(&identity, int(identityLength)) { 2006 return 0, errors.New("tls: invalid PSK extension") 2007 } 2008 2009 identitiesLength -= identityLength // identity 2010 2011 var obfuscatedTicketAge uint32 2012 if !s.ReadUint32(&obfuscatedTicketAge) { 2013 return 0, errors.New("tls: invalid PSK extension") 2014 } 2015 2016 e.PskIdentities = append(e.PskIdentities, PskIdentity{ 2017 Label: identity, 2018 ObfuscatedTicketAge: obfuscatedTicketAge, 2019 }) 2020 2021 identitiesLength -= 4 // obfuscated ticket age 2022 } 2023 2024 var bindersLength uint16 2025 if !s.ReadUint16(&bindersLength) { 2026 return 0, errors.New("tls: invalid PSK extension") 2027 } 2028 2029 // binders 2030 for bindersLength > 0 { 2031 var binderLength uint8 2032 if !s.ReadUint8(&binderLength) { 2033 return 0, errors.New("tls: invalid PSK extension") 2034 } 2035 bindersLength -= 1 2036 2037 if uint16(binderLength) > bindersLength { 2038 return 0, errors.New("tls: invalid PSK extension") 2039 } 2040 2041 var binder []byte 2042 if !s.ReadBytes(&binder, int(binderLength)) { 2043 return 0, errors.New("tls: invalid PSK extension") 2044 } 2045 2046 e.PskBinders = append(e.PskBinders, binder) 2047 2048 bindersLength -= uint16(binderLength) 2049 } 2050 2051 return fullLen, nil 2052 } 2053 2054 func (e *FakePreSharedKeyExtension) UnmarshalJSON(data []byte) error { 2055 var pskAccepter struct { 2056 PskIdentities []PskIdentity `json:"identities"` 2057 PskBinders [][]byte `json:"binders"` 2058 } 2059 2060 if err := json.Unmarshal(data, &pskAccepter); err != nil { 2061 return err 2062 } 2063 2064 e.PskIdentities = pskAccepter.PskIdentities 2065 e.PskBinders = pskAccepter.PskBinders 2066 return nil 2067 }