-
Notifications
You must be signed in to change notification settings - Fork 1
/
authVerifyServer.go
1509 lines (1420 loc) · 51.5 KB
/
authVerifyServer.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
package vermouth
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/ipifony/vermouth/logger"
"github.com/ipifony/vermouth/stivs"
"gopkg.in/square/go-jose.v2"
"io"
"math"
"net"
"net/http"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
var ourSigner = &SigningAuth{}
func startAuthVerifyServer(responseChan chan<- Message, crlWorkChan chan string) {
logger.LogChan <- &logger.LogMessage{Severity: logger.INFO, MsgStr: "Auth Verify Server: Starting..."}
// Start ACME services
initializeAcme()
// Ready verification cache to shortcut fetching certs/cert chains
stivs.InitCertCache()
//gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.CustomRecovery(func(c *gin.Context, err interface{}) {
str := fmt.Sprintf("%v", err)
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: " Panic Recovered in Gin: " + str}
if strings.HasPrefix(c.Request.URL.Path, "/ezstir") {
c.String(http.StatusInternalServerError, "500 Server Error")
return
}
thisError := generateServiceErrorResponse(InternalServerError, nil)
c.JSON(InternalServerError.toHttpResponseCode(), &thisError)
}))
r.NoRoute(func(c *gin.Context) {
if strings.HasPrefix(c.Request.URL.Path, "/ezstir") {
c.String(http.StatusNotFound, "404 Not Found")
return
}
thisError := generateServiceErrorResponse(NotFound, nil)
c.JSON(NotFound.toHttpResponseCode(), &thisError)
})
r.GET("/status", func(c *gin.Context) {
getServerStatus(c)
})
// Stripped down quick API
v1Ez := r.Group("/ezstir/v1")
v1Ez.POST("/signing/:orig/:dest/:attest/*origid", func(c *gin.Context) {
processEzStirSign(c)
})
v1Ez.POST("/signing/:orig/:dest", func(c *gin.Context) {
processEzStirSign(c)
})
v1Ez.POST("/verification/:from/:pai/:to/:ruri/*identity", func(c *gin.Context) {
processEzStirVerify(c, crlWorkChan)
})
v1Ez.GET("/signing/:orig/:dest/:attest/*origid", func(c *gin.Context) {
processEzStirSign(c)
})
v1Ez.GET("/signing/:orig/:dest/:attest", func(c *gin.Context) {
processEzStirSign(c)
})
v1Ez.GET("/signing/:orig/:dest", func(c *gin.Context) {
processEzStirSign(c)
})
v1Ez.GET("/verification/:from/:pai/:to/:ruri/*identity", func(c *gin.Context) {
processEzStirVerify(c, crlWorkChan)
})
// Compliant (mostly) API
v1Compliant := r.Group("/stir/v1")
v1Compliant.POST("/signing", func(c *gin.Context) {
processInSpecSign(c)
})
v1Compliant.GET("/signing", func(c *gin.Context) {
thisError := generateServiceErrorResponse(InvalidHttpMethod, nil)
c.JSON(InvalidHttpMethod.toHttpResponseCode(), &thisError)
return
})
v1Compliant.POST("/verification", func(c *gin.Context) {
processInSpecVerify(c, crlWorkChan)
})
v1Compliant.GET("/verification", func(c *gin.Context) {
thisError := generateServiceErrorResponse(InvalidHttpMethod, nil)
c.JSON(InvalidHttpMethod.toHttpResponseCode(), &thisError)
return
})
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
GlobalConfig.GetServerAdminApiUsername(): GlobalConfig.GetServerAdminApiPassword(),
}))
authorized.GET("/reload_config", func(c *gin.Context) {
logger.LogChan <- &logger.LogMessage{Severity: logger.INFO, MsgStr: "Vermouth: Config Reload Requested..."}
err := GlobalConfig.ReloadConfig()
if err != nil {
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "Vermouth: Config Reload failed - " + err.Error()}
}
})
err := r.Run(GlobalConfig.getListenPoint())
if err != nil {
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "Auth Verify Server: Server Crashed - " + err.Error()}
status := Message{
MessageSender: AuthVerifyWorker,
MessageType: Failure,
MsgStr: "Crashed",
}
responseChan <- status
}
}
// The in-spec sign manually unmarshalls the JSON since we must allow unknown/unexpected fields to appear in the JWT
func processInSpecSign(c *gin.Context) {
if !ourSigner.IsReady() {
go SigningData.AddDataPoint(SigningFailureNotReady)
thisError := generateServiceErrorResponse(InternalServerError, nil)
c.JSON(InternalServerError.toHttpResponseCode(), &thisError)
return
}
if c.Request.Body == nil || c.Request.ContentLength < 1 {
go SigningData.AddDataPoint(SigningFailureInvalid)
thisError := generateServiceErrorResponse(MissingJsonBody, nil)
c.JSON(MissingJsonBody.toHttpResponseCode(), &thisError)
return
}
if c.Request.Header.Values("Content-Length") == nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
thisError := generateServiceErrorResponse(MissingContentLength, nil)
c.JSON(MissingContentLength.toHttpResponseCode(), &thisError)
return
}
// In theory, we could only accept application/json...let's ignore this for now
//if c.Request.Header.Get("Accept") != "application/json" {
// thisError := generateServiceErrorResponse(UnsupportedBodyTypeInAccept)
// c.JSON(UnsupportedBodyTypeInAccept.toHttpResponseCode(), &thisError)
// return
//}
if c.Request.Header.Get("Content-Type") != "application/json" {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"content type ('application/json')"}
thisError := generateServiceErrorResponse(UnsupportedContentType, vars)
c.JSON(UnsupportedContentType.toHttpResponseCode(), &thisError)
return
}
bytes, err := io.ReadAll(io.LimitReader(c.Request.Body, c.Request.ContentLength))
if err != nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
thisError := generateServiceErrorResponse(InternalServerError, nil)
c.JSON(InternalServerError.toHttpResponseCode(), &thisError)
return
}
var signingRequestJsonContainer map[string]interface{}
err = json.Unmarshal(bytes, &signingRequestJsonContainer)
if err != nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"invalid message body length specified/invalid JSON body"}
thisError := generateServiceErrorResponse(JsonParseError, vars)
c.JSON(JsonParseError.toHttpResponseCode(), &thisError)
return
}
signingRequestJsonInterface := signingRequestJsonContainer["signingRequest"]
if signingRequestJsonInterface == nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"signingRequest"}
thisError := generateServiceErrorResponse(MissingParam, vars)
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
signingRequestJson, ok := signingRequestJsonInterface.(map[string]interface{})
if !ok {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"invalid message body length specified/invalid JSON body"}
thisError := generateServiceErrorResponse(JsonParseError, vars)
c.JSON(JsonParseError.toHttpResponseCode(), &thisError)
return
}
// Check attest
if signingRequestJson["attest"] == nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"attest"}
thisError := generateServiceErrorResponse(MissingParam, vars)
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
attestVal, ok := signingRequestJson["attest"].(string)
if ok && stringInSlice(attestVal, allowedAttestationLevels) {
signingRequestJson["attest"] = strings.ToUpper(attestVal)
} else {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"attest", attestVal}
thisError := generateServiceErrorResponse(InvalidParamValue, vars)
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
// Check iat
if signingRequestJson["iat"] == nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"iat"}
thisError := generateServiceErrorResponse(MissingParam, vars)
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
if iat, ok := signingRequestJson["iat"].(float64); ok {
distance := math.Abs(float64(time.Now().Unix()) - iat)
if distance > 30*1000 {
// We got a request more than 30 seconds old. Let's quietly replace this iat
signingRequestJson["iat"] = time.Now().Unix()
}
} else {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"iat", "bad value"}
thisError := generateServiceErrorResponse(InvalidParamValue, vars)
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
// check origid
// We will generate one if none exists or if it is invalid
if signingRequestJson["origid"] == nil {
signingRequestJson["origid"] = uuid.New().String()
} else {
if origId, ok := signingRequestJson["origid"].(string); !ok || len(origId) < 1 {
signingRequestJson["origid"] = uuid.New().String()
}
}
// dest could contain an array of TNs or an array of URIs or both
if signingRequestJson["dest"] == nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"dest"}
thisError := generateServiceErrorResponse(MissingParam, vars)
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
var dstTn string
if dest, ok := signingRequestJson["dest"].(map[string]interface{}); ok {
validDest := false
if dest["tn"] != nil {
if tnArray, ok := dest["tn"].([]interface{}); ok {
if len(tnArray) > 0 {
validDest = true
for i, ph := range tnArray {
cleanPh := cleanTn(ph.(string))
tnArray[i] = cleanPh
if i == 0 {
dstTn = cleanPh
}
}
}
}
}
if dest["uri"] != nil {
if uriArray, ok := dest["uri"].([]interface{}); ok {
if len(uriArray) > 0 {
// Something is in the URI array...Probably ok!
validDest = true
}
}
}
if !validDest {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"dest", "bad value"}
thisError := generateServiceErrorResponse(InvalidParamValue, vars)
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
}
// Check orig
if signingRequestJson["orig"] == nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"orig"}
thisError := generateServiceErrorResponse(MissingParam, vars)
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
var origTn string
if orig, ok := signingRequestJson["orig"].(map[string]interface{}); ok {
if origTn, ok = orig["tn"].(string); ok {
cleanedTn := cleanTn(origTn)
orig["tn"] = cleanedTn
dnoStatus := doNotOriginate.getDNOStatusForCaller(cleanedTn)
c.Header(DNOResponseHeader, dnoStatus)
} else {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"orig", "bad value"}
thisError := generateServiceErrorResponse(InvalidParamValue, vars)
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
} else {
go SigningData.AddDataPoint(SigningFailureInvalid)
vars := []string{"orig", "bad value"}
thisError := generateServiceErrorResponse(InvalidParamValue, vars)
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
jsonStr, _ := json.Marshal(signingRequestJson)
origId := signingRequestJson["origid"].(string)
// We either received one and honored it, or we generated one. Either way, we send it back in header form
c.Header("X-RequestID", origId)
// Time to build JWS
signedJwt, err := ourSigner.Sign(jsonStr)
if signedJwt == "" || err != nil {
go SigningData.AddDataPoint(SigningFailureNotReady)
thisError := generateServiceErrorResponse(InternalServerError, nil)
c.JSON(InternalServerError.toHttpResponseCode(), &thisError)
return
}
go WriteSigningRecord(&origTn, &dstTn, &attestVal, &origId)
go SigningData.AddDataPoint(SigningSuccess)
var response SigningResponse
response.SigningResponseBody.Identity = &signedJwt
c.PureJSON(http.StatusOK, response)
}
func processEzStirSign(c *gin.Context) {
if !ourSigner.IsReady() {
go SigningData.AddDataPoint(SigningFailureNotReady)
c.String(http.StatusInternalServerError, "error: not ready to sign")
return
}
orig := c.Param("orig")
if len(orig) < 3 {
go SigningData.AddDataPoint(SigningFailureInvalid)
c.String(http.StatusBadRequest, "error: orig")
return
}
orig = cleanTn(orig)
dest := c.Param("dest")
if len(dest) < 3 {
go SigningData.AddDataPoint(SigningFailureInvalid)
c.String(http.StatusBadRequest, "error: dest")
return
}
dest = cleanTn(dest)
destArray := []string{dest}
attest := c.Param("attest")
if len(attest) < 1 {
attest = "A"
} else {
if stringInSlice(attest, allowedAttestationLevels) {
attest = strings.ToUpper(attest)
} else {
go SigningData.AddDataPoint(SigningFailureInvalid)
c.String(http.StatusBadRequest, "error: attest")
return
}
}
origId := c.Param("origid")
if len(origId) < 2 {
origId = uuid.New().String()
} else {
// Optional URL params contain the leading '/'
origId = origId[1:]
}
iat := time.Now().Unix()
signingRequest := EzRequest{
attest,
Dest{destArray},
iat,
Orig{orig},
origId,
}
jsonBytes, err := json.Marshal(signingRequest)
if err != nil {
go SigningData.AddDataPoint(SigningFailureInvalid)
c.String(http.StatusInternalServerError, "error: struct -> json failed")
return
}
serializedPayload, err := ourSigner.Sign(jsonBytes)
if err != nil {
go SigningData.AddDataPoint(SigningFailureNotReady)
c.String(http.StatusInternalServerError, "error: signing failed")
return
}
go WriteSigningRecord(&orig, &dest, &attest, &origId)
go SigningData.AddDataPoint(SigningSuccess)
// SIP Header Friendly Version
retString := "Identity: " + serializedPayload
dnoStatus := doNotOriginate.getDNOStatusForCaller(orig)
c.Header(DNOResponseHeader, dnoStatus)
c.String(http.StatusOK, retString)
}
func processInSpecVerify(c *gin.Context, crlWorkChan chan string) {
thisRecord := VerificationRecord{}
if c.Request.Body == nil || c.Request.ContentLength < 1 {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(MissingJsonBody, nil)
c.JSON(MissingJsonBody.toHttpResponseCode(), &thisError)
return
}
if c.Request.Header.Values("Content-Length") == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(MissingContentLength, nil)
c.JSON(MissingContentLength.toHttpResponseCode(), &thisError)
return
}
if c.Request.Header.Get("Content-Type") != "application/json" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
vars := []string{"content type ('application/json')"}
thisError := generateServiceErrorResponse(UnsupportedContentType, vars)
c.JSON(UnsupportedContentType.toHttpResponseCode(), &thisError)
return
}
readBytes, err := io.ReadAll(io.LimitReader(c.Request.Body, c.Request.ContentLength))
if err != nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InternalServerError, nil)
c.JSON(InternalServerError.toHttpResponseCode(), &thisError)
return
}
defer c.Request.Body.Close()
jsonPayload := VerificationRequestPayload{}
err = json.Unmarshal(readBytes, &jsonPayload)
if err != nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
vars := []string{"invalid JSON body"}
thisError := generateServiceErrorResponse(JsonParseError, vars)
c.JSON(JsonParseError.toHttpResponseCode(), &thisError)
return
}
// Error Case E1
if jsonPayload.VerificationRequest.To == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(MissingParam, []string{"to"})
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
if jsonPayload.VerificationRequest.From == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(MissingParam, []string{"from"})
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
// DNO Header being added
dnoStatus := doNotOriginate.getDNOStatusForCaller(jsonPayload.VerificationRequest.From.Tn)
c.Header(DNOResponseHeader, dnoStatus)
if jsonPayload.VerificationRequest.Time == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(MissingParam, []string{"time"})
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
if jsonPayload.VerificationRequest.Identity == nil {
thisRecord.StatusNoSignature = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNoSignature)
thisError := generateServiceErrorResponse(MissingParam, []string{"identity"})
c.JSON(MissingParam.toHttpResponseCode(), &thisError)
return
}
// Error Case E2
fromVal := jsonPayload.VerificationRequest.From.Tn
thisRecord.From = &fromVal
if len(fromVal) < 3 {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InvalidParamValue, []string{"from", "bad value"})
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
toArray := jsonPayload.VerificationRequest.To.Tn
if len(toArray) < 1 || len(toArray[0]) < 3 {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InvalidParamValue, []string{"to", "bad value"})
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
thisRecord.To = &toArray[0]
if *jsonPayload.VerificationRequest.Time < 1 {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InvalidParamValue, []string{"time", "bad value"})
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
if len(*jsonPayload.VerificationRequest.Identity) < 1 {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InvalidParamValue, []string{"identity", "bad value"})
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
identityParts := strings.Split(*jsonPayload.VerificationRequest.Identity, ";")
if len(identityParts) < 2 {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InvalidParamValue, []string{"identity", "bad value"})
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
thisRecord.Identity = &identityParts[0]
jws, err := jose.ParseSigned(identityParts[0])
if err != nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
thisError := generateServiceErrorResponse(InvalidParamValue, []string{"identity", "bad value"})
c.JSON(InvalidParamValue.toHttpResponseCode(), &thisError)
return
}
// Error Case E3
timeDiff := time.Now().Unix() - *jsonPayload.VerificationRequest.Time
if timeDiff > 60 || timeDiff < -60 {
thisRecord.StatusStale = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationStale)
resp := generateVerificationResponse("Received 'time' value is not fresh.", http.StatusForbidden, "Stale Date", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E4
if len(jws.UnsafePayloadWithoutVerification()) == 0 {
thisRecord.StatusNoSignature = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNoSignature)
resp := generateVerificationResponse("Identity header in compact form instead of required by SHAKEN spec full form.", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E5
if jws.Signatures[0].Header.ExtraHeaders["ppt"] != "shaken" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Identity header is received with with 'ppt' parameter value that is not 'shaken'.", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E6
if !strings.HasPrefix(identityParts[1], "info") {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing 'info' parameter in the 'identity'.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
infoUrl := strings.TrimPrefix(identityParts[1], "info=<")
infoUrl = strings.TrimSuffix(infoUrl, ">")
// Error Case E7
if !IsUrl(infoUrl) {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Invalid 'info' URI.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
thisRecord.X5U = &infoUrl
// We should check whether we already have cached info for this url
cachedEntry, cachedEntryFound := stivs.GetCertCache().GetEntry(infoUrl)
var leafCert *x509.Certificate
var intermediates []*x509.Certificate
cacheHeader := ""
// We need to check if our cached entry is still valid
// If the cached entry is invalid for any reason, we remove the entry and let the process continue as though we had no cache hit
if cachedEntryFound {
thisRecord.CertBytes = cachedEntry.CertBytes
_, errVerify := jws.Verify(cachedEntry.Leaf.PublicKey)
if errVerify != nil {
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "STI-VS: JWT was not signed by cached leaf - " + errVerify.Error()}
}
errValid := ourTrustAnchors.assertValidLeafCert(cachedEntry.Leaf, cachedEntry.Intermediates, crlWorkChan)
if errValid != nil {
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "STI-VS: Cached leaf cert could not be validated - " + errValid.Error()}
}
if errVerify != nil || errValid != nil {
stivs.GetCertCache().RemoveEntry(infoUrl)
cachedEntryFound = false
if cachedEntry.Forced {
logger.LogChan <- &logger.LogMessage{Severity: logger.INFO, MsgStr: "STI-VS: A forced cached entry for " + infoUrl + " was problematic"}
}
}
}
var certRespBytes []byte
if cachedEntryFound {
leafCert = cachedEntry.Leaf
intermediates = cachedEntry.Intermediates
} else {
// Error Case E8
certResp, err := httpClient.Get(infoUrl)
if err != nil {
thisRecord.StatusNotTrusted = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNotTrusted)
resp := generateVerificationResponse("Failed to dereference 'info' URI.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
certRespBytes, err = io.ReadAll(certResp.Body)
if err != nil {
thisRecord.StatusNotTrusted = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNotTrusted)
resp := generateVerificationResponse("Failed to dereference 'info' URI.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
defer certResp.Body.Close()
thisRecord.CertBytes = &certRespBytes
leafCert, intermediates = getLeafAndIntermediatesFromBytes(certRespBytes)
cacheHeader = certResp.Header.Get("Cache-Control")
}
// Error Case E9
ppt := jws.Signatures[0].Header.ExtraHeaders["ppt"]
if ppt == "" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing ppt claim in the PASSporT header.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
typ := jws.Signatures[0].Header.ExtraHeaders["typ"]
if typ == "" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing typ claim in the PASSporT header.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
x5u := jws.Signatures[0].Header.ExtraHeaders["x5u"]
if x5u == "" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing x5u claim in the PASSporT header.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
alg := jws.Signatures[0].Header.Algorithm
if alg == "" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing alg claim in the PASSporT header.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E10
if x5u != infoUrl {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("'x5u' from PASSporT header doesn't match the 'info' parameter of identity header value.", 436, "Bad identity Info", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E11
if typ != "passport" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("'typ' from PASSporT header is not 'passport'.", 437, "Unsupported credential", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E12
if alg != "ES256" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("'alg' from PASSporT header is not 'ES256'.", 437, "Unsupported credential", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E13
if ppt != "shaken" {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("'ppt' from PASSporT header is not 'shaken'.", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E14
idJwt := IdentityJwt{}
err = json.Unmarshal(jws.UnsafePayloadWithoutVerification(), &idJwt)
if err != nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Payload is corrupt", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
if idJwt.IdDest == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing 'dest' mandatory claim in PASSporT payload", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
if idJwt.IdOrig == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing 'orig' mandatory claim in PASSporT payload", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
if idJwt.Attest == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing 'attest' mandatory claim in PASSporT payload", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
if idJwt.Origid == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing 'origid' mandatory claim in PASSporT payload", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
if idJwt.Iat == nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("Missing 'iat' mandatory claim in PASSporT payload", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E16
if idJwt.IdOrig.Tn != jsonPayload.VerificationRequest.From.Tn {
thisRecord.StatusTnMismatch = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationTnMismatch)
resp := generateVerificationResponse("'orig' claim from PASSporT payload doesn't match the received in the verification request claim.", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
foundToMismatch := false
if len(jsonPayload.VerificationRequest.To.Tn) != len(idJwt.IdDest.Tn) {
foundToMismatch = true
}
if !foundToMismatch {
for index := range idJwt.IdDest.Tn {
if jsonPayload.VerificationRequest.To.Tn[index] != idJwt.IdDest.Tn[index] {
foundToMismatch = true
break
}
}
}
if foundToMismatch {
thisRecord.StatusTnMismatch = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationTnMismatch)
resp := generateVerificationResponse("'dest' claim from PASSporT payload doesn't match the received in the verification request claim.", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// If we made it this far and were already cached, there is no need to recheck since we already performed these tasks
if !cachedEntryFound {
// Error Case E17
err = ourTrustAnchors.assertValidLeafCert(leafCert, intermediates, crlWorkChan)
if err != nil {
thisRecord.StatusNotTrusted = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNotTrusted)
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "STI-VS: Leaf cert could not be validated - " + err.Error()}
resp := generateVerificationResponse("Failed to authenticate CA.", 437, "Unsupported credential", TNValidationFailed)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E18
_, err = jws.Verify(leafCert.PublicKey)
if err != nil {
thisRecord.StatusInvalidSignature = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationInvalidSignature)
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "STI-VS: JWT was not signed by leaf - " + err.Error()}
resp := generateVerificationResponse("Signature validation failed.", 438, "Invalid Identity Header", TNValidationFailed)
c.JSON(http.StatusOK, &resp)
return
}
}
// Error Case E15 (for stat collection purposes, this was moved lower)
iatDiff := time.Now().Unix() - *idJwt.Iat
if iatDiff > 60 || iatDiff < -60 {
thisRecord.StatusStale = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationStale)
resp := generateVerificationResponse("'iat' from PASSporT payload is not fresh.", http.StatusForbidden, "Stale Date", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
// Error Case E19
if !stringInSlice(*idJwt.Attest, allowedAttestationLevels) {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
resp := generateVerificationResponse("'attest' claim in PASSporT is not valid.", 438, "Invalid Identity Header", NoTNValidation)
c.JSON(http.StatusOK, &resp)
return
}
if !cachedEntryFound {
// Cache response for future look-ups
expireTime, forced := getCacheDirective(cacheHeader)
newEntry := stivs.CertCacheEntry{
Leaf: leafCert,
Intermediates: intermediates,
Expires: expireTime,
Forced: forced,
CertBytes: &certRespBytes,
}
stivs.GetCertCache().AddEntry(infoUrl, newEntry)
logger.LogChan <- &logger.LogMessage{Severity: logger.INFO, MsgStr: "Added cache entry for: " + infoUrl}
}
thisRecord.StatusValid = true
thisRecord.Attestation = idJwt.Attest
go WriteVerificationRecord(&thisRecord)
go collectValidVerification(*idJwt.Attest)
// Made it through all error cases. We can issue a 'TN-Validation-Passed'
resp := VerificationResponsePayload{VerificationResponse{Verstat: string(TNValidationPassed)}}
c.JSON(http.StatusOK, resp)
}
func collectValidVerification(attestation string) {
switch attestation {
case "A":
VerificationData.AddDataPoint(VerificationValidA)
case "a":
VerificationData.AddDataPoint(VerificationValidA)
case "B":
VerificationData.AddDataPoint(VerificationValidB)
case "b":
VerificationData.AddDataPoint(VerificationValidB)
case "C":
VerificationData.AddDataPoint(VerificationValidC)
case "c":
VerificationData.AddDataPoint(VerificationValidC)
}
}
// Out-of-spec verification designed to play friendly with limited call processing engines where certain shortcuts are necessary.
// The call processing engine (or SBC) is free to naively use the to/from info and signed JWT from the SIP headers
//
// with very little overhead and get, in response, actionable (and quickly parsable) info
func processEzStirVerify(c *gin.Context, crlWorkChan chan string) {
thisRecord := VerificationRecord{}
from := c.Param("from")
pai := c.Param("pai")
to := c.Param("to")
ruri := c.Param("ruri")
identity := (c.Param("identity"))[1:]
thisRecord.From = &from
thisRecord.Pai = &pai
thisRecord.To = &to
thisRecord.Ruri = &ruri
if len(identity) == 0 {
thisRecord.StatusNoSignature = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNoSignature)
c.String(http.StatusOK, "NO-SIGNATURE")
return
}
identityParts := strings.Split(identity, ";")
thisRecord.Identity = &identityParts[0]
jws, err := jose.ParseSigned(identityParts[0])
if err != nil {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
c.String(http.StatusOK, "BAD-SIGNATURE")
return
}
x5uUrl := fmt.Sprintf("%v", jws.Signatures[0].Header.ExtraHeaders["x5u"])
thisRecord.X5U = &x5uUrl
if !IsUrl(x5uUrl) {
thisRecord.StatusBadFormat = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationBadFormat)
c.String(http.StatusOK, "BAD-SIGNATURE")
return
}
// We should check whether we already have cached info for this url
cachedEntry, cachedEntryFound := stivs.GetCertCache().GetEntry(x5uUrl)
var leafCert *x509.Certificate
var intermediates []*x509.Certificate
cacheHeader := ""
// If the cached entry is invalid for any reason, we remove the entry and let the process continue as though we had no cache hit
if cachedEntryFound {
thisRecord.CertBytes = cachedEntry.CertBytes
_, errVerify := jws.Verify(cachedEntry.Leaf.PublicKey)
if errVerify != nil {
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "STI-VS: JWT was not signed by cached leaf - " + errVerify.Error()}
}
errValid := ourTrustAnchors.assertValidLeafCert(cachedEntry.Leaf, cachedEntry.Intermediates, crlWorkChan)
if errValid != nil {
logger.LogChan <- &logger.LogMessage{Severity: logger.ERROR, MsgStr: "STI-VS: Cached leaf cert could not be validated - " + errValid.Error()}
}
if errVerify != nil || errValid != nil {
stivs.GetCertCache().RemoveEntry(x5uUrl)
cachedEntryFound = false
if cachedEntry.Forced {
logger.LogChan <- &logger.LogMessage{Severity: logger.INFO, MsgStr: "STI-VS: A forced cached entry for " + x5uUrl + " was problematic"}
}
}
}
var certRespBytes []byte
if cachedEntryFound {
leafCert = cachedEntry.Leaf
intermediates = cachedEntry.Intermediates
} else {
certResp, err := httpClient.Get(x5uUrl)
if err != nil {
thisRecord.StatusNotTrusted = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNotTrusted)
c.String(http.StatusOK, "BAD-SIGNATURE")
return
}
certRespBytes, err = io.ReadAll(certResp.Body)
if err != nil {
thisRecord.StatusNotTrusted = true
go WriteVerificationRecord(&thisRecord)
go VerificationData.AddDataPoint(VerificationNotTrusted)
c.String(http.StatusOK, "BAD-SIGNATURE")
return
}
defer certResp.Body.Close()
thisRecord.CertBytes = &certRespBytes
leafCert, intermediates = getLeafAndIntermediatesFromBytes(certRespBytes)