cfprobe 0.1.0

Cloudflare reverse proxy and CDN detection engine
Documentation
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
use std::collections::{BTreeMap, BTreeSet};

use serde::Serialize;

use super::model::{DetectionClassification, EvidenceCategory, EvidenceKind, PolicyMetadata};

/**
 * 评分模型 v1.0 default

当前基础分:

Network
    Cloudflare IP      +80
    Outside CF         -100

DNS
    Cloudflare DNS     +25
    Resolver consensus +0~10

TLS
    Handshake            +5
    Cert SAN match      +10
    Cert verified        +5
    Cert mismatch        -5

HTTP
    CF-Ray              +35
    CF-Cache-Status       +5
    Server: cloudflare    +5
    CF-Connecting-IP      +1
    CF-IPCountry           +1
    CF-Mitigated           +2

然后:

Network max = +80 / -100
DNS max     = +35
TLS max     = +20
HTTP max    = +45

最后:

[-100, +100]
 *
 *
 *
 */

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ScoreCap {
    pub min: i16,

    pub max: i16,
}

impl ScoreCap {
    pub const fn new(min: i16, max: i16) -> Self {
        Self { min, max }
    }

    pub fn clamp(&self, value: i16) -> i16 {
        value.clamp(self.min, self.max)
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct DnsRuleSet {
    /*
     * Minimum ratio of successful resolvers.
     *
     * Example:
     *
     * resolver_count = 3
     * successful = 2
     * ratio = 0.67
     */
    pub min_successful_ratio: f32,

    /*
     * Minimum ratio of successful resolvers that
     * must resolve to Cloudflare in order to generate
     * positive DNS evidence.
     */
    pub min_cloudflare_ratio: f32,

    /*
     * Whether a DNS result with zero Cloudflare
     * resolvers should produce negative evidence.
     */
    pub negative_when_no_cloudflare: bool,
}

impl Default for DnsRuleSet {
    fn default() -> Self {
        Self {
            min_successful_ratio: 0.50,

            min_cloudflare_ratio: 0.50,

            negative_when_no_cloudflare: true,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ClassificationRuleSet {
    /*
     * Score required for a positive classification.
     */
    pub cloudflare_threshold: i16,

    /*
     * Score at or below which a target can be
     * classified as NotCloudflare.
     */
    pub not_cloudflare_threshold: i16,

    /*
     * For hostname-based detection, require at least
     * one hostname-specific positive signal.
     *
     * This prevents:
     *
     * IP = Cloudflare
     * Host = unrelated.example
     *
     * from being classified as Cloudflare.
     */
    pub require_host_specific_positive: bool,

    /*
     * Kinds that count as host-specific positive evidence.
     */
    pub host_specific_positive_kinds: BTreeSet<EvidenceKind>,

    /*
     * Whether IP-only queries can be classified solely
     * from the provider IP range.
     */
    pub allow_ip_only_classification: bool,
}

impl Default for ClassificationRuleSet {
    fn default() -> Self {
        let mut kinds = BTreeSet::new();

        kinds.insert(EvidenceKind::DnsResolvesToCloudflare);

        kinds.insert(EvidenceKind::DnsCnameToCloudflare);

        kinds.insert(EvidenceKind::TlsCertificateHostnameMatch);

        kinds.insert(EvidenceKind::HttpCfRay);

        kinds.insert(EvidenceKind::HttpCfCacheStatus);

        kinds.insert(EvidenceKind::HttpServerCloudflare);

        kinds.insert(EvidenceKind::HttpCfConnectingIp);

        kinds.insert(EvidenceKind::HttpCfMitigated);

        Self {
            cloudflare_threshold: 65,

            not_cloudflare_threshold: -50,

            require_host_specific_positive: true,

            host_specific_positive_kinds: kinds,

            allow_ip_only_classification: true,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct ConfidenceRuleSet {
    /*
     * Used for positive classification:
     *
     * confidence =
     *   positive_base + score / positive_divisor
     */
    pub positive_base: f32,

    pub positive_divisor: f32,

    /*
     * Used for negative classification when there
     * is no absolute negative signal.
     */
    pub negative_base: f32,

    pub negative_divisor: f32,

    pub max_confidence: f32,

    pub very_high_threshold: f32,

    pub high_threshold: f32,

    pub medium_threshold: f32,
}

impl Default for ConfidenceRuleSet {
    fn default() -> Self {
        Self {
            positive_base: 0.50,

            positive_divisor: 200.0,

            negative_base: 0.50,

            negative_divisor: 200.0,

            max_confidence: 0.99,

            very_high_threshold: 0.95,

            high_threshold: 0.85,

            medium_threshold: 0.70,
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct RuleSet {
    /*
     * Individual evidence weights.
     *
     * EvidenceEngine NEVER hard-codes these values.
     */
    pub weights: BTreeMap<EvidenceKind, i16>,

    /*
     * Maximum contribution of each evidence category.
     */
    pub category_caps: BTreeMap<EvidenceCategory, ScoreCap>,

    pub dns: DnsRuleSet,

    pub classification: ClassificationRuleSet,

    pub confidence: ConfidenceRuleSet,

    /*
     * Absolute overall score boundary.
     */
    pub overall_cap: ScoreCap,
}

impl RuleSet {
    pub fn weight(&self, kind: EvidenceKind) -> i16 {
        self.weights.get(&kind).copied().unwrap_or(0)
    }

    pub fn category_cap(&self, category: EvidenceCategory) -> ScoreCap {
        self.category_caps
            .get(&category)
            .copied()
            .unwrap_or(ScoreCap::new(-100, 100))
    }

    pub fn cloudflare_web_proxy_v1() -> Self {
        let mut weights = BTreeMap::new();

        /*
         * Network
         */
        weights.insert(EvidenceKind::CloudflareIpRange, 80);

        weights.insert(EvidenceKind::IpOutsideCloudflareRange, -100);

        /*
         * DNS
         */
        weights.insert(EvidenceKind::DnsResolvesToCloudflare, 25);

        weights.insert(EvidenceKind::DnsResolverConsensus, 10);

        weights.insert(EvidenceKind::DnsNoCloudflareResolution, -10);

        weights.insert(EvidenceKind::DnsCnameToCloudflare, 20);

        weights.insert(EvidenceKind::DnsCnameChain, 5);

        /*
         * TLS
         */
        weights.insert(EvidenceKind::TlsHandshakeSucceeded, 5);

        weights.insert(EvidenceKind::TlsCertificateHostnameMatch, 10);

        weights.insert(EvidenceKind::TlsCertificateHostnameMismatch, -5);

        weights.insert(EvidenceKind::TlsCertificateVerified, 5);

        weights.insert(EvidenceKind::TlsCertificateVerificationUnavailable, 0);

        /*
         * HTTP
         */
        weights.insert(EvidenceKind::HttpCfRay, 35);

        weights.insert(EvidenceKind::HttpCfCacheStatus, 5);

        weights.insert(EvidenceKind::HttpServerCloudflare, 5);

        weights.insert(EvidenceKind::HttpCfConnectingIp, 1);

        weights.insert(EvidenceKind::HttpCfIpCountry, 1);

        weights.insert(EvidenceKind::HttpCfMitigated, 2);

        weights.insert(EvidenceKind::HttpNoCloudflareSignals, 0);

        let mut caps = BTreeMap::new();

        caps.insert(EvidenceCategory::Network, ScoreCap::new(-100, 80));

        caps.insert(EvidenceCategory::Dns, ScoreCap::new(-35, 60));

        caps.insert(EvidenceCategory::Tls, ScoreCap::new(-20, 20));

        /*
         * HTTP evidence is strongly correlated.
         *
         * CF-Ray + CF-Cache-Status +
         * Server: cloudflare
         *
         * must not become unlimited evidence.
         */
        caps.insert(EvidenceCategory::Http, ScoreCap::new(0, 45));

        Self {
            weights,

            category_caps: caps,

            dns: DnsRuleSet {
                min_successful_ratio: 0.50,

                min_cloudflare_ratio: 0.50,

                negative_when_no_cloudflare: true,
            },

            classification: ClassificationRuleSet::default(),

            confidence: ConfidenceRuleSet::default(),

            overall_cap: ScoreCap::new(-100, 100),
        }
    }
}

/// 可插拔的证据评分策略接口。
///
/// 决定:证据权重、正负分类阈值、置信度分档,以及最终是 Cloudflare / NotCloudflare / Unknown。
pub trait DetectionPolicy: Send + Sync {
    /// 策略元数据(id、版本、描述等)。
    fn metadata(&self) -> &PolicyMetadata;

    /// 规则集(IP / DNS / TLS / HTTP + 证据合并规则)。
    fn rules(&self) -> &RuleSet;

    /// 正向分类(即达到阈值时判定为什么类),默认 `Cloudflare`。
    fn positive_classification(&self) -> DetectionClassification {
        DetectionClassification::Cloudflare
    }

    /// 反向分类(反证据达到阈值时判定为什么类),默认 `NotCloudflare`。
    fn negative_classification(&self) -> DetectionClassification {
        DetectionClassification::NotCloudflare
    }
}

/// 预置的 “Cloudflare Web Proxy V1” 标准评分策略。
#[derive(Debug, Clone)]
pub struct CloudflareWebProxyV1 {
    metadata: PolicyMetadata,

    rules: RuleSet,
}

impl Default for CloudflareWebProxyV1 {
    fn default() -> Self {
        Self {
            metadata:
                PolicyMetadata {
                    id:
                        "cloudflare-web-proxy"
                            .to_string(),

                    version:
                        1,

                    name:
                        "Cloudflare Web Proxy V1"
                            .to_string(),

                    description:
                        "Evidence policy for identifying web traffic served through Cloudflare's published edge network"
                            .to_string(),
                },

            rules:
                RuleSet::
                    cloudflare_web_proxy_v1(),
        }
    }
}

impl DetectionPolicy for CloudflareWebProxyV1 {
    fn metadata(&self) -> &PolicyMetadata {
        &self.metadata
    }

    fn rules(&self) -> &RuleSet {
        &self.rules
    }
}

impl CloudflareWebProxyV1 {
    pub fn rules_mut(&mut self) -> &mut RuleSet {
        &mut self.rules
    }

    pub fn metadata(&self) -> &PolicyMetadata {
        &self.metadata
    }
}