-
Notifications
You must be signed in to change notification settings - Fork 31
/
sigv4.c
3109 lines (2703 loc) · 126 KB
/
sigv4.c
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
/*
* SigV4 Utility Library v1.0.0
* Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file sigv4.c
* @brief Implements the user-facing functions in sigv4.h
*/
#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "sigv4.h"
#include "sigv4_internal.h"
#include "sigv4_quicksort.h"
/*-----------------------------------------------------------*/
#if ( SIGV4_USE_CANONICAL_SUPPORT == 1 )
/**
* @brief Normalize a URI string according to RFC 3986 and fill destination
* buffer with the formatted string.
*
* @param[in] pUri The URI string to encode.
* @param[in] uriLen Length of pUri.
* @param[out] pCanonicalURI The resulting canonicalized URI.
* @param[in, out] canonicalURILen input: the length of pCanonicalURI,
* output: the length of the generated canonical URI.
* @param[in] encodeSlash Option to indicate if slashes should be encoded.
* @param[in] doubleEncodeEquals Option to indicate if equals should be double-encoded.
*/
static SigV4Status_t encodeURI( const char * pUri,
size_t uriLen,
char * pCanonicalURI,
size_t * canonicalURILen,
bool encodeSlash,
bool doubleEncodeEquals );
/**
* @brief Canonicalize the full URI path. The input URI starts after the
* HTTP host and ends at the question mark character ("?") that begins the
* query string parameters (if any). Example: folder/subfolder/item.txt"
*
* @param[in] pUri HTTP request URI, also known that the request absolute
* path.
* @param[in] uriLen Length of pUri.
* @param[in] encodeTwice Service-dependent option to indicate whether
* encoding should be done twice. For example, S3 requires that the
* URI is encoded only once, while other services encode twice.
* @param[in, out] pCanonicalRequest Struct to maintain intermediary buffer
* and state of canonicalization.
*/
static SigV4Status_t generateCanonicalURI( const char * pUri,
size_t uriLen,
bool encodeTwice,
CanonicalContext_t * pCanonicalRequest );
/**
* @brief Canonicalize the query string HTTP URL, beginning (but not
* including) at the "?" character. Does not include "/".
*
* @param[in] pQuery HTTP request query.
* @param[in] queryLen Length of pQuery.
* @param[in, out] pCanonicalContext Struct to maintain intermediary buffer
* and state of canonicalization.
*/
static SigV4Status_t generateCanonicalQuery( const char * pQuery,
size_t queryLen,
CanonicalContext_t * pCanonicalContext );
/**
* @brief Determine if a character can be written without needing URI encoding when generating Canonical Request.
*
* @param[in] c The character to evaluate.
* @param[in] encodeSlash Whether slashes may be encoded.
*
* @return `true` if the character does not need encoding, `false` if it does.
*/
static bool isAllowedChar( char c,
bool encodeSlash );
/**
* @brief Compare two SigV4 data structures lexicographically, without case-sensitivity.
*
* @param[in] pFirstVal SigV4 key value data structure to sort.
* @param[in] pSecondVal SigV4 key value data structure to sort.
*
* @return Returns a value less than 0 if @pFirstVal < @pSecondVal, or
* a value greater than 0 if @pSecondVal < @pFirstVal. 0 is never returned in
* order to provide stability to quickSort() calls.
*/
static int32_t cmpHeaderField( const void * pFirstVal,
const void * pSecondVal );
#endif /* #if (SIGV4_USE_CANONICAL_SUPPORT == 1) */
/**
* @brief Converts an integer value to its ASCII representation, and stores the
* result in the provided buffer.
*
* @param[in] value The value to convert to ASCII.
* @param[in, out] pBuffer The starting location of the buffer on input, and the
* ending location on output.
* @param[in] bufferLen Width of value to write (padded with leading 0s if
* necessary).
*/
static void intToAscii( int32_t value,
char ** pBuffer,
size_t bufferLen );
/**
* @brief Extract all header key-value pairs from the passed headers data and add them
* to the canonical request.
*
* @param[in] pHeaders HTTP headers to canonicalize.
* @param[in] headersLen Length of HTTP headers to canonicalize.
* @param[in] flags Flag to indicate if headers are already
* in the canonical form.
* @param[out] canonicalRequest Struct to maintain intermediary buffer
* and state of canonicalization.
* @param[out] pSignedHeaders The starting location of the signed headers.
* @param[out] pSignedHeadersLen The length of the signed headers.
*
* @return Following statuses will be returned by the function:
* #SigV4Success if headers are successfully added to the canonical request.
* #SigV4InsufficientMemory if canonical request buffer cannot accommodate the header.
* #SigV4InvalidParameter if HTTP headers are invalid.
* #SigV4MaxHeaderPairCountExceeded if number of headers that needs to be canonicalized
* exceed the SIGV4_MAX_HTTP_HEADER_COUNT macro defined in the config file.
*/
static SigV4Status_t generateCanonicalAndSignedHeaders( const char * pHeaders,
size_t headersLen,
uint32_t flags,
CanonicalContext_t * canonicalRequest,
char ** pSignedHeaders,
size_t * pSignedHeadersLen );
/**
* @brief Append Signed Headers to the Canonical Request buffer.
*
* @param[in] headerCount Number of headers which needs to be appended.
* @param[in] flags Flag to indicate if headers are already
* in the canonical form.
* @param[in,out] canonicalRequest Struct to maintain intermediary buffer
* and state of canonicalization.
* @param[out] pSignedHeaders The starting location of the signed headers.
* @param[out] pSignedHeadersLen The length of the signed headers.
*/
static SigV4Status_t appendSignedHeaders( size_t headerCount,
uint32_t flags,
CanonicalContext_t * canonicalRequest,
char ** pSignedHeaders,
size_t * pSignedHeadersLen );
/**
* @brief Canonicalize headers and append it to the Canonical Request buffer.
*
* @param[in] headerCount Number of headers which needs to be appended.
* @param[in] flags Flag to indicate if headers are already
* in the canonical form.
* @param[in,out] canonicalRequest Struct to maintain intermediary buffer
* and state of canonicalization.
*
* @return Following statuses will be returned by the function:
* #SigV4Success if headers are successfully added to the canonical request.
* #SigV4InsufficientMemory if canonical request buffer cannot accommodate the header.
*/
static SigV4Status_t appendCanonicalizedHeaders( size_t headerCount,
uint32_t flags,
CanonicalContext_t * canonicalRequest );
/**
* @brief Parse each header key and value pair from HTTP headers.
*
* @param[in] pHeaders HTTP headers to parse.
* @param[in] headersDataLen Length of HTTP headers to parse.
* @param[in] flags Flag to indicate if headers are already
* in the canonical form.
* @param[out] headerCount Count of key-value pairs parsed from pData.
* @param[out] canonicalRequest Struct to maintain intermediary buffer
* and state of canonicalization.
*
* @return Following statuses will be returned by the function:
* #SigV4Success if header key or value is successfully added to the canonical request.
* #SigV4InsufficientMemory if canonical request buffer cannot accommodate the header.
* #SigV4MaxHeaderPairCountExceeded if number of key-value entries in the headers data
* exceeds the SIGV4_MAX_HTTP_HEADER_COUNT macro defined in the config file.
*/
static SigV4Status_t parseHeaderKeyValueEntries( const char * pHeaders,
size_t headersDataLen,
uint32_t flags,
size_t * headerCount,
CanonicalContext_t * canonicalRequest );
/**
* @brief Copy header key or header value to the Canonical Request buffer.
*
* @param[in] pData Header Key or value to be copied to the canonical request.
* @param[in] dataLen Length of Header Key or value.
* @param[in] flags Flag to indicate if headers are already
* in the canonical form.
* @param[in] separator Character separating the multiple key-value pairs or key and values.
* @param[in,out] canonicalRequest Struct to maintain intermediary buffer
* and state of canonicalization.
*
* @return Following statuses will be returned by the function:
* #SigV4Success if the headers are successfully added to the canonical request.
* #SigV4InsufficientMemory if canonical request buffer cannot accommodate the header.
*/
static SigV4Status_t copyHeaderStringToCanonicalBuffer( const char * pData,
size_t dataLen,
uint32_t flags,
char separator,
CanonicalContext_t * canonicalRequest );
/**
* @brief Helper function to determine whether a header string character represents a space
* that can be trimmed when creating "Canonical Headers".
* All leading and trailing spaces in the header strings need to be trimmed. Also, sequential spaces
* in the header value need to be trimmed to a single space.
*
* Example of modifying header field for Canonical Headers:
* Actual header pair: | Modifier header pair
* My-Header2: "a b c" \n | my-header2:"a b c"\n
*
* @param[in] value Header value or key string to be trimmed.
* @param[in] index Index of current character.
* @param[in] valLen Length of the string.
* @param[in] trimmedLength Current length of trimmed string.
*
* @return `true` if the character needs to be trimmed, else `false`.
*/
static bool isTrimmableSpace( const char * value,
size_t index,
size_t valLen,
size_t trimmedLength );
/**
* @brief Generate the canonical request but excluding the canonical headers
* and anything that goes after it. Write it onto @p pSignedHeaders and update
* it to point to the next location to write the rest of the canonical request.
*
* @param[in] pParams The application-defined parameters used to
* generate the canonical request.
* @param[in] pCanonicalContext The context of the canonical request.
* @param[in,out] pSignedHeaders The location to start writing the canonical request and
* becomes the location to write the rest of it when this function returns.
* @param[in,out] pSignedHeadersLen The amount of buffer available and becomes the number
* of bytes actually written when this function returns.
* @return SigV4InsufficientMemory if the length of the canonical request output
* buffer cannot fit the actual request before the headers, #SigV4Success otherwise.
*/
static SigV4Status_t generateCanonicalRequestUntilHeaders( const SigV4Parameters_t * pParams,
CanonicalContext_t * pCanonicalContext,
char ** pSignedHeaders,
size_t * pSignedHeadersLen );
/**
* @brief Generates the prefix of the Authorization header of the format:
* "<algorithm> Credential=<access key ID>/<credential scope>, SignedHeaders=<SignedHeaders>, Signature="
*
* @param[in] pParams The application-defined parameters used to
* generate the canonical request.
* @param[in] pAlgorithm The signing algorithm used for SigV4 authentication.
* @param[in] algorithmLen The length of @p pAlgorithm.
* @param[in] pSignedHeaders The signed headers of the SigV4 request.
* @param[in] signedHeadersLen The length of @p pSignedHeaders.
* @param[in,out] pAuthBuf The authorization buffer where to write the prefix.
* Pointer is updated with the next location to write the value of the signature.
* @param[in, out] pAuthPrefixLen On input, it should contain the total length of @p pAuthBuf.
* On output, this will be filled with the length of the Authorization header, if
* operation is successful.
*
* @return #SigV4InsufficientMemory if the length of the authorization buffer, @p pAuthBuf
* is insufficient to store the entire authorization header value (i.e. Prefix + HexEncoded Signature);
* otherwise #SigV4Success.
*/
static SigV4Status_t generateAuthorizationValuePrefix( const SigV4Parameters_t * pParams,
const char * pAlgorithm,
size_t algorithmLen,
const char * pSignedHeaders,
size_t signedHeadersLen,
char * pAuthBuf,
size_t * pAuthPrefixLen );
/**
* @brief Write a line in the canonical request.
* @note Used whenever there are components of the request that
* are already canonicalized.
*
* @param[in] pLine The line to write to the canonical request.
* @param[in] lineLen The length of @p pLine
* @param[in,out] pCanonicalContext The canonical context where
* the line should be written.
* @return SigV4InsufficientMemory if the length of the canonical request
* buffer cannot write the desired line, #SigV4Success otherwise.
*/
static SigV4Status_t writeLineToCanonicalRequest( const char * pLine,
size_t lineLen,
CanonicalContext_t * pCanonicalContext );
/**
* @brief Set a query parameter key in the canonical request.
*
* @param[in] currentParameter The index of the query key to set
* @param[in] pKey The pointer to the query key
* @param[in] keyLen The length of @p pKey
* @param[in,out] pCanonicalRequest The canonical request containing the
* query parameter array of keys and values
*/
static void setQueryParameterKey( size_t currentParameter,
const char * pKey,
size_t keyLen,
CanonicalContext_t * pCanonicalRequest );
/**
* @brief Set a query parameter value in the canonical request.
*
* @param[in] currentParameter The index of the query value to set
* @param[in] pValue The pointer to the query value
* @param[in] valueLen The length of @p pValue
* @param[in,out] pCanonicalRequest The canonical request containing the
* query parameter array of keys and values
*/
static void setQueryParameterValue( size_t currentParameter,
const char * pValue,
size_t valueLen,
CanonicalContext_t * pCanonicalRequest );
/**
* @brief Generates the key for the HMAC operation.
*
* @note This function can be called multiple times before calling
* #hmacIntermediate. Appending multiple substrings, then calling #hmacAddKey
* on the appended string is also equivalent to calling #hmacAddKey on
* each individual substring.
* @note This function accepts a const char * so that string literals
* can be passed in.
*
* @param[in] pHmacContext The context used for HMAC calculation.
* @param[in] pKey The key used as input for HMAC calculation.
* @param[in] keyLen The length of @p pKey.
* @param[in] isKeyPrefix Flag to indicate whether the passed key is
* prefix of a complete key for an HMAC operation. If this is a prefix,
* then it will be stored in cache for use with remaining part of the
* key that will be provided in a subsequent call to @ref hmacAddKey.
*
* @return Zero on success, all other return values are failures.
*/
static int32_t hmacAddKey( HmacContext_t * pHmacContext,
const char * pKey,
size_t keyLen,
bool isKeyPrefix );
/**
* @brief Generates the intermediate hash output in the HMAC signing process.
* This represents the H( K' ^ i_pad || message ) part of the HMAC algorithm.
*
* @note This MUST be ONLY called after #hmacAddKey; otherwise results in
* undefined behavior. Likewise, one SHOULD NOT call #hmacAddKey after
* calling #hmacIntermediate. One must call #hmacFinal first before calling
* #hmacAddKey again.
*
* @param[in] pHmacContext The context used for HMAC calculation.
* @param[in] pData The data used as input for HMAC calculation.
* @param[in] dataLen The length of @p pData.
*
* @return Zero on success, all other return values are failures.
*/
static int32_t hmacIntermediate( HmacContext_t * pHmacContext,
const char * pData,
size_t dataLen );
/**
* @brief Generates the end output of the HMAC algorithm.
*
* This represents the second hash operation in the HMAC algorithm:
* H( K' ^ o_pad || Intermediate Hash Output )
* where the Intermediate Hash Output is generated from the call
* to @ref hmacIntermediate.
*
* @param[in] pHmacContext The context used for HMAC calculation.
* @param[out] pMac The buffer onto which to write the HMAC digest.
* @param[in] macLen The length of @p pMac.
*
* @return Zero on success, all other return values are failures.
*/
static int32_t hmacFinal( HmacContext_t * pHmacContext,
char * pMac,
size_t macLen );
/**
* @brief Generates the complete HMAC digest given a key and value, then write
* the digest in the provided output buffer.
*
* @param[in] pHmacContext The context used for the current HMAC calculation.
* @param[in] pKey The key passed as input to the HMAC function.
* @param[in] keyLen The length of @p pKey.
* @param[in] pData The data passed as input to the HMAC function.
* @param[in] dataLen The length of @p pData.
* @param[out] pOutput The buffer onto which to write the HMAC digest.
* @param[out] outputLen The length of @p pOutput and must be greater
* than pCryptoInterface->hashDigestLen for this function to succeed.
* @return Zero on success, all other return values are failures.
*/
static int32_t completeHmac( HmacContext_t * pHmacContext,
const char * pKey,
size_t keyLen,
const char * pData,
size_t dataLen,
char * pOutput,
size_t outputLen );
/**
* @brief Generates the complete hash of an input string, then write
* the digest in the provided output buffer.
* @note Unlike #completeHashAndHexEncode, this function will not
* encode the hash and will simply output the bytes written by the
* hash function.
*
* @param[in] pInput The data passed as input to the hash function.
* @param[in] inputLen The length of @p pInput.
* @param[out] pOutput The buffer onto which to write the hash.
* @param[out] outputLen The length of @p pOutput and must be greater
* than pCryptoInterface->hashDigestLen for this function to succeed.
* @param[in] pCryptoInterface The interface used to call hash functions.
* @return Zero on success, all other return values are failures.
*/
static int32_t completeHash( const uint8_t * pInput,
size_t inputLen,
uint8_t * pOutput,
size_t outputLen,
const SigV4CryptoInterface_t * pCryptoInterface );
/**
* @brief Generate the complete hash of an input string, then write
* the digest in an intermediary buffer before hex encoding and
* writing it onto @p pOutput.
*
* @param[in] pInput The data passed as input to the hash function.
* @param[in] inputLen The length of @p pInput.
* @param[out] pOutput The buffer onto which to write the hex-encoded hash.
* @param[out] pOutputLen The length of @p pOutput and must be greater
* than pCryptoInterface->hashDigestLen * 2 for this function to succeed.
* @param[in] pCryptoInterface The interface used to call hash functions.
* @return Zero on success, all other return values are failures.
*/
static SigV4Status_t completeHashAndHexEncode( const char * pInput,
size_t inputLen,
char * pOutput,
size_t * pOutputLen,
const SigV4CryptoInterface_t * pCryptoInterface );
/**
* @brief Generate the prefix of the string to sign containing the
* algorithm and date then write it onto @p pBufStart.
* @note This function assumes that enough bytes remain in @p pBufStart in
* order to write the algorithm and date.
*
* @param[in] pBufStart The starting location of the buffer to write the string
* to sign.
* @param[in] pAlgorithm The algorithm used for generating the SigV4 signature.
* @param[in] algorithmLen The length of @p pAlgorithm.
* @param[in] pDateIso8601 The date used as part of the string to sign.
* @return The number of bytes written to @p pBufStart.
*/
static size_t writeStringToSignPrefix( char * pBufStart,
const char * pAlgorithm,
size_t algorithmLen,
const char * pDateIso8601 );
/**
* @brief Generate the string to sign and write it onto a #SigV4String_t.
*
* @param[in] pParams The application-defined parameters used to
* generate the string to sign.
* @param[in] pAlgorithm The algorithm used for generating the SigV4 signature.
* @param[in] algorithmLen The length of @p pAlgorithm.
* @param[in,out] pCanonicalContext The context of the canonical request.
* @return SigV4InsufficientMemory if the length of the canonical request output
* buffer cannot fit the string to sign, #SigV4Success otherwise.
*/
static SigV4Status_t writeStringToSign( const SigV4Parameters_t * pParams,
const char * pAlgorithm,
size_t algorithmLen,
CanonicalContext_t * pCanonicalContext );
/**
* @brief Generate the signing key and write it onto a #SigV4String_t.
*
* @param[in] pSigV4Params The application-defined parameters used to
* generate the signing key.
* @param[in] pHmacContext The context used for the current HMAC calculation.
* @param[out] pSigningKey The #SigV4String_t onto which the signing key will be written.
* @param[in,out] pBytesRemaining The number of bytes remaining in the canonical buffer.
* @return SigV4InsufficientMemory if the length of @p pSigningKey was insufficient to
* fit the actual signing key, #SigV4Success otherwise.
*/
static SigV4Status_t generateSigningKey( const SigV4Parameters_t * pSigV4Params,
HmacContext_t * pHmacContext,
SigV4String_t * pSigningKey,
size_t * pBytesRemaining );
/**
* @brief Format the credential scope for the authorization header.
* Credential scope includes the access key ID, date, region, and service parameters, and
* ends with "aws4_request" terminator.
*
* @param[in] pSigV4Params The application parameters defining the credential's scope.
* @param[in, out] pCredScope The credential scope in the SigV4 format.
*/
static void generateCredentialScope( const SigV4Parameters_t * pSigV4Params,
SigV4String_t * pCredScope );
/**
* @brief Check if the date represents a valid leap year day.
*
* @param[in] pDateElements The date representation to be verified.
*
* @return #SigV4Success if the date corresponds to a valid leap year,
* #SigV4ISOFormattingError otherwise.
*/
static SigV4Status_t checkLeap( const SigV4DateTime_t * pDateElements );
/**
* @brief Verify the date stored in a SigV4DateTime_t date representation.
*
* @param[in] pDateElements The date representation to be verified.
*
* @return #SigV4Success if the date is valid, and #SigV4ISOFormattingError if
* any member of SigV4DateTime_t is invalid or represents an out-of-range date.
*/
static SigV4Status_t validateDateTime( const SigV4DateTime_t * pDateElements );
/**
* @brief Append the value of a date element to the internal date representation
* structure.
*
* @param[in] formatChar The specifier identifying the struct member to fill.
* @param[in] result The value to assign to the specified struct member.
* @param[out] pDateElements The date representation structure to modify.
*/
static void addToDate( const char formatChar,
int32_t result,
SigV4DateTime_t * pDateElements );
/**
* @brief Interpret the value of the specified characters in date, based on the
* format specifier, and append to the internal date representation.
*
* @param[in] pDate The date to be parsed.
* @param[in] formatChar The format specifier used to interpret characters.
* @param[in] readLoc The index of pDate to read from.
* @param[in] lenToRead The number of characters to read.
* @param[out] pDateElements The date representation to modify.
*
* @return #SigV4Success if parsing succeeded, #SigV4ISOFormattingError if the
* characters read did not match the format specifier.
*/
static SigV4Status_t scanValue( const char * pDate,
const char formatChar,
size_t readLoc,
size_t lenToRead,
SigV4DateTime_t * pDateElements );
/**
* @brief Parses date according to format string parameter, and populates date
* representation struct SigV4DateTime_t with its elements.
*
* @param[in] pDate The date to be parsed.
* @param[in] dateLen Length of pDate, the date to be formatted.
* @param[in] pFormat The format string used to extract date pDateElements from
* pDate. This string, among other characters, may contain specifiers of the
* form "%LV", where L is the number of characters to be read, and V is one of
* {Y, M, D, h, m, s, *}, representing a year, month, day, hour, minute, second,
* or skipped (un-parsed) value, respectively.
* @param[in] formatLen Length of the format string pFormat.
* @param[out] pDateElements The deconstructed date representation of pDate.
*
* @return #SigV4Success if all format specifiers were matched successfully,
* #SigV4ISOFormattingError otherwise.
*/
static SigV4Status_t parseDate( const char * pDate,
size_t dateLen,
const char * pFormat,
size_t formatLen,
SigV4DateTime_t * pDateElements );
/**
* @brief Verify input parameters to the SigV4_GenerateHTTPAuthorization API.
*
* @param[in] pParams Complete SigV4 configurations passed by application.
* @param[in] pAuthBuf The user-supplied buffer for filling Authorization Header.
* @param[in] authBufLen The user-supplied size value of @p pAuthBuf buffer.
* @param[in] pSignature The user-supplied pointer memory to store starting location of
* Signature in Authorization Buffer.
* @param[in] signatureLen The user-supplied pointer to store length of Signature.
*
* @return #SigV4Success if successful, #SigV4InvalidParameter otherwise.
*/
static SigV4Status_t verifyParamsToGenerateAuthHeaderApi( const SigV4Parameters_t * pParams,
const char * pAuthBuf,
const size_t * authBufLen,
char * const * pSignature,
const size_t * signatureLen );
/**
* @brief Assign default arguments based on parameters set in @p pParams.
*
* @param[in] pParams Complete SigV4 configurations passed by application.
* @param[out] pAlgorithm The algorithm used for SigV4 authentication.
* @param[out] algorithmLen The length of @p pAlgorithm.
*/
static void assignDefaultArguments( const SigV4Parameters_t * pParams,
const char ** pAlgorithm,
size_t * algorithmLen );
/**
* @brief Hex digest of provided string parameter.
*
* @param[in] pInputStr String to encode.
* @param[out] pHexOutput Hex representation of @p pInputStr.
*
* @return #SigV4Success if successful, #SigV4InsufficientMemory otherwise.
*/
static SigV4Status_t lowercaseHexEncode( const SigV4String_t * pInputStr,
SigV4String_t * pHexOutput );
/**
* @brief Calculate number of bytes needed for the credential scope.
* @note This does not include the linefeed character.
*
* @param[in] pSigV4Params SigV4 configurations passed by application.
*
* @return Number of bytes needed for credential scope.
*/
static size_t sizeNeededForCredentialScope( const SigV4Parameters_t * pSigV4Params );
/**
* @brief Copy a string into a char * buffer.
* @note This function can be used to copy a string literal without
* MISRA warnings.
*
* @note This function assumes the destination buffer is large enough to hold
* the string to copy, so will always write @p length bytes.
*
* @param[in] destination The buffer to write.
* @param[in] source String to copy.
* @param[in] length Number of characters to copy.
*
* @return @p length The number of characters written from @p source into
* @p destination.
*/
static size_t copyString( char * destination,
const char * source,
size_t length );
/*-----------------------------------------------------------*/
static void intToAscii( int32_t value,
char ** pBuffer,
size_t bufferLen )
{
int32_t currentVal = value;
size_t lenRemaining = bufferLen;
assert( pBuffer != NULL );
assert( bufferLen > 0U );
/* Write base-10 remainder in its ASCII representation, and fill any
* remaining width with '0' characters. */
while( lenRemaining > 0U )
{
lenRemaining--;
( *pBuffer )[ lenRemaining ] = ( char ) ( ( currentVal % 10 ) + '0' );
currentVal /= 10;
}
/* Move pointer to follow last written character. */
*pBuffer += bufferLen;
}
/*-----------------------------------------------------------*/
static SigV4Status_t checkLeap( const SigV4DateTime_t * pDateElements )
{
SigV4Status_t returnStatus = SigV4ISOFormattingError;
assert( pDateElements != NULL );
/* If the date represents a leap day, verify that the leap year is valid. */
if( ( pDateElements->tm_mon == 2 ) && ( pDateElements->tm_mday == 29 ) )
{
if( ( ( pDateElements->tm_year % 400 ) != 0 ) &&
( ( ( pDateElements->tm_year % 4 ) != 0 ) ||
( ( pDateElements->tm_year % 100 ) == 0 ) ) )
{
LogError( ( "%ld is not a valid leap year.",
( long int ) pDateElements->tm_year ) );
}
else
{
returnStatus = SigV4Success;
}
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static SigV4Status_t validateDateTime( const SigV4DateTime_t * pDateElements )
{
SigV4Status_t returnStatus = SigV4Success;
const int32_t daysPerMonth[] = MONTH_DAYS;
assert( pDateElements != NULL );
if( pDateElements->tm_year < YEAR_MIN )
{
LogError( ( "Invalid 'year' value parsed from date string. "
"Expected an integer %ld or greater, received: %ld",
( long int ) YEAR_MIN,
( long int ) pDateElements->tm_year ) );
returnStatus = SigV4ISOFormattingError;
}
if( ( pDateElements->tm_mon < 1 ) || ( pDateElements->tm_mon > 12 ) )
{
LogError( ( "Invalid 'month' value parsed from date string. "
"Expected an integer between 1 and 12, received: %ld",
( long int ) pDateElements->tm_mon ) );
returnStatus = SigV4ISOFormattingError;
}
/* Ensure that the day of the month is valid for the relevant month. */
if( ( returnStatus != SigV4ISOFormattingError ) &&
( ( pDateElements->tm_mday < 1 ) ||
( pDateElements->tm_mday > daysPerMonth[ pDateElements->tm_mon - 1 ] ) ) )
{
/* Check if the date is a valid leap year day. */
returnStatus = checkLeap( pDateElements );
if( returnStatus == SigV4ISOFormattingError )
{
LogError( ( "Invalid 'day' value parsed from date string. "
"Expected an integer between 1 and %ld, received: %ld",
( long int ) daysPerMonth[ pDateElements->tm_mon - 1 ],
( long int ) pDateElements->tm_mday ) );
}
}
/* SigV4DateTime_t values are asserted to be non-negative before they are
* assigned in function addToDate(). Therefore, we only verify logical upper
* bounds for the following values. */
if( pDateElements->tm_hour > 23 )
{
LogError( ( "Invalid 'hour' value parsed from date string. "
"Expected an integer between 0 and 23, received: %ld",
( long int ) pDateElements->tm_hour ) );
returnStatus = SigV4ISOFormattingError;
}
if( pDateElements->tm_min > 59 )
{
LogError( ( "Invalid 'minute' value parsed from date string. "
"Expected an integer between 0 and 59, received: %ld",
( long int ) pDateElements->tm_min ) );
returnStatus = SigV4ISOFormattingError;
}
/* An upper limit of 60 accounts for the occasional leap second UTC
* adjustment. */
if( pDateElements->tm_sec > 60 )
{
LogError( ( "Invalid 'second' value parsed from date string. "
"Expected an integer between 0 and 60, received: %ld",
( long int ) pDateElements->tm_sec ) );
returnStatus = SigV4ISOFormattingError;
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static void addToDate( const char formatChar,
int32_t result,
SigV4DateTime_t * pDateElements )
{
assert( pDateElements != NULL );
assert( result >= 0 );
switch( formatChar )
{
case 'Y':
pDateElements->tm_year = result;
break;
case 'M':
pDateElements->tm_mon = result;
break;
case 'D':
pDateElements->tm_mday = result;
break;
case 'h':
pDateElements->tm_hour = result;
break;
case 'm':
pDateElements->tm_min = result;
break;
case 's':
pDateElements->tm_sec = result;
break;
default:
/* Do not assign values for skipped characters ('*'), or
* unrecognized format specifiers. */
break;
}
}
/*-----------------------------------------------------------*/
static SigV4Status_t scanValue( const char * pDate,
const char formatChar,
size_t readLoc,
size_t lenToRead,
SigV4DateTime_t * pDateElements )
{
SigV4Status_t returnStatus = SigV4InvalidParameter;
const char * const pMonthNames[] = MONTH_NAMES;
const char * pLoc = pDate + readLoc;
size_t remainingLenToRead = lenToRead;
int32_t result = 0;
assert( pDate != NULL );
assert( pDateElements != NULL );
if( formatChar == '*' )
{
remainingLenToRead = 0U;
}
/* Determine if month value is non-numeric. */
if( ( formatChar == 'M' ) && ( remainingLenToRead == MONTH_ASCII_LEN ) )
{
while( result++ < 12 )
{
/* Search month array for parsed string. */
if( strncmp( pMonthNames[ result - 1 ], pLoc, MONTH_ASCII_LEN ) == 0 )
{
returnStatus = SigV4Success;
break;
}
}
if( returnStatus != SigV4Success )
{
LogError( ( "Unable to match string '%.3s' to a month value.",
pLoc ) );
returnStatus = SigV4ISOFormattingError;
}
remainingLenToRead = 0U;
}
/* Interpret integer value of numeric representation. */
while( ( remainingLenToRead > 0U ) && ( *pLoc >= '0' ) && ( *pLoc <= '9' ) )
{
result = ( result * 10 ) + ( int32_t ) ( *pLoc - '0' );
remainingLenToRead--;
pLoc += 1;
}
if( remainingLenToRead != 0U )
{
LogError( ( "Parsing Error: Expected numerical string of type '%%%d%c', "
"but received '%.*s'.",
( int ) lenToRead,
formatChar,
( int ) lenToRead,
pLoc ) );
returnStatus = SigV4ISOFormattingError;
}
if( returnStatus != SigV4ISOFormattingError )
{
addToDate( formatChar,
result,
pDateElements );
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static SigV4Status_t parseDate( const char * pDate,
size_t dateLen,
const char * pFormat,
size_t formatLen,
SigV4DateTime_t * pDateElements )
{
SigV4Status_t returnStatus = SigV4InvalidParameter;
size_t readLoc = 0U, formatIndex = 0U;
uint8_t lenToRead = 0U;
assert( pDate != NULL );
assert( pFormat != NULL );
assert( pDateElements != NULL );
( void ) dateLen;
/* Loop through the format string. */
while( ( formatIndex < formatLen ) && ( returnStatus != SigV4ISOFormattingError ) )
{
if( pFormat[ formatIndex ] == '%' )
{
/* '%' must be followed by a length and type specification. */
assert( formatIndex < formatLen - 2 );
formatIndex++;
/* Numerical value of length specifier character. */
lenToRead = ( ( uint8_t ) pFormat[ formatIndex ] - ( uint8_t ) '0' );
formatIndex++;
/* Ensure read is within buffer bounds. */
assert( readLoc + lenToRead - 1 < dateLen );
returnStatus = scanValue( pDate,
pFormat[ formatIndex ],
readLoc,
lenToRead,
pDateElements );
readLoc += lenToRead;
}
else if( pDate[ readLoc ] != pFormat[ formatIndex ] )
{
LogError( ( "Parsing error: Expected character '%c', "
"but received '%c'.",
pFormat[ formatIndex ], pDate[ readLoc ] ) );
returnStatus = SigV4ISOFormattingError;
}
else
{
readLoc++;
LogDebug( ( "Successfully matched character '%c' found in format string.",
pDate[ readLoc - 1 ] ) );
}
formatIndex++;
}
if( ( returnStatus != SigV4ISOFormattingError ) )
{
returnStatus = SigV4Success;
}
else
{
LogError( ( "Parsing Error: Date did not match expected string format." ) );
returnStatus = SigV4ISOFormattingError;
}
return returnStatus;
}
/*-----------------------------------------------------------*/
static SigV4Status_t lowercaseHexEncode( const SigV4String_t * pInputStr,
SigV4String_t * pHexOutput )
{
SigV4Status_t returnStatus = SigV4Success;