forked from Psiphon-Labs/psiphon-tunnel-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
1531 lines (1304 loc) · 50.4 KB
/
api.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
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
/*
* Copyright (c) 2016, Psiphon Inc.
* All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package server
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/json"
std_errors "errors"
"net"
"regexp"
"strconv"
"strings"
"time"
"unicode"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/errors"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/fragmentor"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/protocol"
"github.com/Psiphon-Labs/psiphon-tunnel-core/psiphon/common/tactics"
)
const (
MAX_API_PARAMS_SIZE = 256 * 1024 // 256KB
PADDING_MAX_BYTES = 16 * 1024
CLIENT_PLATFORM_ANDROID = "Android"
CLIENT_PLATFORM_WINDOWS = "Windows"
CLIENT_PLATFORM_IOS = "iOS"
)
// sshAPIRequestHandler routes Psiphon API requests transported as
// JSON objects via the SSH request mechanism.
//
// The API request handlers, handshakeAPIRequestHandler, etc., are
// reused by webServer which offers the Psiphon API via web transport.
//
// The API request parameters and event log values follow the legacy
// psi_web protocol and naming conventions. The API is compatible with
// all tunnel-core clients but are not backwards compatible with all
// legacy clients.
//
func sshAPIRequestHandler(
support *SupportServices,
clientAddr string,
geoIPData GeoIPData,
authorizedAccessTypes []string,
name string,
requestPayload []byte) ([]byte, error) {
// Notes:
//
// - For SSH requests, MAX_API_PARAMS_SIZE is implicitly enforced
// by max SSH request packet size.
//
// - The param protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS is an
// array of base64-encoded strings; the base64 representation should
// not be decoded to []byte values. The default behavior of
// https://golang.org/pkg/encoding/json/#Unmarshal for a target of
// type map[string]interface{} will unmarshal a base64-encoded string
// to a string, not a decoded []byte, as required.
var params common.APIParameters
err := json.Unmarshal(requestPayload, ¶ms)
if err != nil {
return nil, errors.Tracef(
"invalid payload for request name: %s: %s", name, err)
}
return dispatchAPIRequestHandler(
support,
protocol.PSIPHON_SSH_API_PROTOCOL,
clientAddr,
geoIPData,
authorizedAccessTypes,
name,
params)
}
// dispatchAPIRequestHandler is the common dispatch point for both
// web and SSH API requests.
func dispatchAPIRequestHandler(
support *SupportServices,
apiProtocol string,
clientAddr string,
geoIPData GeoIPData,
authorizedAccessTypes []string,
name string,
params common.APIParameters) (response []byte, reterr error) {
// Before invoking the handlers, enforce some preconditions:
//
// - A handshake request must precede any other requests.
// - When the handshake results in a traffic rules state where
// the client is immediately exhausted, no requests
// may succeed. This case ensures that blocked clients do
// not log "connected", etc.
//
// Only one handshake request may be made. There is no check here
// to enforce that handshakeAPIRequestHandler will be called at
// most once. The SetHandshakeState call in handshakeAPIRequestHandler
// enforces that only a single handshake is made; enforcing that there
// ensures no race condition even if concurrent requests are
// in flight.
if name != protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME {
// TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
// applies here.
sessionID, err := getStringRequestParam(params, "client_session_id")
if err == nil {
// Note: follows/duplicates baseParams validation
if !isHexDigits(support.Config, sessionID) {
err = std_errors.New("invalid param: client_session_id")
}
}
if err != nil {
return nil, errors.Trace(err)
}
completed, exhausted, err := support.TunnelServer.GetClientHandshaked(sessionID)
if err != nil {
return nil, errors.Trace(err)
}
if !completed {
return nil, errors.TraceNew("handshake not completed")
}
if exhausted {
return nil, errors.TraceNew("exhausted after handshake")
}
}
switch name {
case protocol.PSIPHON_API_HANDSHAKE_REQUEST_NAME:
return handshakeAPIRequestHandler(
support, apiProtocol, clientAddr, geoIPData, params)
case protocol.PSIPHON_API_CONNECTED_REQUEST_NAME:
return connectedAPIRequestHandler(
support, clientAddr, geoIPData, authorizedAccessTypes, params)
case protocol.PSIPHON_API_STATUS_REQUEST_NAME:
return statusAPIRequestHandler(
support, clientAddr, geoIPData, authorizedAccessTypes, params)
case protocol.PSIPHON_API_CLIENT_VERIFICATION_REQUEST_NAME:
return clientVerificationAPIRequestHandler(
support, clientAddr, geoIPData, authorizedAccessTypes, params)
}
return nil, errors.Tracef("invalid request name: %s", name)
}
var handshakeRequestParams = append(
append(
append(
[]requestParamSpec{
// Legacy clients may not send "session_id" in handshake
{"session_id", isHexDigits, requestParamOptional},
{"missing_server_entry_signature", isBase64String, requestParamOptional}},
baseParams...),
baseDialParams...),
tacticsParams...)
// handshakeAPIRequestHandler implements the "handshake" API request.
// Clients make the handshake immediately after establishing a tunnel
// connection; the response tells the client what homepage to open, what
// stats to record, etc.
func handshakeAPIRequestHandler(
support *SupportServices,
apiProtocol string,
clientAddr string,
geoIPData GeoIPData,
params common.APIParameters) ([]byte, error) {
// Note: ignoring legacy "known_servers" params
err := validateRequestParams(support.Config, params, handshakeRequestParams)
if err != nil {
return nil, errors.Trace(err)
}
sessionID, _ := getStringRequestParam(params, "client_session_id")
sponsorID, _ := getStringRequestParam(params, "sponsor_id")
clientVersion, _ := getStringRequestParam(params, "client_version")
clientPlatform, _ := getStringRequestParam(params, "client_platform")
isMobile := isMobileClientPlatform(clientPlatform)
normalizedPlatform := normalizeClientPlatform(clientPlatform)
// establishedTunnelsCount is used in traffic rule selection. When omitted by
// the client, a value of 0 will be used.
establishedTunnelsCount, _ := getIntStringRequestParam(params, "established_tunnels_count")
// splitTunnelOwnRegion indicates if the client is requesting split tunnel
// mode to be applied to the client's own country. When omitted by the
// client, the value will be false.
//
// When split_tunnel_regions is non-empty, split tunnel mode will be
// applied for the specified country codes. When omitted by the client,
// the value will be an empty slice.
splitTunnelOwnRegion, _ := getBoolStringRequestParam(params, "split_tunnel")
splitTunnelOtherRegions, _ := getStringArrayRequestParam(params, "split_tunnel_regions")
ownRegion := ""
if splitTunnelOwnRegion {
ownRegion = geoIPData.Country
}
var splitTunnelLookup *splitTunnelLookup
if ownRegion != "" || len(splitTunnelOtherRegions) > 0 {
splitTunnelLookup, err = newSplitTunnelLookup(ownRegion, splitTunnelOtherRegions)
if err != nil {
return nil, errors.Trace(err)
}
}
var authorizations []string
if params[protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS] != nil {
authorizations, err = getStringArrayRequestParam(params, protocol.PSIPHON_API_HANDSHAKE_AUTHORIZATIONS)
if err != nil {
return nil, errors.Trace(err)
}
}
// Note: no guarantee that PsinetDatabase won't reload between database calls
db := support.PsinetDatabase
httpsRequestRegexes, domainBytesChecksum := db.GetHttpsRequestRegexes(sponsorID)
// Flag the SSH client as having completed its handshake. This
// may reselect traffic rules and starts allowing port forwards.
// TODO: in the case of SSH API requests, the actual sshClient could
// be passed in and used here. The session ID lookup is only strictly
// necessary to support web API requests.
handshakeStateInfo, err := support.TunnelServer.SetClientHandshakeState(
sessionID,
handshakeState{
completed: true,
apiProtocol: apiProtocol,
apiParams: copyBaseSessionAndDialParams(params),
domainBytesChecksum: domainBytesChecksum,
establishedTunnelsCount: establishedTunnelsCount,
splitTunnelLookup: splitTunnelLookup,
},
authorizations)
if err != nil {
return nil, errors.Trace(err)
}
tacticsPayload, err := support.TacticsServer.GetTacticsPayload(
common.GeoIPData(geoIPData), params)
if err != nil {
return nil, errors.Trace(err)
}
var marshaledTacticsPayload []byte
if tacticsPayload != nil {
marshaledTacticsPayload, err = json.Marshal(tacticsPayload)
if err != nil {
return nil, errors.Trace(err)
}
// Log a metric when new tactics are issued. Logging here indicates that
// the handshake tactics mechanism is active; but logging for every
// handshake creates unneccesary log data.
if len(tacticsPayload.Tactics) > 0 {
logFields := getRequestLogFields(
tactics.TACTICS_METRIC_EVENT_NAME,
geoIPData,
handshakeStateInfo.authorizedAccessTypes,
params,
handshakeRequestParams)
logFields[tactics.NEW_TACTICS_TAG_LOG_FIELD_NAME] = tacticsPayload.Tag
logFields[tactics.IS_TACTICS_REQUEST_LOG_FIELD_NAME] = false
log.LogRawFieldsWithTimestamp(logFields)
}
}
// The log comes _after_ SetClientHandshakeState, in case that call rejects
// the state change (for example, if a second handshake is performed)
//
// The handshake event is no longer shipped to log consumers, so this is
// simply a diagnostic log. Since the "server_tunnel" event includes all
// common API parameters and "handshake_completed" flag, this handshake
// log is mostly redundant and set to debug level.
log.WithTraceFields(
getRequestLogFields(
"",
geoIPData,
handshakeStateInfo.authorizedAccessTypes,
params,
handshakeRequestParams)).Debug("handshake")
pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
// Discover new servers
disableDiscovery, err := support.TunnelServer.GetClientDisableDiscovery(sessionID)
if err != nil {
return nil, errors.Trace(err)
}
var encodedServerList []string
if !disableDiscovery {
host, _, err := net.SplitHostPort(clientAddr)
if err != nil {
return nil, errors.Trace(err)
}
clientIP := net.ParseIP(host)
if clientIP == nil {
return nil, errors.TraceNew("missing client IP")
}
encodedServerList = db.DiscoverServers(
calculateDiscoveryValue(support.Config.DiscoveryValueHMACKey, clientIP))
}
// When the client indicates that it used an unsigned server entry for this
// connection, return a signed copy of the server entry for the client to
// upgrade to. See also: comment in psiphon.doHandshakeRequest.
//
// The missing_server_entry_signature parameter value is a server entry tag,
// which is used to select the correct server entry for servers with multiple
// entries. Identifying the server entries tags instead of server IPs prevents
// an enumeration attack, where a malicious client can abuse this facilty to
// check if an arbitrary IP address is a Psiphon server.
serverEntryTag, ok := getOptionalStringRequestParam(
params, "missing_server_entry_signature")
if ok {
ownServerEntry, ok := support.Config.GetOwnEncodedServerEntry(serverEntryTag)
if ok {
encodedServerList = append(encodedServerList, ownServerEntry)
}
}
// PageViewRegexes is obsolete and not used by any tunnel-core clients. In
// the JSON response, return an empty array instead of null for legacy
// clients.
handshakeResponse := protocol.HandshakeResponse{
SSHSessionID: sessionID,
Homepages: db.GetRandomizedHomepages(sponsorID, geoIPData.Country, geoIPData.ASN, isMobile),
UpgradeClientVersion: db.GetUpgradeClientVersion(clientVersion, normalizedPlatform),
PageViewRegexes: make([]map[string]string, 0),
HttpsRequestRegexes: httpsRequestRegexes,
EncodedServerList: encodedServerList,
ClientRegion: geoIPData.Country,
ClientAddress: clientAddr,
ServerTimestamp: common.GetCurrentTimestamp(),
ActiveAuthorizationIDs: handshakeStateInfo.activeAuthorizationIDs,
TacticsPayload: marshaledTacticsPayload,
UpstreamBytesPerSecond: handshakeStateInfo.upstreamBytesPerSecond,
DownstreamBytesPerSecond: handshakeStateInfo.downstreamBytesPerSecond,
Padding: strings.Repeat(" ", pad_response),
}
responsePayload, err := json.Marshal(handshakeResponse)
if err != nil {
return nil, errors.Trace(err)
}
return responsePayload, nil
}
// calculateDiscoveryValue derives a value from the client IP address to be
// used as input in the server discovery algorithm.
// See https://github.com/Psiphon-Inc/psiphon-automation/tree/master/Automation/psi_ops_discovery.py
// for full details.
func calculateDiscoveryValue(discoveryValueHMACKey string, ipAddress net.IP) int {
// From: psi_ops_discovery.calculate_ip_address_strategy_value:
// # Mix bits from all octets of the client IP address to determine the
// # bucket. An HMAC is used to prevent pre-calculation of buckets for IPs.
// return ord(hmac.new(HMAC_KEY, ip_address, hashlib.sha256).digest()[0])
// TODO: use 3-octet algorithm?
hash := hmac.New(sha256.New, []byte(discoveryValueHMACKey))
hash.Write([]byte(ipAddress.String()))
return int(hash.Sum(nil)[0])
}
// uniqueUserParams are the connected request parameters which are logged for
// unique_user events.
var uniqueUserParams = append(
[]requestParamSpec{
{"last_connected", isLastConnected, 0}},
baseSessionParams...)
var connectedRequestParams = append(
[]requestParamSpec{
{"establishment_duration", isIntString, requestParamOptional | requestParamLogStringAsInt}},
uniqueUserParams...)
// updateOnConnectedParamNames are connected request parameters which are
// copied to update data logged with server_tunnel: these fields either only
// ship with or ship newer data with connected requests.
var updateOnConnectedParamNames = append(
[]string{
"last_connected",
"establishment_duration",
},
fragmentor.GetUpstreamMetricsNames()...)
// connectedAPIRequestHandler implements the "connected" API request. Clients
// make the connected request once a tunnel connection has been established
// and at least once per 24h for long-running tunnels. The last_connected
// input value, which should be a connected_timestamp output from a previous
// connected response, is used to calculate unique user stats.
// connected_timestamp is truncated as a privacy measure.
func connectedAPIRequestHandler(
support *SupportServices,
clientAddr string,
geoIPData GeoIPData,
authorizedAccessTypes []string,
params common.APIParameters) ([]byte, error) {
err := validateRequestParams(support.Config, params, connectedRequestParams)
if err != nil {
return nil, errors.Trace(err)
}
sessionID, _ := getStringRequestParam(params, "client_session_id")
lastConnected, _ := getStringRequestParam(params, "last_connected")
// Update, for server_tunnel logging, upstream fragmentor metrics, as the
// client may have performed more upstream fragmentation since the previous
// metrics reported by the handshake request. Also, additional fields that
// are reported only in the connected request are added to server_tunnel
// here.
// TODO: same session-ID-lookup TODO in handshakeAPIRequestHandler
// applies here.
err = support.TunnelServer.UpdateClientAPIParameters(
sessionID, copyUpdateOnConnectedParams(params))
if err != nil {
return nil, errors.Trace(err)
}
connectedTimestamp := common.TruncateTimestampToHour(common.GetCurrentTimestamp())
// The finest required granularity for unique users is daily. To save space,
// only record a "unique_user" log event when the client's last_connected is
// in the previous day relative to the new connected_timestamp.
logUniqueUser := false
if lastConnected == "None" {
logUniqueUser = true
} else {
t1, _ := time.Parse(time.RFC3339, lastConnected)
year, month, day := t1.Date()
d1 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
t2, _ := time.Parse(time.RFC3339, connectedTimestamp)
year, month, day = t2.Date()
d2 := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
if t1.Before(t2) && d1 != d2 {
logUniqueUser = true
}
}
if logUniqueUser {
log.LogRawFieldsWithTimestamp(
getRequestLogFields(
"unique_user",
geoIPData,
authorizedAccessTypes,
params,
uniqueUserParams))
}
pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
connectedResponse := protocol.ConnectedResponse{
ConnectedTimestamp: connectedTimestamp,
Padding: strings.Repeat(" ", pad_response),
}
responsePayload, err := json.Marshal(connectedResponse)
if err != nil {
return nil, errors.Trace(err)
}
return responsePayload, nil
}
var statusRequestParams = baseSessionParams
var remoteServerListStatParams = append(
[]requestParamSpec{
{"client_download_timestamp", isISO8601Date, 0},
{"tunneled", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
{"url", isAnyString, 0},
{"etag", isAnyString, 0},
{"bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"authenticated", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool}},
baseSessionParams...)
// Backwards compatibility case: legacy clients do not include these fields in
// the remote_server_list_stats entries. Use the values from the outer status
// request as an approximation (these values reflect the client at persistent
// stat shipping time, which may differ from the client at persistent stat
// recording time). Note that all but client_build_rev and device_region are
// required fields.
var remoteServerListStatBackwardsCompatibilityParamNames = []string{
"session_id",
"propagation_channel_id",
"sponsor_id",
"client_version",
"client_platform",
"client_build_rev",
"device_region",
}
var failedTunnelStatParams = append(
[]requestParamSpec{
{"server_entry_tag", isAnyString, requestParamOptional},
{"session_id", isHexDigits, 0},
{"last_connected", isLastConnected, 0},
{"client_failed_timestamp", isISO8601Date, 0},
{"liveness_test_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"liveness_test_sent_upstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"liveness_test_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"liveness_test_received_downstream_bytes", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"bytes_up", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"bytes_down", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"tunnel_error", isAnyString, 0}},
baseSessionAndDialParams...)
// statusAPIRequestHandler implements the "status" API request.
// Clients make periodic status requests which deliver client-side
// recorded data transfer and tunnel duration stats.
// Note from psi_web implementation: no input validation on domains;
// any string is accepted (regex transform may result in arbitrary
// string). Stats processor must handle this input with care.
func statusAPIRequestHandler(
support *SupportServices,
clientAddr string,
geoIPData GeoIPData,
authorizedAccessTypes []string,
params common.APIParameters) ([]byte, error) {
err := validateRequestParams(support.Config, params, statusRequestParams)
if err != nil {
return nil, errors.Trace(err)
}
sessionID, _ := getStringRequestParam(params, "client_session_id")
statusData, err := getJSONObjectRequestParam(params, "statusData")
if err != nil {
return nil, errors.Trace(err)
}
// Logs are queued until the input is fully validated. Otherwise, stats
// could be double counted if the client has a bug in its request
// formatting: partial stats would be logged (counted), the request would
// fail, and clients would then resend all the same stats again.
logQueue := make([]LogFields, 0)
// Domain bytes transferred stats
// Older clients may not submit this data
// Clients are expected to send host_bytes/domain_bytes stats only when
// configured to do so in the handshake reponse. Legacy clients may still
// report "(OTHER)" host_bytes when no regexes are set. Drop those stats.
acceptDomainBytes, err := support.TunnelServer.AcceptClientDomainBytes(sessionID)
if err != nil {
return nil, errors.Trace(err)
}
if acceptDomainBytes && statusData["host_bytes"] != nil {
hostBytes, err := getMapStringInt64RequestParam(statusData, "host_bytes")
if err != nil {
return nil, errors.Trace(err)
}
for domain, bytes := range hostBytes {
domainBytesFields := getRequestLogFields(
"domain_bytes",
geoIPData,
authorizedAccessTypes,
params,
statusRequestParams)
domainBytesFields["domain"] = domain
domainBytesFields["bytes"] = bytes
logQueue = append(logQueue, domainBytesFields)
}
}
// Limitation: for "persistent" stats, host_id and geolocation is time-of-sending
// not time-of-recording.
// Remote server list download persistent stats.
// Older clients may not submit this data.
if statusData["remote_server_list_stats"] != nil {
remoteServerListStats, err := getJSONObjectArrayRequestParam(statusData, "remote_server_list_stats")
if err != nil {
return nil, errors.Trace(err)
}
for _, remoteServerListStat := range remoteServerListStats {
for _, name := range remoteServerListStatBackwardsCompatibilityParamNames {
if _, ok := remoteServerListStat[name]; !ok {
if field, ok := params[name]; ok {
remoteServerListStat[name] = field
}
}
}
// For validation, copy expected fields from the outer
// statusRequestParams.
remoteServerListStat["server_secret"] = params["server_secret"]
remoteServerListStat["client_session_id"] = params["client_session_id"]
err := validateRequestParams(support.Config, remoteServerListStat, remoteServerListStatParams)
if err != nil {
// Occasionally, clients may send corrupt persistent stat data. Do not
// fail the status request, as this will lead to endless retries.
log.WithTraceFields(LogFields{"error": err}).Warning("remote_server_list_stats entry dropped")
continue
}
remoteServerListFields := getRequestLogFields(
"remote_server_list",
geoIPData,
authorizedAccessTypes,
remoteServerListStat,
remoteServerListStatParams)
logQueue = append(logQueue, remoteServerListFields)
}
}
// Failed tunnel persistent stats.
// Older clients may not submit this data.
var invalidServerEntryTags map[string]bool
if statusData["failed_tunnel_stats"] != nil {
// Note: no guarantee that PsinetDatabase won't reload between database calls
db := support.PsinetDatabase
invalidServerEntryTags = make(map[string]bool)
failedTunnelStats, err := getJSONObjectArrayRequestParam(statusData, "failed_tunnel_stats")
if err != nil {
return nil, errors.Trace(err)
}
for _, failedTunnelStat := range failedTunnelStats {
// failed_tunnel supplies a full set of base params, but the server secret
// must use the correct value from the outer statusRequestParams.
failedTunnelStat["server_secret"] = params["server_secret"]
err := validateRequestParams(support.Config, failedTunnelStat, failedTunnelStatParams)
if err != nil {
// Occasionally, clients may send corrupt persistent stat data. Do not
// fail the status request, as this will lead to endless retries.
//
// TODO: trigger pruning if the data corruption indicates corrupt server
// entry storage?
log.WithTraceFields(LogFields{"error": err}).Warning("failed_tunnel_stats entry dropped")
continue
}
failedTunnelFields := getRequestLogFields(
"failed_tunnel",
geoIPData,
authorizedAccessTypes,
failedTunnelStat,
failedTunnelStatParams)
// Return a list of servers, identified by server entry tag, that are
// invalid and presumed to be deleted. This information is used by clients
// to prune deleted servers from their local datastores and stop attempting
// connections to servers that no longer exist.
//
// This mechanism uses tags instead of server IPs: (a) to prevent an
// enumeration attack, where a malicious client can query the entire IPv4
// range and build a map of the Psiphon network; (b) to deal with recyling
// cases where a server deleted and its IP is reused for a new server with
// a distinct server entry.
//
// IsValidServerEntryTag ensures that the local copy of psinet is not stale
// before returning a negative result, to mitigate accidental pruning.
//
// In addition, when the reported dial port number is 0, flag the server
// entry as invalid to trigger client pruning. This covers a class of
// invalid/semi-functional server entries, found in practice to be stored
// by clients, where some protocol port number has been omitted -- due to
// historical bugs in various server entry handling implementations. When
// missing from a server entry loaded by a client, the port number
// evaluates to 0, the zero value, which is not a valid port number even if
// were not missing.
serverEntryTag, ok := getOptionalStringRequestParam(failedTunnelStat, "server_entry_tag")
if ok {
serverEntryValid := db.IsValidServerEntryTag(serverEntryTag)
if serverEntryValid {
dialPortNumber, err := getIntStringRequestParam(failedTunnelStat, "dial_port_number")
if err == nil && dialPortNumber == 0 {
serverEntryValid = false
}
}
if !serverEntryValid {
invalidServerEntryTags[serverEntryTag] = true
}
// Add a field to the failed_tunnel log indicating if the server entry is
// valid.
failedTunnelFields["server_entry_valid"] = serverEntryValid
}
// Log failed_tunnel.
logQueue = append(logQueue, failedTunnelFields)
}
}
for _, logItem := range logQueue {
log.LogRawFieldsWithTimestamp(logItem)
}
pad_response, _ := getPaddingSizeRequestParam(params, "pad_response")
statusResponse := protocol.StatusResponse{
Padding: strings.Repeat(" ", pad_response),
}
if len(invalidServerEntryTags) > 0 {
statusResponse.InvalidServerEntryTags = make([]string, len(invalidServerEntryTags))
i := 0
for tag := range invalidServerEntryTags {
statusResponse.InvalidServerEntryTags[i] = tag
i++
}
}
responsePayload, err := json.Marshal(statusResponse)
if err != nil {
return nil, errors.Trace(err)
}
return responsePayload, nil
}
// clientVerificationAPIRequestHandler is just a compliance stub
// for older Android clients that still send verification requests
func clientVerificationAPIRequestHandler(
support *SupportServices,
clientAddr string,
geoIPData GeoIPData,
authorizedAccessTypes []string,
params common.APIParameters) ([]byte, error) {
return make([]byte, 0), nil
}
var tacticsParams = []requestParamSpec{
{tactics.STORED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
{tactics.SPEED_TEST_SAMPLES_PARAMETER_NAME, nil, requestParamOptional | requestParamJSON},
}
var tacticsRequestParams = append(
append([]requestParamSpec(nil), tacticsParams...),
baseSessionAndDialParams...)
func getTacticsAPIParameterValidator(config *Config) common.APIParameterValidator {
return func(params common.APIParameters) error {
return validateRequestParams(config, params, tacticsRequestParams)
}
}
func getTacticsAPIParameterLogFieldFormatter() common.APIParameterLogFieldFormatter {
return func(geoIPData common.GeoIPData, params common.APIParameters) common.LogFields {
logFields := getRequestLogFields(
tactics.TACTICS_METRIC_EVENT_NAME,
GeoIPData(geoIPData),
nil, // authorizedAccessTypes are not known yet
params,
tacticsRequestParams)
return common.LogFields(logFields)
}
}
// requestParamSpec defines a request parameter. Each param is expected to be
// a string, unless requestParamArray is specified, in which case an array of
// strings is expected.
type requestParamSpec struct {
name string
validator func(*Config, string) bool
flags uint32
}
const (
requestParamOptional = 1
requestParamNotLogged = 1 << 1
requestParamArray = 1 << 2
requestParamJSON = 1 << 3
requestParamLogStringAsInt = 1 << 4
requestParamLogStringAsFloat = 1 << 5
requestParamLogStringLengthAsInt = 1 << 6
requestParamLogFlagAsBool = 1 << 7
requestParamLogOnlyForFrontedMeekOrConjure = 1 << 8
requestParamNotLoggedForUnfrontedMeekNonTransformedHeader = 1 << 9
)
// baseParams are the basic request parameters that are expected for all API
// requests and log events.
var baseParams = []requestParamSpec{
{"server_secret", isServerSecret, requestParamNotLogged},
{"client_session_id", isHexDigits, requestParamNotLogged},
{"propagation_channel_id", isHexDigits, 0},
{"sponsor_id", isHexDigits, 0},
{"client_version", isIntString, requestParamLogStringAsInt},
{"client_platform", isClientPlatform, 0},
{"client_features", isAnyString, requestParamOptional | requestParamArray},
{"client_build_rev", isHexDigits, requestParamOptional},
{"device_region", isAnyString, requestParamOptional},
}
// baseSessionParams adds to baseParams the required session_id parameter. For
// all requests except handshake, all existing clients are expected to send
// session_id. Legacy clients may not send "session_id" in handshake.
var baseSessionParams = append(
[]requestParamSpec{
{"session_id", isHexDigits, 0}},
baseParams...)
// baseDialParams are the dial parameters, per-tunnel network protocol and
// obfuscation metrics which are logged with server_tunnel, failed_tunnel, and
// tactics.
var baseDialParams = []requestParamSpec{
{"relay_protocol", isRelayProtocol, 0},
{"ssh_client_version", isAnyString, requestParamOptional},
{"upstream_proxy_type", isUpstreamProxyType, requestParamOptional},
{"upstream_proxy_custom_header_names", isAnyString, requestParamOptional | requestParamArray},
{"fronting_provider_id", isAnyString, requestParamOptional},
{"meek_dial_address", isDialAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
{"meek_resolved_ip_address", isIPAddress, requestParamOptional | requestParamLogOnlyForFrontedMeekOrConjure},
{"meek_sni_server_name", isDomain, requestParamOptional},
{"meek_host_header", isHostHeader, requestParamOptional | requestParamNotLoggedForUnfrontedMeekNonTransformedHeader},
{"meek_transformed_host_name", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
{"user_agent", isAnyString, requestParamOptional},
{"tls_profile", isAnyString, requestParamOptional},
{"tls_version", isAnyString, requestParamOptional},
{"server_entry_region", isRegionCode, requestParamOptional},
{"server_entry_source", isServerEntrySource, requestParamOptional},
{"server_entry_timestamp", isISO8601Date, requestParamOptional},
{tactics.APPLIED_TACTICS_TAG_PARAMETER_NAME, isAnyString, requestParamOptional},
{"dial_port_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"quic_version", isAnyString, requestParamOptional},
{"quic_dial_sni_address", isAnyString, requestParamOptional},
{"quic_disable_client_path_mtu_discovery", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
{"upstream_bytes_fragmented", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"upstream_min_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"upstream_max_bytes_written", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"upstream_min_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"upstream_max_delayed", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"padding", isAnyString, requestParamOptional | requestParamLogStringLengthAsInt},
{"pad_response", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"is_replay", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
{"egress_region", isRegionCode, requestParamOptional},
{"dial_duration", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"candidate_number", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"established_tunnels_count", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"upstream_ossh_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"meek_cookie_size", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"meek_limit_request", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"meek_tls_padding", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"network_latency_multiplier", isFloatString, requestParamOptional | requestParamLogStringAsFloat},
{"client_bpf", isAnyString, requestParamOptional},
{"network_type", isAnyString, requestParamOptional},
{"conjure_cached", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
{"conjure_delay", isIntString, requestParamOptional | requestParamLogStringAsInt},
{"conjure_transport", isAnyString, requestParamOptional},
{"split_tunnel", isBooleanFlag, requestParamOptional | requestParamLogFlagAsBool},
{"split_tunnel_regions", isRegionCode, requestParamOptional | requestParamArray},
}
// baseSessionAndDialParams adds baseDialParams to baseSessionParams.
var baseSessionAndDialParams = append(
append(
[]requestParamSpec{},
baseSessionParams...),
baseDialParams...)
func validateRequestParams(
config *Config,
params common.APIParameters,
expectedParams []requestParamSpec) error {
for _, expectedParam := range expectedParams {
value := params[expectedParam.name]
if value == nil {
if expectedParam.flags&requestParamOptional != 0 {
continue
}
return errors.Tracef("missing param: %s", expectedParam.name)
}
var err error
switch {
case expectedParam.flags&requestParamArray != 0:
err = validateStringArrayRequestParam(config, expectedParam, value)
case expectedParam.flags&requestParamJSON != 0:
// No validation: the JSON already unmarshalled; the parameter
// user will validate that the JSON contains the expected
// objects/data.
// TODO: without validation, any valid JSON will be logged
// by getRequestLogFields, even if the parameter user validates
// and rejects the parameter.
default:
err = validateStringRequestParam(config, expectedParam, value)
}
if err != nil {
return errors.Trace(err)
}
}
return nil
}
// copyBaseSessionAndDialParams makes a copy of the params which includes only
// the baseSessionAndDialParams.
func copyBaseSessionAndDialParams(params common.APIParameters) common.APIParameters {
// Note: not a deep copy; assumes baseSessionAndDialParams values are all
// scalar types (int, string, etc.)
paramsCopy := make(common.APIParameters)
for _, baseParam := range baseSessionAndDialParams {
value := params[baseParam.name]
if value == nil {
continue
}
paramsCopy[baseParam.name] = value
}
return paramsCopy
}
func copyUpdateOnConnectedParams(params common.APIParameters) common.APIParameters {
// Note: not a deep copy
paramsCopy := make(common.APIParameters)
for _, name := range updateOnConnectedParamNames {
value := params[name]
if value == nil {
continue
}
paramsCopy[name] = value
}
return paramsCopy
}