Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
363 lines (301 loc) · 17.1 KB
/
Copy pathProgram.cs
File metadata and controls
363 lines (301 loc) · 17.1 KB
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
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
using nanoFramework.Networking;
using System;
using System.Diagnostics;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Resources;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
#if HAS_WIFI
using System.Device.Wifi;
#endif
namespace SecureClient
{
public class Program
{
public static void Main()
{
Debug.WriteLine("Waiting for network up and IP address...");
bool success;
CancellationTokenSource cs = new(60000);
#if HAS_WIFI
Debug.WriteLine("This expectes that there is already a previously configured WiFi connection.");
success = WifiNetworkHelper.Reconnect(requiresDateTime: true, token: cs.Token);
// If that's not the case, then uncomment the code snippet below to setup the WiFi connection
// Make sure to comment the line above
// success = WifiNetworkHelper.ConnectDhcp("<MY-SSIDS>", "<MY-WIFI-PASSWORD>", requiresDateTime: true, token: cs.Token);
#else
success = NetworkHelper.SetupAndConnectNetwork(requiresDateTime: true, token: cs.Token);
#endif
if (!success)
{
Debug.WriteLine($"Can't get a proper IP address and DateTime, error: {NetworkHelper.Status}.");
if (NetworkHelper.HelperException != null)
{
Debug.WriteLine($"Exception: {NetworkHelper.HelperException}");
}
return;
}
/////////////////////////////////////////////////////////////////////////////////////
// add certificate in PEM format (as a string in the app)
X509Certificate letsEncryptCACert = new X509Certificate(_dstRootCAX3);
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
// add certificate in CER format (as a managed resource)
X509Certificate digiCertGlobalRootCACert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.DigiCertGlobalRootCA));
/////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////
// add certificate in CER format (as a managed resource)
X509Certificate digiCertGlobalG2CACert = new X509Certificate(Resources.GetBytes(Resources.BinaryResources.DigiCert_Global_G2_Azure));
/////////////////////////////////////////////////////////////////////////////////////
// **** get host entry for How's my SSL test site
//IPHostEntry hostEntry = Dns.GetHostEntry("www.howsmyssl.com");
// **** get host entry for Global Root test site
IPHostEntry hostEntry = Dns.GetHostEntry("global-root-ca.chain-demos.digicert.com");
// **** get host entry for Azure IoT test site
//IPHostEntry hostEntry = Dns.GetHostEntry("g2cert.azure-devices.net");
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// MAKE sure your using the same URL when calling AuthenticateAsClient below ///
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// need an IPEndPoint from that one above
IPEndPoint ep = new IPEndPoint(hostEntry.AddressList[0], 443);
Debug.WriteLine("Opening socket...");
using (Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
// keep track of the operation being performed, to report it in case of failure
string operation = OperationConnecting;
try
{
Debug.WriteLine("Connecting...");
// connect socket
mySocket.Connect(ep);
Debug.WriteLine("Authenticating with server...");
operation = OperationAuthenticating;
// setup SSL stream
using (SslStream sslStream = new SslStream(mySocket))
{
///////////////////////////////////////////////////////////////////////////////////
// Authenticating using a client certificate stored in the device is possible by
// setting the UseStoredDeviceCertificate property.
//
// In practice it's equivalent to providing a client certificate in
// the 'clientCertificate' parameter when calling AuthenticateAsClient(...)
//
///////////////////////////////////////////////////////////////////////////////////
//sslStream.UseStoredDeviceCertificate = true;
///////////////////////////////////////////////////////////////////////////////////
// Authenticating the server can be handled in one of three ways:
//
// 1. By providing the root CA certificate of the server being connected to.
//
// 2. Having the target device preloaded with the root CA certificate.
//
// !! NOT SECURED !! NOT RECOMENDED !!
// 3. Forcing the authentication work-flow to NOT validate the server certificate.
//
///////////////////////////////////////////////////////////////////////////////////
// option 1
// setup authentication (add CA root certificate to the call)
// **** Let's encrypt test certificate for How's My SSL
//sslStream.AuthenticateAsClient("www.howsmyssl.com", null, letsEncryptCACert, SslProtocols.Tls11);
// **** GlobalRoot CA cert from resources
sslStream.AuthenticateAsClient("global-root-ca.chain-demos.digicert.com", null, digiCertGlobalRootCACert, SslProtocols.Tls12);
// **** DigiCert Global G2 cert from resources
//sslStream.AuthenticateAsClient("g2cert.azure-devices.net", null, digiCertGlobalG2CACert, SslProtocols.Tls12);
// option 2
// setup authentication (without providing root CA certificate)
// this requires that the trusted root CA certificates are available in the device certificate store
//sslStream.AuthenticateAsClient("www.howsmyssl.com", SslProtocols.Tls11);
//sslStream.AuthenticateAsClient("global-root-ca.chain-demos.digicert.com", SslProtocols.Tls12);
// option 3
// disable certificate validation
//sslStream.SslVerification = SslVerification.NoVerification;
//sslStream.AuthenticateAsClient("www.howsmyssl.com", SslProtocols.TLSv11);
Debug.WriteLine("SSL handshake OK!");
operation = "sending the request";
// write an HTTP GET request to receive data
byte[] buffer = Encoding.UTF8.GetBytes("GET / HTTP/1.0\r\n\r\n");
sslStream.Write(buffer, 0, buffer.Length);
Debug.WriteLine($"Wrote {buffer.Length} bytes");
operation = "reading the response";
int bytesCounter = 0;
do
{
var bufferLenght = sslStream.Length;
// if available length is 0, need to read at least 1 byte to get it started
if (bufferLenght == 0)
{
bufferLenght = 1;
}
// setup buffer to read data from socket
buffer = new byte[bufferLenght];
// trying to read from socket
int bytes = sslStream.Read(buffer, 0, buffer.Length);
bytesCounter += bytes;
if (bytes > 0)
{
// data was read!
// output as string
// mind to use only the amount of data actually read because it could be less than the requested count
Debug.Write(new String(Encoding.UTF8.GetChars(buffer, 0, bytes)));
}
}
while (sslStream.DataAvailable);
Debug.WriteLine($"Read {bytesCounter} bytes");
}
}
catch (Exception ex)
{
OutputConnectionError(ex, operation);
}
}
Thread.Sleep(Timeout.Infinite);
}
private const string OperationConnecting = "connecting";
private const string OperationAuthenticating = "authenticating with the server";
/// <summary>
/// Outputs the details of an exception thrown while communicating with the server.
/// </summary>
/// <param name="ex">The exception to output.</param>
/// <param name="operation">The operation that was being performed when the exception was thrown.</param>
private static void OutputConnectionError(Exception ex, string operation)
{
Debug.WriteLine($"** {ex.GetType().FullName} while {operation}: {ex.Message} **");
if (ex is SocketException socketException)
{
Debug.WriteLine($" socket error code {socketException.ErrorCode}");
}
else if (ex is CryptographicException cryptographicException)
{
int errorCode = cryptographicException.ErrorCode;
if (errorCode < 0)
{
// the error code is the raw mbedTLS error code
Debug.WriteLine($" mbedTLS error -0x{-errorCode:X4}");
}
else if (operation == OperationAuthenticating)
{
// when authenticating, the meaning of the error code depends on the native call that failed,
// which isn't known here: SecureClientInit (SSL context setup) or SecureConnect (TLS handshake)
// check the stack trace below to find out which one applies
Debug.WriteLine($" error code {errorCode} (0x{errorCode:X}), possible causes:");
Debug.WriteLine($" - if thrown by SecureClientInit: {GetSslErrorDescription(errorCode)}");
Debug.WriteLine($" - if thrown by SecureConnect: {GetCertificateVerifyFlags(errorCode)}");
}
else
{
Debug.WriteLine($" error code {errorCode} (0x{errorCode:X})");
}
}
else if (ex is OutOfMemoryException)
{
Debug.WriteLine(" the device may be low on heap");
}
if (ex.StackTrace != null)
{
Debug.WriteLine(ex.StackTrace);
}
}
/// <summary>
/// Gets a description of an <see cref="SslError"/> reported when setting up the SSL context.
/// </summary>
private static string GetSslErrorDescription(int errorCode)
{
switch ((SslError)errorCode)
{
case SslError.DrbgSeedFailed:
return "DrbgSeedFailed, the entropy source (hardware RNG) could not be initialised";
case SslError.ConfigDefaultsFailed:
return "ConfigDefaultsFailed, setting the TLS configuration defaults failed";
case SslError.UnsupportedProtocolVersion:
return "UnsupportedProtocolVersion, the requested TLS version is not supported on this device";
case SslError.PrivateKeyParseFailed:
return "PrivateKeyParseFailed, the private key could not be parsed";
case SslError.CertificateParseFailed:
return "CertificateParseFailed, a certificate could not be parsed";
case SslError.OwnCertConfigFailed:
return "OwnCertConfigFailed, configuring the client certificate and private key failed";
case SslError.SetupFailed:
return "SetupFailed, the SSL context setup failed";
default:
return "unknown";
}
}
/// <summary>
/// Gets the reasons for a server certificate verification failure from the <c>MBEDTLS_X509_BADCERT_*</c> flags.
/// </summary>
private static string GetCertificateVerifyFlags(int flags)
{
StringBuilder reasons = new StringBuilder();
AppendFlag(reasons, flags, 0x0001, "expired");
AppendFlag(reasons, flags, 0x0002, "revoked");
AppendFlag(reasons, flags, 0x0004, "host name doesn't match the certificate CN");
AppendFlag(reasons, flags, 0x0008, "not signed by a trusted CA");
AppendFlag(reasons, flags, 0x0040, "certificate missing");
AppendFlag(reasons, flags, 0x0080, "verification skipped");
AppendFlag(reasons, flags, 0x0100, "other");
AppendFlag(reasons, flags, 0x0200, "not valid yet (check the device date and time)");
AppendFlag(reasons, flags, 0x0800, "key usage mismatch");
AppendFlag(reasons, flags, 0x1000, "extended key usage mismatch");
AppendFlag(reasons, flags, 0x2000, "certificate type mismatch");
AppendFlag(reasons, flags, 0x4000, "signed with an unsupported hash");
AppendFlag(reasons, flags, 0x8000, "signed with an unsupported public key algorithm");
AppendFlag(reasons, flags, 0x10000, "signed with an unsupported key (curve or key size)");
return reasons.Length > 0 ? reasons.ToString() : "unknown";
}
private static void AppendFlag(StringBuilder reasons, int flags, int flag, string reason)
{
if ((flags & flag) != 0)
{
if (reasons.Length > 0)
{
reasons.Append(", ");
}
reasons.Append(reason);
}
}
// Identrust DST Root CA X3
// from https://www.identrust.com/dst-root-ca-x3
private const string _dstRootCAX3 =
@"-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y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