This repository has been archived by the owner on May 7, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 70
/
processor.go
287 lines (260 loc) · 10.8 KB
/
processor.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
// MITMEngine (monster-in-the-middle engine) is a library for detecting HTTPS
// interception from the server's vantage point, and is based on heuristics
// developed in https://zakird.com/papers/https_interception.pdf.
package mitmengine
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"github.com/cloudflare/mitmengine/db"
fp "github.com/cloudflare/mitmengine/fputil"
"github.com/cloudflare/mitmengine/loader"
)
var (
// ErrorUnknownUserAgent indicates that the user agent is not supported.
ErrorUnknownUserAgent = errors.New("unknown_user_agent")
)
// A Processor generates heuristic-based monster-in-the-middle (MITM) detection
// reports for a TLS client hello and corresponding HTTP user agent.
type Processor struct {
FileNameMap map[string]string
BrowserDatabase db.Database
MitmDatabase db.Database
BadHeaderSet fp.StringSet
}
// A Config contains information for initializing the processor such as the
// file names to read records from, as well as Loader information in the case
// the fingerprints are read from any datasource.
type Config struct {
BrowserFileName string
MitmFileName string
BadHeaderFileName string
Loader loader.Loader
}
// NewProcessor returns a new Processor initialized from the config.
func NewProcessor(config *Config) (Processor, error) {
var a Processor
err := a.Load(config)
return a, err
}
// Load (or reload) the processor state from the provided configuration.
func (a *Processor) Load(config *Config) error {
browserFingerprints, err := LoadFile(config.BrowserFileName, config.Loader)
if err != nil {
log.Printf("WARNING: loading file \"%s\" produced error \"%s\"", config.BrowserFileName, err)
browserFingerprints = ioutil.NopCloser(bytes.NewReader(nil))
}
if a.BrowserDatabase, err = db.NewDatabase(browserFingerprints); err != nil {
return err
}
browserFingerprints.Close()
mitmFingerprints, err := LoadFile(config.MitmFileName, config.Loader)
if err != nil {
log.Printf("WARNING: loading file \"%s\" produced error \"%s\"", config.MitmFileName, err)
mitmFingerprints = ioutil.NopCloser(bytes.NewReader(nil))
}
if a.MitmDatabase, err = db.NewDatabase(mitmFingerprints); err != nil {
return err
}
mitmFingerprints.Close()
badHeaders, err := LoadFile(config.BadHeaderFileName, config.Loader)
if err != nil {
log.Printf("WARNING: loading file \"%s\" produced error \"%s\"", config.BadHeaderFileName, err)
badHeaders = ioutil.NopCloser(bytes.NewReader(nil))
}
scanner := bufio.NewScanner(badHeaders)
var badHeaderList fp.StringList
for scanner.Scan() {
badHeaderList = append(badHeaderList, scanner.Text())
}
a.BadHeaderSet = badHeaderList.Set()
badHeaders.Close()
return nil
}
// LoadFile loads individual files from local file storage or from a Loader interface.
func LoadFile(fileName string, dbReader loader.Loader) (io.ReadCloser, error) {
var file io.ReadCloser
var readErr error
if dbReader == nil { // read directly from file
file, readErr = os.Open(fileName)
} else {
file, readErr = dbReader.LoadFile(fileName)
}
return file, readErr
}
// Check if the supplied client hello fields match the expected client hello
// fields for the the brower specified by the supplied user agent, and return a
// report including the mitm detection result, security details, and client
// hello fingerprints.
func (a *Processor) Check(uaFingerprint fp.UAFingerprint, rawUa string, actualReqFin fp.RequestFingerprint) Report {
// Add user agent fingerprint quirks.
if strings.Contains(rawUa, "Dragon/") {
uaFingerprint.Quirk = append(uaFingerprint.Quirk, "dragon")
}
if strings.Contains(rawUa, "GSA/") {
uaFingerprint.Quirk = append(uaFingerprint.Quirk, "gsa")
}
if strings.Contains(rawUa, "Silk-Accelerated=true") {
uaFingerprint.Quirk = append(uaFingerprint.Quirk, "silk_accelerated")
}
if strings.Contains(rawUa, "PlayStation Vita") {
uaFingerprint.Quirk = append(uaFingerprint.Quirk, "playstation")
}
// Remove grease ciphers, extensions, and curves from request fingerprint and add as quirk instead.
hasGreaseCipher, newSize := removeGrease(actualReqFin.Cipher)
actualReqFin.Cipher = actualReqFin.Cipher[:newSize] // Remove grease ciphers
hasGreaseExtension, newSize := removeGrease(actualReqFin.Extension)
actualReqFin.Extension = actualReqFin.Extension[:newSize] // Remove grease extensions
hasGreaseCurve, newSize := removeGrease(actualReqFin.Curve)
actualReqFin.Curve = actualReqFin.Curve[:newSize] // Remove grease curves
if hasGreaseCipher || hasGreaseExtension || hasGreaseCurve {
actualReqFin.Quirk = append(actualReqFin.Quirk, "grease")
}
// Check for 'bad' headers that browsers never send and add as quirk.
hasBadHeader := false
for _, elem := range actualReqFin.Header {
if a.BadHeaderSet[elem] {
hasBadHeader = true
}
}
if hasBadHeader {
actualReqFin.Quirk = append(actualReqFin.Quirk, "badhdr")
}
// Create mitm detection report
var r Report
// Find the browser record matching the user agent fingerprint
browserRecordIds := a.BrowserDatabase.GetByUAFingerprint(uaFingerprint)
if len(browserRecordIds) == 0 {
return Report{Error: ErrorUnknownUserAgent}
}
var browserRecord db.Record
var maxSimilarity int
match := false
for _, id := range browserRecordIds {
tempRecord := a.BrowserDatabase.Records[id]
recordMatch, similarity := tempRecord.RequestSignature.Match(actualReqFin)
if recordMatch == fp.MatchPossible {
match = true
browserRecord = tempRecord
break
} else { // else, if similarity of unmatched record is greater than previously saved similarity, save record
if similarity >= maxSimilarity {
browserRecord = tempRecord
maxSimilarity = similarity
}
}
}
browserReqSig := browserRecord.RequestSignature
r.MatchedUASignature = browserRecord.UASignature.String()
r.BrowserSignature = browserReqSig.String()
r.BrowserGrade = browserReqSig.Grade()
r.ActualGrade = actualReqFin.Version.Grade().Merge(fp.GlobalCipherCheck.Grade(actualReqFin.Cipher))
// No need to add to the report if we have match.
if match {
r.BrowserSignatureMatch = fp.MatchPossible
return r
}
// Find the heuristics that flagged the connection as invalid
matchMap, _ := browserReqSig.MatchMap(actualReqFin)
var reason []string
var reasonDetails []string
switch {
case matchMap["version"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_version")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Version, actualReqFin.Version))
case matchMap["cipher"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_cipher")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Cipher, actualReqFin.Cipher.String()))
case matchMap["extension"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_extension")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Extension, actualReqFin.Extension.String()))
case matchMap["curve"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_curve")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Curve, actualReqFin.Curve.String()))
case matchMap["ecpointfmt"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_ecpointfmt")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.EcPointFmt, actualReqFin.EcPointFmt.String()))
case matchMap["header"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_header")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Header, actualReqFin.Header))
case matchMap["quirk"] == fp.MatchImpossible:
r.BrowserSignatureMatch = fp.MatchImpossible
reason = append(reason, "impossible_quirk")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Quirk, actualReqFin.Quirk))
// put 'unlikely' reasons after 'impossible' reasons
case matchMap["version"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_version")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Version, actualReqFin.Version))
case matchMap["cipher"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_cipher")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Cipher, actualReqFin.Cipher.String()))
case matchMap["extension"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_extension")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Extension, actualReqFin.Extension.String()))
case matchMap["curve"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_curve")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Curve, actualReqFin.Curve.String()))
case matchMap["ecpointfmt"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_ecpointfmt")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.EcPointFmt, actualReqFin.EcPointFmt.String()))
case matchMap["header"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_header")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Header, actualReqFin.Header))
case matchMap["quirk"] == fp.MatchUnlikely:
r.BrowserSignatureMatch = fp.MatchUnlikely
reason = append(reason, "unlikely_quirk")
reasonDetails = append(reasonDetails, fmt.Sprintf("%s vs %s", browserReqSig.Quirk, actualReqFin.Quirk))
default:
r.BrowserSignatureMatch = fp.MatchPossible
}
r.Reason = strings.Join(reason, ",")
r.ReasonDetails = strings.Join(reasonDetails, ",")
// Check if MITM affects the connection security level
switch r.BrowserSignatureMatch {
case fp.MatchImpossible, fp.MatchUnlikely:
if browserReqSig.IsPfs() && fp.GlobalCipherCheck.IsFirstPfs(actualReqFin.Cipher) {
r.LosesPfs = true
}
mitmRecordIds := a.MitmDatabase.GetByRequestFingerprint(actualReqFin)
if len(mitmRecordIds) == 0 {
break
}
mitmRecord := a.MitmDatabase.Records[mitmRecordIds[0]]
r.ActualGrade = r.ActualGrade.Merge(mitmRecord.MitmInfo.Grade)
r.MatchedMitmName = mitmRecord.MitmInfo.NameList.String()
r.MatchedMitmType = mitmRecord.MitmInfo.Type
r.MatchedMitmSignature = mitmRecord.RequestSignature.String()
}
return r
}
func removeGrease(list fp.IntList) (bool, int) {
hasGrease := false
idx := 0
for _, elem := range list {
if (elem & 0x0f0f) == 0x0a0a {
hasGrease = true
} else {
list[idx] = elem
idx++
}
}
return hasGrease, idx
}