-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdkimverify.cpp
1511 lines (1305 loc) · 36.5 KB
/
dkimverify.cpp
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 2005 Alt-N Technologies, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* This code incorporates intellectual property owned by Yahoo! and licensed
* pursuant to the Yahoo! DomainKeys Patent License Agreement.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*****************************************************************************/
#ifdef WIN32
#include <windows.h>
#pragma warning( disable: 4786 )
#else
#define _strnicmp strncasecmp
#define _stricmp strcasecmp
#endif
#include "dkim.h"
#include "dkimverify.h"
#include "dns.h"
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <vector>
#include <algorithm>
#define MAX_SIGNATURES 10 // maximum number of DKIM signatures to process in a message
SignatureInfo::SignatureInfo(bool s)
{
VerifiedBodyCount = 0;
UnverifiedBodyCount = 0;
m_Hdr_ctx = EVP_MD_CTX_create();
m_Bdy_ctx = EVP_MD_CTX_create();
EVP_MD_CTX_init(m_Hdr_ctx);
EVP_MD_CTX_init(m_Bdy_ctx);
m_pSelector = NULL;
Status = DKIM_SUCCESS;
m_nHash = 0;
EmptyLineCount = 0;
m_SaveCanonicalizedData = s;
}
SignatureInfo::~SignatureInfo()
{
EVP_MD_CTX_destroy(m_Hdr_ctx);
EVP_MD_CTX_destroy(m_Bdy_ctx);
}
inline bool isswsp(char ch)
{
return( ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n' );
}
////////////////////////////////////////////////////////////////////////////////
//
// Parse a DKIM tag-list. Returns true for success
//
////////////////////////////////////////////////////////////////////////////////
bool ParseTagValueList(char *tagvaluelist, const char *wanted[], char *values[])
{
char *s = tagvaluelist;
for (;;)
{
// skip whitespace
while (isswsp(*s))
s++;
// if at the end of the string, return success. note: this allows a list with no entries
if (*s == '\0')
return true;
// get tag name
if (!isalpha(*s))
return false;
char *tag = s;
do {
s++;
} while (isalnum(*s) || *s == '-');
char *endtag = s;
// skip whitespace before equals
while (isswsp(*s))
s++;
// next character must be equals
if (*s != '=')
return false;
s++;
// null-terminate tag name
*endtag = '\0';
// skip whitespace after equals
while (isswsp(*s))
s++;
// get tag value
char *value = s;
while (*s != ';' && ((*s == '\t' || *s == '\r' || *s == '\n') || (*s >= ' ' && *s <= '~')))
s++;
char *e = s;
// make sure the next character is the null terminator (which means we're done) or a semicolon (not done)
bool done = false;
if (*s == '\0')
done = true;
else
{
if (*s != ';')
return false;
s++;
}
// skip backwards past any trailing whitespace
while (e > value && isswsp(e[-1]))
e--;
// null-terminate tag value
*e = '\0';
// check to see if we want this tag
for (unsigned i=0; wanted[i] != NULL; i++)
{
if (strcmp(wanted[i], tag) == 0)
{
// return failure if we already have a value for this tag (duplicates not allowed)
if (values[i] != NULL)
return false;
values[i] = value;
break;
}
}
if (done)
return true;
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Convert hex char to value (0-15)
//
////////////////////////////////////////////////////////////////////////////////
char tohex(char ch)
{
if (ch >= '0' && ch <= '9')
return (ch-'0');
else if (ch >= 'A' && ch <= 'F')
return (ch-'A'+10);
else if (ch >= 'a' && ch <= 'f')
return (ch-'a'+10);
else
{
assert(0);
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Decode quoted printable string in-place
//
////////////////////////////////////////////////////////////////////////////////
void DecodeQuotedPrintable(char *ptr)
{
char *s = ptr;
while (*s != '\0' && *s != '=')
s++;
if (*s == '\0')
return;
char *d = s;
do {
if (*s == '=' && isxdigit(s[1]) && isxdigit(s[2]))
{
*d++ = (tohex(s[1]) << 4) | tohex(s[2]);
s += 3;
}
else
{
*d++ = *s++;
}
} while (*s != '\0');
*d = '\0';
}
////////////////////////////////////////////////////////////////////////////////
//
// Decode base64 string in-place, returns number of bytes output
//
////////////////////////////////////////////////////////////////////////////////
unsigned DecodeBase64(char *ptr)
{
static const unsigned char base64_table[256] = {
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,
-1, 0, 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,-1,-1,-1,-1,-1,
-1,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,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
unsigned char *s = (unsigned char *)ptr;
unsigned char *d = (unsigned char *)ptr;
unsigned b64accum=0;
unsigned char b64shift=0;
while (*s != '\0')
{
unsigned char value = base64_table[*s++];
if ( (signed char)value >= 0 )
{
b64accum = (b64accum << 6) | value;
b64shift += 6;
if (b64shift >= 8)
{
b64shift -= 8;
*d++ = (b64accum >> b64shift);
}
}
}
return (char*)d-ptr;
}
////////////////////////////////////////////////////////////////////////////////
//
// Match a string with a pattern (used for g= value)
// Supports a single, optional "*" wildcard character.
//
////////////////////////////////////////////////////////////////////////////////
bool WildcardMatch( const char *p, const char *s )
{
// special case: An empty "g=" value never matches any addresses
if (*p == '\0')
return false;
const char *wildcard = strchr(p, '*');
if (wildcard == NULL)
{
return strcmp(s, p) == 0;
}
else
{
unsigned beforewildcardlen = wildcard-p;
unsigned afterwildcardlen = strlen(wildcard+1);
unsigned slen = strlen(s);
return (slen >= beforewildcardlen+afterwildcardlen) &&
(strncmp(s, p, beforewildcardlen) == 0) && strcmp(s+slen-afterwildcardlen, wildcard+1) == 0;
}
}
////////////////////////////////////////////////////////////////////////////////
//
// Parse addresses from a string. Returns true if at least one address found
//
////////////////////////////////////////////////////////////////////////////////
bool ParseAddresses( string str, vector<string> &Addresses )
{
char *s = (char*) str.c_str();
while (*s != '\0')
{
char *start = s;
char *from = s;
char *to = s;
char *lt = NULL; // pointer to less than character (<) which starts the address if found
while (*from != '\0')
{
if (*from == '(')
{
// skip over comment
from++;
for (int depth=1; depth != 0; from++)
{
if (*from == '\0')
break;
else if (*from == '(')
depth++;
else if (*from == ')')
depth--;
else if (*from == '\\' && from[1] != '\0')
from++;
}
}
else if (*from == ')')
{
// ignore closing parenthesis outside of comment
from++;
}
else if (*from == ',' || *from == ';')
{
// comma/selicolon ends the address
from++;
break;
}
else if (*from == ' ' || *from == '\t' || *from == '\r' || *from == '\n')
{
// ignore whitespace
from++;
}
else if (*from == '"')
{
// copy the contents of a quoted string
from++;
while (*from != '\0')
{
if (*from == '"')
{
from++;
break;
}
else if (*from == '\\' && from[1] != '\0')
*to++ = *from++;
*to++ = *from++;
}
}
else if (*from == '\\' && from[1] != '\0')
{
// copy quoted-pair
*to++ = *from++;
*to++ = *from++;
}
else
{
// copy any other char
*to = *from++;
// save pointer to '<' for later...
if (*to == '<')
lt = to;
to++;
}
}
*to = '\0';
// if there's < > get what's inside
if (lt != NULL)
{
start = lt+1;
char *gt = strchr(start, '>');
if (gt != NULL)
*gt = '\0';
}
else
{
// look for and strip group name
char *colon = strchr(start, ':');
if (colon != NULL)
{
char *at = strchr(start, '@');
if (at == NULL || colon < at)
start = colon+1;
}
}
if (*start != '\0' && strchr(start, '@') != NULL)
{
Addresses.push_back(start);
}
s = from;
}
return !Addresses.empty();
}
////////////////////////////////////////////////////////////////////////////////
CDKIMVerify::CDKIMVerify()
{
m_pfnSelectorCallback = NULL;
m_pfnPracticesCallback = NULL;
m_HonorBodyLengthTag = false;
m_CheckPractices = false;
m_SubjectIsRequired = true;
m_SaveCanonicalizedData = false;
m_AllowUnsignedFromHeaders = false;
}
CDKIMVerify::~CDKIMVerify()
{
}
////////////////////////////////////////////////////////////////////////////////
//
// Init - save the options
//
////////////////////////////////////////////////////////////////////////////////
int CDKIMVerify::Init( DKIMVerifyOptions* pOptions )
{
int nRet = CDKIMBase::Init();
m_pfnSelectorCallback = pOptions->pfnSelectorCallback;
m_pfnPracticesCallback = pOptions->pfnPracticesCallback;
#ifdef WIN32
if (m_pfnSelectorCallback)
assert(!IsBadCodePtr( (FARPROC) m_pfnSelectorCallback ));
if (m_pfnPracticesCallback)
assert(!IsBadCodePtr( (FARPROC) m_pfnPracticesCallback ));
#endif
m_HonorBodyLengthTag = pOptions->nHonorBodyLengthTag != 0;
m_CheckPractices = pOptions->nCheckPractices != 0;
m_SubjectIsRequired = pOptions->nSubjectRequired == 0;
m_SaveCanonicalizedData = pOptions->nSaveCanonicalizedData != 0;
m_AllowUnsignedFromHeaders = pOptions->nAllowUnsignedFromHeaders != 0;
return nRet;
}
////////////////////////////////////////////////////////////////////////////////
//
// GetResults - return the pass/fail/neutral verification result
//
////////////////////////////////////////////////////////////////////////////////
int CDKIMVerify::GetResults(void)
{
ProcessFinal();
int SuccessCount=0;
int TestingFailures=0;
int RealFailures=0;
list<string> SuccessfulDomains; // can contain duplicates
for (list<SignatureInfo>::iterator i = Signatures.begin(); i != Signatures.end(); ++i)
{
if (i->Status == DKIM_SUCCESS)
{
if (!i->BodyHashData.empty())
{
// check the body hash
unsigned char md[EVP_MAX_MD_SIZE];
unsigned len = 0;
int res = EVP_DigestFinal(i->m_Bdy_ctx, md, &len);
if (!res || len != i->BodyHashData.length() || memcmp(i->BodyHashData.data(), md, len) != 0)
{
// body hash mismatch
// if the selector is in testing mode...
if (i->m_pSelector->Testing)
{
i->Status = DKIM_SIGNATURE_BAD_BUT_TESTING; // todo: make a new error code for this?
TestingFailures++;
}
else
{
i->Status = DKIM_BODY_HASH_MISMATCH;
RealFailures++;
}
continue;
}
}
else
{
// hash CRLF separating the body from the signature
i->Hash( "\r\n", 2 );
}
// check the header hash
string sSignedSig = i->Header;
string sSigValue = sSignedSig.substr( sSignedSig.find(':')+1 );
static const char *tags[] = {"b",NULL};
char *values[sizeof(tags)/sizeof(tags[0])] = {NULL};
char *pSigValue = (char *) sSigValue.c_str();
if (ParseTagValueList(pSigValue, tags, values) && values[0] != NULL)
{
sSignedSig.erase( 15+values[0]-pSigValue, strlen(values[0]) );
}
if ( i->HeaderCanonicalization == DKIM_CANON_RELAXED )
{
sSignedSig = RelaxHeader( sSignedSig );
}
else if ( i->HeaderCanonicalization == DKIM_CANON_NOWSP )
{
RemoveSWSP( sSignedSig );
// convert "DKIM-Signature" to lower case
sSignedSig.replace( 0, 14, "dkim-signature", 14 );
}
i->Hash( sSignedSig.c_str(), sSignedSig.length() );
assert( i->m_pSelector != NULL );
int res = EVP_VerifyFinal(i->m_Hdr_ctx, (unsigned char*)i->SignatureData.data(), i->SignatureData.length(), i->m_pSelector->PublicKey);
if (res == 1)
{
if (i->UnverifiedBodyCount == 0)
i->Status = DKIM_SUCCESS;
else
i->Status = DKIM_SUCCESS_BUT_EXTRA;
SuccessCount++;
SuccessfulDomains.push_back( i->Domain );
}
else
{
// if the selector is in testing mode...
if (i->m_pSelector->Testing)
{
i->Status = DKIM_SIGNATURE_BAD_BUT_TESTING;
TestingFailures++;
}
else
{
i->Status = DKIM_SIGNATURE_BAD;
RealFailures++;
}
}
}
else if (i->Status == DKIM_SELECTOR_GRANULARITY_MISMATCH || i->Status == DKIM_SELECTOR_ALGORITHM_MISMATCH || i->Status == DKIM_SELECTOR_KEY_REVOKED)
{
// treat these as failures
// todo: maybe see if the selector is in testing mode?
RealFailures++;
}
}
// get the From address's domain if we might need it
string sFromDomain;
if (SuccessCount > 0 || m_CheckPractices)
{
for (list<string>::iterator i = HeaderList.begin(); i != HeaderList.end(); ++i)
{
if (_strnicmp(i->c_str(), "From", 4) == 0)
{
// skip over whitespace between the header name and :
const char *s = i->c_str()+4;
while (*s == ' ' || *s == '\t')
s++;
if (*s == ':')
{
vector<string> Addresses;
if (ParseAddresses(s+1, Addresses))
{
unsigned atpos = Addresses[0].find('@');
sFromDomain = Addresses[0].substr(atpos+1);
break;
}
}
}
}
}
// if a signature from the From domain verified successfully, return success now
// without checking the author domain signing practices
if (SuccessCount > 0 && !sFromDomain.empty())
{
for (list<string>::iterator i = SuccessfulDomains.begin(); i != SuccessfulDomains.end(); ++i)
{
// see if the successful domain is the same as or a parent of the From domain
if (i->length() > sFromDomain.length())
continue;
if (_stricmp(i->c_str(), sFromDomain.c_str()+sFromDomain.length()-i->length()) != 0)
continue;
if (i->length() == sFromDomain.length() || sFromDomain.c_str()[sFromDomain.length()-i->length()-1] == '.')
{
return SuccessCount == Signatures.size() ? DKIM_SUCCESS : DKIM_PARTIAL_SUCCESS;
}
}
}
// get the author domain signing practices
int iPractices = DKIM_ADSP_UNKNOWN;
if (m_CheckPractices && !sFromDomain.empty())
{
int ADSPStatus = GetADSP(sFromDomain, iPractices);
if (ADSPStatus != DKIM_SUCCESS)
{
// could not get practices, leave values at the defaults
}
}
// if there was a successful signature and policy is not discardable, return success
if (SuccessCount > 0 && (iPractices == DKIM_ADSP_UNKNOWN || iPractices == DKIM_ADSP_ALL))
{
return SuccessCount == Signatures.size() ? DKIM_SUCCESS : DKIM_PARTIAL_SUCCESS;
}
// if the message should be signed, return fail
if (iPractices == DKIM_ADSP_ALL || iPractices == DKIM_ADSP_DISCARDABLE)
return DKIM_FAIL;
// return neutral for everything else
return DKIM_NEUTRAL;
}
////////////////////////////////////////////////////////////////////////////////
//
// Hash - update the hash
//
////////////////////////////////////////////////////////////////////////////////
void SignatureInfo::Hash( const char* szBuffer, unsigned nBufLength, bool IsBody )
{
#if 0
/** START DEBUG CODE **/
if( nBufLength == 2 && szBuffer[0] == '\r' && szBuffer[1] == '\n' )
{
printf( "[CRLF]\n" );
}
else
{
char* szDbg = new char[nBufLength+1];
strncpy( szDbg, szBuffer, nBufLength );
szDbg[nBufLength] = '\0';
printf( "[%s]\n", szDbg );
}
/** END DEBUG CODE **/
#endif
if (IsBody && BodyLength != -1)
{
VerifiedBodyCount += nBufLength;
if (VerifiedBodyCount > BodyLength)
{
nBufLength = BodyLength - (VerifiedBodyCount - nBufLength);
UnverifiedBodyCount += VerifiedBodyCount - BodyLength;
VerifiedBodyCount = BodyLength;
if (nBufLength == 0)
return;
}
}
if (IsBody && !BodyHashData.empty())
{
EVP_DigestUpdate(m_Bdy_ctx, szBuffer, nBufLength);
}
else
{
EVP_VerifyUpdate(m_Hdr_ctx, szBuffer, nBufLength);
}
if (m_SaveCanonicalizedData)
{
CanonicalizedData.append( szBuffer, nBufLength );
}
}
////////////////////////////////////////////////////////////////////////////////
//
// ProcessHeaders - Look for DKIM-Signatures and start processing them
//
////////////////////////////////////////////////////////////////////////////////
int CDKIMVerify::ProcessHeaders(void)
{
// look for DKIM-Signature header(s)
for( list<string>::iterator i = HeaderList.begin(); i != HeaderList.end(); ++i )
{
if( _strnicmp(i->c_str(), "DKIM-Signature", 14 ) == 0 )
{
// skip over whitespace between the header name and :
const char *s = i->c_str()+14;
while (*s == ' ' || *s == '\t')
s++;
if (*s == ':')
{
// found
SignatureInfo sig(m_SaveCanonicalizedData);
sig.Status = ParseDKIMSignature( *i, sig );
Signatures.push_back( sig );
if (Signatures.size() >= MAX_SIGNATURES)
break;
}
}
}
if ( Signatures.empty() )
return DKIM_NO_SIGNATURES;
bool ValidSigFound = false;
for ( list<SignatureInfo>::iterator s = Signatures.begin(); s != Signatures.end(); ++s )
{
SignatureInfo &sig = *s;
if ( sig.Status != DKIM_SUCCESS)
continue;
SelectorInfo &sel = GetSelector(sig.Selector, sig.Domain);
sig.m_pSelector = &sel;
if (sel.Status != DKIM_SUCCESS)
{
sig.Status = sel.Status;
}
else
{
// check the granularity
if (!WildcardMatch(sel.Granularity.c_str(), sig.IdentityLocalPart.c_str()))
sig.Status = DKIM_SELECTOR_GRANULARITY_MISMATCH; // this error causes the signature to fail
// check the hash algorithm
if ( (sig.m_nHash == DKIM_HASH_SHA1 && !sel.AllowSHA1) || (sig.m_nHash == DKIM_HASH_SHA256 && !sel.AllowSHA256) )
sig.Status = DKIM_SELECTOR_ALGORITHM_MISMATCH; // causes signature to fail
// check for same domain
if (sel.SameDomain && _stricmp(sig.Domain.c_str(), sig.IdentityDomain.c_str()) != 0)
sig.Status = DKIM_BAD_SYNTAX;
}
if (sig.Status != DKIM_SUCCESS)
continue;
// initialize the hashes
if (sig.m_nHash == DKIM_HASH_SHA256)
{
EVP_VerifyInit(sig.m_Hdr_ctx, EVP_sha256());
EVP_DigestInit(sig.m_Bdy_ctx, EVP_sha256());
}
else
{
EVP_VerifyInit(sig.m_Hdr_ctx, EVP_sha1());
EVP_DigestInit(sig.m_Bdy_ctx, EVP_sha1());
}
// compute the hash of the header
vector<list<string>::reverse_iterator> used;
for (vector<string>::iterator x = sig.SignedHeaders.begin(); x != sig.SignedHeaders.end(); ++x)
{
list<string>::reverse_iterator i;
for( i = HeaderList.rbegin(); i != HeaderList.rend(); ++i )
{
if (_strnicmp(i->c_str(), x->c_str(), x->length()) == 0)
{
// skip over whitespace between the header name and :
const char *s = i->c_str()+x->length();
while (*s == ' ' || *s == '\t')
s++;
if (*s == ':' && find(used.begin(), used.end(), i) == used.end())
break;
}
}
if (i != HeaderList.rend())
{
used.push_back(i);
// hash this header
if (sig.HeaderCanonicalization == DKIM_CANON_SIMPLE)
{
sig.Hash( i->c_str(), i->length() );
}
else if (sig.HeaderCanonicalization == DKIM_CANON_RELAXED)
{
string sTemp = RelaxHeader( *i );
sig.Hash( sTemp.c_str(), sTemp.length() );
}
else if (sig.HeaderCanonicalization == DKIM_CANON_NOWSP)
{
string sTemp = *i;
RemoveSWSP( sTemp );
// convert characters before ':' to lower case
for( char* s = (char*)sTemp.c_str(); *s != '\0' && *s != ':'; s++ )
{
if( *s >= 'A' && *s <= 'Z' )
*s += 'a'-'A';
}
sig.Hash( sTemp.c_str(), sTemp.length() );
}
sig.Hash( "\r\n", 2 );
}
}
if (sig.BodyHashData.empty())
{
// hash CRLF separating headers from body
sig.Hash( "\r\n", 2 );
}
if (!m_AllowUnsignedFromHeaders)
{
// make sure the message has no unsigned From headers
list<string>::reverse_iterator i;
for( i = HeaderList.rbegin(); i != HeaderList.rend(); ++i )
{
if( _strnicmp(i->c_str(), "From", 4 ) == 0 )
{
// skip over whitespace between the header name and :
const char *s = i->c_str()+4;
while (*s == ' ' || *s == '\t')
s++;
if (*s == ':')
{
if (find(used.begin(), used.end(), i) == used.end())
{
// this From header was not signed
break;
}
}
}
}
if (i != HeaderList.rend())
{
// treat signature as invalid
sig.Status = DKIM_UNSIGNED_FROM;
continue;
}
}
ValidSigFound = true;
}
if ( !ValidSigFound )
return DKIM_NO_VALID_SIGNATURES;
return DKIM_SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////
//
// Strictly parse an unsigned integer. Don't allow spaces, negative sign,
// 0x prefix, etc. Values greater than 2^32-1 are capped at 2^32-1
//
////////////////////////////////////////////////////////////////////////////////
bool ParseUnsigned(const char *s, unsigned *result)
{
unsigned temp=0, last=0;
bool overflowed = false;
do {
if (*s < '0' || *s > '9')
return false; // returns false for an initial '\0'
temp = temp * 10 + (*s - '0');
if (temp < last)
overflowed = true;
last = temp;
s++;
} while (*s != '\0');
*result = overflowed ? -1 : temp;
return true;
}
////////////////////////////////////////////////////////////////////////////////
//
// ParseDKIMSignature - Parse a DKIM-Signature header field
//
////////////////////////////////////////////////////////////////////////////////
int CDKIMVerify::ParseDKIMSignature( const string& sHeader, SignatureInfo &sig )
{
// for strtok_s()
char* saveptr;
// save header for later
sig.Header = sHeader;
string sValue = sHeader.substr( sHeader.find(':')+1 );
static const char *tags[] = {"v","a","b","d","h","s","c","i","l","q","t","x","bh",NULL};
char *values[sizeof(tags)/sizeof(tags[0])] = {NULL};
if (!ParseTagValueList( (char*) sValue.c_str(), tags, values))
return DKIM_BAD_SYNTAX;
// check signature version
if (values[0] != NULL)
{
if (strcmp(values[0], "1") == 0 || strcmp(values[0], "0.5") == 0 || strcmp(values[0], "0.4") == 0 || strcmp(values[0], "0.3") == 0 || strcmp(values[0], "0.2") == 0)
{
sig.Version = DKIM_SIG_VERSION_02_PLUS;
}
else
{
// unknown version
return DKIM_STAT_INCOMPAT;
}
}
else
{
// Note: DKIM Interop 1 pointed out that v= is now required, but we do
// not enforce that in order to verify signatures made by older drafts.
// prior to 0.2, there MUST NOT have been a v=
// (optionally) support these signatures, for backwards compatibility
if (true)
{
sig.Version = DKIM_SIG_VERSION_PRE_02;
}
else
{
return DKIM_BAD_SYNTAX;
}
}
// signature MUST have a=, b=, d=, h=, s=
if (values[1] == NULL || values[2] == NULL || values[3] == NULL || values[4] == NULL || values[5] == NULL)
return DKIM_BAD_SYNTAX;
// algorithm can be "rsa-sha1" or "rsa-sha256"
if (strcmp(values[1], "rsa-sha1") == 0)
{
sig.m_nHash = DKIM_HASH_SHA1;
}
else if (strcmp(values[1], "rsa-sha256") == 0)
{
sig.m_nHash = DKIM_HASH_SHA256;
}
else
{
return DKIM_BAD_SYNTAX; // todo: maybe create a new error code for unknown algorithm
}
// make sure the signature data is not empty
unsigned SigDataLen = DecodeBase64(values[2]);
if (SigDataLen == 0)
return DKIM_BAD_SYNTAX;
sig.SignatureData.assign(values[2], SigDataLen);
// check for body hash
if (values[12] == NULL)
{
// use the old single hash way for backwards compatibility
if (sig.Version != DKIM_SIG_VERSION_PRE_02)
return DKIM_BAD_SYNTAX;
}
else
{
unsigned BodyHashLen = DecodeBase64(values[12]);
if (BodyHashLen == 0)
return DKIM_BAD_SYNTAX;
sig.BodyHashData.assign(values[12], BodyHashLen);
}
// domain must not be empty
if (*values[3] == '\0')
return DKIM_BAD_SYNTAX;
sig.Domain = values[3];
// signed headers must not be empty (more verification is done later)
if (*values[4] == '\0')
return DKIM_BAD_SYNTAX;
// selector must not be empty
if (*values[5] == '\0')
return DKIM_BAD_SYNTAX;
sig.Selector = values[5];
// canonicalization
if (values[6] == NULL)
{
sig.HeaderCanonicalization = sig.BodyCanonicalization = DKIM_CANON_SIMPLE;
}
else if (sig.Version == DKIM_SIG_VERSION_PRE_02 && strcmp(values[6], "nowsp") == 0)
{
// for backwards compatibility
sig.HeaderCanonicalization = sig.BodyCanonicalization = DKIM_CANON_NOWSP;
}
else
{
char *slash = strchr(values[6], '/');
if (slash != NULL)
*slash = '\0';