/
Program.cs
213 lines (183 loc) · 9.25 KB
/
Program.cs
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
namespace Opc.Ua.Cloud.Commander
{
using Opc.Ua;
using Opc.Ua.Configuration;
using Serilog;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
public class Program
{
private static AzureFileStorage _storage = new AzureFileStorage();
public static async Task Main()
{
InitLogging(Directory.GetCurrentDirectory());
// create OPC UA client app
string appName = "UACloudCommander";
if (Environment.GetEnvironmentVariable("APPNAME") != null)
{
appName = Environment.GetEnvironmentVariable("APPNAME");
}
ApplicationInstance app = new ApplicationInstance
{
ApplicationName = appName,
ApplicationType = ApplicationType.Client,
ConfigSectionName = "UA.Cloud.Commander"
};
// update app name in config file
string fileContent = File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(), "UA.Cloud.Commander.Config.xml"));
fileContent = fileContent.Replace("UndefinedAppName", appName);
File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "UA.Cloud.Commander.Config.xml"), fileContent);
LoadCertsFromCloud(appName);
await app.LoadApplicationConfiguration(false).ConfigureAwait(false);
bool certOK = await app.CheckApplicationInstanceCertificate(false, 0).ConfigureAwait(false);
if (!certOK)
{
throw new Exception("Application instance certificate invalid!");
}
else
{
StoreCertsInCloud();
}
// create OPC UA cert validator
app.ApplicationConfiguration.CertificateValidator = new CertificateValidator();
app.ApplicationConfiguration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(OPCUAServerCertificateValidationCallback);
app.ApplicationConfiguration.CertificateValidator.Update(app.ApplicationConfiguration.SecurityConfiguration).GetAwaiter().GetResult();
MQTTClient methodHandlerMQTT = null;
KafkaClient methodHandlerKafka = null;
if (Environment.GetEnvironmentVariable("USE_KAFKA") != null)
{
methodHandlerKafka = new KafkaClient(app.ApplicationConfiguration);
methodHandlerKafka.Connect();
}
else
{
// connect to the MQTT broker
methodHandlerMQTT = new MQTTClient(app.ApplicationConfiguration);
methodHandlerMQTT.Connect();
}
Log.Logger.Information("UA Cloud Commander is running.");
await Task.Delay(Timeout.Infinite).ConfigureAwait(false);
}
private static void OPCUAServerCertificateValidationCallback(CertificateValidator validator, CertificateValidationEventArgs e)
{
// always trust the OPC UA server certificate
if (e.Error.StatusCode == StatusCodes.BadCertificateUntrusted)
{
e.Accept = true;
}
}
private static void InitLogging(string pathToLogFile)
{
LoggerConfiguration loggerConfiguration = new LoggerConfiguration();
#if DEBUG
loggerConfiguration.MinimumLevel.Debug();
#else
loggerConfiguration.MinimumLevel.Information();
#endif
if (!Directory.Exists(pathToLogFile))
{
Directory.CreateDirectory(pathToLogFile);
}
// set logging sinks
loggerConfiguration.WriteTo.Console();
loggerConfiguration.WriteTo.File(Path.Combine(pathToLogFile, "uacloudcommander.logfile.txt"), fileSizeLimitBytes: 1024 * 1024, rollOnFileSizeLimit: true, retainedFileCountLimit: 10);
Log.Logger = loggerConfiguration.CreateLogger();
Log.Logger.Information($"Log file is: {Path.Combine(pathToLogFile, "uacloudcommander.logfile.txt")}");
}
private static void StoreCertsInCloud()
{
// store app certs
foreach (string filePath in Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "pki", "own", "certs"), "*.der"))
{
_storage.StoreFileAsync(filePath, File.ReadAllBytesAsync(filePath).GetAwaiter().GetResult()).GetAwaiter().GetResult();
}
// store private keys
foreach (string filePath in Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "pki", "own", "private"), "*.pfx"))
{
_storage.StoreFileAsync(filePath, File.ReadAllBytesAsync(filePath).GetAwaiter().GetResult()).GetAwaiter().GetResult();
}
// store trusted certs
foreach (string filePath in Directory.EnumerateFiles(Path.Combine(Directory.GetCurrentDirectory(), "pki", "trusted", "certs"), "*.der"))
{
_storage.StoreFileAsync(filePath, File.ReadAllBytesAsync(filePath).GetAwaiter().GetResult()).GetAwaiter().GetResult();
}
}
private static void LoadCertsFromCloud(string appName)
{
try
{
// load app cert from storage
string certFilePath = _storage.FindFileAsync(Path.Combine(Directory.GetCurrentDirectory(), "pki", "own", "certs"), appName).GetAwaiter().GetResult();
byte[] certFile = _storage.LoadFileAsync(certFilePath).GetAwaiter().GetResult();
if (certFile == null)
{
Console.WriteLine("Could not load cert file, creating a new one. This means the new cert needs to be trusted by all OPC UA servers we connect to!");
}
else
{
if (!Path.IsPathRooted(certFilePath))
{
certFilePath = Path.DirectorySeparatorChar.ToString() + certFilePath;
}
if (!Directory.Exists(Path.GetDirectoryName(certFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(certFilePath));
}
File.WriteAllBytes(certFilePath, certFile);
}
// load app private key from storage
string keyFilePath = _storage.FindFileAsync(Path.Combine(Directory.GetCurrentDirectory(), "pki", "own", "private"), appName).GetAwaiter().GetResult();
byte[] keyFile = _storage.LoadFileAsync(keyFilePath).GetAwaiter().GetResult();
if (keyFile == null)
{
Console.WriteLine("Could not load key file, creating a new one. This means the new cert generated from the key needs to be trusted by all OPC UA servers we connect to!");
}
else
{
if (!Path.IsPathRooted(keyFilePath))
{
keyFilePath = Path.DirectorySeparatorChar.ToString() + keyFilePath;
}
if (!Directory.Exists(Path.GetDirectoryName(keyFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(keyFilePath));
}
File.WriteAllBytes(keyFilePath, keyFile);
}
// load trusted certs
string[] trustedcertFilePath = _storage.FindFilesAsync(Path.Combine(Directory.GetCurrentDirectory(), "pki", "trusted", "certs")).GetAwaiter().GetResult();
if (trustedcertFilePath != null)
{
foreach (string filePath in trustedcertFilePath)
{
byte[] trustedcertFile = _storage.LoadFileAsync(filePath).GetAwaiter().GetResult();
if (trustedcertFile == null)
{
Console.WriteLine("Could not load trusted cert file " + filePath);
}
else
{
string localFilePath = filePath;
if (!Path.IsPathRooted(localFilePath))
{
localFilePath = Path.DirectorySeparatorChar.ToString() + localFilePath;
}
if (!Directory.Exists(Path.GetDirectoryName(localFilePath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(localFilePath));
}
File.WriteAllBytes(localFilePath, trustedcertFile);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Cloud not load cert or private key files, creating a new ones. This means the new cert needs to be trusted by all OPC UA servers we connect to!: " + ex.Message);
}
}
}
}