port security and schema to .NetStandard

This commit is contained in:
Martin Regen
2016-06-12 16:36:51 +02:00
parent 1fc531f4c5
commit de6a6d5c00
17 changed files with 188 additions and 151 deletions
+39
View File
@@ -0,0 +1,39 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Opc.Ua
{
public static class ApplicationData
{
//public static AppData ApplicationData;
public static class Current
{
public static class LocalFolder
{
public static string Path;
}
public static class LocalSettings
{
public static ApplicationDataContainer CreateContainer(string application, ApplicationDataCreateDisposition adcd)
{
return new ApplicationDataContainer();
}
}
}
}
public enum ApplicationDataCreateDisposition
{
Always = 0,
Existing = 1
}
public class ApplicationDataContainer
{
public IDictionary Values;
}
}
-3
View File
@@ -23,8 +23,5 @@ using System.Runtime.InteropServices;
[assembly: AssemblyProduct("OPC UA SDK")]
[assembly: AssemblyCopyright(AssemblyVersionInfo.Copyright)]
[assembly: ComVisible(false)]
[assembly: Guid("b59483cd-5ba9-4e53-8451-5ab7e1edd192")]
[assembly: AssemblyVersion(AssemblyVersionInfo.CurrentVersion)]
[assembly: AssemblyFileVersion(AssemblyVersionInfo.CurrentFileVersion)]
@@ -14,7 +14,7 @@ using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using Windows.Storage;
namespace Opc.Ua
{
@@ -15,9 +15,7 @@ using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Diagnostics;
using System.IO;
using Windows.Storage;
using System.Threading.Tasks;
namespace Opc.Ua
@@ -336,7 +334,9 @@ namespace Opc.Ua
if (storeType == CertificateStoreType.Windows)
{
#if TODO
store = new Opc.Ua.WindowsCertificateStore();
#endif
}
else
{
@@ -765,8 +765,8 @@ namespace Opc.Ua
return certificate;
}
#endregion
#region PInvoke Declarations
#endregion
#region PInvoke Declarations
private const string KEY_CONTAINER_NAME = "UASDKDefaultKeyContainer3";
private const string MS_STRONG_PROV_W = "Microsoft Strong Cryptographic Provider";
private const string DEFAULT_CRYPTO_PROVIDER = MS_STRONG_PROV_W;
@@ -1508,9 +1508,9 @@ namespace Opc.Ua
private const int CERT_CLOSE_STORE_FORCE_FLAG = 0x00000001;
private const int CERT_CLOSE_STORE_CHECK_FLAG = 0x00000002;
#endregion
#endregion
#region Private Methods
#region Private Methods
/// <summary>
/// Sets the parameters to suitable defaults.
/// </summary>
@@ -1800,7 +1800,7 @@ namespace Opc.Ua
}
}
#endregion
#endregion
}
}
@@ -135,7 +135,9 @@ namespace Opc.Ua
{
case CertificateStoreType.Windows:
{
store = new WindowsCertificateStore();
#if TODO
store = new WindowsCertificateStore();
#endif
break;
}
@@ -158,10 +160,10 @@ namespace Opc.Ua
t.Wait();
return store;
}
#endregion
#endregion
}
#region CertificateStoreType Class
#region CertificateStoreType Class
/// <summary>
/// The type of certificate store.
/// </summary>
@@ -177,5 +179,5 @@ namespace Opc.Ua
/// </summary>
public const string Directory = "Directory";
}
#endregion
#endregion
}
@@ -17,7 +17,6 @@ using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Security.Cryptography;
using Windows.Storage;
namespace Opc.Ua
{
@@ -81,6 +80,7 @@ namespace Opc.Ua
public async Task Open(string location)
{
bool certsInRemovableStorageRootFound = false;
#if TODO
IReadOnlyList<StorageFolder> folders = new List<StorageFolder>();
try
@@ -99,9 +99,10 @@ namespace Opc.Ua
{
// do nothing
}
#endif
lock (m_lock)
{
#if TODO
if (certsInRemovableStorageRootFound && (folders.Count > 0))
{
m_directory = new DirectoryInfo(folders[0].Path);
@@ -109,6 +110,7 @@ namespace Opc.Ua
m_privateKeySubdir = m_directory;
}
else
#endif
{
location = Utils.ReplaceSpecialFolderNames(location);
m_directory = new DirectoryInfo(location);
@@ -426,17 +428,15 @@ namespace Opc.Ua
(password == null) ? String.Empty : password,
X509KeyStorageFlags.Exportable | X509KeyStorageFlags.DefaultKeySet);
using (RSA rsa = certificate.GetRSAPrivateKey())
RSA rsa = certificate.GetRSAPrivateKey();
if (rsa != null)
{
if (rsa != null)
int inputBlockSize = rsa.KeySize / 8 - 42;
byte[] bytes1 = rsa.Encrypt(new byte[inputBlockSize], RSAEncryptionPadding.OaepSHA1);
byte[] bytes2 = rsa.Decrypt(bytes1, RSAEncryptionPadding.OaepSHA1);
if (bytes2 != null)
{
int inputBlockSize = rsa.KeySize / 8 - 42;
byte[] bytes1 = rsa.Encrypt(new byte[inputBlockSize], RSAEncryptionPadding.OaepSHA1);
byte[] bytes2 = rsa.Decrypt(bytes1, RSAEncryptionPadding.OaepSHA1);
if (bytes2 != null)
{
return certificate;
}
return certificate;
}
}
}
@@ -486,9 +486,9 @@ namespace Opc.Ua
// can't find a valid CRL.
return StatusCodes.BadCertificateRevocationUnknown;
}
#endregion
#endregion
#region Private Methods
#region Private Methods
/// <summary>
/// Reads the current contents of the directory from disk.
/// </summary>
@@ -725,9 +725,9 @@ namespace Opc.Ua
m_certificateSubdir.Refresh();
m_privateKeySubdir.Refresh();
}
#endregion
#endregion
#region Private Fields
#region Private Fields
private class Entry
{
public FileInfo CertificateFile;
@@ -735,15 +735,15 @@ namespace Opc.Ua
public FileInfo PrivateKeyFile;
public X509Certificate2 CertificateWithPrivateKey;
}
#endregion
#endregion
#region Private Fields
#region Private Fields
private object m_lock = new object();
private DirectoryInfo m_directory;
private DirectoryInfo m_certificateSubdir;
private DirectoryInfo m_privateKeySubdir;
private Dictionary<string, Entry> m_certificates;
private DateTime m_lastDirectoryCheck;
#endregion
#endregion
}
}
@@ -11,7 +11,6 @@
*/
using Windows.Storage;
namespace Opc.Ua
{
@@ -10,33 +10,32 @@
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Certificates;
using Windows.Storage.Streams;
namespace Opc.Ua
{
#if TODO
/// <summary>
/// Provides access to a simple file based certificate store.
/// </summary>
public class WindowsCertificateStore : ICertificateStore
{
#region Constructors
#region Constructors
/// <summary>
/// Initializes a store.
/// </summary>
public WindowsCertificateStore()
{
}
#endregion
#endregion
#region IDisposable Members
#region IDisposable Members
/// <summary>
/// May be called by the application to clean up resources.
/// </summary>
@@ -56,9 +55,9 @@ namespace Opc.Ua
Close();
}
}
#endregion
#endregion
#region ICertificateStore Members
#region ICertificateStore Members
/// <summary cref="ICertificateStore.Open(string)" />
/// <remarks>
/// Syntax (items enclosed in [] are optional):
@@ -271,9 +270,9 @@ namespace Opc.Ua
{
return StatusCodes.BadNotSupported;
}
#endregion
#endregion
#region Public Methods
#region Public Methods
/// <summary>
/// Returns the string representation of the store.
/// </summary>
@@ -327,9 +326,9 @@ namespace Opc.Ua
return buffer.ToString();
}
#endregion
#endregion
#region Private Methods
#region Private Methods
/// <summary>
/// Opens the certificate store.
/// </summary>
@@ -493,9 +492,9 @@ namespace Opc.Ua
location);
}
}
#endregion
#endregion
#region Public Properties
#region Public Properties
/// <summary>
/// The symbolic name for the store.
/// </summary>
@@ -535,16 +534,16 @@ namespace Opc.Ua
{
get { return m_displayName; }
}
#endregion
#endregion
#region Private Fields
#region Private Fields
private object m_lock = new object();
private string m_symbolicName;
private WindowsStoreType m_storeType;
private string m_hostName;
private string m_serviceNameOrUserSid;
private string m_displayName;
#endregion
#endregion
}
/// <summary>
@@ -572,4 +571,6 @@ namespace Opc.Ua
/// </summary>
Service
}
#endif
}
@@ -14,12 +14,11 @@ using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using Windows.ApplicationModel;
using Windows.Storage;
namespace Opc.Ua
{
@@ -28,7 +27,7 @@ namespace Opc.Ua
/// </summary>
public class ApplicationConfigurationSection
{
#region IConfigurationSectionHandler Members
#region IConfigurationSectionHandler Members
/// <summary>
/// Creates the configuration object from the configuration section.
/// </summary>
@@ -63,7 +62,7 @@ namespace Opc.Ua
reader.Dispose();
}
}
#endregion
#endregion
}
/// <summary>
/// Represents the location of a configuration file.
@@ -71,7 +70,7 @@ namespace Opc.Ua
[DataContract(Namespace = Namespaces.OpcUaConfig)]
public class ConfigurationLocation
{
#region Persistent Properties
#region Persistent Properties
/// <summary>
/// Gets or sets the relative or absolute path to the configuration file.
/// </summary>
@@ -82,11 +81,11 @@ namespace Opc.Ua
get { return m_filePath; }
set { m_filePath = value; }
}
#endregion
#endregion
#region Private Fields
#region Private Fields
private string m_filePath;
#endregion
#endregion
}
/// <summary>
@@ -94,7 +93,7 @@ namespace Opc.Ua
/// </summary>
public partial class ApplicationConfiguration
{
#region Public Methods
#region Public Methods
/// <summary>
/// Gets the file that was used to load the configuration.
/// </summary>
@@ -403,7 +402,7 @@ namespace Opc.Ua
string filePath = null;
// get the default application name from the executable file.
FileInfo file = new FileInfo(Package.Current.DisplayName);
FileInfo file = new FileInfo(/*Package.Current.DisplayName*/"TODO: Displayname");
// choose a default configuration file.
filePath = Utils.Format(
@@ -300,7 +300,7 @@ namespace Opc.Ua.Gds
/// <exclude />
[System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")]
[CollectionDataContract(Name = "ListOfApplicationRecordDataType", Namespace = Opc.Ua.Gds.Namespaces.OpcUaGdsXsd, ItemName = "ApplicationRecordDataType")]
public partial class ApplicationRecordDataTypeCollection : List<ApplicationRecordDataType>, ICloneable
public partial class ApplicationRecordDataTypeCollection : List<ApplicationRecordDataType>
{
#region Constructors
/// <summary>
+4 -1
View File
@@ -14,7 +14,6 @@ using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Windows.ApplicationModel.Background;
using System.Net;
using System.Threading.Tasks;
@@ -1686,4 +1685,8 @@ namespace Opc.Ua
private RequestQueue m_requestQueue;
#endregion
}
// TODO: implement interface
public interface IBackgroundTask
{
}
}
+13 -8
View File
@@ -14,8 +14,7 @@ using System;
using System.Text;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using Windows.Security.Cryptography;
using Windows.Storage.Streams;
using System.Security.Cryptography;
namespace Opc.Ua.Bindings
{
@@ -93,6 +92,7 @@ namespace Opc.Ua.Bindings
set { m_clientCertificate = value; }
}
/// <summary>
/// Creates a new nonce.
/// </summary>
@@ -100,9 +100,14 @@ namespace Opc.Ua.Bindings
{
byte[] bytes = new byte[GetNonceLength()];
#if TODO
RandomNumberGenerator r = new RandomNumberGenerator();
private static RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
rngCsp.GetBytes();
IBuffer buffer = CryptographicBuffer.GenerateRandom((uint) GetNonceLength());
CryptographicBuffer.CopyToByteArray(buffer, out bytes);
#endif
return bytes;
}
@@ -183,9 +188,9 @@ namespace Opc.Ua.Bindings
(actual != null) ? actual.Thumbprint : "(null)");
}
}
#endregion
#endregion
#region Asymmetric Cryptography Functions
#region Asymmetric Cryptography Functions
/// <summary>
/// Returns the length of the symmetric encryption key.
/// </summary>
@@ -1070,9 +1075,9 @@ namespace Opc.Ua.Bindings
}
}
}
#endregion
#endregion
#region Private Fields
#region Private Fields
private EndpointDescriptionCollection m_endpoints;
private MessageSecurityMode m_securityMode;
private string m_securityPolicyUri;
@@ -1081,6 +1086,6 @@ namespace Opc.Ua.Bindings
private X509Certificate2 m_serverCertificate;
private X509Certificate2 m_clientCertificate;
private bool m_uninitialized;
#endregion
#endregion
}
}
+3 -3
View File
@@ -693,14 +693,14 @@ namespace Opc.Ua.Bindings
bool useClientKeys)
{
// get the encrypting key.
SymmetricAlgorithm decryptingKey = (useClientKeys)?token.ClientEncryptor:token.ServerEncryptor;
SymmetricAlgorithm encryptingKey = (useClientKeys)?token.ClientEncryptor:token.ServerEncryptor;
if (decryptingKey == null)
if (encryptingKey == null)
{
throw ServiceResultException.Create(StatusCodes.BadSecurityChecksFailed, "Token missing symmetric key object.");
}
using (ICryptoTransform decryptor = decryptingKey.CreateDecryptor())
using (ICryptoTransform decryptor = encryptingKey.CreateDecryptor())
{
byte[] blockToDecrypt = dataToDecrypt.Array;
-1
View File
@@ -13,7 +13,6 @@
using System;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using Windows.System.Threading;
using System.Net.Sockets;
using System.Threading.Tasks;
@@ -189,7 +189,7 @@ namespace Opc.Ua.Schema.Binary
return;
}
TypeDictionary dictionary = (TypeDictionary) await Load(typeof(TypeDictionary), directive.Namespace, directive.Location);
TypeDictionary dictionary = (TypeDictionary) Load(typeof(TypeDictionary), directive.Namespace, directive.Location);
// verify namespace.
if (!String.IsNullOrEmpty(dictionary.TargetNamespace) && directive.Namespace != dictionary.TargetNamespace)
+45 -31
View File
@@ -17,8 +17,6 @@ using System.Xml.Serialization;
using System.IO;
using System.Reflection;
using System.Globalization;
using Windows.Storage;
using System.Threading.Tasks;
namespace Opc.Ua.Schema
{
@@ -155,7 +153,7 @@ namespace Opc.Ua.Schema
/// <summary>
/// Loads the dictionary from a file.
/// </summary>
protected async Task<object> Load(System.Type type, string namespaceUri, string path)
protected object Load(System.Type type, string namespaceUri, string path)
{
// check if already loaded.
if (m_loadedFiles.ContainsKey(namespaceUri))
@@ -164,12 +162,16 @@ namespace Opc.Ua.Schema
}
// check if a valid path provided.
StorageFile fileInfo = null;
FileInfo fileInfo = null;
if (!String.IsNullOrEmpty(path))
{
fileInfo = await StorageFile.GetFileFromPathAsync(path);
return LoadFile(type, path);
fileInfo = new FileInfo(path);
if (fileInfo.Exists)
{
return LoadFile(type, path);
}
}
// check if path specified in the file table.
@@ -177,30 +179,43 @@ namespace Opc.Ua.Schema
if (m_knownFiles.TryGetValue(namespaceUri, out location))
{
try
fileInfo = new FileInfo(location);
if (fileInfo.Exists)
{
fileInfo = await StorageFile.GetFileFromPathAsync(location);
return LoadFile(type, location);
}
catch (Exception)
{
// load embedded resource.
return LoadResource(type, location, null);
}
// load embedded resource.
return LoadResource(type, location, null);
}
//check for file in the same directory as the input file.
try
{
fileInfo = await StorageFile.GetFileFromPathAsync(m_inputPath + "\\" + fileInfo.Name);
return LoadFile(type, fileInfo.Path);
}
catch (Exception)
if (!String.IsNullOrEmpty(path))
{
if (!File.Exists(path))
{
// load embedded resource.
return LoadResource(type, path, null);
}
// check for file in the same directory as the input file.
FileInfo inputInfo = new FileInfo(m_inputPath);
fileInfo = new FileInfo(inputInfo.DirectoryName + "\\" + fileInfo.Name);
if (fileInfo.Exists)
{
return LoadFile(type, fileInfo.FullName);
}
// check for file in the process directory.
fileInfo = await StorageFile.GetFileFromPathAsync(Windows.Storage.ApplicationData.Current.LocalFolder + "\\" + fileInfo.Name);
return LoadFile(type, fileInfo.Path);
}
fileInfo = new FileInfo(ApplicationData.Current.LocalFolder.Path + "\\" + fileInfo.Name);
if (fileInfo.Exists)
{
return LoadFile(type, fileInfo.FullName);
}
}
throw Exception("Cannot import file '{0}' from '{1}'.", namespaceUri, path);
}
@@ -208,10 +223,9 @@ namespace Opc.Ua.Schema
/// <summary>
/// Loads a schema from a file.
/// </summary>
protected static async Task<object> LoadFile(System.Type type, string path)
protected static object LoadFile(System.Type type, string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
StreamReader reader = new StreamReader(await file.OpenStreamForReadAsync());
StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open));
try
{
@@ -283,9 +297,9 @@ namespace Opc.Ua.Schema
}
}
}
#endregion
#endregion
#region Public Methods
#region Public Methods
/// <summary>
/// Returns the schema for the specified type (returns the entire schema if null).
/// </summary>
@@ -293,12 +307,12 @@ namespace Opc.Ua.Schema
{
return null;
}
#endregion
#endregion
#region Private Fields
#region Private Fields
private string m_inputPath;
private Dictionary<string,string> m_knownFiles;
private Dictionary<string,object> m_loadedFiles;
#endregion
#endregion
}
}
+21 -42
View File
@@ -20,17 +20,14 @@ using System.Security.Cryptography.X509Certificates;
using System.Reflection;
using System.Runtime.Serialization;
using System.IO;
using Windows.Storage;
using System.Linq;
using Windows.ApplicationModel;
using Windows.Networking;
using Windows.Networking.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading.Tasks;
using System.Diagnostics;
using Windows.Networking.Connectivity;
using System.Security.Cryptography;
using System.Xml.Linq;
using System.Runtime.InteropServices;
namespace Opc.Ua
{
@@ -780,7 +777,7 @@ namespace Opc.Ua
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings.CreateContainer(applicationName, ApplicationDataCreateDisposition.Always);
return (List<string>) settings.Values["Recent File List"];
}
#if TODO
/// <summary>
/// Updates the contents of the recent file list for the application.
/// </summary>
@@ -813,7 +810,7 @@ namespace Opc.Ua
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings.CreateContainer(applicationName, ApplicationDataCreateDisposition.Always);
settings.Values["Recent File List"] = files;
}
#endif
/// <summary>
/// Truncates a file path so it can be displayed in a limited width view.
/// </summary>
@@ -850,8 +847,8 @@ namespace Opc.Ua
// format the result.
return Utils.Format("{0}...{1}", filePath.Substring(0, start+1), filePath.Substring(end));
}
#endregion
#region String, Object and Data Convienence Functions
#endregion
#region String, Object and Data Convienence Functions
private const int MAX_MESSAGE_LENGTH = 1024;
private const uint FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200;
@@ -873,16 +870,16 @@ namespace Opc.Ua
{
disposable.Dispose();
}
#if DEBUG
#if DEBUG
catch (Exception e)
{
Utils.Trace(e, "Error disposing object: {0}", disposable.GetType().Name);
}
#else
#else
catch (Exception)
{
}
#endif
#endif
}
}
@@ -928,12 +925,12 @@ namespace Opc.Ua
return (int)timeSpan.TotalMilliseconds;
}
#if TODO
public static IPAddress[] GetIPAddresses()
{
IPAddress[] addresses = null;
if (NetworkInformation.GetHostNames().Count > 0)
if (System.Net.NetworkInformation.GetHostNames().Count > 0)
{
int count = 0;
addresses = new IPAddress[NetworkInformation.GetHostNames().Count];
@@ -954,26 +951,12 @@ namespace Opc.Ua
return null;
}
public static bool HasIPAddresses(HostNameType hnt)
{
foreach (HostName localHostInfo in NetworkInformation.GetHostNames())
{
if (localHostInfo.Type == hnt)
{
return true;
}
}
return false;
}
#endif
public static async Task<IPAddress[]> GetHostAddresses(string remoteHostName)
{
IPAddress[] addresses = null;
IReadOnlyList<EndpointPair> data = null;
if (remoteHostName == GetHostName() && NetworkInformation.GetHostNames().Count > 0)
#if TODO
if (remoteHostName == GetHostName() && System.Net.NetworkInformation.GetHostNames().Count > 0)
{
addresses = GetIPAddresses();
if (addresses != null)
@@ -982,6 +965,7 @@ namespace Opc.Ua
}
}
IReadOnlyList<EndpointPair> data = null;
try
{
data = await DatagramSocket.GetEndpointPairsAsync(new HostName(remoteHostName), "0");
@@ -1002,25 +986,19 @@ namespace Opc.Ua
}
}
}
#endif
return addresses;
}
static HostName hostName;
public static string GetHostName()
{
if (hostName == null)
{
var hostNames = NetworkInformation.GetHostNames();
hostName = hostNames.FirstOrDefault(name => name.Type == HostNameType.DomainName);
}
return hostName.CanonicalName.Split('.')[0];
return null;// Environment.MachineName;
}
/// <summary>
/// Replaces the localhost domain with the current host name.
/// </summary>
/// Replaces the localhost domain with the current host name.
/// </summary>
public static string ReplaceLocalhost(string uri, string hostname = null)
{
// ignore nulls.
@@ -2322,7 +2300,7 @@ namespace Opc.Ua
{
return DateTime.Now;
}
#if TODO
/// <summary>
/// Returns the major/minor version number for an assembly formatted as a string.
/// </summary>
@@ -2340,6 +2318,7 @@ namespace Opc.Ua
PackageVersion version = Package.Current.Id.Version;
return Utils.Format("{0}.{1}", version.Build, (version.Revision << 16) + version.Build);
}
#endif
#endregion
#region Security Helper Functions