-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnect.go
More file actions
3074 lines (2823 loc) · 96 KB
/
Copy pathconnect.go
File metadata and controls
3074 lines (2823 loc) · 96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package certkit
import (
"bufio"
"bytes"
"cmp"
"context"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/binary"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net"
"slices"
"strings"
"sync"
"time"
)
const defaultConnectTimeout = 10 * time.Second
const nonTLSPeekLimit = 256
const startTLSDetectTimeout = 1 * time.Second
const maxLDAPStartTLSResponseBytes = 64 * 1024
const maxTextLineBytes = 16 * 1024
var (
errConnectHostRequired = errors.New("connecting to TLS server: host is required")
errConnectUnsupportedVersion = errors.New("connecting to TLS server: unsupported TLS version")
errConnectPresentedChain = errors.New("server did not present a valid trust path")
errCipherScanHostRequired = errors.New("scanning cipher suites: host is required")
errConnectNonTLSService = errors.New("remote service does not appear to speak TLS")
errStartTLSUnsupportedProtocol = errors.New("unsupported STARTTLS protocol")
errStartTLSLDAPRejected = errors.New("LDAP service rejected StartTLS")
errStartTLSLDAPMalformed = errors.New("malformed LDAP StartTLS response")
errStartTLSSMTPUnsupported = errors.New("SMTP service did not advertise STARTTLS")
errStartTLSSMTPUnexpected = errors.New("unexpected SMTP response")
errStartTLSSMTPMalformed = errors.New("malformed SMTP response")
errStartTLSIMAPGreeting = errors.New("unexpected IMAP greeting")
errStartTLSIMAPRejected = errors.New("IMAP service rejected STARTTLS")
errStartTLSPOP3Greeting = errors.New("unexpected POP3 greeting")
errStartTLSPOP3Rejected = errors.New("POP3 service rejected STLS")
errLineTooLong = errors.New("line exceeds maximum length")
)
type startTLSProtocol string
const (
startTLSProtocolSMTP startTLSProtocol = "smtp"
startTLSProtocolIMAP startTLSProtocol = "imap"
startTLSProtocolPOP3 startTLSProtocol = "pop3"
startTLSProtocolLDAP startTLSProtocol = "ldap"
)
// ChainDiagnostic describes a single chain configuration issue found during connection probing.
type ChainDiagnostic struct {
// Check is the diagnostic identifier (e.g. "root-in-chain", "duplicate-cert", "misordered-chain", "missing-intermediate").
Check string `json:"check"`
// Status is the severity level: "warn" for configuration issues, "error" for verification failures.
Status string `json:"status"`
// Detail is a human-readable description of the issue.
Detail string `json:"detail"`
}
// DiagnoseConnectChainInput contains parameters for diagnosing a TLS peer chain.
type DiagnoseConnectChainInput struct {
// PeerChain is the certificate chain presented by the server.
PeerChain []*x509.Certificate
}
// DiagnoseConnectChain inspects a server-presented certificate chain for
// misconfigurations: root certificates included in the chain (wastes bandwidth,
// per RFC 8446 §4.4.2), duplicate certificates, and misordered intermediates.
func DiagnoseConnectChain(input DiagnoseConnectChainInput) []ChainDiagnostic {
var diags []ChainDiagnostic
fingerprints := make(map[string]int) // fingerprint → first position
for i, cert := range input.PeerChain {
fp := CertFingerprint(cert)
// Check for duplicates.
if firstPos, seen := fingerprints[fp]; seen {
diags = append(diags, ChainDiagnostic{
Check: "duplicate-cert",
Status: "warn",
Detail: fmt.Sprintf("certificate %q appears at positions %d and %d", FormatDNFromRaw(cert.RawSubject, cert.Subject), firstPos, i),
})
} else {
fingerprints[fp] = i
}
// Check for root certs in non-leaf positions.
if i > 0 && GetCertificateType(cert) == "root" {
diags = append(diags, ChainDiagnostic{
Check: "root-in-chain",
Status: "warn",
Detail: fmt.Sprintf("server sent root certificate %q (position %d)", FormatDNFromRaw(cert.RawSubject, cert.Subject), i),
})
}
}
// Check for misordered chains where the correct issuer is present later in
// the server-sent list, but not directly after the certificate it issued.
for i := 0; i+1 < len(input.PeerChain); i++ {
cert := input.PeerChain[i]
next := input.PeerChain[i+1]
// Adjacent issuer matches expected order.
if bytes.Equal(cert.RawIssuer, next.RawSubject) {
continue
}
expectedPos := -1
for j := i + 2; j < len(input.PeerChain); j++ {
if bytes.Equal(cert.RawIssuer, input.PeerChain[j].RawSubject) {
expectedPos = j
break
}
}
// If the issuer is absent, this is likely an incomplete chain, not
// a misordered one.
if expectedPos == -1 {
continue
}
expectedIssuer := input.PeerChain[expectedPos]
diags = append(diags, ChainDiagnostic{
Check: "misordered-chain",
Status: "warn",
Detail: fmt.Sprintf(
"certificate %q (position %d) is issued by %q (position %d), but position %d contains %q",
FormatDNFromRaw(cert.RawSubject, cert.Subject),
i,
FormatDNFromRaw(expectedIssuer.RawSubject, expectedIssuer.Subject),
expectedPos,
i+1,
FormatDNFromRaw(next.RawSubject, next.Subject),
),
})
break
}
if !presentedChainHasIssuerPath(input.PeerChain) && len(input.PeerChain) > 0 {
leaf := input.PeerChain[0]
diags = append(diags, ChainDiagnostic{
Check: "missing-intermediate",
Status: "warn",
Detail: fmt.Sprintf("presented chain does not contain an issuer path for leaf %q to a higher CA certificate", FormatDNFromRaw(leaf.RawSubject, leaf.Subject)),
})
}
return diags
}
func diagnoseAIARepairedChain(peerChain, aiaCerts []*x509.Certificate) []ChainDiagnostic {
if len(peerChain) == 0 || len(aiaCerts) == 0 {
return nil
}
if isPeerChainMissingIssuer(peerChain) {
return []ChainDiagnostic{{
Check: "missing-intermediate",
Status: "warn",
Detail: "server does not send intermediate certificates; chain was completed via AIA",
}}
}
return []ChainDiagnostic{{
Check: "aia-repaired-chain",
Status: "warn",
Detail: "server did not present a valid trust path; local validation succeeded after AIA fetch",
}}
}
func isPeerChainMissingIssuer(peerChain []*x509.Certificate) bool {
for i, cert := range peerChain {
if cert == nil || bytes.Equal(cert.RawIssuer, cert.RawSubject) {
continue
}
issuerPresent := false
for j := i + 1; j < len(peerChain); j++ {
candidate := peerChain[j]
if candidate != nil && bytes.Equal(cert.RawIssuer, candidate.RawSubject) {
issuerPresent = true
break
}
}
if !issuerPresent {
return true
}
}
return false
}
func presentedChainHasIssuerPath(peerChain []*x509.Certificate) bool {
if len(peerChain) == 0 {
return false
}
var dfs func(index int, visited map[int]bool) bool
dfs = func(index int, visited map[int]bool) bool {
cert := peerChain[index]
if cert == nil {
return false
}
candidateFound := false
for j, issuer := range peerChain {
if j == index || issuer == nil || !bytes.Equal(cert.RawIssuer, issuer.RawSubject) {
continue
}
if cert.CheckSignatureFrom(issuer) != nil {
continue
}
candidateFound = true
if visited[j] {
continue
}
nextVisited := make(map[int]bool, len(visited)+1)
maps.Copy(nextVisited, visited)
nextVisited[j] = true
if dfs(j, nextVisited) {
return true
}
}
return !candidateFound && (len(peerChain) == 1 || index != 0)
}
return dfs(0, map[int]bool{0: true})
}
func presentedChainBuildsVerifiedPath(peerChain []*x509.Certificate, verifiedChains [][]*x509.Certificate) bool {
if len(peerChain) == 0 || len(verifiedChains) == 0 {
return false
}
peerCerts := make(map[string]bool, len(peerChain))
for _, cert := range peerChain {
if cert != nil {
peerCerts[string(cert.Raw)] = true
}
}
for _, chain := range verifiedChains {
if len(chain) == 0 {
continue
}
requiredCount := len(chain) - 1
if len(chain) == 1 {
requiredCount = 1
}
complete := true
for i := range requiredCount {
cert := chain[i]
if cert == nil || !peerCerts[string(cert.Raw)] {
complete = false
break
}
}
if complete {
return true
}
}
return false
}
// SortDiagnostics sorts diagnostics: errors before warnings, then alphabetically
// by check name within each group for stable output order.
func SortDiagnostics(diags []ChainDiagnostic) {
slices.SortStableFunc(diags, func(a, b ChainDiagnostic) int {
// Errors first.
if a.Status != b.Status {
if a.Status == "error" {
return -1
}
if b.Status == "error" {
return 1
}
}
return cmp.Compare(a.Check, b.Check)
})
}
// DiagnoseVerifyError returns diagnostics derived from a chain verification error.
// Currently detects hostname mismatches (x509.HostnameError).
func DiagnoseVerifyError(verifyErr error) []ChainDiagnostic {
if verifyErr == nil {
return nil
}
if hostErr, ok := errors.AsType[x509.HostnameError](verifyErr); ok {
return []ChainDiagnostic{{
Check: "hostname-mismatch",
Status: "error",
Detail: hostErr.Error(),
}}
}
return nil
}
func validateConnectVersion(version uint16) error {
switch version {
case 0, tls.VersionTLS10, tls.VersionTLS11, tls.VersionTLS12, tls.VersionTLS13:
return nil
default:
return fmt.Errorf("%w: 0x%04x", errConnectUnsupportedVersion, version)
}
}
func allowLegacyFallback(version uint16) bool {
return version == 0 || version <= tls.VersionTLS12
}
// DiagnoseNegotiatedCipher returns diagnostics for the cipher suite and protocol
// version that were actually negotiated during the TLS handshake. This catches
// issues like CBC mode or deprecated TLS versions even without a full --ciphers scan.
func DiagnoseNegotiatedCipher(protocol, cipherSuite string) []ChainDiagnostic {
var diags []ChainDiagnostic
// Deprecated TLS versions (RFC 8996).
switch protocol {
case "TLS 1.0":
diags = append(diags, ChainDiagnostic{
Check: "deprecated-tls10",
Status: "warn",
Detail: "negotiated TLS 1.0 — deprecated since RFC 8996",
})
case "TLS 1.1":
diags = append(diags, ChainDiagnostic{
Check: "deprecated-tls11",
Status: "warn",
Detail: "negotiated TLS 1.1 — deprecated since RFC 8996",
})
}
// CBC mode — vulnerable to padding oracle attacks (BEAST, Lucky13).
if strings.Contains(cipherSuite, "CBC") {
diags = append(diags, ChainDiagnostic{
Check: "cbc-cipher",
Status: "warn",
Detail: fmt.Sprintf("negotiated CBC mode cipher suite %s — vulnerable to padding oracle attacks", cipherSuite),
})
}
// 3DES — 64-bit block size, vulnerable to Sweet32.
if strings.Contains(cipherSuite, "3DES") {
diags = append(diags, ChainDiagnostic{
Check: "3des-cipher",
Status: "warn",
Detail: fmt.Sprintf("negotiated 3DES cipher suite %s — 64-bit block size, vulnerable to Sweet32", cipherSuite),
})
}
// Key exchange issues.
kex := cipherKeyExchange(cipherSuite, protocol)
switch kex {
case "RSA":
diags = append(diags, ChainDiagnostic{
Check: "static-rsa-kex",
Status: "warn",
Detail: fmt.Sprintf("negotiated static RSA key exchange (%s) — no forward secrecy", cipherSuite),
})
case "DHE", "DHE-DSS":
diags = append(diags, ChainDiagnostic{
Check: "dhe-kex",
Status: "warn",
Detail: fmt.Sprintf("negotiated DHE key exchange (%s) — deprecated, no guaranteed forward secrecy with small DH parameters", cipherSuite),
})
}
return diags
}
// ConnectTLSInput contains parameters for a TLS connection probe.
type ConnectTLSInput struct {
// Host is the hostname or IP to connect to.
Host string
// Port is the TCP port (default: "443").
Port string
// Version pins the TLS protocol version. Zero means auto-negotiate.
Version uint16
// ConnectTimeout is used when ctx has no deadline (default: 10s).
ConnectTimeout time.Duration
// ServerName overrides the SNI hostname (defaults to Host).
ServerName string
// DisableAIA disables automatic AIA certificate fetching when chain verification fails.
DisableAIA bool
// AIATimeout is the timeout for AIA certificate fetching (default: 5s).
AIATimeout time.Duration
// DisableOCSP disables the automatic best-effort OCSP check on the leaf certificate.
DisableOCSP bool
// OCSPTimeout is the timeout for OCSP checking (default: 5s).
OCSPTimeout time.Duration
// CheckCRL enables CRL-based revocation checking on the leaf certificate.
CheckCRL bool
// CRLTimeout is the timeout for CRL fetching (default: 5s).
CRLTimeout time.Duration
// RootCAs overrides system roots for chain verification. When nil,
// the system root pool is used. Useful for testing against private CAs.
RootCAs *x509.CertPool
// AllowPrivateNetworks allows AIA/OCSP/CRL fetches to private/internal endpoints.
AllowPrivateNetworks bool
// Policy enables optional strict transport/certificate diagnostics.
Policy SecurityPolicy
}
// ClientAuthInfo describes the server's client certificate request (mTLS).
type ClientAuthInfo struct {
// Requested is true when the server sent a CertificateRequest.
Requested bool `json:"requested"`
// AcceptableCAs are the DN strings of CAs the server trusts for client certs.
AcceptableCAs []string `json:"acceptable_cas,omitempty"`
// SignatureSchemes are the signature algorithms the server will accept.
SignatureSchemes []string `json:"signature_schemes,omitempty"`
}
// CRLCheckResult contains the result of a CRL revocation check during a TLS connection probe.
type CRLCheckResult struct {
// Status is the check result: "good", "revoked", or "unavailable".
// Unlike OCSPResult's "unknown" (an explicit responder status), "unavailable"
// means the CRL could not be fetched, parsed, or verified.
Status string `json:"status"`
// URL is the CRL distribution point that was fetched.
URL string `json:"url,omitempty"`
// Detail provides context when Status is "unavailable" (the error message)
// or "revoked" (the serial number).
Detail string `json:"detail,omitempty"`
}
// ConnectResult contains the results of a TLS connection probe.
type ConnectResult struct {
// Host is the hostname that was connected to.
Host string `json:"host"`
// Port is the TCP port that was connected to.
Port string `json:"port"`
// Protocol is the negotiated TLS version (e.g. "TLS 1.3").
Protocol string `json:"protocol"`
tlsVersion string
// Policy is the optional strictness profile used when rating this result.
Policy SecurityPolicy `json:"policy,omitempty"`
// CipherSuite is the negotiated cipher suite name.
CipherSuite string `json:"cipher_suite"`
// ServerName is the SNI value sent.
ServerName string `json:"server_name"`
// ALPN is the negotiated application protocol (e.g. "h2", "http/1.1").
ALPN string `json:"alpn,omitempty"`
// ClientAuth describes whether the server requested a client certificate (mTLS).
ClientAuth *ClientAuthInfo `json:"client_auth,omitempty"`
// PeerChain is the certificate chain presented by the server.
PeerChain []*x509.Certificate `json:"-"`
// ChainTrustAnchors holds per-certificate trust sources for PeerChain.
ChainTrustAnchors [][]string `json:"-"`
// ChainTrustWarnings holds per-certificate trust-source load warnings for PeerChain.
ChainTrustWarnings [][]string `json:"-"`
// TLSSCTs contains serialized SCTs from the TLS handshake extension.
TLSSCTs [][]byte `json:"-"`
// VerifiedChains contains the verified certificate chains.
VerifiedChains [][]*x509.Certificate `json:"-"`
// TrustPathStatus records whether the server-presented certificates
// themselves formed a valid trust path during connection verification.
TrustPathStatus ConnectTrustPathStatus `json:"-"`
// VerifyError is non-empty if chain verification failed.
VerifyError string `json:"verify_error,omitempty"`
// Diagnostics contains chain configuration warnings (root-in-chain, duplicate-cert, missing-intermediate).
Diagnostics []ChainDiagnostic `json:"diagnostics,omitempty"`
// AIAFetched is true when missing intermediates were successfully fetched via AIA.
AIAFetched bool `json:"aia_fetched,omitempty"`
// OCSP contains the leaf certificate's OCSP revocation status.
// Nil only when OCSP is explicitly disabled (DisableOCSP is true).
// Status "skipped" means preconditions were not met (no issuer in chain,
// or no OCSP responder URL). Status "unavailable" means the query was
// attempted but failed (network error, parse error, etc.).
OCSP *OCSPResult `json:"ocsp,omitempty"`
// CRL contains the leaf certificate's CRL revocation status.
// Nil when CRL checking is not requested (CheckCRL is false).
CRL *CRLCheckResult `json:"crl,omitempty"`
// CipherScan contains the cipher suite enumeration results.
// Nil when cipher scanning is not requested.
CipherScan *CipherScanResult `json:"cipher_scan,omitempty"`
// CT contains Certificate Transparency verification results.
CT *CTResult `json:"ct,omitempty"`
// LegacyProbe is true when the certificate chain was obtained via a raw
// TLS handshake (legacy fallback) because Go's crypto/tls could not
// negotiate any cipher suite. The chain is still valid for inspection
// but no full TLS connection was established.
LegacyProbe bool `json:"legacy_probe,omitempty"`
}
// ConnectTrustPathStatus describes whether the certificates presented by the
// peer formed a complete trust path to a trusted anchor.
type ConnectTrustPathStatus string
// ConnectTLS trust-path status values.
const (
ConnectTrustPathStatusUnknown ConnectTrustPathStatus = ""
ConnectTrustPathStatusPresentedValid ConnectTrustPathStatus = "presented-valid"
ConnectTrustPathStatusPresentedInvalid ConnectTrustPathStatus = "presented-invalid"
)
// ConnectTLS connects to a TLS server and returns connection details including
// the negotiated protocol, cipher suite, and peer certificate chain.
func ConnectTLS(ctx context.Context, input ConnectTLSInput) (*ConnectResult, error) {
if input.Host == "" {
return nil, errConnectHostRequired
}
if err := validateConnectVersion(input.Version); err != nil {
return nil, err
}
port := input.Port
if port == "" {
port = "443"
}
serverName := input.ServerName
if serverName == "" {
serverName = input.Host
}
addr := net.JoinHostPort(input.Host, port)
connectCtx := ctx
connectCancel := func() {}
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
connectTimeout := input.ConnectTimeout
if connectTimeout == 0 {
connectTimeout = defaultConnectTimeout
}
connectCtx, connectCancel = context.WithTimeout(ctx, connectTimeout)
}
defer connectCancel()
dialer := &net.Dialer{}
conn, err := dialer.DialContext(connectCtx, "tcp", addr)
if err != nil {
return nil, fmt.Errorf("connecting to %s: %w", addr, err)
}
sniffConn := &prefixCapturingConn{Conn: conn}
var clientAuth *ClientAuthInfo
tlsConf := newConnectTLSConfig(connectTLSConfigInput{
serverName: serverName,
clientAuth: &clientAuth,
version: input.Version,
})
tlsConn := tls.Client(sniffConn, tlsConf)
defer func() { _ = tlsConn.Close() }()
if deadline, ok := connectCtx.Deadline(); ok {
if err := tlsConn.SetDeadline(deadline); err != nil {
return nil, fmt.Errorf("setting deadline: %w", err)
}
}
handshakeErr := tlsConn.HandshakeContext(connectCtx)
var tlsAlert tls.AlertError
if handshakeErr != nil && clientAuth == nil && errors.As(handshakeErr, &tlsAlert) && allowLegacyFallback(input.Version) {
// Close the failed TLS connection before opening a new one.
// The deferred tlsConn.Close() will be a no-op after this.
_ = tlsConn.Close()
// Try raw legacy handshake to detect DHE/static-RSA-only servers.
// Only attempt this when the server sent a TLS alert (cipher
// negotiation failure), not for network errors or certificate errors.
// Use a dedicated timeout so a stalling server can't hold the
// fallback connection open indefinitely.
fallbackCtx, fallbackCancel := context.WithTimeout(connectCtx, 5*time.Second)
defer fallbackCancel()
legacyResult, legacyErr := legacyFallbackConnect(fallbackCtx, legacyFallbackInput{
addr: addr,
serverName: serverName,
version: input.Version,
})
if legacyErr != nil {
return nil, fmt.Errorf("tls handshake with %s: %w; legacy fallback: %w", addr, handshakeErr, legacyErr)
}
result := &ConnectResult{
Host: input.Host,
Port: port,
Protocol: tlsVersionString(legacyResult.version),
tlsVersion: tlsVersionString(legacyResult.version),
Policy: input.Policy,
CipherSuite: cipherSuiteName(legacyResult.cipherSuite),
ServerName: serverName,
PeerChain: legacyResult.certificates,
LegacyProbe: true,
}
result.populate(ctx, input)
result.Diagnostics = append(result.Diagnostics, ChainDiagnostic{
Check: "legacy-only",
Status: "warn",
Detail: "server only supports cipher suites not available in standard TLS libraries; certificate chain verified but server key possession not proven",
})
return result, nil
} else if handshakeErr != nil && clientAuth == nil {
// Non-alert failure (network error, certificate error, etc.) — return
// immediately. The mTLS fallback path below is only for client auth
// rejection, which only occurs when clientAuth is non-nil.
_ = tlsConn.Close()
prefix := sniffConn.prefix()
startTLSCtx, startTLSCancel := startTLSFallbackContext(connectCtx, input.ConnectTimeout)
defer startTLSCancel()
if detectedProtocol, ok := detectStartTLSProtocol(addr, prefix); ok {
result, startTLSErr := connectViaStartTLS(startTLSCtx, ctx, connectViaStartTLSInput{
connectInput: input,
addr: addr,
serverName: serverName,
protocol: detectedProtocol,
})
if startTLSErr != nil {
return nil, fmt.Errorf("STARTTLS with %s: %w", addr, startTLSErr)
}
return result, nil
}
if matchesGenericSMTPBanner(firstBannerLine(prefix)) {
result, startTLSErr := connectViaStartTLS(startTLSCtx, ctx, connectViaStartTLSInput{
connectInput: input,
addr: addr,
serverName: serverName,
protocol: startTLSProtocolSMTP,
})
if startTLSErr == nil {
return result, nil
}
slog.Debug("smtp starttls attempt failed, falling back to tls handshake error", "addr", addr, "error", startTLSErr)
}
if matchesGenericIMAPBanner(firstBannerLine(prefix)) {
result, startTLSErr := connectViaStartTLS(startTLSCtx, ctx, connectViaStartTLSInput{
connectInput: input,
addr: addr,
serverName: serverName,
protocol: startTLSProtocolIMAP,
})
if startTLSErr == nil {
return result, nil
}
slog.Debug("imap starttls attempt failed, falling back to tls handshake error", "addr", addr, "error", startTLSErr)
}
if matchesGenericPOP3Banner(firstBannerLine(prefix)) {
result, startTLSErr := connectViaStartTLS(startTLSCtx, ctx, connectViaStartTLSInput{
connectInput: input,
addr: addr,
serverName: serverName,
protocol: startTLSProtocolPOP3,
})
if startTLSErr == nil {
return result, nil
}
slog.Debug("pop3 stls attempt failed, falling back to tls handshake error", "addr", addr, "error", startTLSErr)
}
if len(prefix) == 0 {
// LDAP is the one STARTTLS protocol we intentionally probe without a
// plaintext banner because anonymous LDAP on 389 stays silent until the
// client sends the extended operation. This retry stays under
// startTLSCtx, so silent non-LDAP services still fail within the same
// bounded fallback budget instead of hanging indefinitely.
result, startTLSErr := connectViaStartTLS(startTLSCtx, ctx, connectViaStartTLSInput{
connectInput: input,
addr: addr,
serverName: serverName,
protocol: startTLSProtocolLDAP,
})
if startTLSErr == nil {
return result, nil
}
slog.Debug("ldap starttls attempt failed, falling back to tls handshake error", "addr", addr, "error", startTLSErr)
}
if inferredErr := inferNonTLSError(inferNonTLSErrorInput{
handshakeErr: handshakeErr,
addr: addr,
prefix: prefix,
}); inferredErr != nil {
return nil, fmt.Errorf("tls handshake with %s: %w", addr, inferredErr)
}
return nil, fmt.Errorf("tls handshake with %s: %w", addr, handshakeErr)
}
// When the server requested a client cert and rejected our empty
// response, the handshake fails but we still have useful state:
// peer certs arrived before the CertificateRequest, so we can
// verify the chain and report mTLS info normally.
state := tlsConn.ConnectionState()
result := &ConnectResult{
Host: input.Host,
Port: port,
Protocol: tlsVersionString(state.Version),
tlsVersion: tlsVersionString(state.Version),
Policy: input.Policy,
CipherSuite: tls.CipherSuiteName(state.CipherSuite),
ServerName: serverName,
ALPN: state.NegotiatedProtocol,
ClientAuth: clientAuth,
PeerChain: state.PeerCertificates,
TLSSCTs: state.SignedCertificateTimestamps,
}
result.populate(ctx, input)
return result, nil
}
func startTLSFallbackContext(parent context.Context, connectTimeout time.Duration) (context.Context, context.CancelFunc) {
if _, hasDeadline := parent.Deadline(); hasDeadline {
return parent, func() {}
}
if connectTimeout == 0 {
connectTimeout = defaultConnectTimeout
}
ctx, cancel := context.WithTimeout(parent, connectTimeout)
return ctx, cancel
}
// populate runs chain diagnostics, verification, OCSP, and CRL checks on the
// ConnectResult. It is shared between the normal handshake path and the legacy
// fallback path.
func (result *ConnectResult) populate(ctx context.Context, input ConnectTLSInput) {
serverName := result.ServerName
// Diagnose the negotiated cipher suite and protocol version.
protocolVersion := result.tlsVersion
if protocolVersion == "" {
protocolVersion = result.Protocol
}
result.Diagnostics = append(result.Diagnostics, DiagnoseNegotiatedCipher(protocolVersion, result.CipherSuite)...)
result.Diagnostics = append(result.Diagnostics, diagnoseNegotiatedCipherPolicy(negotiatedCipherPolicyInput{
protocol: protocolVersion,
cipherSuite: result.CipherSuite,
policy: input.Policy,
})...)
// Run chain diagnostics on the raw peer chain.
if len(result.PeerChain) > 0 {
result.Diagnostics = append(result.Diagnostics, DiagnoseConnectChain(DiagnoseConnectChainInput{
PeerChain: result.PeerChain,
})...)
if !presentedChainHasIssuerPath(result.PeerChain) {
result.TrustPathStatus = ConnectTrustPathStatusPresentedInvalid
}
}
// Verify the chain ourselves to capture the error message.
if len(result.PeerChain) > 0 {
leaf := result.PeerChain[0]
serverIntermediates := x509.NewCertPool()
for _, cert := range result.PeerChain[1:] {
serverIntermediates.AddCert(cert)
}
serverVerifyOpts := x509.VerifyOptions{
DNSName: serverName,
Intermediates: serverIntermediates,
Roots: input.RootCAs,
}
chains, verifyErr := leaf.Verify(serverVerifyOpts)
if verifyErr != nil && !input.DisableAIA && len(leaf.IssuingCertificateURL) > 0 {
// Attempt AIA walking to fetch missing intermediates.
aiaTimeout := input.AIATimeout
if aiaTimeout == 0 {
aiaTimeout = 5 * time.Second
}
aiaCerts, aiaWarnings := FetchAIACertificates(ctx, FetchAIACertificatesInput{
Cert: leaf,
Timeout: aiaTimeout,
MaxDepth: 5,
AllowPrivateNetworks: input.AllowPrivateNetworks,
})
for _, w := range aiaWarnings {
slog.Debug("AIA fetch warning", "warning", w)
}
if len(aiaCerts) > 0 {
aiaIntermediates := x509.NewCertPool()
for _, cert := range result.PeerChain[1:] {
aiaIntermediates.AddCert(cert)
}
for _, c := range aiaCerts {
aiaIntermediates.AddCert(c)
}
aiaChains, aiaVerifyErr := leaf.Verify(x509.VerifyOptions{
DNSName: serverName,
Intermediates: aiaIntermediates,
Roots: input.RootCAs,
})
if aiaVerifyErr == nil {
result.AIAFetched = true
result.VerifiedChains = aiaChains
result.TrustPathStatus = ConnectTrustPathStatusPresentedInvalid
result.Diagnostics = append(result.Diagnostics, diagnoseAIARepairedChain(result.PeerChain, aiaCerts)...)
}
}
}
if verifyErr != nil {
result.VerifyError = verifyErr.Error()
result.Diagnostics = append(result.Diagnostics, DiagnoseVerifyError(verifyErr)...)
} else {
if !presentedChainBuildsVerifiedPath(result.PeerChain, chains) {
result.VerifyError = errConnectPresentedChain.Error()
result.TrustPathStatus = ConnectTrustPathStatusPresentedInvalid
} else {
result.VerifiedChains = chains
result.TrustPathStatus = ConnectTrustPathStatusPresentedValid
}
}
}
// Certificate Transparency checks (best-effort, warn-only).
if len(result.PeerChain) > 0 || len(result.TLSSCTs) > 0 {
ctChain := result.PeerChain
if len(result.VerifiedChains) > 0 && len(result.VerifiedChains[0]) > 0 {
ctChain = result.VerifiedChains[0]
}
ctResult, ctDiags := CheckCT(CheckCTInput{
Chain: ctChain,
TLSSCTs: result.TLSSCTs,
})
result.CT = ctResult
result.Diagnostics = append(result.Diagnostics, ctDiags...)
}
// No peer certificates means TLS completed without sending certs (unlikely
// but possible on a partially-completed handshake). Return early.
if len(result.PeerChain) == 0 {
return
}
result.Diagnostics = append(result.Diagnostics, diagnosePeerChainPolicy(result.PeerChain, input.Policy)...)
// For legacy probes, certificate chain verification has been run above and
// the result is included in the output. However, OCSP and CRL revocation
// checks require a verified issuer from a real TLS channel — skipping
// them prevents misleading "skipped (no issuer in chain)" OCSP output
// when the legacy handshake produced an untrusted certificate.
if result.LegacyProbe {
return
}
// Resolve the issuer certificate for revocation checks.
// Only use VerifiedChains (cryptographically validated). Do not fall back
// to PeerCertificates — those are raw, unverified certs from the server and
// using them would let an attacker forge valid OCSP/CRL responses.
leaf := result.PeerChain[0]
var issuer *x509.Certificate
if len(result.VerifiedChains) > 0 && len(result.VerifiedChains[0]) > 1 {
issuer = result.VerifiedChains[0][1]
}
// Best-effort OCSP check on the leaf certificate.
switch {
case input.DisableOCSP:
case issuer == nil:
result.OCSP = &OCSPResult{
Status: "skipped",
Detail: "no issuer certificate in chain",
}
case len(leaf.OCSPServer) == 0:
result.OCSP = &OCSPResult{
Status: "skipped",
Detail: "certificate has no OCSP responder URL",
}
default:
ocspTimeout := input.OCSPTimeout
if ocspTimeout == 0 {
ocspTimeout = 5 * time.Second
}
ocspCtx, ocspCancel := context.WithTimeout(ctx, ocspTimeout)
ocspResult, ocspErr := CheckOCSP(ocspCtx, CheckOCSPInput{
Cert: leaf,
Issuer: issuer,
AllowPrivateNetworks: input.AllowPrivateNetworks,
})
ocspCancel()
if ocspErr != nil {
slog.Debug("OCSP check failed", "error", ocspErr)
result.OCSP = &OCSPResult{
Status: "unavailable",
URL: leaf.OCSPServer[0],
Detail: ocspErr.Error(),
}
} else {
result.OCSP = ocspResult
}
}
// Opt-in CRL check on the leaf certificate.
if input.CheckCRL && issuer != nil {
result.CRL = CheckLeafCRL(ctx, CheckLeafCRLInput{
Leaf: leaf,
Issuer: issuer,
Timeout: input.CRLTimeout,
AllowPrivateNetworks: input.AllowPrivateNetworks,
})
} else if input.CheckCRL {
result.CRL = &CRLCheckResult{
Status: "unavailable",
Detail: "no issuer certificate available to verify CRL signature",
}
}
}
type connectTLSConfigInput struct {
serverName string
clientAuth **ClientAuthInfo
version uint16
}
func newConnectTLSConfig(input connectTLSConfigInput) *tls.Config {
cfg := &tls.Config{
ServerName: input.serverName,
InsecureSkipVerify: true, //nolint:gosec // We do our own verification below.
GetClientCertificate: func(cri *tls.CertificateRequestInfo) (*tls.Certificate, error) {
info := &ClientAuthInfo{Requested: true}
for i, rawDN := range cri.AcceptableCAs {
var rdnSeq pkix.RDNSequence
if _, err := asn1.Unmarshal(rawDN, &rdnSeq); err != nil {
slog.Debug("failed to unmarshal acceptable CA DN",
slog.Int("index", i),
slog.Any("error", err),
)
continue
}
var name pkix.Name
name.FillFromRDNSequence(&rdnSeq)
info.AcceptableCAs = append(info.AcceptableCAs, FormatDN(name))
}
for _, scheme := range cri.SignatureSchemes {
info.SignatureSchemes = append(info.SignatureSchemes, signatureSchemeString(scheme))
}
*input.clientAuth = info
return &tls.Certificate{}, nil
},
}
if input.version != 0 {
cfg.MinVersion = input.version
cfg.MaxVersion = input.version
}
return cfg
}
type connectResultFromTLSStateInput struct {
connectInput ConnectTLSInput
addr string
serverName string
state tls.ConnectionState
clientAuth *ClientAuthInfo
startTLS startTLSProtocol
}
func connectResultFromTLSState(ctx context.Context, input connectResultFromTLSStateInput) *ConnectResult {
rawProtocol := tlsVersionString(input.state.Version)
protocol := rawProtocol
if input.startTLS != "" {
protocol = formatProtocolWithStartTLS(protocol, input.startTLS)
}
port := input.connectInput.Port
if _, splitPort, splitErr := net.SplitHostPort(input.addr); splitErr == nil {
port = splitPort
}
host := input.connectInput.Host
if host == "" {
host = input.serverName
}
result := &ConnectResult{
Host: host,
Port: port,
Protocol: protocol,
tlsVersion: rawProtocol,
Policy: input.connectInput.Policy,
CipherSuite: tls.CipherSuiteName(input.state.CipherSuite),
ServerName: input.serverName,
ALPN: input.state.NegotiatedProtocol,
ClientAuth: input.clientAuth,
PeerChain: input.state.PeerCertificates,
TLSSCTs: input.state.SignedCertificateTimestamps,
}
result.populate(ctx, input.connectInput)
return result
}
func dialProbeConn(ctx context.Context, input cipherProbeInput) (net.Conn, error) {
dialer := &net.Dialer{}
conn, err := dialer.DialContext(ctx, "tcp", input.addr)
if err != nil {
return nil, fmt.Errorf("dialing probe connection: %w", err)
}
if input.startTLS == "" {
return conn, nil
}
if deadline, ok := ctx.Deadline(); ok {
if err := conn.SetDeadline(deadline); err != nil {
_ = conn.Close()
return nil, fmt.Errorf("setting STARTTLS probe deadline: %w", err)
}
}
reader := bufio.NewReader(conn)
if err := negotiateStartTLS(negotiateStartTLSInput{
reader: reader,
conn: conn,
protocol: input.startTLS,
}); err != nil {