-
Notifications
You must be signed in to change notification settings - Fork 76
/
ztls.go
313 lines (279 loc) · 9.82 KB
/
ztls.go
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
// Package ztls implements a tls grabbing implementation using
// zmap zcrypto/tls library.
package ztls
import (
"context"
"errors"
"fmt"
"net"
"os"
"time"
"github.com/projectdiscovery/fastdialer/fastdialer"
"github.com/projectdiscovery/gologger"
"github.com/projectdiscovery/tlsx/pkg/output/stats"
"github.com/projectdiscovery/tlsx/pkg/tlsx/clients"
"github.com/projectdiscovery/tlsx/pkg/tlsx/ztls/ja3"
"github.com/projectdiscovery/utils/conn/connpool"
errorutil "github.com/projectdiscovery/utils/errors"
iputil "github.com/projectdiscovery/utils/ip"
stringsutil "github.com/projectdiscovery/utils/strings"
"github.com/rs/xid"
"github.com/zmap/zcrypto/encoding/asn1"
"github.com/zmap/zcrypto/tls"
"github.com/zmap/zcrypto/x509"
)
func init() {
asn1.AllowPermissiveParsing = true
}
// Client is a TLS grabbing client using crypto/tls
type Client struct {
dialer *fastdialer.Dialer
tlsConfig *tls.Config
options *clients.Options
}
// versionStringToTLSVersion converts tls version string to version
var versionStringToTLSVersion = map[string]uint16{
"ssl30": tls.VersionSSL30,
"tls10": tls.VersionTLS10,
"tls11": tls.VersionTLS11,
"tls12": tls.VersionTLS12,
}
// versionToTLSVersionString converts tls version to version string
var versionToTLSVersionString = map[uint16]string{
tls.VersionSSL30: "ssl30",
tls.VersionTLS10: "tls10",
tls.VersionTLS11: "tls11",
tls.VersionTLS12: "tls12",
}
// New creates a new grabbing client using crypto/tls
func New(options *clients.Options) (*Client, error) {
c := &Client{
dialer: options.Fastdialer,
tlsConfig: &tls.Config{
CertsOnly: options.CertsOnly,
MinVersion: tls.VersionSSL30,
MaxVersion: tls.VersionTLS12,
InsecureSkipVerify: !options.VerifyServerCertificate,
},
options: options,
}
if len(options.Ciphers) > 0 {
if customCiphers, err := toZTLSCiphers(options.Ciphers); err != nil {
return nil, errorutil.NewWithTag("ztls", "could not get ztls ciphers").Wrap(err)
} else {
c.tlsConfig.CipherSuites = customCiphers
}
} else {
// unless explicitly specified client should advertise all supported ciphers
// Note: Go stdlib by default only advertises a safe/default list of ciphers
c.tlsConfig.CipherSuites = AllCiphers
}
if options.CACertificate != "" {
caCert, err := os.ReadFile(options.CACertificate)
if err != nil {
return nil, errorutil.NewWithTag("ztls", "could not read ca certificate").Wrap(err)
}
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(caCert) {
gologger.Error().Msgf("Could not append parsed ca-cert to config!")
}
c.tlsConfig.RootCAs = certPool
}
if options.MinVersion != "" {
version, ok := versionStringToTLSVersion[options.MinVersion]
if !ok {
return nil, fmt.Errorf("invalid min version specified: %s", options.MinVersion)
} else {
c.tlsConfig.MinVersion = version
}
}
if options.MaxVersion != "" {
version, ok := versionStringToTLSVersion[options.MaxVersion]
if !ok {
return nil, fmt.Errorf("invalid max version specified: %s", options.MaxVersion)
} else {
c.tlsConfig.MaxVersion = version
}
}
return c, nil
}
// Connect connects to a host and grabs the response data
func (c *Client) ConnectWithOptions(hostname, ip, port string, options clients.ConnectOptions) (*clients.Response, error) {
// Get ztls config using input
config, err := c.getConfig(hostname, ip, port, options)
if err != nil {
return nil, errorutil.NewWithErr(err).Msgf("failed to create ztls config")
}
ctx := context.Background()
if c.options.Timeout != 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, time.Duration(c.options.Timeout)*time.Second)
defer cancel()
}
// setup tcp connection
conn, err := clients.GetConn(ctx, hostname, ip, port, c.options)
if err != nil {
return nil, errorutil.NewWithErr(err).Msgf("failed to setup connection").WithTag("ztls")
}
defer conn.Close() //internally done by conn.Close() so just a placeholder
// get resolvedIp
resolvedIP, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
return nil, err
}
// new tls connection
tlsConn := tls.Client(conn, config)
if err := c.tlsHandshakeWithTimeout(tlsConn, ctx); err != nil {
return nil, errorutil.NewWithTag("ztls", "could not do tls handshake").Wrap(err)
}
defer tlsConn.Close()
hl := tlsConn.GetHandshakeLog()
now := time.Now()
response := &clients.Response{
Timestamp: &now,
Host: hostname,
IP: resolvedIP,
ProbeStatus: true,
Port: port,
TLSConnection: "ztls",
ServerName: config.ServerName,
}
if hl != nil && hl.ServerCertificates != nil {
response.CertificateResponse = ConvertCertificateToResponse(c.options, hostname, ParseSimpleTLSCertificate(hl.ServerCertificates.Certificate))
if response.CertificateResponse != nil {
response.Untrusted = clients.IsZTLSUntrustedCA(hl.ServerCertificates.Chain)
}
}
if hl.ServerHello != nil {
response.Version = versionToTLSVersionString[uint16(hl.ServerHello.Version)]
response.Cipher = hl.ServerHello.CipherSuite.String()
}
if c.options.TLSChain {
for _, cert := range hl.ServerCertificates.Chain {
response.Chain = append(response.Chain, ConvertCertificateToResponse(c.options, hostname, ParseSimpleTLSCertificate(cert)))
}
}
if c.options.Ja3 {
response.Ja3Hash = ja3.GetJa3Hash(hl.ClientHello)
}
if c.options.ClientHello {
response.ClientHello = hl.ClientHello
}
if c.options.ServerHello {
response.ServerHello = hl.ServerHello
}
return response, nil
}
// EnumerateCiphers enumerate target with ciphers supported by ztls
func (c *Client) EnumerateCiphers(hostname, ip, port string, options clients.ConnectOptions) ([]string, error) {
// filter ciphers based on given seclevel
toEnumerate := clients.GetCiphersWithLevel(AllCiphersNames, options.CipherLevel...)
enumeratedCiphers := []string{}
// get network address
var address string
if iputil.IsIP(ip) && (c.options.ScanAllIPs || len(c.options.IPVersion) > 0) {
address = net.JoinHostPort(ip, port)
} else {
address = net.JoinHostPort(hostname, port)
}
threads := c.options.CipherConcurrency
if len(toEnumerate) < threads {
threads = len(toEnumerate)
}
// setup connection pool
pool, err := connpool.NewOneTimePool(context.Background(), address, threads)
if err != nil {
return enumeratedCiphers, errorutil.NewWithErr(err).Msgf("failed to setup connection pool")
}
pool.Dialer = c.dialer
go func() {
if err := pool.Run(); err != nil && !errors.Is(err, context.Canceled) {
gologger.Error().Msgf("tlsx: ztls: failed to run connection pool: %v", err)
}
}()
defer pool.Close()
// create ztls base config
baseCfg, err := c.getConfig(hostname, ip, port, options)
if err != nil {
return enumeratedCiphers, errorutil.NewWithErr(err).Msgf("failed to setup cfg")
}
gologger.Debug().Label("ztls").Msgf("Starting cipher enumeration with %v ciphers in %v", len(toEnumerate), options.VersionTLS)
for _, v := range toEnumerate {
baseConn, err := pool.Acquire(context.Background())
if err != nil {
return enumeratedCiphers, errorutil.NewWithErr(err).WithTag("ztls")
}
stats.IncrementZcryptoTLSConnections()
conn := tls.Client(baseConn, baseCfg)
baseCfg.CipherSuites = []uint16{ztlsCiphers[v]}
if err := c.tlsHandshakeWithTimeout(conn, context.TODO()); err == nil {
h1 := conn.GetHandshakeLog()
enumeratedCiphers = append(enumeratedCiphers, h1.ServerHello.CipherSuite.String())
}
_ = conn.Close() // also closes baseConn internally
}
return enumeratedCiphers, nil
}
// SupportedTLSVersions returns the list of ztls library supported tls versions
func (c *Client) SupportedTLSVersions() ([]string, error) {
return SupportedTlsVersions, nil
}
// SupportedTLSCiphers returns the list of ztls library supported ciphers
func (c *Client) SupportedTLSCiphers() ([]string, error) {
return AllCiphersNames, nil
}
// getConfig returns tlsconfig for ztls
func (c *Client) getConfig(hostname, ip, port string, options clients.ConnectOptions) (*tls.Config, error) {
// In enum mode return if given options are not supported
if options.EnumMode == clients.Version && (options.VersionTLS == "" || !stringsutil.EqualFoldAny(options.VersionTLS, SupportedTlsVersions...)) {
// version not supported
return nil, errorutil.NewWithTag("ztls", "tlsversion `%v` not supported in ztls", options.VersionTLS)
}
if options.EnumMode == clients.Cipher && !stringsutil.EqualFoldAny(options.VersionTLS, SupportedTlsVersions...) {
return nil, errorutil.NewWithTag("ztls", "cipher enum with version %v not implemented", options.VersionTLS)
}
config := c.tlsConfig
if config.ServerName == "" {
cfg := config.Clone()
if options.SNI != "" {
cfg.ServerName = options.SNI
} else if iputil.IsIP(hostname) && c.options.RandomForEmptyServerName {
// using a random sni will return the default server certificate
cfg.ServerName = xid.New().String()
} else {
cfg.ServerName = hostname
}
config = cfg
}
if options.VersionTLS != "" {
version, ok := versionStringToTLSVersion[options.VersionTLS]
if !ok {
return nil, errorutil.NewWithTag("ztls", "invalid tls version specified: %s", options.VersionTLS)
}
config.MinVersion = version
config.MaxVersion = version
}
if len(options.Ciphers) > 0 && options.EnumMode != clients.Cipher {
customCiphers, err := toZTLSCiphers(options.Ciphers)
if err != nil {
return nil, errorutil.NewWithTag("ztls", "could not get tls ciphers").Wrap(err)
}
c.tlsConfig.CipherSuites = customCiphers
}
return config, nil
}
// tlsHandshakeWithCtx attempts tls handshake with given timeout
func (c *Client) tlsHandshakeWithTimeout(tlsConn *tls.Conn, ctx context.Context) error {
errChan := make(chan error, 1)
defer close(errChan)
select {
case <-ctx.Done():
return errorutil.NewWithTag("ztls", "timeout while attempting handshake")
case errChan <- tlsConn.Handshake():
}
err := <-errChan
if err == tls.ErrCertsOnly {
err = nil
}
return err
}