forked from u-blox/ubxlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
u_security_test.c
1405 lines (1264 loc) · 62.9 KB
/
u_security_test.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
/*
* Copyright 2020 u-blox
*
* 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
*
* 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.
*/
/* Only #includes of u_* and the C standard library are allowed here,
* no platform stuff and no OS stuff. Anything required from
* the platform/OS must be brought in through u_port* to maintain
* portability.
*/
/** @file
* @brief Test for the u-blox security API: these should pass on all
* platforms that include the appropriate communications hardware,
* i.e. currently cellular SARA-R5.
* IMPORTANT: see notes in u_cfg_test_platform_specific.h for the
* naming rules that must be followed when using the U_PORT_TEST_FUNCTION()
* macro.
*/
#ifdef U_CFG_OVERRIDE
# include "u_cfg_override.h" // For a customer's configuration override
#endif
#include "stdlib.h" // malloc(), free(), rand()
#include "stddef.h" // NULL, size_t etc.
#include "stdint.h" // int32_t etc.
#include "stdbool.h"
#include "string.h" // memset(), strcmp()
#include "u_cfg_sw.h"
#include "u_cfg_app_platform_specific.h"
#include "u_cfg_test_platform_specific.h"
#include "u_cfg_os_platform_specific.h" // For U_CFG_OS_CLIB_LEAKS.
#include "u_error_common.h" // For U_ERROR_COMMON_NOT_SUPPORTED
#include "u_port.h"
#include "u_port_debug.h"
#include "u_port_os.h"
#ifdef U_CFG_TEST_CELL_MODULE_TYPE
#include "u_cell_module_type.h"
#include "u_cell_test_cfg.h" // For the cellular test macros
#endif
#include "u_network.h"
#include "u_network_test_shared_cfg.h"
#ifdef U_CFG_TEST_SECURITY_C2C_TE_SECRET
#include "u_port_event_queue.h"
#include "u_sock.h"
#include "u_sock_test_shared_cfg.h"
# ifdef U_CFG_AT_CLIENT_DETAILED_DEBUG
extern void uAtClientDetailedDebugOn();
extern void uAtClientDetailedDebugOff();
extern void uAtClientDetailedDebugPrint();
# endif
#endif
#include "u_security.h"
/* ----------------------------------------------------------------
* COMPILE-TIME MACROS
* -------------------------------------------------------------- */
#ifdef U_CFG_SECURITY_DEVICE_PROFILE_UID
/** Timeout for the security sealing operation.
*/
# define U_SECURITY_TEST_SEAL_TIMEOUT_SECONDS (60 * 4)
#endif
#ifdef U_CFG_TEST_SECURITY_C2C_TE_SECRET
#ifndef U_SECURITY_TEST_TASK_STACK_SIZE_BYTES
/** The stack size to use for the test task created during
* async sockets testing with C2C.
*/
# define U_SECURITY_TEST_TASK_STACK_SIZE_BYTES 2048
#endif
#ifndef U_SECURITY_TEST_TASK_PRIORITY
/** The priority to use for the test task created during
* async sockets testing with C2C. If an AT client is running
* make sure that this is lower priority than its URC handler.
*/
# define U_SECURITY_TEST_TASK_PRIORITY (U_CFG_OS_PRIORITY_MIN + 5)
#endif
#ifndef U_SECURITY_TEST_RECEIVE_QUEUE_LENGTH
/** The queue length, used for asynchronous tests.
*/
# define U_SECURITY_TEST_RECEIVE_QUEUE_LENGTH 10
#endif
# ifndef U_SECURITY_TEST_C2C_MAX_TCP_READ_WRITE_SIZE
/** The maximum TCP read/write size to use during C2C testing.
*/
# define U_SECURITY_TEST_C2C_MAX_TCP_READ_WRITE_SIZE 1024
# endif
# ifndef U_SECURITY_TEST_C2C_SMALL_CHUNK_SIZE
/** The small packet size to send when what we're actually
* trying to test is the URC behaviour of C2C.
*/
# define U_SECURITY_TEST_C2C_SMALL_CHUNK_SIZE 50
# endif
# ifndef U_SECURITY_TEST_C2C_SMALL_CHUNK_TOTAL_SIZE
/** The total amount of data to send during the small
* chunks test.
*/
# define U_SECURITY_TEST_C2C_SMALL_CHUNK_TOTAL_SIZE 250
# endif
# ifdef U_CFG_AT_CLIENT_DETAILED_DEBUG
# define LOG_ON uAtClientDetailedDebugOn()
# define LOG_OFF uAtClientDetailedDebugOff()
# define LOG_PRINT uAtClientDetailedDebugPrint()
# else
# define LOG_ON
# define LOG_OFF
# define LOG_PRINT
# endif
#endif
/* ----------------------------------------------------------------
* TYPES
* -------------------------------------------------------------- */
/* ----------------------------------------------------------------
* VARIABLES
* -------------------------------------------------------------- */
#ifdef U_CFG_SECURITY_DEVICE_PROFILE_UID
/** Used for keepGoingCallback() timeout.
*/
static int64_t gStopTimeMs;
#endif
// A string of all possible characters, used
// when testing end to end encryption
static const char gAllChars[] = "the quick brown fox jumps over the lazy dog "
"THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 0123456789 "
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e"
"\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c"
"\x1d\x1e!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\x7f";
#ifdef U_CFG_TEST_SECURITY_C2C_TE_SECRET
/** Data to exchange in a sockets test.
*/
static const char gSendData[] = "_____0000:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0100:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0200:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0300:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0400:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0500:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0600:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0700:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0800:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789"
"_____0900:0123456789012345678901234567890123456789"
"01234567890123456789012345678901234567890123456789";
/** Descriptor for asynchronous data reception.
*/
uSockDescriptor_t gDescriptor;
/** Handle for the event queue used during asynchronous data testing.
*/
int32_t gEventQueueHandle = -1;
/** Pointer to buffer for asynchronous data reception.
*/
char *gpBuffer = NULL;
#endif
/* ----------------------------------------------------------------
* STATIC FUNCTIONS
* -------------------------------------------------------------- */
#ifdef U_CFG_SECURITY_DEVICE_PROFILE_UID
// Callback function for the security sealing processes.
static bool keepGoingCallback()
{
bool keepGoing = true;
if (uPortGetTickTimeMs() > gStopTimeMs) {
keepGoing = false;
}
return keepGoing;
}
#endif
// Standard preamble for all security tests
static void stdPreamble()
{
#if (U_CFG_APP_GNSS_UART < 0)
int32_t networkHandle = -1;
#endif
U_PORT_TEST_ASSERT(uPortInit() == 0);
U_PORT_TEST_ASSERT(uNetworkInit() == 0);
// Add each network type if its not already been added
for (size_t x = 0; x < gUNetworkTestCfgSize; x++) {
if (gUNetworkTestCfg[x].handle < 0) {
if (*((const uNetworkType_t *) (gUNetworkTestCfg[x].pConfiguration)) != U_NETWORK_TYPE_NONE) {
uPortLog("U_SECURITY_TEST: adding %s network...\n",
gpUNetworkTestTypeName[gUNetworkTestCfg[x].type]);
#if (U_CFG_APP_GNSS_UART < 0)
// If there is no GNSS UART then any GNSS chip must
// be connected via the cellular module's AT interface
// hence we capture the cellular network handle here and
// modify the GNSS configuration to use it before we add
// the GNSS network
uNetworkTestGnssAtConfiguration(networkHandle,
gUNetworkTestCfg[x].pConfiguration);
#endif
gUNetworkTestCfg[x].handle = uNetworkAdd(gUNetworkTestCfg[x].type,
gUNetworkTestCfg[x].pConfiguration);
U_PORT_TEST_ASSERT(gUNetworkTestCfg[x].handle >= 0);
#if (U_CFG_APP_GNSS_UART < 0)
if (gUNetworkTestCfg[x].type == U_NETWORK_TYPE_CELL) {
networkHandle = gUNetworkTestCfg[x].handle;
}
#endif
}
}
}
// Bring up each network type
for (size_t x = 0; x < gUNetworkTestCfgSize; x++) {
if (gUNetworkTestCfg[x].handle >= 0) {
uPortLog("U_SECURITY_TEST: bringing up %s...\n",
gpUNetworkTestTypeName[gUNetworkTestCfg[x].type]);
U_PORT_TEST_ASSERT(uNetworkUp(gUNetworkTestCfg[x].handle) == 0);
}
}
}
#ifdef U_CFG_TEST_SECURITY_C2C_TE_SECRET
// Send an entire TCP data buffer until done
static size_t sendTcp(uSockDescriptor_t descriptor,
const char *pData, size_t sizeBytes)
{
int32_t x;
size_t sentSizeBytes = 0;
int64_t startTimeMs;
uPortLog("U_SECURITY_TEST: sending %d byte(s) of TCP data...\n",
sizeBytes);
startTimeMs = uPortGetTickTimeMs();
while ((sentSizeBytes < sizeBytes) &&
((uPortGetTickTimeMs() - startTimeMs) < 10000)) {
x = uSockWrite(descriptor, (const void *) pData,
sizeBytes - sentSizeBytes);
if (x > 0) {
sentSizeBytes += x;
uPortLog("U_SECURITY_TEST: sent %d byte(s) of TCP data @%d ms.\n",
sentSizeBytes, (int32_t) uPortGetTickTimeMs());
} else {
uPortLog("U_SECURITY_TEST: send returned %d.\n", x);
}
}
return sentSizeBytes;
}
// Make sure that size is greater than 0 and no more than limit,
// useful since, when moduloing a very large number number,
// compilers sometimes screw up and produce a small *negative*
// number.
static size_t fix(size_t size, size_t limit)
{
if (size == 0) {
size = limit / 2; // better than 1
} else if (size > limit) {
size = limit;
}
return size;
}
// Event task triggered by the arrival of data.
static void rxAsyncEventTask(void *pParameter, size_t parameterLength)
{
int32_t thisSizeReceived;
int32_t totalSizeReceived = 0;
// The parameter that arrives here is a pointer to the
// payload which is itself a pointer to sizeBytesReceive,
// hence the need to double dereference here.
int32_t *pSizeBytes = *((int32_t **) pParameter);
(void) parameterLength;
if (gpBuffer != NULL) {
// Read from the socket until there's nothing left to read
//lint -e{776} Suppress possible truncation of addition
do {
thisSizeReceived = uSockRead(gDescriptor, gpBuffer + totalSizeReceived,
U_SECURITY_TEST_C2C_SMALL_CHUNK_SIZE - totalSizeReceived);
if (thisSizeReceived > 0) {
totalSizeReceived += thisSizeReceived;
}
} while ((thisSizeReceived > 0) && (totalSizeReceived < U_SECURITY_TEST_C2C_SMALL_CHUNK_SIZE));
*pSizeBytes += totalSizeReceived;
}
}
// Callback to send to event queue triggered by
// data arriving.
//lint -e{818} Suppress could be const, need to follow
// function signature
static void sendToEventQueue(void *pParameter)
{
U_PORT_TEST_ASSERT(gEventQueueHandle >= 0);
// Forward the pointer to rxAsyncEventTask().
// Note: uPortEventQueueSend() expects to
// receive a pointer to a payload, so here
// we give it the address of pParameter,
// so that it will send on a copy
// of the pointer that is pParameter.
uPortEventQueueSend(gEventQueueHandle,
&pParameter, sizeof(size_t *));
}
#endif // U_CFG_TEST_SECURITY_C2C_TE_SECRET
/* ----------------------------------------------------------------
* PUBLIC FUNCTIONS: TESTS
* -------------------------------------------------------------- */
#ifdef U_CFG_TEST_SECURITY_C2C_TE_SECRET
/** Test chip to chip security, basic test.
*
* IMPORTANT: see notes in u_cfg_test_platform_specific.h for the
* naming rules that must be followed when using the
* U_PORT_TEST_FUNCTION() macro.
*/
U_PORT_TEST_FUNCTION("[security]", "securityC2cBasic")
{
int32_t networkHandle;
int32_t heapUsed;
char key[U_SECURITY_C2C_ENCRYPTION_KEY_LENGTH_BYTES];
char hmac[U_SECURITY_C2C_HMAC_TAG_LENGTH_BYTES];
// The first time rand() is called the C library may
// allocate memory, not something we can do anything
// about, so call it once here to move that number
// out of our sums.
rand();
// Do the standard preamble to make sure there is
// a network underneath us
stdPreamble();
// Repeat for all bearers
for (size_t x = 0; x < gUNetworkTestCfgSize; x++) {
networkHandle = gUNetworkTestCfg[x].handle;
if (networkHandle >= 0) {
// Get the initial-ish heap
heapUsed = uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: checking if u-blox security"
" is supported by handle %d...\n", networkHandle);
if (uSecurityIsSupported(networkHandle)) {
uPortLog("U_SECURITY_TEST: security is supported.\n");
// Note: don't check sealed status here, C2C key pairing
// is intended to be performed by a customer only BEFORE
// bootstrapping or sealing is completed, in a sanitized
// environment where the returned values can be stored
// in the MCU.
// On the u-blox test farm we enable the feature
// LocalC2CKeyPairing via the u-blox security services REST
// API for all our modules so that we can complete the
// pairing process even after sealing.
// Test that closing a session that is not open is fine
U_PORT_TEST_ASSERT(uSecurityC2cClose(networkHandle) == 0);
uPortLog("U_SECURITY_TEST: pairing...\n");
LOG_ON;
U_PORT_TEST_ASSERT(uSecurityC2cPair(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_TEST_SECURITY_C2C_TE_SECRET),
key, hmac) == 0);
// Make sure it's still fine
U_PORT_TEST_ASSERT(uSecurityC2cClose(networkHandle) == 0);
uPortLog("U_SECURITY_TEST: opening a secure session...\n");
U_PORT_TEST_ASSERT(uSecurityC2cOpen(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_TEST_SECURITY_C2C_TE_SECRET),
key, hmac) == 0);
uPortLog("U_SECURITY_TEST: closing the session again...\n");
U_PORT_TEST_ASSERT(uSecurityC2cClose(networkHandle) == 0);
LOG_OFF;
LOG_PRINT;
}
// Check for memory leaks
heapUsed -= uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: we have leaked %d byte(s).\n",
heapUsed);
// heapUsed < 0 for the Zephyr case where the heap can look
// like it increases (negative leak)
U_PORT_TEST_ASSERT(heapUsed <= 0);
}
}
}
/** Test chip to chip security but this time there's a sock in it.
*/
U_PORT_TEST_FUNCTION("[security]", "securityC2cSock")
{
int32_t errorCode;
int32_t networkHandle;
char key[U_SECURITY_C2C_ENCRYPTION_KEY_LENGTH_BYTES];
char hmac[U_SECURITY_C2C_HMAC_TAG_LENGTH_BYTES];
uSockAddress_t remoteAddress;
uSockDescriptor_t descriptor;
size_t sizeBytes;
size_t offset;
int32_t y;
char *pDataReceived;
int64_t startTimeMs;
int32_t heapUsed;
int32_t heapSockInitLoss = 0;
int32_t heapXxxSockInitLoss = 0;
// Do the standard preamble to make sure there is
// a network underneath us
stdPreamble();
// Repeat for all bearers
for (size_t x = 0; x < gUNetworkTestCfgSize; x++) {
networkHandle = gUNetworkTestCfg[x].handle;
if (networkHandle >= 0) {
// Get the initial-ish heap
heapUsed = uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: checking if u-blox security"
" is supported by handle %d...\n", networkHandle);
if (uSecurityIsSupported(networkHandle)) {
uPortLog("U_SECURITY_TEST: security is supported.\n");
// Note: don't check sealed status here, C2C key pairing
// is intended to be performed by a customer only BEFORE
// bootstrapping or sealing is completed, in a sanitized
// environment where the returned values can be stored
// in the MCU.
// On the u-blox test farm we enable the feature
// LocalC2CKeyPairing via the u-blox security services REST
// API for all our modules so that we can complete the
// pairing process even after sealing.
uPortLog("U_SECURITY_TEST: pairing...\n");
U_PORT_TEST_ASSERT(uSecurityC2cPair(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_TEST_SECURITY_C2C_TE_SECRET),
key, hmac) == 0);
// Open a new secure session and perform a sockets operation
uPortLog("U_SECURITY_TEST: opening a secure session...\n");
LOG_ON;
U_PORT_TEST_ASSERT(uSecurityC2cOpen(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_TEST_SECURITY_C2C_TE_SECRET),
key, hmac) == 0);
uPortLog("U_SECURITY_TEST: looking up echo server \"%s\"...\n",
U_SOCK_TEST_ECHO_TCP_SERVER_DOMAIN_NAME);
// Look up the address of the server we use for TCP echo
// The first call to a sockets API needs to
// initialise the underlying sockets layer; take
// account of that initialisation heap cost here.
heapSockInitLoss = uPortGetHeapFree();
U_PORT_TEST_ASSERT(uSockGetHostByName(networkHandle,
U_SOCK_TEST_ECHO_TCP_SERVER_DOMAIN_NAME,
&(remoteAddress.ipAddress)) == 0);
heapSockInitLoss -= uPortGetHeapFree();
// Add the port number we will use
remoteAddress.port = U_SOCK_TEST_ECHO_TCP_SERVER_PORT;
// Create a TCP socket
// Creating a socket may use heap in the underlying
// network layer which will be reclaimed when the
// network layer is closed but we don't do that here
// to save time so need to allow for it in the heap loss
// calculation
heapXxxSockInitLoss += uPortGetHeapFree();
descriptor = uSockCreate(networkHandle, U_SOCK_TYPE_STREAM,
U_SOCK_PROTOCOL_TCP);
heapXxxSockInitLoss -= uPortGetHeapFree();
U_PORT_TEST_ASSERT(descriptor >= 0);
// Connect the socket
uPortLog("U_SECURITY_TEST: connect socket to \"%s:%d\"...\n",
U_SOCK_TEST_ECHO_TCP_SERVER_DOMAIN_NAME,
U_SOCK_TEST_ECHO_TCP_SERVER_PORT);
// Connections can fail so allow this a few goes
errorCode = -1;
for (y = 2; (y > 0) && (errorCode < 0); y--) {
errorCode = uSockConnect(descriptor, &remoteAddress);
}
U_PORT_TEST_ASSERT(errorCode == 0);
uPortLog("U_SECURITY_TEST: sending/receiving %d bytes"
" of data over a TCP socket with data reception"
" into the same task...\n",
sizeof(gSendData) - 1);
// Throw random sized TCP segments up...
offset = 0;
y = 0;
startTimeMs = uPortGetTickTimeMs();
while ((offset < sizeof(gSendData) - 1) &&
(uPortGetTickTimeMs() - startTimeMs < 20000)) {
sizeBytes = (rand() % U_SECURITY_TEST_C2C_MAX_TCP_READ_WRITE_SIZE) + 1;
sizeBytes = fix(sizeBytes,
U_SECURITY_TEST_C2C_MAX_TCP_READ_WRITE_SIZE);
if (offset + sizeBytes > sizeof(gSendData) - 1) {
sizeBytes = (sizeof(gSendData) - 1) - offset;
}
if (sendTcp(descriptor, gSendData + offset,
sizeBytes) == sizeBytes) {
offset += sizeBytes;
}
y++;
}
sizeBytes = offset;
uPortLog("U_SECURITY_TEST: %d byte(s) sent via TCP @%d ms,"
" now receiving...\n", sizeBytes,
(int32_t) uPortGetTickTimeMs());
U_PORT_TEST_ASSERT(sizeBytes >= sizeof(gSendData) - 1);
// ...and capture them all again afterwards
pDataReceived = (char *) malloc(sizeof(gSendData) - 1);
U_PORT_TEST_ASSERT(pDataReceived != NULL);
startTimeMs = uPortGetTickTimeMs();
offset = 0;
//lint -e{441} Suppress loop variable not found in
// condition: we're using time instead
for (y = 0; (offset < sizeof(gSendData) - 1) &&
(uPortGetTickTimeMs() - startTimeMs < 20000); y++) {
//lint -e{613} Suppress possible use of NULL pointer
// for pDataReceived
sizeBytes = uSockRead(descriptor,
pDataReceived + offset,
(sizeof(gSendData) - 1) - offset);
if (sizeBytes > 0) {
offset += sizeBytes;
uPortLog("U_SECURITY_TEST: received %d byte(s) out of"
" %d on TCP socket.\n",
offset, sizeof(gSendData) - 1);
}
}
sizeBytes = offset;
if (sizeBytes < sizeof(gSendData) - 1) {
uPortLog("U_SECURITY_TEST: only %d byte(s) received after %d ms.\n",
sizeBytes,
(int32_t) (uPortGetTickTimeMs() - startTimeMs));
//lint -e(506, 774) Suppress constant Boolean always evaluates to false
U_PORT_TEST_ASSERT(false);
} else {
uPortLog("U_SECURITY_TEST: all %d byte(s) received back after"
" %d ms, checking if they were as expected...\n",
sizeBytes,
(int32_t) (uPortGetTickTimeMs() - startTimeMs));
// Check the characters are the same
//lint -e(668) Suppress possible use of NULL pointer
// for pDataReceived
U_PORT_TEST_ASSERT(memcmp(pDataReceived, gSendData, sizeBytes) == 0);
}
// Close the socket
U_PORT_TEST_ASSERT(uSockClose(descriptor) == 0);
uSockCleanUp();
free(pDataReceived);
uPortLog("U_SECURITY_TEST: closing the session again...\n");
U_PORT_TEST_ASSERT(uSecurityC2cClose(networkHandle) == 0);
LOG_OFF;
LOG_PRINT;
}
#ifndef __XTENSA__
// Check for memory leaks
// This if'ed out for ESP32 (xtensa compiler) as
// the way it's heap work means that if blocks are
// freed in a different order to they were allocated and
// any one of those blocks remains allocated (which sockets
// will do here as we allocate two mutexes when they are first
// used) then the amount of heap remaining is not possible
// to calculate with any degree of confidence (a four byte
// variant due to block length tracking in their
// implementation).
heapUsed -= uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: during this part of the test %d"
" byte(s) were lost to sockets initialisation;"
" we have leaked %d byte(s).\n",
heapSockInitLoss + heapXxxSockInitLoss,
heapUsed - (heapSockInitLoss + heapXxxSockInitLoss));
// heapUsed < 0 for the Zephyr case where the heap can look
// like it increases (negative leak)
U_PORT_TEST_ASSERT(heapUsed <= heapSockInitLoss + heapXxxSockInitLoss);
#else
(void) heapUsed;
(void) heapSockInitLoss;
(void) heapXxxSockInitLoss;
#endif
}
}
}
/** Test chip to chip security but this time with asynchronous
* data reception in order to test URCs are properly handled.
*/
U_PORT_TEST_FUNCTION("[security]", "securityC2cSockAsync")
{
int32_t errorCode;
int32_t networkHandle;
char key[U_SECURITY_C2C_ENCRYPTION_KEY_LENGTH_BYTES];
char hmac[U_SECURITY_C2C_HMAC_TAG_LENGTH_BYTES];
uSockAddress_t remoteAddress;
size_t sizeBytesSend;
size_t sizeBytesReceive = 0;
size_t offset;
int32_t y;
int64_t startTimeMs;
int32_t heapUsed;
int32_t heapSockInitLoss = 0;
int32_t heapXxxSockInitLoss = 0;
// Do the standard preamble to make sure there is
// a network underneath us
stdPreamble();
// Repeat for all bearers
for (size_t x = 0; x < gUNetworkTestCfgSize; x++) {
networkHandle = gUNetworkTestCfg[x].handle;
if (networkHandle >= 0) {
// Get the initial-ish heap
heapUsed = uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: checking if u-blox security"
" is supported by handle %d...\n", networkHandle);
if (uSecurityIsSupported(networkHandle)) {
uPortLog("U_SECURITY_TEST: security is supported.\n");
// Note: don't check sealed status here, C2C key pairing
// is intended to be performed by a customer only BEFORE
// bootstrapping or sealing is completed, in a sanitized
// environment where the returned values can be stored
// in the MCU.
// On the u-blox test farm we enable the feature
// LocalC2CKeyPairing via the u-blox security services REST
// API for all our modules so that we can complete the
// pairing process even after sealing.
uPortLog("U_SECURITY_TEST: pairing...\n");
U_PORT_TEST_ASSERT(uSecurityC2cPair(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_TEST_SECURITY_C2C_TE_SECRET),
key, hmac) == 0);
// Open a new secure session and perform a sockets operation
uPortLog("U_SECURITY_TEST: opening a secure session...\n");
LOG_ON;
U_PORT_TEST_ASSERT(uSecurityC2cOpen(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_TEST_SECURITY_C2C_TE_SECRET),
key, hmac) == 0);
uPortLog("U_SECURITY_TEST: looking up echo server \"%s\"...\n",
U_SOCK_TEST_ECHO_TCP_SERVER_DOMAIN_NAME);
// Look up the address of the server we use for TCP echo
// The first call to a sockets API needs to
// initialise the underlying sockets layer; take
// account of that initialisation heap cost here.
heapSockInitLoss = uPortGetHeapFree();
U_PORT_TEST_ASSERT(uSockGetHostByName(networkHandle,
U_SOCK_TEST_ECHO_TCP_SERVER_DOMAIN_NAME,
&(remoteAddress.ipAddress)) == 0);
heapSockInitLoss -= uPortGetHeapFree();
// Add the port number we will use
remoteAddress.port = U_SOCK_TEST_ECHO_TCP_SERVER_PORT;
// Create a TCP socket
// Creating a socket may use heap in the underlying
// network layer which will be reclaimed when the
// network layer is closed but we don't do that here
// to save time so need to allow for it in the heap loss
// calculation
heapXxxSockInitLoss += uPortGetHeapFree();
gDescriptor = uSockCreate(networkHandle, U_SOCK_TYPE_STREAM,
U_SOCK_PROTOCOL_TCP);
heapXxxSockInitLoss -= uPortGetHeapFree();
U_PORT_TEST_ASSERT(gDescriptor >= 0);
// Connect the socket
uPortLog("U_SECURITY_TEST: connect socket to \"%s:%d\"...\n",
U_SOCK_TEST_ECHO_TCP_SERVER_DOMAIN_NAME,
U_SOCK_TEST_ECHO_TCP_SERVER_PORT);
// Connections can fail so allow this a few goes
errorCode = -1;
for (y = 2; (y > 0) && (errorCode < 0); y--) {
errorCode = uSockConnect(gDescriptor, &remoteAddress);
}
U_PORT_TEST_ASSERT(errorCode == 0);
// Create the event queue with, at the end of it,
// a task that will handle the received TCP packets.
// The thing it gets sent on the event queue is a pointer
// to sizeBytesReceive
gEventQueueHandle = uPortEventQueueOpen(rxAsyncEventTask,
"testTaskRxData",
//lint -e(866) Suppress unusual
// use of & in sizeof()
sizeof(&sizeBytesReceive),
U_SECURITY_TEST_TASK_STACK_SIZE_BYTES,
U_SECURITY_TEST_TASK_PRIORITY,
U_SECURITY_TEST_RECEIVE_QUEUE_LENGTH);
U_PORT_TEST_ASSERT(gEventQueueHandle >= 0);
// Ask the sockets API for a pointer to sizeBytesReceive
// to be sent to our trampoline function,
// sendToEventQueue(), whenever UDP data arrives.
// sendToEventQueue() will then forward the
// pointer to the event queue and hence to
// rxAsyncEventTask()
uSockRegisterCallbackData(gDescriptor,
sendToEventQueue,
&sizeBytesReceive);
// Set the port to be non-blocking; we will pick up
// the TCP data that we have been called-back to
// say has arrived and then if we ask again we want
// to know that there is nothing more to receive
// without hanging about so that we can leave the
// event handler quickly.
uSockBlockingSet(gDescriptor, false);
uPortLog("U_SECURITY_TEST: sending/receiving data over a"
" TCP socket with data reception into another"
" task...\n");
// Throw small TCP segments up and wait
// for them to come back...
gpBuffer = (char *) malloc(U_SECURITY_TEST_C2C_SMALL_CHUNK_SIZE);
U_PORT_TEST_ASSERT(gpBuffer != NULL);
offset = 0;
y = 0;
startTimeMs = uPortGetTickTimeMs();
while ((offset < U_SECURITY_TEST_C2C_SMALL_CHUNK_TOTAL_SIZE) &&
(uPortGetTickTimeMs() - startTimeMs < 120000)) {
sizeBytesSend = U_SECURITY_TEST_C2C_SMALL_CHUNK_SIZE;
if (offset + sizeBytesSend > sizeof(gSendData) - 1) {
sizeBytesSend = (sizeof(gSendData) - 1) - offset;
}
sizeBytesReceive = 0;
if (sendTcp(gDescriptor, gSendData + offset,
sizeBytesSend) == sizeBytesSend) {
uPortLog("U_SECURITY_TEST: %d byte(s) sent via TCP @%d ms,"
" now receiving...\n", sizeBytesSend,
(int32_t) uPortGetTickTimeMs());
// Give the data time to come back
for (size_t z = 20; (z > 0) &&
(sizeBytesReceive < sizeBytesSend); z--) {
uPortTaskBlock(1000);
}
if (sizeBytesReceive < sizeBytesSend) {
uPortLog("U_SECURITY_TEST: after sending a total"
" of %d byte(s), receiving failed.\n",
sizeBytesSend + offset);
//lint -e(506, 774) Suppress constant Boolean always
// evaluates to false
U_PORT_TEST_ASSERT(false);
}
// Check it
//lint -e(668) Suppress possible use of NULL pointer
// for gpBuffer
if (memcmp(gpBuffer, gSendData + offset, sizeBytesReceive) != 0) {
uPortLog("U_SECURITY_TEST: expected received data contents"
" not what was expected.\n");
uPortLog("U_SECURITY_TEST: expected \"%*s\", received"
" \"%*s\".\n",
sizeBytesSend, gSendData + offset,
sizeBytesReceive, gpBuffer);
//lint -e(506, 774) Suppress constant Boolean always
// evaluates to false
U_PORT_TEST_ASSERT(false);
}
offset += sizeBytesSend;
}
y++;
}
sizeBytesSend = offset;
if (sizeBytesSend < U_SECURITY_TEST_C2C_SMALL_CHUNK_TOTAL_SIZE) {
uPortLog("U_SECURITY_TEST: only %d byte(s) sent after %d ms.\n",
sizeBytesSend,
(int32_t) (uPortGetTickTimeMs() - startTimeMs));
//lint -e(506, 774) Suppress constant Boolean always evaluates to false
U_PORT_TEST_ASSERT(false);
}
// As a sanity check, make sure that
// U_SECURITY_TEST_TASK_STACK_SIZE_BYTES
// was big enough
y = uPortEventQueueStackMinFree(gEventQueueHandle);
uPortLog("U_SOCK_TEST: event queue task had %d byte(s)"
" free at a minimum.\n", y);
U_PORT_TEST_ASSERT((y > 0) ||
(y == (int32_t) U_ERROR_COMMON_NOT_SUPPORTED));
// Close the socket
U_PORT_TEST_ASSERT(uSockClose(gDescriptor) == 0);
uSockCleanUp();
// Close the event queue
U_PORT_TEST_ASSERT(uPortEventQueueClose(gEventQueueHandle) == 0);
gEventQueueHandle = -1;
free(gpBuffer);
uPortLog("U_SECURITY_TEST: closing the session again...\n");
U_PORT_TEST_ASSERT(uSecurityC2cClose(networkHandle) == 0);
LOG_OFF;
LOG_PRINT;
}
#if !defined(__XTENSA__) && !U_CFG_OS_CLIB_LEAKS
// Check for memory leaks, if the platform isn't leaky
// This if'ed out for ESP32 (xtensa compiler) as
// the way it's heap work means that if blocks are
// freed in a different order to they were allocated and
// any one of those blocks remains allocated (which sockets
// will do here as we allocate two mutexes when they are first
// used) then the amount of heap remaining is not possible
// to calculate with any degree of confidence (a four byte
// variant due to block length tracking in their
// implementation).
heapUsed -= uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: during this part of the test %d"
" byte(s) were lost to sockets initialisation;"
" we have leaked %d byte(s).\n",
heapSockInitLoss + heapXxxSockInitLoss,
heapUsed - (heapSockInitLoss + heapXxxSockInitLoss));
// heapUsed < 0 for the Zephyr case where the heap can look
// like it increases (negative leak)
U_PORT_TEST_ASSERT(heapUsed <= heapSockInitLoss + heapXxxSockInitLoss);
#else
(void) heapUsed;
(void) heapSockInitLoss;
(void) heapXxxSockInitLoss;
#endif
}
}
}
#endif // U_CFG_TEST_SECURITY_C2C_TE_SECRET
/** Test security sealing, requires a network connection.
* Note: this test will *only* attempt a seal if
* U_CFG_SECURITY_DEVICE_PROFILE_UID is defined to contain
* a valid device profile UID string (without quotes).
*/
U_PORT_TEST_FUNCTION("[security]", "securitySeal")
{
int32_t networkHandle;
int32_t heapUsed;
int32_t z;
char serialNumber[U_SECURITY_SERIAL_NUMBER_MAX_LENGTH_BYTES];
char rotUid[U_SECURITY_ROOT_OF_TRUST_UID_LENGTH_BYTES];
// Do the standard preamble to make sure there is
// a network underneath us
stdPreamble();
// Repeat for all bearers
for (size_t x = 0; x < gUNetworkTestCfgSize; x++) {
networkHandle = gUNetworkTestCfg[x].handle;
if (networkHandle >= 0) {
// Get the initial-ish heap
heapUsed = uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: checking if u-blox security"
" is supported by handle %d...\n", networkHandle);
if (uSecurityIsSupported(networkHandle)) {
uPortLog("U_SECURITY_TEST: security is supported.\n");
// Get the serial number
z = uSecurityGetSerialNumber(networkHandle, serialNumber);
U_PORT_TEST_ASSERT((z > 0) && (z < (int32_t) sizeof(serialNumber)));
uPortLog("U_SECURITY_TEST: module serial number is \"%s\".\n",
serialNumber);
// Get the root of trust UID with NULL rotUid
U_PORT_TEST_ASSERT(uSecurityGetRootOfTrustUid(networkHandle, NULL) >= 0);
// Get the root of trust UID properly
U_PORT_TEST_ASSERT(uSecurityGetRootOfTrustUid(networkHandle,
rotUid) == sizeof(rotUid));
uPortLog("U_SECURITY_TEST: root of trust UID is 0x");
for (size_t y = 0; y < sizeof(rotUid); y++) {
uPortLog("%02x", rotUid[y]);
}
uPortLog(".\n");
uPortLog("U_SECURITY_TEST: waiting for bootstrap status...\n");
// Try 10 times with a wait in-between to get bootstrapped
// status
for (size_t y = 10; (y > 0) &&
!uSecurityIsBootstrapped(networkHandle); y--) {
uPortTaskBlock(5000);
}
if (uSecurityIsBootstrapped(networkHandle)) {
uPortLog("U_SECURITY_TEST: device is bootstrapped.\n");
if (!uSecurityIsSealed(networkHandle)) {
#ifdef U_CFG_SECURITY_DEVICE_PROFILE_UID
uPortLog("U_SECURITY_TEST: device is bootstrapped, performing"
" security seal with device profile UID string \"%s\""
" and serial number \"%s\"...\n",
U_PORT_STRINGIFY_QUOTED(U_CFG_SECURITY_DEVICE_PROFILE_UID),
serialNumber);
gStopTimeMs = uPortGetTickTimeMs() +
(U_SECURITY_TEST_SEAL_TIMEOUT_SECONDS * 1000);
if (uSecuritySealSet(networkHandle,
U_PORT_STRINGIFY_QUOTED(U_CFG_SECURITY_DEVICE_PROFILE_UID),
serialNumber, keepGoingCallback) == 0) {
uPortLog("U_SECURITY_TEST: device is security sealed"
" with device profile UID string \"%s\""
" and serial number \"%s\".\n",
U_PORT_STRINGIFY_QUOTED(U_CFG_SECURITY_DEVICE_PROFILE_UID),
serialNumber);
U_PORT_TEST_ASSERT(uSecurityIsSealed(networkHandle));
} else {
uPortLog("U_SECURITY_TEST: unable to security seal device.\n");
U_PORT_TEST_ASSERT(!uSecurityIsSealed(networkHandle));
//lint -e(774) Suppress always evaluates to false
U_PORT_TEST_ASSERT(false);
}
#else
uPortLog("U_SECURITY_TEST: device is bootstrapped but"
" U_CFG_SECURITY_DEVICE_PROFILE_UID is not"
" defined so no test of security sealing"
" will be performed.\n");
#endif
} else {
uPortLog("U_SECURITY_TEST: this device supports u-blox"
" security and is already security sealed, no"
" test of security sealing will be carried out.\n");
}
} else {
uPortLog("U_SECURITY_TEST: this device supports u-blox"
" security but will not bootstrap.\n");
U_PORT_TEST_ASSERT(!uSecurityIsSealed(networkHandle));
//lint -e(506, 774) Suppress constant Boolean always evaluates to false
U_PORT_TEST_ASSERT(false);
}
}
// Check for memory leaks
heapUsed -= uPortGetHeapFree();
uPortLog("U_SECURITY_TEST: we have leaked %d byte(s).\n",
heapUsed);
// heapUsed < 0 for the Zephyr case where the heap can look
// like it increases (negative leak)
U_PORT_TEST_ASSERT(heapUsed <= 0);
}
}
}
/** Test end to end encryption.
*/
U_PORT_TEST_FUNCTION("[security]", "securityE2eEncryption")
{
int32_t networkHandle;
//lint -esym(838, y) Suppress not used, which will be true
// if logging is compiled out