Esempio n. 1
0
        // Install the certificate in the given file path into the My store.
        // It will not install the certificate if it is already present in the store.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallMyCertificate(BridgeConfiguration configuration, string certificateName)
        {
            // Installing any MY certificate guarantees the certificate authority is loaded first
            InstallRootCertificate(configuration, configuration.BridgeCertificateAuthority);

            lock (s_certificateLock)
            {
                CertificateCacheEntry entry = null;
                if (s_myCertificates.TryGetValue(certificateName, out entry))
                {
                    return(entry.ThumbPrint);
                }

                string           certificateFilePath = CreateCertificateFilePath(configuration, certificateName);
                X509Certificate2 cert = new X509Certificate2();
                // "test" is currently the required password to allow exportable private keys
                cert.Import(certificateFilePath, "test", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

                bool added = AddToStoreIfNeeded(StoreName.My, StoreLocation.LocalMachine, cert);
                s_myCertificates[certificateName] = new CertificateCacheEntry
                {
                    ThumbPrint   = cert.Thumbprint,
                    AddedToStore = added
                };

                return(cert.Thumbprint);
            }
        }
Esempio n. 2
0
        // Install the certificate in the given file path into the Root store and returns its thumbprint.
        // It will not install the certificate if there is already one with the same full SubjectName present.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallRootCertificate(BridgeConfiguration configuration, string certificateName)
        {
            string certificateFilePath = CreateCertificateFilePath(configuration, certificateName);

            lock (s_certificateLock)
            {
                foreach (var pair in s_rootCertificates)
                {
                    if (string.Equals(certificateName, pair.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        return(pair.Key);
                    }
                }

                X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                X509Certificate2 cert       = new X509Certificate2(certificateFilePath);
                string           thumbprint = null;
                if (!TryFindCertificate(store, cert.SubjectName.Name, out thumbprint))
                {
                    store.Add(cert);
                    thumbprint = cert.Thumbprint;
                    s_rootCertificates[cert.Thumbprint] = certificateName;
                    Console.WriteLine("Added to root store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }
                else
                {
                    Console.WriteLine("Reusing existing root store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }

                store.Close();

                return(thumbprint);
            }
        }
Esempio n. 3
0
        internal static CertificateGenerator GetCertificateGeneratorInstance(BridgeConfiguration config)
        {
            if (s_certificateGenerator == null)
            {
                lock (s_certificateHelperLock)
                {
                    if (s_certificateGenerator == null)
                    {
                        s_certificateGenerator = new CertificateGenerator()
                        {
                            CertificatePassword = config.BridgeCertificatePassword,
                            CrlUriBridgeHost = string.Format("http://{0}:{1}", config.BridgeHost, config.BridgePort),
                            CrlUriRelativePath = s_crlUriRelativePath,
                            ValidityPeriod = config.BridgeCertificateValidityPeriod
                        };

                        // Upon creation, we want to immediately get the authority certificate and install it 
                        // as it means we are about to run a test requiring certs
                        CertificateManager.InstallCertificateToRootStore(s_certificateGenerator.AuthorityCertificate.Certificate);
                    }
                }
            }

            return s_certificateGenerator;
        }
Esempio n. 4
0
        internal static string EnsureSslPortCertificateInstalled(BridgeConfiguration configuration)
        {
            // Ensure the https certificate is installed before this endpoint resource is used
            X509Certificate2 cert = CertificateManager.CreateAndInstallLocalMachineCertificates(GetCertificateGeneratorInstance(configuration));

            // Ensure http.sys has been told to use this certificate on the https port
            CertificateManager.InstallSSLPortCertificate(cert.Thumbprint, configuration.BridgeHttpsPort);

            return cert.Thumbprint;
        }
Esempio n. 5
0
        // This ctor accepts an existing BridgeConfiguration and a set of name/value pairs.
        // It will create a new BridgeConfiguration instance that is a clone of the existing
        // one and will overwrite any properties with corresponding entries found in the name/value pairs.
        public BridgeConfiguration(BridgeConfiguration configuration, Dictionary<string, string> properties)
        {
            BridgeResourceFolder = configuration.BridgeResourceFolder;
            BridgeUrl = configuration.BridgeUrl;
            BridgeMaxIdleTimeSpan = configuration.BridgeMaxIdleTimeSpan;
            UseFiddlerUrl = configuration.UseFiddlerUrl;

            string propertyValue = null;
            if (properties.TryGetValue(BridgeResourceFolder_PropertyName, out propertyValue))
            {
                if (string.IsNullOrEmpty(propertyValue) || !Directory.Exists(propertyValue))
                {
                    throw new ArgumentException(
                        String.Format("The BridgeResourceFolder '{0}' does not exist.", propertyValue),
                        BridgeResourceFolder_PropertyName);
                }

                BridgeResourceFolder = Path.GetFullPath(propertyValue);
            }

            if (properties.TryGetValue(BridgeUrl_PropertyName, out propertyValue))
            {
                BridgeUrl = propertyValue;
            }

            if (properties.TryGetValue(BridgeMaxIdleTimeSpan_PropertyName, out propertyValue))
            {
                TimeSpan span;
                if (!TimeSpan.TryParse(propertyValue, out span))
                {
                    throw new ArgumentException(
                        String.Format("The BridgeMaxIdleTimeSpan value '{0}' is not a valid TimeSpan.", propertyValue),
                        BridgeMaxIdleTimeSpan_PropertyName);
                }

                BridgeMaxIdleTimeSpan = span;
            }

            if (properties.TryGetValue(UseFiddlerUrl_PropertyName, out propertyValue))
            {
                bool boolValue = false;
                if (!bool.TryParse(propertyValue, out boolValue))
                {
                    throw new ArgumentException(
                        String.Format("The UseFiddlerUrl value '{0}' is not a valid boolean.", propertyValue),
                        UseFiddlerUrl_PropertyName);
                }

                UseFiddlerUrl = boolValue;
            }
        }
Esempio n. 6
0
        private static string CreateCertificateFilePath(BridgeConfiguration configuration, string certificateName)
        {
            if (String.IsNullOrWhiteSpace(configuration.BridgeResourceFolder))
            {
                throw new ArgumentNullException("The BridgeResourceFolder has not been set.", "BridgeResourceFolder");
            }

            string path = Path.Combine(Path.Combine(configuration.BridgeResourceFolder, "Certificates"), certificateName);
            if (!File.Exists(path))
            {
                throw new InvalidOperationException(String.Format("The requested certificate file at {0} does not exist.",
                                                    path));
            }

            return path;
        }
Esempio n. 7
0
        private static string CreateCertificateFilePath(BridgeConfiguration configuration, string certificateName)
        {
            if (String.IsNullOrWhiteSpace(configuration.BridgeResourceFolder))
            {
                throw new ArgumentNullException("The BridgeResourceFolder has not been set.", "BridgeResourceFolder");
            }

            string path = Path.Combine(Path.Combine(configuration.BridgeResourceFolder, "Certificates"), certificateName);

            if (!File.Exists(path))
            {
                throw new InvalidOperationException(String.Format("The requested certificate file at {0} does not exist.",
                                                                  path));
            }

            return(path);
        }
Esempio n. 8
0
        // Install the certificate in the given file path into the My store.
        // It will not install the certificate if there is already one with the same full SubjectName present.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallMyCertificate(BridgeConfiguration configuration, string certificateName)
        {
            // Installing any certificate guarantees the certificate authority is loaded first
            InstallRootCertificate(configuration, configuration.BridgeCertificateAuthority);

            string certificateFilePath = CreateCertificateFilePath(configuration, certificateName);

            lock (s_certificateLock)
            {
                foreach (var pair in s_myCertificates)
                {
                    if (string.Equals(certificateName, pair.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        return(pair.Key);
                    }
                }

                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);

                X509Certificate2 cert = new X509Certificate2();
                // "test" is currently the required password to allow exportable private keys
                cert.Import(certificateFilePath, "test", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
                string thumbprint = null;
                if (!TryFindCertificate(store, cert.SubjectName.Name, out thumbprint))
                {
                    store.Add(cert);
                    thumbprint = cert.Thumbprint;
                    s_myCertificates[cert.Thumbprint] = certificateName;
                    Console.WriteLine("Added to my store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }
                else
                {
                    Console.WriteLine("Reusing existing my store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }

                store.Close();
                return(thumbprint);
            }
        }
Esempio n. 9
0
        // Install the certificate in the given file path into the Root store and returns its thumbprint.
        // It will not install the certificate if it is already present in the store.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallRootCertificate(BridgeConfiguration configuration, string certificateName)
        {
            lock (s_certificateLock)
            {
                CertificateCacheEntry entry = null;
                if (s_rootCertificates.TryGetValue(certificateName, out entry))
                {
                    return(entry.ThumbPrint);
                }

                string           certificateFilePath = CreateCertificateFilePath(configuration, certificateName);
                X509Certificate2 cert  = new X509Certificate2(certificateFilePath);
                bool             added = AddToStoreIfNeeded(StoreName.Root, StoreLocation.LocalMachine, cert);
                s_rootCertificates[certificateName] = new CertificateCacheEntry
                {
                    ThumbPrint   = cert.Thumbprint,
                    AddedToStore = added
                };

                return(cert.Thumbprint);
            }
        }
Esempio n. 10
0
        // This ctor accepts an existing BridgeConfiguration and a set of name/value pairs.
        // It will create a new BridgeConfiguration instance that is a clone of the existing
        // one and will overwrite any properties with corresponding entries found in the name/value pairs.
        public BridgeConfiguration(BridgeConfiguration configuration, Dictionary<string, string> properties)
        {
            BridgeResourceFolder = configuration.BridgeResourceFolder;
            BridgeHost = configuration.BridgeHost;
            BridgePort = configuration.BridgePort;
            BridgeHttpPort = configuration.BridgeHttpPort;
            BridgeHttpsPort = configuration.BridgeHttpsPort;
            BridgeTcpPort = configuration.BridgeTcpPort;
            BridgeWebSocketPort = configuration.BridgeWebSocketPort;
            BridgeSecureWebSocketPort = configuration.BridgeSecureWebSocketPort;
            TestRootCertificatePassword = configuration.TestRootCertificatePassword;
            TestRootCertificateValidityPeriod = configuration.TestRootCertificateValidityPeriod;
            BridgeMaxIdleTimeSpan = configuration.BridgeMaxIdleTimeSpan;
            UseFiddlerUrl = configuration.UseFiddlerUrl;

            if (properties != null)
            {
                string propertyValue = null;
                if (properties.TryGetValue(BridgeResourceFolder_PropertyName, out propertyValue))
                {
                    if (string.IsNullOrEmpty(propertyValue) || !Directory.Exists(propertyValue))
                    {
                        throw new ArgumentException(
                            String.Format("The BridgeResourceFolder '{0}' does not exist.", propertyValue),
                            BridgeResourceFolder_PropertyName);
                    }

                    BridgeResourceFolder = Path.GetFullPath(propertyValue);
                }

                if (properties.TryGetValue(BridgeHost_PropertyName, out propertyValue))
                {
                    BridgeHost = propertyValue;
                }

                if (properties.TryGetValue(TestRootCertificatePassword_PropertyName, out propertyValue))
                {
                    TestRootCertificatePassword = propertyValue;
                }

                TimeSpan validity;
                if (TryParseTimeSpanProperty(TestRootCertificateValidityPeriod_PropertyName, properties, out validity))
                {
                    TestRootCertificateValidityPeriod = validity;
                }

                int port;

                if (TryParseIntegerProperty(BridgePort_PropertyName, properties, out port))
                {
                    BridgePort = port;
                }

                if (TryParseIntegerProperty(BridgeHttpPort_PropertyName, properties, out port))
                {
                    BridgeHttpPort = port;
                }

                if (TryParseIntegerProperty(BridgeHttpsPort_PropertyName, properties, out port))
                {
                    BridgeHttpsPort = port;
                }

                if (TryParseIntegerProperty(BridgeTcpPort_PropertyName, properties, out port))
                {
                    BridgeTcpPort = port;
                }

                if (TryParseIntegerProperty(BridgeWebSocketPort_PropertyName, properties, out port))
                {
                    BridgeWebSocketPort = port;
                }

                if (TryParseIntegerProperty(BridgeSecureWebSocketPort_PropertyName, properties, out port))
                {
                    BridgeSecureWebSocketPort = port;
                }

                if (properties.TryGetValue(BridgeMaxIdleTimeSpan_PropertyName, out propertyValue))
                {
                    TimeSpan span;
                    if (!TimeSpan.TryParse(propertyValue, out span))
                    {
                        throw new ArgumentException(
                            String.Format("The BridgeMaxIdleTimeSpan value '{0}' is not a valid TimeSpan.", propertyValue),
                            BridgeMaxIdleTimeSpan_PropertyName);
                    }

                    BridgeMaxIdleTimeSpan = span;
                }

                if (properties.TryGetValue(UseFiddlerUrl_PropertyName, out propertyValue))
                {
                    bool boolValue = false;
                    if (!bool.TryParse(propertyValue, out boolValue))
                    {
                        throw new ArgumentException(
                            String.Format("The UseFiddlerUrl value '{0}' is not a valid boolean.", propertyValue),
                            UseFiddlerUrl_PropertyName);
                    }

                    UseFiddlerUrl = boolValue;
                }
            }
        }
Esempio n. 11
0
        // Install the certificate in the given file path into the Root store and returns its thumbprint.
        // It will not install the certificate if it is already present in the store.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallRootCertificate(BridgeConfiguration configuration, string certificateName)
        {
            lock (s_certificateLock)
            {
                CertificateCacheEntry entry = null;
                if (s_rootCertificates.TryGetValue(certificateName, out entry))
                {
                    return entry.ThumbPrint;
                }

                string certificateFilePath = CreateCertificateFilePath(configuration, certificateName);
                X509Certificate2 cert = new X509Certificate2(certificateFilePath);
                bool added = AddToStoreIfNeeded(StoreName.Root, StoreLocation.LocalMachine, cert);
                s_rootCertificates[certificateName] = new CertificateCacheEntry
                {
                    ThumbPrint = cert.Thumbprint,
                    AddedToStore = added
                };

                return cert.Thumbprint;
            }
        }
Esempio n. 12
0
        // Install the certificate in the given file path into the Root store and returns its thumbprint.
        // It will not install the certificate if there is already one with the same full SubjectName present.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallRootCertificate(BridgeConfiguration configuration, string certificateName)
        {
            string certificateFilePath = CreateCertificateFilePath(configuration, certificateName);

            lock (s_certificateLock)
            {
                foreach (var pair in s_rootCertificates)
                {
                    if (string.Equals(certificateName, pair.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        return pair.Key;
                    }
                }

                X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);
                X509Certificate2 cert = new X509Certificate2(certificateFilePath);
                string thumbprint = null;
                if (!TryFindCertificate(store, cert.SubjectName.Name, out thumbprint))
                {
                    store.Add(cert);
                    thumbprint = cert.Thumbprint;
                    s_rootCertificates[cert.Thumbprint] = certificateName;
                    Console.WriteLine("Added to root store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }
                else
                {
                    Console.WriteLine("Reusing existing root store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }

                store.Close();

                return thumbprint;
            }
        }
Esempio n. 13
0
        // This ctor accepts an existing BridgeConfiguration and a set of name/value pairs.
        // It will create a new BridgeConfiguration instance that is a clone of the existing
        // one and will overwrite any properties with corresponding entries found in the name/value pairs.
        public BridgeConfiguration(BridgeConfiguration configuration, Dictionary <string, string> properties)
        {
            BridgeResourceFolder            = configuration.BridgeResourceFolder;
            BridgeHost                      = configuration.BridgeHost;
            BridgePort                      = configuration.BridgePort;
            BridgeHttpPort                  = configuration.BridgeHttpPort;
            BridgeHttpsPort                 = configuration.BridgeHttpsPort;
            BridgeTcpPort                   = configuration.BridgeTcpPort;
            BridgeWebSocketPort             = configuration.BridgeWebSocketPort;
            BridgeSecureWebSocketPort       = configuration.BridgeSecureWebSocketPort;
            BridgeCertificatePassword       = configuration.BridgeCertificatePassword;
            BridgeCertificateValidityPeriod = configuration.BridgeCertificateValidityPeriod;
            BridgeMaxIdleTimeSpan           = configuration.BridgeMaxIdleTimeSpan;
            UseFiddlerUrl                   = configuration.UseFiddlerUrl;

            if (properties != null)
            {
                string propertyValue = null;
                if (properties.TryGetValue(BridgeResourceFolder_PropertyName, out propertyValue))
                {
                    if (string.IsNullOrEmpty(propertyValue) || !Directory.Exists(propertyValue))
                    {
                        throw new ArgumentException(
                                  String.Format("The BridgeResourceFolder '{0}' does not exist.", propertyValue),
                                  BridgeResourceFolder_PropertyName);
                    }

                    BridgeResourceFolder = Path.GetFullPath(propertyValue);
                }

                if (properties.TryGetValue(BridgeHost_PropertyName, out propertyValue))
                {
                    BridgeHost = propertyValue;
                }

                if (properties.TryGetValue(BridgeCertificatePassword_PropertyName, out propertyValue))
                {
                    BridgeCertificatePassword = propertyValue;
                }

                TimeSpan validity;
                if (TryParseTimeSpanProperty(BridgeCertificateValidityPeriod_PropertyName, properties, out validity))
                {
                    BridgeCertificateValidityPeriod = validity;
                }

                int port;

                if (TryParseIntegerProperty(BridgePort_PropertyName, properties, out port))
                {
                    BridgePort = port;
                }

                if (TryParseIntegerProperty(BridgeHttpPort_PropertyName, properties, out port))
                {
                    BridgeHttpPort = port;
                }

                if (TryParseIntegerProperty(BridgeHttpsPort_PropertyName, properties, out port))
                {
                    BridgeHttpsPort = port;
                }

                if (TryParseIntegerProperty(BridgeTcpPort_PropertyName, properties, out port))
                {
                    BridgeTcpPort = port;
                }

                if (TryParseIntegerProperty(BridgeWebSocketPort_PropertyName, properties, out port))
                {
                    BridgeWebSocketPort = port;
                }

                if (TryParseIntegerProperty(BridgeSecureWebSocketPort_PropertyName, properties, out port))
                {
                    BridgeSecureWebSocketPort = port;
                }

                if (properties.TryGetValue(BridgeMaxIdleTimeSpan_PropertyName, out propertyValue))
                {
                    TimeSpan span;
                    if (!TimeSpan.TryParse(propertyValue, out span))
                    {
                        throw new ArgumentException(
                                  String.Format("The BridgeMaxIdleTimeSpan value '{0}' is not a valid TimeSpan.", propertyValue),
                                  BridgeMaxIdleTimeSpan_PropertyName);
                    }

                    BridgeMaxIdleTimeSpan = span;
                }

                if (properties.TryGetValue(UseFiddlerUrl_PropertyName, out propertyValue))
                {
                    bool boolValue = false;
                    if (!bool.TryParse(propertyValue, out boolValue))
                    {
                        throw new ArgumentException(
                                  String.Format("The UseFiddlerUrl value '{0}' is not a valid boolean.", propertyValue),
                                  UseFiddlerUrl_PropertyName);
                    }

                    UseFiddlerUrl = boolValue;
                }
            }
        }
Esempio n. 14
0
        // Install the certificate in the given file path into the My store.
        // It will not install the certificate if there is already one with the same full SubjectName present.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallMyCertificate(BridgeConfiguration configuration, string certificateName)
        {
            // Installing any certificate guarantees the certificate authority is loaded first
            InstallRootCertificate(configuration, configuration.BridgeCertificateAuthority);

            string certificateFilePath = CreateCertificateFilePath(configuration, certificateName);

            lock (s_certificateLock)
            {
                foreach (var pair in s_myCertificates)
                {
                    if (string.Equals(certificateName, pair.Value, StringComparison.OrdinalIgnoreCase))
                    {
                        return pair.Key;
                    }
                }

                X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadWrite);

                X509Certificate2 cert = new X509Certificate2();
                // "test" is currently the required password to allow exportable private keys
                cert.Import(certificateFilePath, "test", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
                string thumbprint = null;
                if (!TryFindCertificate(store, cert.SubjectName.Name, out thumbprint))
                {
                    store.Add(cert);
                    thumbprint = cert.Thumbprint;
                    s_myCertificates[cert.Thumbprint] = certificateName;
                    Console.WriteLine("Added to my store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }
                else
                {
                    Console.WriteLine("Reusing existing my store certificate '{0}' : '{1}'", certificateName, cert.SubjectName.Name);
                }

                store.Close();
                return thumbprint;
            }
        }
 internal static X509Certificate2 EnsureRevokedCertificateInstalled(BridgeConfiguration configuration, CertificateCreationSettings certificateCreationSettings, string resourceAddress)
 {
     return CertificateManager.CreateAndInstallNonDefaultMachineCertificates(GetCertificateGeneratorInstance(configuration), certificateCreationSettings, resourceAddress);
 }
Esempio n. 16
0
            private bool Parse(string[] args)
            {
                // Build a dictionary of all command line arguments.
                // This allows us to initialize BridgeConfiguration from it.
                // Precedence of values in the BridgeConfiguration is this:
                //   - Lowest precedence is the BridgeConfiguration ctor defaults
                //   - Next precedence is any value found in a specified configuration file
                //   - Next precedence is environment variables
                //   - Highest precedence is a BridgeConfiguration value explicitly set on the command line

                Dictionary<string, string> argumentDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

                foreach (string arg in args)
                {
                    if (!arg.StartsWith("/") && !arg.StartsWith("-"))
                    {
                        return false;
                    }

                    // Cannot use split because some argument values could contain colons
                    int index = arg.IndexOf(':');
                    string argName = (index < 0) ? arg.Substring(1) : arg.Substring(1, index - 1);
                    string argValue = (index < 0) ? String.Empty : arg.Substring(index+1);

                    if (String.Equals(argName, "?", StringComparison.OrdinalIgnoreCase))
                    {
                        return false;
                    }

                    argumentDictionary[argName] = argValue;
                }

                BridgeConfiguration = new BridgeConfiguration();

                // If the user specified a configuration file, deserialize it as json
                // and treat each name-value pair as if it had been on the command line.
                // But options explicitly on the command line take precedence over these file options.
                string argumentValue;
                if (argumentDictionary.TryGetValue("bridgeConfig", out argumentValue))
                {
                    if (!File.Exists(argumentValue))
                    {
                        Console.WriteLine("The configuration file '{0}' does not exist.");
                        return false;
                    }

                    // Read the configuration file as json and deserialize it
                    string configurationAsJson = File.ReadAllText(argumentValue);
                    Dictionary<string, string> deserializedConfig = null;

                    try
                    {
                        deserializedConfig = JsonSerializer.DeserializeDictionary(configurationAsJson);
                    }
                    catch (Exception ex)
                    {
                        // Catch all exceptions because any will cause
                        // this application to terminate.
                        Console.WriteLine("Error deserializing {0} : {1}",
                                            argumentValue, ex.Message);
                        return false;
                    }

                    // Every name/value pair in the config file not explicitly set on the command line
                    // is treated as if it had been on the command line.
                    foreach (var pair in deserializedConfig)
                    {
                        if (!argumentDictionary.ContainsKey(pair.Key))
                        {
                            argumentDictionary[pair.Key] = pair.Value;
                        }
                    }
                }

                // For every property in the BridgeConfiguration that has not been explicitly
                // specified on the command line or via the config file, check if there is an
                // Environment variable set for it.  If so, use it as if it had been on the command line.
                foreach (string key in BridgeConfiguration.ToDictionary().Keys)
                {
                    // If the property is explicitly on the command line, it has highest precedence
                    if (!argumentDictionary.ContainsKey(key))
                    {
                        // But if it is not explicitly on the command line but 
                        // an environment variable exists for it, it has higher precedence
                        // than defaults or the config file.
                        string environmentVariable = Environment.GetEnvironmentVariable(key);
                        if (!String.IsNullOrWhiteSpace(environmentVariable))
                        {
                            argumentDictionary[key] = environmentVariable;
                        }
                    }
                }

                // Finally, apply all our command line arguments to the BridgeConfiguration,
                // overwriting any values that were the default or came from the optional config file
                BridgeConfiguration = new BridgeConfiguration(BridgeConfiguration, argumentDictionary);

                // Finish parsing the command line arguments that are not part of BridgeConfiguration
                if (argumentDictionary.ContainsKey("allowRemote"))
                {
                    AllowRemote = true;
                }

                if (argumentDictionary.ContainsKey("ping"))
                {
                    Ping = true;
                }

                if (argumentDictionary.ContainsKey("stop"))
                {
                    Stop = true;
                }

                if (argumentDictionary.ContainsKey("stopiflocal"))
                {
                    StopIfLocal = true;
                }

                string remoteAddresses;
                if (argumentDictionary.TryGetValue("remoteAddresses", out remoteAddresses))
                {
                    RemoteAddresses = remoteAddresses;
                }

                if (argumentDictionary.ContainsKey("reset"))
                {
                    Reset = true;
                }

                return true;
            }
Esempio n. 17
0
        // Returns 'true' if the BridgeConfiguration describes a Bridge that
        // would run locally.
        private static bool IsBridgeHostLocal(BridgeConfiguration configuration)
        {
            if (String.Equals("localhost", configuration.BridgeHost, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            if (String.Equals(Environment.MachineName, configuration.BridgeHost, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }

            return false;
        }
Esempio n. 18
0
        // Install the certificate in the given file path into the My store.
        // It will not install the certificate if it is already present in the store.
        // It returns the thumbprint of the certificate, regardless whether it was added or found.
        public static string InstallMyCertificate(BridgeConfiguration configuration, string certificateName)
        {
            // Installing any MY certificate guarantees the certificate authority is loaded first
            InstallRootCertificate(configuration, configuration.BridgeCertificateAuthority);

            lock (s_certificateLock)
            {
                CertificateCacheEntry entry = null;
                if (s_myCertificates.TryGetValue(certificateName, out entry))
                {
                    return entry.ThumbPrint;
                }

                string certificateFilePath = CreateCertificateFilePath(configuration, certificateName);
                X509Certificate2 cert = new X509Certificate2();
                // "test" is currently the required password to allow exportable private keys
                cert.Import(certificateFilePath, "test", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

                bool added = AddToStoreIfNeeded(StoreName.My, StoreLocation.LocalMachine, cert);
                s_myCertificates[certificateName] = new CertificateCacheEntry
                {
                    ThumbPrint = cert.Thumbprint,
                    AddedToStore = added
                };

                return cert.Thumbprint;
            }
        }
 internal static string EnsureSslPortCertificateInstalled(BridgeConfiguration configuration)
 {
     return EnsureSslPortCertificateInstalled(configuration, configuration.BridgeHttpsPort);
 }
        internal static string EnsureNonDefaultCertificateInstalled(BridgeConfiguration configuration, CertificateCreationSettings certificateCreationSettings, string resourceAddress)
        {
            X509Certificate2 cert = CertificateManager.CreateAndInstallNonDefaultMachineCertificates(GetCertificateGeneratorInstance(configuration), certificateCreationSettings, resourceAddress);

            return cert.Thumbprint;
        }
        public HttpResponseMessage POST(HttpRequestMessage request)
        {
            // A configuration change can have wide impact, so we don't allow concurrent use
            lock(ConfigLock)
            {
                try
                {
                    // Handle deserialization explicitly to bypass MediaTypeFormatter use
                    string nameValuePairs = request.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                    Dictionary<string, string> configInfo = JsonSerializer.DeserializeDictionary(nameValuePairs);

                    Trace.WriteLine(String.Format("{0:T} -- POST config received raw content:{1}{2}",
                                                  DateTime.Now, Environment.NewLine, nameValuePairs),
                                    typeof(ConfigController).Name);

                    // Create a new configuration combining the existing one with any provided properties.
                    BridgeConfiguration newConfiguration = new BridgeConfiguration(BridgeConfiguration, configInfo);
                    Trace.WriteLine(String.Format("{0:T} -- applying new config:{0}{1}",
                                                  DateTime.Now, Environment.NewLine, newConfiguration),
                                    typeof(ConfigController).Name);

                    // Take the new configuration and notify listeners of the change.
                    BridgeConfiguration oldConfiguration = BridgeConfiguration;
                    BridgeConfiguration = newConfiguration;

                    // Notify of change of resource folder
                    bool resourceFolderChanged = !String.Equals(oldConfiguration.BridgeResourceFolder, newConfiguration.BridgeResourceFolder, StringComparison.OrdinalIgnoreCase);
                    if (ResourceFolderChanged != null && resourceFolderChanged)
                    {
                        ResourceFolderChanged(this, new ChangedEventArgs<string>(
                                                        oldConfiguration.BridgeResourceFolder,
                                                        newConfiguration.BridgeResourceFolder));
                    }

                    // Notify of change of the idle timeout
                    if (IdleTimeoutChanged != null &&
                        oldConfiguration.BridgeMaxIdleTimeSpan != newConfiguration.BridgeMaxIdleTimeSpan)
                    {
                        IdleTimeoutChanged(this, new ChangedEventArgs<TimeSpan>(
                                                    oldConfiguration.BridgeMaxIdleTimeSpan,
                                                    newConfiguration.BridgeMaxIdleTimeSpan));
                    }

                    // When the resource folder changes, the response is an array of
                    // resource types.  Any other changes returns an empty string.
                    string configResponse = resourceFolderChanged
                                                ? PrepareConfigResponse(TypeCache.Cache[CurrentAppDomainName])
                                                : String.Empty;

                    Trace.WriteLine(String.Format("{0:T} - POST config returning raw content:{1}{2}",
                                                  DateTime.Now, Environment.NewLine, configResponse),
                                    typeof(ConfigController).Name);

                    // Directly return a json string to avoid use of MediaTypeFormatters
                    HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK);
                    response.Content = new StringContent(configResponse);
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue(JsonSerializer.JsonMediaType);
                    return response;
                }
                catch (Exception ex)
                {
                    var exceptionResponse = ex.Message;
                    Trace.WriteLine(String.Format("{0:T} - POST config exception:{1}{2}",
                                                    DateTime.Now, Environment.NewLine, ex),
                                    typeof(ConfigController).Name);

                    return request.CreateResponse(HttpStatusCode.BadRequest, exceptionResponse);
                }
            }
        }
Esempio n. 22
0
        // This ctor accepts an existing BridgeConfiguration and a set of name/value pairs.
        // It will create a new BridgeConfiguration instance that is a clone of the existing
        // one and will overwrite any properties with corresponding entries found in the name/value pairs.
        public BridgeConfiguration(BridgeConfiguration configuration, Dictionary <string, string> properties)
        {
            BridgeResourceFolder  = configuration.BridgeResourceFolder;
            BridgeHost            = configuration.BridgeHost;
            BridgePort            = configuration.BridgePort;
            BridgeMaxIdleTimeSpan = configuration.BridgeMaxIdleTimeSpan;
            UseFiddlerUrl         = configuration.UseFiddlerUrl;

            string propertyValue = null;

            if (properties.TryGetValue(BridgeResourceFolder_PropertyName, out propertyValue))
            {
                if (string.IsNullOrEmpty(propertyValue) || !Directory.Exists(propertyValue))
                {
                    throw new ArgumentException(
                              String.Format("The BridgeResourceFolder '{0}' does not exist.", propertyValue),
                              BridgeResourceFolder_PropertyName);
                }

                BridgeResourceFolder = Path.GetFullPath(propertyValue);
            }

            if (properties.TryGetValue(BridgeHost_PropertyName, out propertyValue))
            {
                BridgeHost = propertyValue;
            }

            if (properties.TryGetValue(BridgePort_PropertyName, out propertyValue))
            {
                int port = 0;
                if (!int.TryParse(propertyValue, out port))
                {
                    throw new ArgumentException(
                              String.Format("The BridgePort value '{0}' is not a valid port number.", propertyValue),
                              BridgeMaxIdleTimeSpan_PropertyName);
                }

                BridgePort = port;
            }

            if (properties.TryGetValue(BridgeMaxIdleTimeSpan_PropertyName, out propertyValue))
            {
                TimeSpan span;
                if (!TimeSpan.TryParse(propertyValue, out span))
                {
                    throw new ArgumentException(
                              String.Format("The BridgeMaxIdleTimeSpan value '{0}' is not a valid TimeSpan.", propertyValue),
                              BridgeMaxIdleTimeSpan_PropertyName);
                }

                BridgeMaxIdleTimeSpan = span;
            }

            if (properties.TryGetValue(UseFiddlerUrl_PropertyName, out propertyValue))
            {
                bool boolValue = false;
                if (!bool.TryParse(propertyValue, out boolValue))
                {
                    throw new ArgumentException(
                              String.Format("The UseFiddlerUrl value '{0}' is not a valid boolean.", propertyValue),
                              UseFiddlerUrl_PropertyName);
                }

                UseFiddlerUrl = boolValue;
            }
        }