-
Notifications
You must be signed in to change notification settings - Fork 48
/
ualds.c
1980 lines (1740 loc) · 66 KB
/
ualds.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 (c) 1996-2024, OPC Foundation. All rights reserved.
The source code in this file is covered under a dual-license scenario:
- RCL: for OPC Foundation members in good-standing
- GPL V2: everybody else
RCL license terms accompanied with this source code. See http://opcfoundation.org/License/RCL/1.00/
GNU General Public License as published by the Free Software Foundation;
version 2 of the License are accompanied with this source code. See http://opcfoundation.org/License/GPLv2
This source code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
/* system includes */
#include <stdlib.h>
#include <errno.h>
#include <time.h>
/* uastack includes */
#include <opcua_serverstub.h>
#include <opcua_core.h>
#include <opcua_memory.h>
#include <opcua_string.h>
#include <opcua_pkifactory.h>
#include <opcua_endpoint.h>
/* openssl includes */
#if OPCUA_SUPPORT_PKI
#include <openssl/sha.h>
#include <openssl/ossl_typ.h>
#include <openssl/x509.h>
#endif /* OPCUA_SUPPORT_PKI */
/* local includes */
#include "config.h"
#include "ualds.h"
#include "utils.h"
#ifdef _WIN32
#include "service.h"
#endif /* _WIN32 */
#include "settings.h"
#ifdef HAVE_HDS
# include "zeroconf.h"
# include "findserversonnetwork.h"
#endif
/* local platform includes */
#include <platform.h>
#include <log.h>
#if OPCUA_SUPPORT_PKI_WIN32
# include <certstore.h>
#endif /* OPCUA_SUPPORT_PKI_WIN32 */
static int g_shutdown = 0;
static OpcUa_P_OpenSSL_CertificateStore_Config g_PKIConfig;
static OpcUa_PKIProvider g_PkiProvider;
static OpcUa_P_OpenSSL_CertificateStore_Config g_LinuxConfig;
static OpcUa_PKIProvider g_LinuxOverride;
static OpcUa_P_OpenSSL_CertificateStore_Config g_Win32Config;
static OpcUa_PKIProvider g_Win32Override;
static char g_szCertificateFile[PATH_MAX];
static char g_szCertificateKeyFile[PATH_MAX];
static char g_szCRLPath[PATH_MAX];
static char g_szTrustListPath[PATH_MAX];
static char g_szIssuerPath[PATH_MAX];
static char g_szRejectedPath[PATH_MAX];
static char g_szCertificateStorePath[PATH_MAX];
static char g_szTrustListPathOldEditedLocation[PATH_MAX];
OpcUa_ByteString g_server_certificate = OPCUA_BYTESTRING_STATICINITIALIZER;
static OpcUa_Key g_server_key;
extern OpcUa_P_TraceHook g_OpcUa_P_TraceHook;
static OpcUa_UInt32 g_StackTraceLevel = OPCUA_TRACE_OUTPUT_LEVEL_NONE;
static OpcUa_UInt32 g_numEndpoints;
static ualds_endpoint *g_pEndpoints;
static char g_szServerUri[UALDS_CONF_MAX_URI_LENGTH];
static char g_szProductUri[UALDS_CONF_MAX_URI_LENGTH];
static char g_szApplicationName[UALDS_CONF_MAX_URI_LENGTH];
static char g_szHostname[256];
static int g_ExpirationMaxAge = 600; /* 10 minutes */
static int g_bAllowLocalRegistration = 0;
static int g_MaxRejectedCertificates = 5;
static int g_MaxAgeRejectedCertificates = 1; /* days */
#ifdef _WIN32
static int g_bWin32StoreCheck = 0;
#endif /* _WIN32 */
OpcUa_Mutex g_mutex = OpcUa_Null;
int g_bEnableZeroconf = 0;
#if HAVE_OPENSSL
/* basic extensions */
#define EXT_COUNT 6
static OpcUa_Crypto_Extension ext_ent[EXT_COUNT] =
{
{"subjectAltName", 0},
{"basicConstraints", "critical, CA:FALSE"},
{"subjectKeyIdentifier", "hash"},
{"authorityKeyIdentifier", "keyid, issuer:always"},
{"keyUsage", "critical, nonRepudiation, digitalSignature, keyEncipherment, dataEncipherment, keyCertSign"},
{"extendedKeyUsage", "critical, serverAuth"}
};
#endif /* HAVE_OPENSSL */
/** event table for enum/string conversion */
static const char *g_szEndpointEventNames[] = {
"Invalid",
"SecureChannelOpened",
"SecureChannelClosed",
"SecureChannelRenewed",
"SecureChannelOpenVerifyCertificate",
"SecureChannelRenewVerifyCertificate",
"UnsupportedServiceRequested",
"RawRequest",
"DecoderError"
};
#define SECONDS_PER_YEAR 86400*365
typedef struct Status_Code_String_
{
OpcUa_StatusCode status_code;
char* status_code_str;
} Status_Code_String;
#define Status_Code_String_Count 16
static Status_Code_String status_code_to_string[Status_Code_String_Count] =
{
{ OpcUa_BadCertificateChainIncomplete, "CertificateChainIncomplete" },
{ OpcUa_BadCertificateHostNameInvalid, "CertificateHostNameInvalid" },
{ OpcUa_BadCertificateInvalid, "CertificateInvalid" },
{ OpcUa_BadCertificateIssuerRevocationUnknown, "CertificateIssuerRevocationUnknown" },
{ OpcUa_BadCertificateIssuerRevoked, "CertificateIssuerRevoked" },
{ OpcUa_BadCertificateIssuerTimeInvalid, "CertificateIssuerTimeInvalid" },
{ OpcUa_BadCertificateIssuerUseNotAllowed, "CertificateIssuerUseNotAllowed" },
{ OpcUa_BadCertificatePolicyCheckFailed, "CertificatePolicyCheckFailed" },
{ OpcUa_BadCertificateRevocationUnknown, "CertificateRevocationUnknown" },
{ OpcUa_BadCertificateRevoked, "CertificateRevoked" },
{ OpcUa_BadCertificateTimeInvalid, "CertificateTimeInvalid" },
{ OpcUa_BadCertificateUntrusted , "CertificateUntrusted" },
{ OpcUa_BadCertificateUriInvalid, "CertificateUriInvalid" },
{ OpcUa_BadCertificateUseNotAllowed, "CertificateUseNotAllowed" },
{ OpcUa_BadNoValidCertificates, "NoValidCertificates" },
{ OpcUa_BadSecurityChecksFailed, "SecurityChecksFailed" }
};
void print_failed_certificate_vaidation(OpcUa_StatusCode uaStatusCode, OpcUa_ByteString* pCertificate);
char* get_statuscode_pretty_print(OpcUa_StatusCode status_code)
{
int i = 0;
for (i = 0; i < Status_Code_String_Count; i++)
{
if (status_code_to_string[i].status_code == status_code)
{
return status_code_to_string[i].status_code_str;
}
}
return NULL;
}
/** Returns a list of configured UA LDS endpoints. */
const ualds_endpoint* ualds_endpoints(OpcUa_UInt32 *pNumEndpoints)
{
if (pNumEndpoints)
{
*pNumEndpoints = g_numEndpoints;
}
return g_pEndpoints;
}
/** Returns the lds server uri. */
const char* ualds_serveruri()
{
return g_szServerUri;
}
/** Returns the lds product uri. */
const char* ualds_producturi()
{
return g_szProductUri;
}
/** Returns the lds application name for the given locale. */
const char* ualds_applicationname(const char *szLocale)
{
/** TODO: add locale handling */
OpcUa_ReferenceParameter(szLocale);
return g_szApplicationName;
}
/* OPC UA Service forward declarations */
OpcUa_StatusCode ualds_findservers(
OpcUa_Endpoint hEndpoint,
OpcUa_Handle hContext,
OpcUa_Void **ppRequest,
OpcUa_EncodeableType *pRequestType);
OpcUa_StatusCode ualds_getendpoints(
OpcUa_Endpoint hEndpoint,
OpcUa_Handle hContext,
OpcUa_Void **ppRequest,
OpcUa_EncodeableType *pRequestType);
OpcUa_StatusCode ualds_registerserver(
OpcUa_Endpoint hEndpoint,
OpcUa_Handle hContext,
OpcUa_Void **ppRequest,
OpcUa_EncodeableType *pRequestType);
static OpcUa_StatusCode ualds_delete_security_policies();
#ifdef HAVE_HDS
OpcUa_StatusCode ualds_registerserver2(OpcUa_Endpoint hEndpoint,
OpcUa_Handle hContext,
OpcUa_Void **ppRequest,
OpcUa_EncodeableType *pRequestType);
OpcUa_StatusCode ualds_findserversonnetwork(OpcUa_Endpoint hEndpoint,
OpcUa_Handle hContext,
OpcUa_Void **ppRequest,
OpcUa_EncodeableType *pRequestType);
#endif /* HAVE_HDS */
/* OPC UA STACK Service Type configurations */
static OpcUa_ServiceType FindServersService =
{
OpcUaId_FindServersRequest,
&OpcUa_FindServersResponse_EncodeableType,
ualds_findservers,
0
};
static OpcUa_ServiceType GetEndPointsService =
{
OpcUaId_GetEndpointsRequest,
&OpcUa_GetEndpointsResponse_EncodeableType,
ualds_getendpoints,
0
};
static OpcUa_ServiceType RegisterServerService =
{
OpcUaId_RegisterServerRequest,
&OpcUa_RegisterServerResponse_EncodeableType,
ualds_registerserver,
0
};
#ifdef HAVE_HDS
static OpcUa_ServiceType RegisterServer2Service =
{
OpcUaId_RegisterServer2Request,
&OpcUa_RegisterServer2Response_EncodeableType,
ualds_registerserver2,
0
};
static OpcUa_ServiceType FindServersOnNetworkService =
{
OpcUaId_FindServersOnNetworkRequest,
&OpcUa_FindServersOnNetworkResponse_EncodeableType,
ualds_findserversonnetwork,
0
};
#endif /* HAVE_HDS */
/** Service table for EndPointOpen */
static OpcUa_ServiceType *g_ServiceTable[] =
{
&FindServersService,
&GetEndPointsService,
&RegisterServerService,
#ifdef HAVE_HDS
&RegisterServer2Service,
&FindServersOnNetworkService,
#endif /* HAVE_HDS */
0
};
static OpcUa_ServiceType *g_ServiceTableHttps[] =
{
&FindServersService,
&GetEndPointsService,
#ifdef HAVE_HDS
&FindServersOnNetworkService,
#endif /* HAVE_HDS */
0
};
/** Initializes the given \c pEndpoint structure. */
void ualds_endpoint_initialize(ualds_endpoint *pEndpoint)
{
pEndpoint->szUrl[0] = 0;
pEndpoint->nNoOfSecurityPolicies = 0;
pEndpoint->pSecurityPolicies = 0;
}
/** Cleans up all resources referenced by \c pEndpoint. */
void ualds_endpoint_clear(ualds_endpoint *pEndpoint)
{
OpcUa_UInt32 i;
if (pEndpoint->pSecurityPolicies)
{
for (i=0; i<pEndpoint->nNoOfSecurityPolicies; i++)
{
OpcUa_String_Clear(&pEndpoint->pSecurityPolicies[i].sSecurityPolicy);
if (pEndpoint->pSecurityPolicies[i].pbsClientCertificate)
{
OpcUa_ByteString_Clear(pEndpoint->pSecurityPolicies[i].pbsClientCertificate);
}
}
OpcUa_Free(pEndpoint->pSecurityPolicies);
}
}
static OpcUa_StatusCode ualds_create_security_policies()
{
OpcUa_UInt32 i, n;
int j;
char szSecurityPolicies[256] = "";
char szUrl[256] = "";
char szMessageSecurity[50] = "";
const char **szPolicyArray = 0;
const char **szModeArray = 0;
int numModes = 0;
size_t size;
OpcUa_StatusCode ret = OpcUa_Good;
int tmpInt;
int retCode = ualds_settings_begingroup("General");
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read General settings from config file.");
return OpcUa_BadConfigurationError;
}
retCode = ualds_settings_beginreadarray("Endpoints", &tmpInt);
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read number of endpoints from config file.");
return OpcUa_BadConfigurationError;
}
g_numEndpoints = tmpInt;
/* create endpoint configurastion array */
g_pEndpoints = OpcUa_Alloc(sizeof(ualds_endpoint) * g_numEndpoints);
if (g_pEndpoints == 0)
{
ualds_log(UALDS_LOG_CRIT, "Could not create endpoint configurastion array. Out of memory.");
ualds_settings_endarray();
ualds_settings_endgroup();
return OpcUa_BadOutOfMemory;
}
OpcUa_MemSet(g_pEndpoints, 0, sizeof(ualds_endpoint) * g_numEndpoints);
/* read in all endpoints configuration */
for (n=0; n<g_numEndpoints; n++)
{
retCode = ualds_settings_setarrayindex(n);
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read endpoint index from config file.");
ualds_delete_security_policies();
return OpcUa_BadConfigurationError;
}
retCode = ualds_settings_readstring("Url", g_pEndpoints[n].szUrl, UALDS_CONF_MAX_URI_LENGTH);
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read endpoint url from config file.");
ret = OpcUa_BadConfigurationError;
break;
}
replace_string(g_pEndpoints[n].szUrl, UALDS_CONF_MAX_URI_LENGTH, "[gethostname]", g_szHostname);
retCode = ualds_settings_readstring("SecurityPolicies", szSecurityPolicies, sizeof(szSecurityPolicies));
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read security policies for endpoint from config file.");
ret = OpcUa_BadConfigurationError;
break;
}
// check if there is a None secured configured. If not, it must be added manually.
char* findNoneSecured = strstr(szSecurityPolicies, "SecurityPolicy_None");
if (findNoneSecured == NULL)
{
strlcat(szSecurityPolicies, ", SecurityPolicy_None", 256);
}
g_pEndpoints[n].nNoOfSecurityPolicies = split_string(szSecurityPolicies, ',', &szPolicyArray);
if (g_pEndpoints[n].nNoOfSecurityPolicies < 1)
{
ualds_log(UALDS_LOG_ERR, "configuration error: no security policies found.");
ret = OpcUa_BadConfigurationError;
break;
}
/* allocate policy array */
size = sizeof(OpcUa_Endpoint_SecurityPolicyConfiguration) * (g_pEndpoints[n].nNoOfSecurityPolicies);
g_pEndpoints[n].pSecurityPolicies = (OpcUa_Endpoint_SecurityPolicyConfiguration*)OpcUa_Alloc((OpcUa_UInt32)size);
if (g_pEndpoints[n].pSecurityPolicies == 0)
{
/** Note: we need to cast here to non-const (void*) because the MS compiler doesn't understand,
* that this is a pointer to pointer to const data. Freeing the pointer does not modify the data,
* it only frees the array of pointers. With other compilers like GCC this works without the cast.
*/
free((void*)szPolicyArray);
szPolicyArray = 0;
ret = OpcUa_BadOutOfMemory;
break;
}
OpcUa_MemSet(g_pEndpoints[n].pSecurityPolicies, 0, size);
/* fill policy array */
for (i=0; i<g_pEndpoints[n].nNoOfSecurityPolicies; i++)
{
/* temporary store the security policy configuration name */
OpcUa_String_Initialize(&g_pEndpoints[n].pSecurityPolicies[i].sSecurityPolicy);
OpcUa_String_AttachCopy(&g_pEndpoints[n].pSecurityPolicies[i].sSecurityPolicy, (OpcUa_StringA)szPolicyArray[i]);
}
free((void*)szPolicyArray);
szPolicyArray = 0;
}
ualds_settings_endarray();
ualds_settings_endgroup();
if (OpcUa_IsGood(ret))
{
/* fill security policy information */
for (n=0; n<g_numEndpoints; n++)
{
for (i=0; i<g_pEndpoints[n].nNoOfSecurityPolicies; i++)
{
retCode = ualds_settings_begingroup(OpcUa_String_GetRawString(&g_pEndpoints[n].pSecurityPolicies[i].sSecurityPolicy));
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read security policies group from config file.");
ret = OpcUa_BadConfigurationError;
break;
}
retCode = ualds_settings_readstring("Url", szUrl, sizeof(szUrl));
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read Url from security policies group from config file.");
ret = OpcUa_BadConfigurationError;
break;
}
retCode = ualds_settings_readstring("MessageSecurity", szMessageSecurity, sizeof(szMessageSecurity));
if (retCode > 0)
{
ualds_log(UALDS_LOG_ERR, "Configuration error: Could not read MessageSecurity from security policies group from config file.");
ret = OpcUa_BadConfigurationError;
break;
}
ualds_settings_endgroup();
OpcUa_String_Clear(&g_pEndpoints[n].pSecurityPolicies[i].sSecurityPolicy);
OpcUa_String_AttachCopy(&g_pEndpoints[n].pSecurityPolicies[i].sSecurityPolicy, szUrl);
g_pEndpoints[n].pSecurityPolicies[i].uMessageSecurityModes = 0;
szModeArray = 0;
numModes = split_string(szMessageSecurity, ',', &szModeArray);
if (szModeArray == NULL)
{
return OpcUa_BadConfigurationError;
}
for (j=0; j<numModes; j++)
{
if (strcmp(szModeArray[j], "None") == 0)
{
g_pEndpoints[n].pSecurityPolicies[i].uMessageSecurityModes |= OPCUA_ENDPOINT_MESSAGESECURITYMODE_NONE;
}
else if (strcmp(szModeArray[j], "Sign") == 0)
{
g_pEndpoints[n].pSecurityPolicies[i].uMessageSecurityModes |= OPCUA_ENDPOINT_MESSAGESECURITYMODE_SIGN;
}
else if (strcmp(szModeArray[j], "SignAndEncrypt") == 0)
{
g_pEndpoints[n].pSecurityPolicies[i].uMessageSecurityModes |= OPCUA_ENDPOINT_MESSAGESECURITYMODE_SIGNANDENCRYPT;
}
else
{
ualds_log(UALDS_LOG_WARNING, "Ignored invalid message security mode '%s'.", szModeArray[j]);
}
}
if (szModeArray)
{
/* see note above */
free((void*)szModeArray);
szModeArray = 0;
}
}
}
}
return ret;
}
static OpcUa_StatusCode ualds_delete_security_policies()
{
OpcUa_UInt32 i;
if (g_pEndpoints)
{
for (i=0; i<g_numEndpoints; i++)
{
ualds_endpoint_clear(&g_pEndpoints[i]);
}
OpcUa_Free(g_pEndpoints);
g_pEndpoints = 0;
g_numEndpoints = 0;
}
return OpcUa_Good;
}
static void ualds_datetime_from_time_t(time_t t, OpcUa_DateTime *pDate)
{
OpcUa_UInt64 tmp = t;
tmp += UINT64_C(11644473600);
tmp *= 10000000;
pDate->dwHighDateTime = tmp >> 32;
pDate->dwLowDateTime = (OpcUa_UInt32)tmp;
}
#if HAVE_OPENSSL
static OpcUa_StatusCode ualds_create_selfsigned_certificates(OpcUa_Handle hCertificateStore)
{
OpcUa_StatusCode ret = OpcUa_Good;
OpcUa_CryptoProvider crypto;
OpcUa_Int32 serial = (OpcUa_Int32)time(0);
OpcUa_Crypto_NameEntry NameEntries[7];
OpcUa_UInt numNameEntries = 7;
OpcUa_Certificate pCert = OPCUA_BYTESTRING_STATICINITIALIZER;
OpcUa_Key pubKey, prvKey;
char szSubjectAltName[256] = {0};
char szCommonName[50] = {0};
char szOrganization[50] = {0};
char szOrganizationUnit[50] = {0};
char szLocality[50] = {0};
char szState[50] = {0};
char szCountry[5] = {0};
int i = 0;
UALDS_FILE* f;
UALDS_UNUSED(hCertificateStore);
ret = OpcUa_CryptoProvider_Create(OpcUa_SecurityPolicy_Basic128Rsa15, &crypto);
OpcUa_ReturnErrorIfBad(ret);
OpcUa_Key_Initialize(&pubKey);
OpcUa_Key_Initialize(&prvKey);
ret = OpcUa_Crypto_GenerateAsymmetricKeypair(
&crypto,
OpcUa_Crypto_Rsa_Id,
2048,
&pubKey,
&prvKey
);
OpcUa_GotoErrorIfBad(ret);
ualds_settings_begingroup("CertificateInfo");
ualds_settings_readstring("CommonName", szCommonName, sizeof(szCommonName));
ualds_settings_readstring("Organization", szOrganization, sizeof(szOrganization));
ualds_settings_readstring("OrganizationUnit", szOrganizationUnit, sizeof(szOrganizationUnit));
ualds_settings_readstring("Locality", szLocality, sizeof(szLocality));
ualds_settings_readstring("State", szState, sizeof(szState));
ualds_settings_readstring("Country", szCountry, sizeof(szCountry));
ualds_settings_endgroup();
i = 0;
if (strlen(szOrganization) > 0) {
NameEntries[i].key = "O"; /* Organization */
NameEntries[i++].value = szOrganization;
}
if (strlen(szOrganizationUnit) > 0) {
NameEntries[i].key = "OU"; /* Organization Unit */
NameEntries[i++].value = szOrganizationUnit;
}
if (strlen(szLocality) > 0) {
NameEntries[i].key = "L"; /* Locality */
NameEntries[i++].value = szLocality;
}
if (strlen(szState) > 0) {
NameEntries[i].key = "ST"; /* State */
NameEntries[i++].value = szState;
}
if (strlen(szCountry) > 0) {
NameEntries[i].key = "C"; /* Country */
NameEntries[i++].value = szCountry;
}
if (strlen(szCommonName) > 0) {
NameEntries[i].key = "CN"; /* Common Name */
NameEntries[i++].value = szCommonName;
}
if (strlen(g_szHostname) > 0) {
NameEntries[i].key = "DC"; /* Domain Component */
NameEntries[i++].value = g_szHostname;
}
numNameEntries = i;
snprintf(szSubjectAltName, sizeof(szSubjectAltName), "URI:%s, DNS:%s", g_szServerUri, g_szHostname);
replace_string(szSubjectAltName, sizeof(szSubjectAltName), "[gethostname]", g_szHostname);
ext_ent[0].value = szSubjectAltName;
ret = OpcUa_Crypto_CreateCertificate(
&crypto,
serial,
3 * SECONDS_PER_YEAR,
NameEntries,
numNameEntries,
pubKey,
ext_ent,
EXT_COUNT,
OPCUA_P_SHA_256,
prvKey,
&pCert);
OpcUa_GotoErrorIfBad(ret);
f = ualds_platform_fopen(g_szCertificateFile, "wb");
if (f != NULL)
{
ualds_platform_fwrite(pCert.Data, 1, pCert.Length, f);
ualds_platform_fclose(f);
}
else
{
ualds_log(UALDS_LOG_ERR, "ualds_create_selfsigned_certificates: Cloud not create self-signed certificate file. \"%s\"!", g_szCertificateFile);
}
f = ualds_platform_fopen(g_szCertificateKeyFile, "wb");
if (f != NULL)
{
ualds_platform_fwrite(prvKey.Key.Data, 1, prvKey.Key.Length, f);
ualds_platform_fclose(f);
}
else
{
ualds_log(UALDS_LOG_ERR, "ualds_create_selfsigned_certificates: Cloud not create self-signed certificate file. \"%s\"!", g_szCertificateKeyFile);
}
Error:
OpcUa_CryptoProvider_Delete(&crypto);
OpcUa_ByteString_Clear(&pCert);
OpcUa_Key_Clear(&prvKey);
OpcUa_Key_Clear(&pubKey);
return ret;
}
#endif /* HAVE_OPENSSL */
#ifdef _WIN32
static OpcUa_StatusCode ualds_override_validate_certificate(
struct _OpcUa_PKIProvider* pPKI,
OpcUa_ByteString* pCertificate,
OpcUa_Void* pCertificateStore,
OpcUa_Int* pValidationCode)
{
OpcUa_StatusCode uStatus = g_PkiProvider.ValidateCertificate(pPKI, pCertificate, pCertificateStore, pValidationCode);
if (uStatus == OpcUa_BadCertificateUntrusted && g_bAllowLocalRegistration)
{
ualds_log(UALDS_LOG_DEBUG, "ualds_override_validate_certificate: Ignoring BadCertificateUntrusted error, because AllowLocalRegistration is set to yes.");
uStatus = OpcUa_Good;
}
// Certificate store paths have changed at some point.
// Make a check using the old standard paths, for backward compatibility
if (uStatus == OpcUa_BadCertificateUntrusted)
{
OpcUa_StatusCode uStatusVerify = ualds_verify_cert_old_default_location(pCertificate, g_szCRLPath, g_szRejectedPath, pValidationCode);
if (OpcUa_IsGood(uStatusVerify))
{
ualds_log(UALDS_LOG_DEBUG, "Verifying certificate in old default store succeeded.");
uStatus = OpcUa_Good;
}
}
// Certificate store paths have changed at some point.
// Make a check using the old edited paths, for backward compatibility
if (uStatus == OpcUa_BadCertificateUntrusted)
{
OpcUa_StatusCode uStatusVerify = ualds_verify_cert_old_edited_location(pCertificate, g_szCRLPath, g_szRejectedPath, g_szTrustListPathOldEditedLocation, pValidationCode);
if (OpcUa_IsGood(uStatusVerify))
{
ualds_log(UALDS_LOG_DEBUG, "Verifying certificate in old edited store succeeded.");
uStatus = OpcUa_Good;
}
}
#if OPCUA_SUPPORT_PKI_WIN32
if (uStatus == OpcUa_BadCertificateUntrusted && g_bWin32StoreCheck)
{
OpcUa_StatusCode uStatusVerify = ualds_verify_cert_win32(pCertificate);
if (OpcUa_IsGood(uStatusVerify))
{
ualds_log(UALDS_LOG_DEBUG, "Verifying certificate in windows store succeeded.");
uStatus = OpcUa_Good;
}
}
#endif /* OPCUA_SUPPORT_PKI_WIN32 */
if (OpcUa_IsBad(uStatus))
{
print_failed_certificate_vaidation(uStatus, pCertificate);
}
return uStatus;
}
#else
static OpcUa_StatusCode ualds_override_validate_certificate(
struct _OpcUa_PKIProvider *pPKI,
OpcUa_ByteString *pCertificate,
OpcUa_Void *pCertificateStore,
OpcUa_Int *pValidationCode)
{
OpcUa_StatusCode uStatus = g_PkiProvider.ValidateCertificate(pPKI, pCertificate, pCertificateStore, pValidationCode);
if (uStatus == OpcUa_BadCertificateUntrusted && g_bAllowLocalRegistration)
{
ualds_log(UALDS_LOG_DEBUG, "ualds_override_validate_certificate: Ignoring BadCertificateUntrusted error, because AllowLocalRegistration is set to yes.");
uStatus = OpcUa_Good;
}
if (OpcUa_IsBad(uStatus))
{
print_failed_certificate_vaidation(uStatus, pCertificate);
}
return uStatus;
}
#endif /* _WIN32 */
static OpcUa_StatusCode ualds_load_certificate(OpcUa_Handle hCertificateStore)
{
OpcUa_InitializeStatus(OpcUa_Module_Server, "ualds_load_certificate");
/* load DER encoded server certificate */
uStatus = g_PkiProvider.LoadCertificate(
&g_PkiProvider,
g_szCertificateFile,
hCertificateStore,
&g_server_certificate);
if (OpcUa_IsBad(uStatus))
{
ualds_log(UALDS_LOG_ERR, "Failed to load server certificate \"%s\"! (0x%08X)", g_szCertificateFile, uStatus);
OpcUa_GotoError;
}
OpcUa_Key_Initialize(&g_server_key);
/* load DER encoded server certificate private key */
uStatus = g_PkiProvider.LoadPrivateKeyFromFile(
g_szCertificateKeyFile,
OpcUa_Crypto_Encoding_DER,
OpcUa_Null,
OpcUa_Crypto_KeyType_Rsa_Private,
&g_server_key);
if (OpcUa_IsBad(uStatus))
{
/* load PEM encoded server certificate private key */
uStatus = g_PkiProvider.LoadPrivateKeyFromFile(
g_szCertificateKeyFile,
OpcUa_Crypto_Encoding_PEM,
OpcUa_Null,
OpcUa_Crypto_KeyType_Rsa_Private,
&g_server_key);
}
if (OpcUa_IsBad(uStatus))
{
ualds_log(UALDS_LOG_ERR, "Failed to load server private key \"%s\"! (0x%08X)", g_szCertificateKeyFile, uStatus);
OpcUa_GotoError;
}
OpcUa_ReturnStatusCode;
OpcUa_BeginErrorHandling;
OpcUa_ByteString_Clear(&g_server_certificate);
OpcUa_Key_Clear(&g_server_key);
OpcUa_FinishErrorHandling;
}
static OpcUa_StatusCode ualds_security_initialize()
{
OpcUa_Handle hCertificateStore = OpcUa_Null;
char szValue[10];
OpcUa_InitializeStatus(OpcUa_Module_Server, "ualds_security_initialize");
ualds_settings_begingroup("PKI");
int reCreateOwnCertificateOnError = 0;
int reCreateOwnCertificateOnTimeInvalid = 0;
int certificateNotAfterOffset = 0;
UALDS_SETTINGS_READSTRING(CertificateStorePath);
if (g_szCertificateStorePath[0] == 0)
{
ualds_log(UALDS_LOG_WARNING, "Certificate store path (Section: 'PKI', Key: 'CertificateStorePath') is not set in the settings file!");
}
int szCertificateStorePathLen = strlen(g_szCertificateStorePath);
// 50 characters are enough to complete the paths to subfolders. The subfolder structure is fixed.
if (szCertificateStorePathLen > PATH_MAX - 50)
{
ualds_log(UALDS_LOG_WARNING, "Certificate store path is too long!");
uStatus = OpcUa_Bad;
OpcUa_GotoError;
}
//check if path ends with dir separator
char* directory_separator = __ualds_plat_path_sep;
if (szCertificateStorePathLen > 0)
{
if (g_szCertificateStorePath[szCertificateStorePathLen - 1] != *directory_separator)
{
strlcat(g_szCertificateStorePath, directory_separator, PATH_MAX);
}
}
if (ualds_platform_mkpath(g_szCertificateStorePath) != 0)
{
g_szCertificateStorePath[0] = 0;
ualds_platform_getcwd(g_szCertificateStorePath, sizeof(g_szCertificateStorePath));
strlcat(g_szCertificateStorePath, __ualds_plat_path_sep "pki" __ualds_plat_path_sep, PATH_MAX);
ualds_log(UALDS_LOG_ALERT, "Failed to create certificate store path - using %s as path...", g_szCertificateStorePath);
}
else
{
ualds_log(UALDS_LOG_NOTICE, "Using certificate store at %s...", g_szCertificateStorePath);
}
// The folder structure of the CertificateStore is specified in OPC-UA Spec 1.03, Part 12, Table 48
strlcpy(g_szCertificateFile, g_szCertificateStorePath, PATH_MAX);
strlcat(g_szCertificateFile, "own" __ualds_plat_path_sep "certs" __ualds_plat_path_sep, PATH_MAX);
ualds_platform_mkpath(g_szCertificateFile);
strlcat(g_szCertificateFile, "ualdscert.der", PATH_MAX);
strlcpy(g_szCertificateKeyFile, g_szCertificateStorePath, PATH_MAX);
strlcat(g_szCertificateKeyFile, "own" __ualds_plat_path_sep "private" __ualds_plat_path_sep, PATH_MAX);
ualds_platform_mkpath(g_szCertificateKeyFile);
strlcat(g_szCertificateKeyFile, "ualdskey.nopass.pem", PATH_MAX);
strlcpy(g_szTrustListPath, g_szCertificateStorePath, PATH_MAX);
strlcat(g_szTrustListPath, "trusted" __ualds_plat_path_sep "certs" __ualds_plat_path_sep, PATH_MAX);
ualds_platform_mkpath(g_szTrustListPath);
strlcpy(g_szCRLPath, g_szCertificateStorePath, PATH_MAX);
strlcat(g_szCRLPath, "trusted" __ualds_plat_path_sep "crl" __ualds_plat_path_sep, PATH_MAX);
ualds_platform_mkpath(g_szCRLPath);
strlcpy(g_szRejectedPath, g_szCertificateStorePath, PATH_MAX);
strlcat(g_szRejectedPath, "rejected" __ualds_plat_path_sep "certs" __ualds_plat_path_sep, PATH_MAX);
ualds_platform_mkpath(g_szRejectedPath);
strlcpy(g_szIssuerPath, g_szCertificateStorePath, PATH_MAX);
strlcat(g_szIssuerPath, "issuer" __ualds_plat_path_sep "certs" __ualds_plat_path_sep, PATH_MAX);
ualds_platform_mkpath(g_szIssuerPath);
ualds_settings_readstring("TrustListPath", g_szTrustListPathOldEditedLocation, PATH_MAX);
#ifdef _WIN32
if (ualds_settings_readstring("Win32StoreCheck", szValue, sizeof(szValue)) == 0)
{
if (strcmp(szValue, "yes") == 0)
{
#if OPCUA_SUPPORT_PKI_WIN32
ualds_log(UALDS_LOG_DEBUG, "Win32StoreCheck is enabled.");
g_bWin32StoreCheck = 1;
#else /* OPCUA_SUPPORT_PKI_WIN32 */
ualds_log(UALDS_LOG_ERR, "Could not enable Win32StoreCheck because UaStack was built without OPCUA_SUPPORT_PKI_WIN32.");
#endif /* OPCUA_SUPPORT_PKI_WIN32 */
}
}
#endif /* _WIN32 */
/* Check if we should re-create the own certificate if we found an error */
if (ualds_settings_readstring("ReCreateOwnCertificateOnError", szValue, sizeof(szValue)) == 0)
{
if (strcmp(szValue, "yes") == 0)
{
ualds_log(UALDS_LOG_INFO, "ReCreateOwnCertificateOnError is enabled.");
reCreateOwnCertificateOnError = 1;
}
}
/* Check if we should re-create the own certificate if its time is not valid */
if (ualds_settings_readstring("ReCreateOwnCertificateOnTimeInvalid", szValue, sizeof(szValue)) == 0)
{
if (strcmp(szValue, "yes") == 0)
{
ualds_log(UALDS_LOG_INFO, "ReCreateOwnCertificateOnTimeInvalid is enabled.");
reCreateOwnCertificateOnTimeInvalid = 1;
}
int certificateNotAfterOffsetTemp;
if (ualds_settings_readint("CertificateNotAfterOffset", &certificateNotAfterOffsetTemp) == 0)
{
if (certificateNotAfterOffsetTemp >= 0)
{
certificateNotAfterOffset = certificateNotAfterOffsetTemp;
}
}
}
ualds_settings_endgroup();
#if HAVE_OPENSSL
g_PKIConfig.PkiType = OpcUa_OpenSSL_PKI;
g_PKIConfig.CertificateTrustListLocation = g_szTrustListPath;
g_PKIConfig.CertificateRevocationListLocation = g_szCRLPath;
g_PKIConfig.CertificateUntrustedListLocation = g_szRejectedPath;
g_PKIConfig.Flags = OPCUA_P_PKI_OPENSSL_USE_DEFAULT_CERT_CRL_LOOKUP_METHOD;
g_PKIConfig.Override = OpcUa_Null;
uStatus = OpcUa_PKIProvider_Create(&g_PKIConfig, &g_PkiProvider);
OpcUa_GotoErrorIfBad(uStatus);
uStatus = g_PkiProvider.OpenCertificateStore(&g_PkiProvider, &hCertificateStore);
if (OpcUa_IsBad(uStatus))
{
ualds_log(UALDS_LOG_ERR, "Failed to open certificate store! (0x%08X)", uStatus);
OpcUa_GotoError;
}
/* create self-signed certificates if no certificates are provided. */
if (ualds_platform_fileexists(g_szCertificateFile) == 0 ||
ualds_platform_fileexists(g_szCertificateKeyFile) == 0)
{
ualds_create_selfsigned_certificates(hCertificateStore);
}
else
{
if (reCreateOwnCertificateOnError || reCreateOwnCertificateOnTimeInvalid)
{
int reCreateCert = 0;
/* try to load certificate and check domain name */
/* loads the server certificate */
uStatus = ualds_load_certificate(hCertificateStore);
if (OpcUa_IsBad(uStatus))
{
ualds_log(UALDS_LOG_ERR, "Failed to load server certificate! (0x%08X)", uStatus);
reCreateCert = 1;
}
else
{
if (reCreateOwnCertificateOnError)
{
OpcUa_ByteString pSubjectDNS;
uStatus = g_PkiProvider.ExtractCertificateData(&g_server_certificate, NULL, NULL, NULL, NULL, &pSubjectDNS, NULL, NULL, NULL);
if (OpcUa_IsGood(uStatus))
{
if (strcmp(pSubjectDNS.Data, g_szHostname) != 0)
{
ualds_log(UALDS_LOG_ERR, "Server certificate DNS entry (%s) and current hostname (%s) is NOT the same!", pSubjectDNS.Data, g_szHostname);
reCreateCert = 1;
}
}
else
{
ualds_log(UALDS_LOG_ERR, "Failed to extract server certificate DNS subject! (0x%08X)", uStatus);
reCreateCert = 1;
}
OpcUa_ByteString_Clear(&pSubjectDNS);
}
if (reCreateOwnCertificateOnTimeInvalid)
{
X509* pX509Cert = OpcUa_Null;
OpcUa_ByteString* pCertificate = &g_server_certificate;
const unsigned char* p = pCertificate->Data;
if ((pX509Cert = d2i_X509((X509**)OpcUa_Null, &p, pCertificate->Length)))
{
const ASN1_TIME *before = X509_get_notBefore(pX509Cert); // internal pointer which must not be freed up
const ASN1_TIME *after = X509_get_notAfter(pX509Cert); // internal pointer which must not be freed up
time_t timeCurrent;
time(&timeCurrent);
time_t timeOffset = 60 * 60 * 24 * certificateNotAfterOffset;
time_t timeCurrentWithOffset = timeCurrent + timeOffset;
if (X509_cmp_time(before, &timeCurrent) >= 0) {
ualds_log(UALDS_LOG_ERR, "LDS cert is not yet valid. Recreating.");
reCreateCert = 1;
}
if (X509_cmp_time(after, &timeCurrentWithOffset) <= 0) {