Skip to content

Commit

Permalink
Feat/chain (#84)
Browse files Browse the repository at this point in the history
* validating chain

* refactor after chain

* split dps and hub certs

* skip chain test

* import chain

* use gw in rido

Co-authored-by: rido-min <[email protected]>
  • Loading branch information
ridomin and rido-min authored Nov 9, 2022
1 parent 2b35267 commit 461a949
Show file tree
Hide file tree
Showing 26 changed files with 610 additions and 184 deletions.
1 change: 1 addition & 0 deletions docs/ConnectionSettings.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Connection settings can be established using the API or parsing a connection str
- `TcpPort` Sets the TCP port for the MQTT connection, defaults to `8883`
- `UseTls` Enable/Disable Server TLS connection, defaults to `true`
- `CaFile` Path to the CA certificate required to stablish the TLS session
- `GatewayHostName` Allos to connect to IoT Hub through a IoTEdge ($edgeHub) gateway (aka Transparent Gateway)

## Sample Connection Strings

Expand Down
2 changes: 1 addition & 1 deletion samples/iothub-sample/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@
}
},
"ConnectionStrings": {
"cs": "HostName=ridofree.azure-devices.net;DeviceId=leaf02;SharedAccessKey=+icdXc8+XlxlggkOXdpaK7lacuJHOKqdwok8ClkFWFY=;GatewayHostName=localhost;CaFile=c:/certs/localhost/ca.pem"
"cs": "HostName=rido.azure-devices.net;DeviceId=mm01-gw;SharedAccessKey=rU6G8HxfDyegp+/zj9spppPkSsKWok/+w4/5Usjj78Y=;GatewayHostName=localhost;CaFile=C:/certs/RidoFY23CA/RidoFY23CA.pem"
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using MQTTnet.Client;
using System.Net.NetworkInformation;
using System.Security.Cryptography.X509Certificates;

namespace MQTTnet.Extensions.MultiCloud.Connections;
Expand All @@ -12,6 +13,8 @@ internal static MqttClientOptionsBuilder WithAzureIoTHubCredentials(this MqttCli
{
hostName = cs.GatewayHostName;
}

builder.WithTcpServer(hostName, cs.TcpPort);
if (cs?.Auth == AuthType.Sas)
{
if (string.IsNullOrEmpty(cs.ModuleId))
Expand All @@ -22,8 +25,9 @@ internal static MqttClientOptionsBuilder WithAzureIoTHubCredentials(this MqttCli
{
cs.ClientId = $"{cs.DeviceId}/{cs.ModuleId}";
}

builder.WithTlsSettings(cs);
return builder.WithAzureIoTHubCredentialsSas(hostName, cs.DeviceId!, cs.ModuleId!, cs.HostName!, cs.SharedAccessKey!, cs.ModelId!, cs.SasMinutes, cs.TcpPort);
return builder.WithAzureIoTHubCredentialsSas(hostName, cs.DeviceId!, cs.ModuleId!, cs.HostName!, cs.SharedAccessKey!, cs.ModelId!, cs.SasMinutes);
}
else if (cs?.Auth == AuthType.X509)
{
Expand All @@ -40,43 +44,32 @@ internal static MqttClientOptionsBuilder WithAzureIoTHubCredentials(this MqttCli
{
cs.DeviceId = clientId;
}

builder.WithTlsSettings(cs);
return builder.WithAzureIoTHubCredentialsX509(hostName, cert, cs.ModelId!, cs.TcpPort);
return builder.WithAzureIoTHubCredentialsX509(hostName, cs.ClientId!, cs.ModelId!);
}
else
{
throw new ApplicationException("Auth not supported: " + cs?.Auth);
}
}

public static MqttClientOptionsBuilder WithAzureIoTHubCredentialsSas(this MqttClientOptionsBuilder builder, string hostName, string deviceId, string moduleId, string audience, string sasKey, string modelId, int sasMinutes, int tcpPort)
public static MqttClientOptionsBuilder WithAzureIoTHubCredentialsSas(this MqttClientOptionsBuilder builder, string hostName, string deviceId, string moduleId, string audience, string sasKey, string modelId, int sasMinutes)
{
if (string.IsNullOrEmpty(moduleId))
string target = deviceId;
if (!string.IsNullOrEmpty(moduleId))
{
(string username, string password) = SasAuth.GenerateHubSasCredentials(hostName, deviceId, sasKey, audience, modelId, sasMinutes);
builder
.WithTcpServer(hostName, tcpPort)
.WithCredentials(username, password);
}
else
{
(string username, string password) = SasAuth.GenerateHubSasCredentials(hostName, $"{deviceId}/{moduleId}", sasKey, modelId, audience, sasMinutes);
builder
.WithTcpServer(hostName, tcpPort)
.WithCredentials(username, password);
target = $"{deviceId}/{moduleId}";
}
(string username, string password) = SasAuth.GenerateHubSasCredentials(hostName, target, sasKey, audience, modelId, sasMinutes);
builder.WithCredentials(username, password);
return builder;
}

public static MqttClientOptionsBuilder WithAzureIoTHubCredentialsX509(this MqttClientOptionsBuilder builder, string hostName, X509Certificate2 cert, string modelId, int tcpPort)
public static MqttClientOptionsBuilder WithAzureIoTHubCredentialsX509(this MqttClientOptionsBuilder builder, string hostName, string deviceId, string modelId)
{
string clientId = X509CommonNameParser.GetCNFromCertSubject(cert);

builder
.WithTcpServer(hostName, tcpPort)
.WithCredentials(new MqttClientCredentials(SasAuth.GetUserName(hostName, clientId, modelId)));
string username = SasAuth.GetUserName(hostName, deviceId, modelId);
builder.WithCredentials(username);
return builder;
}


}
26 changes: 10 additions & 16 deletions src/MQTTnet.Extensions.MultiCloud/Connections/WithTlsSettings.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using MQTTnet.Client;
using System.Diagnostics;
using System.Security;
using System.Security.Cryptography.X509Certificates;

namespace MQTTnet.Extensions.MultiCloud.Connections;
Expand All @@ -17,6 +19,10 @@ internal static MqttClientOptionsBuilder WithTlsSettings(this MqttClientOptionsB
if (!string.IsNullOrEmpty(cs.X509Key))
{
var cert = X509ClientCertificateLocator.Load(cs.X509Key);
if (cert.HasPrivateKey == false)
{
throw new SecurityException("Provided Cert Has not Private Key");
}
if (string.IsNullOrEmpty(cs.ClientId))
{
cs.ClientId = X509CommonNameParser.GetCNFromCertSubject(cert);
Expand All @@ -26,22 +32,10 @@ internal static MqttClientOptionsBuilder WithTlsSettings(this MqttClientOptionsB

if (!string.IsNullOrEmpty(cs.CaFile))
{
var caCert = new X509Certificate2(cs.CaFile);
certs.Add(caCert);
tls.CertificateValidationHandler = ea =>
{
X509Chain chain = new();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
chain.ChainPolicy.VerificationTime = DateTime.Now;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
chain.ChainPolicy.CustomTrustStore.Add(caCert);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
var x5092 = new X509Certificate2(ea.Certificate);
var res = chain.Build(x5092);
return res;
};
X509Certificate2Collection caCerts = new();
caCerts.ImportFromPemFile(cs.CaFile);
certs.AddRange(caCerts);
tls.CertificateValidationHandler = ea => X509ChainValidator.ValidateChain(ea.Certificate, cs.CaFile);
}
tls.Certificates = certs;
tls.IgnoreCertificateRevocationErrors = cs.DisableCrl;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using MQTTnet.Client;
using System.Diagnostics;
using System.Security.Cryptography.X509Certificates;

namespace MQTTnet.Extensions.MultiCloud.Connections
{
internal static class X509ChainValidator
{
internal static bool ValidateChain(X509Certificate cert, string caCertFile)
{
X509Chain chain = new();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.NoFlag;
chain.ChainPolicy.VerificationTime = DateTime.Now;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 0, 0);
X509Certificate2Collection caCerts = new();
caCerts.ImportFromPemFile(caCertFile);
chain.ChainPolicy.CustomTrustStore.AddRange(caCerts);
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
var x5092 = new X509Certificate2(cert);
var res = chain.Build(x5092);
if (res == false)
{
Trace.TraceError($"Error validating TLS chain for cert: '{cert.Subject}' issued by '{cert.Issuer}'");
Trace.TraceError($"Loaded {caCerts.Count} certs from caFile: {caCertFile} ");
caCerts.ToList().ForEach(c => Trace.TraceError(c.Subject));
chain.ChainStatus.ToList().ForEach(s => Trace.TraceError(s.StatusInformation));
}
return res;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,13 @@ public DpsConnectionFixture()
[Fact]
public async Task SasAuth()
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}

var cs = new ConnectionSettings()
{
IdScope = "0ne001F8884",
IdScope = "0ne006CCDE4",
DeviceId = "sasdpstest",
SharedAccessKey = "s7g9fIUf4mNNo1m/Ge3hGQi56ZJG9KzsZ46xL7O/rbI="
};
var connAck = await client.ConnectAsync(new MqttClientOptionsBuilder()
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithAzureDpsCredentials(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Expand All @@ -36,17 +31,28 @@ public async Task SasAuth()
[Fact]
public async Task ClientCert()
{
if (client == null)
var cs = new ConnectionSettings()
{
throw new ArgumentNullException(nameof(client));
}
IdScope = "0ne006CCDE4",
X509Key = "ca-device.pem|ca-device.key"
};
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithAzureDpsCredentials(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Assert.True(client.IsConnected);
await client.DisconnectAsync();
}

[Fact]
public async Task IntermediateCert()
{
var cs = new ConnectionSettings()
{
IdScope = "0ne001F8884",
X509Key = "ca-device.pem|ca-device.key"
IdScope = "0ne006CCDE4",
X509Key = "dev03.pem|dev03.key|1234"
};
var connAck = await client.ConnectAsync(new MqttClientOptionsBuilder()
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithAzureDpsCredentials(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,45 @@ public async Task CheckComputedConnectionSettingsWhenUsingDPS()
{
var cs = new ConnectionSettings
{
IdScope = "0ne001F8884",
IdScope = "0ne006CCDE4",
DeviceId = "testDpsDevice",
SharedAccessKey = "DFOYheu+mab5uynYpRBiIut/MqHA61EkirLJ9BBaJdE="
SharedAccessKey = "nnCC1W/tfXYjmnVWhJqp6KNk8zROrObl+I9tW/wzKTM="
};
var client = await HubDpsFactory.CreateFromConnectionSettingsAsync(cs);
Assert.True(client.IsConnected);
Assert.Equal(Environment.GetEnvironmentVariable("TestHubName"), HubDpsFactory.ComputedSettings!.HostName);
Assert.Equal("rido.azure-devices.net", HubDpsFactory.ComputedSettings!.HostName);
await client.DisconnectAsync(
new MqttClientDisconnectOptionsBuilder()
.WithReason(MqttClientDisconnectReason.NormalDisconnection)
.Build());
}


[Fact]
public async Task DpsCert()
{
var cs = new ConnectionSettings
{
IdScope = "0ne006CCDE4",
X509Key = "dpsTestDevice.pem|dpsTestDevice.key"
};
var client = await HubDpsFactory.CreateFromConnectionSettingsAsync(cs);
Assert.True(client.IsConnected);
Assert.Equal("rido.azure-devices.net", HubDpsFactory.ComputedSettings!.HostName);
await client.DisconnectAsync(
new MqttClientDisconnectOptionsBuilder()
.WithReason(MqttClientDisconnectReason.NormalDisconnection)
.Build());
}

[Fact]
public async Task CheckComputedConnectionSettingsWhenNotUsingDPS()
{
var cs = new ConnectionSettings
{
HostName = Environment.GetEnvironmentVariable("TestHubName"),
DeviceId = "testDpsDevice",
SharedAccessKey = "DFOYheu+mab5uynYpRBiIut/MqHA61EkirLJ9BBaJdE="
DeviceId = "testdevice",
SharedAccessKey = "MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA="
};
var client = await HubDpsFactory.CreateFromConnectionSettingsAsync(cs);
Assert.True(client.IsConnected);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,14 @@ public IoTHubConnectionFixture()
[Fact]
public async Task DeviceSas()
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}

var cs = new ConnectionSettings()
{
HostName = Environment.GetEnvironmentVariable("TestHubName"),
DeviceId = "testdevice",
SharedAccessKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.Empty.ToString("N")))

};
var connAck = await client.ConnectAsync(new MqttClientOptionsBuilder()
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithConnectionSettings(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Expand All @@ -38,19 +33,14 @@ public async Task DeviceSas()
[Fact]
public async Task ModuleSas()
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}

var cs = new ConnectionSettings()
{
HostName = Environment.GetEnvironmentVariable("TestHubName"),
DeviceId = "testdevice",
ModuleId = "testmodule",
SharedAccessKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(Guid.Empty.ToString("N")))
SharedAccessKey = "ScXK1VNWksAd+LuYScMyj8c/mkWtXNTQXJHDUUkHgLI="
};
var connAck = await client.ConnectAsync(new MqttClientOptionsBuilder()
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithConnectionSettings(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Expand All @@ -61,17 +51,12 @@ public async Task ModuleSas()
[Fact]
public async Task DeviceCert()
{
if (client == null)
{
throw new ArgumentNullException(nameof(client));
}

var cs = new ConnectionSettings()
{
HostName = Environment.GetEnvironmentVariable("TestHubName"),
X509Key = "ca-device.pem|ca-device.key"
};
var connAck = await client.ConnectAsync(new MqttClientOptionsBuilder()
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithConnectionSettings(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Expand All @@ -80,19 +65,30 @@ public async Task DeviceCert()
}

[Fact]
public async Task ModuleCert()
public async Task DeviceCertFromIntermediate()
{
if (client == null)
var cs = new ConnectionSettings()
{
throw new ArgumentNullException(nameof(client));
}
HostName = Environment.GetEnvironmentVariable("TestHubName"),
X509Key = "dev03.pem|dev03.key|1234"
};
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithConnectionSettings(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Assert.True(client.IsConnected);
await client.DisconnectAsync();
}

[Fact]
public async Task ModuleCert()
{
var cs = new ConnectionSettings()
{
HostName = Environment.GetEnvironmentVariable("TestHubName"),
X509Key = "ca-module.pem|ca-module.key"
};
var connAck = await client.ConnectAsync(new MqttClientOptionsBuilder()
var connAck = await client!.ConnectAsync(new MqttClientOptionsBuilder()
.WithConnectionSettings(cs)
.Build());
Assert.Equal(MqttClientConnectResultCode.Success, connAck.ResultCode);
Expand Down
Loading

0 comments on commit 461a949

Please sign in to comment.