public AzureBaseManager(IAzureCloudAuthenticationInfo authInfo)
        {
            this.AuthInfo = authInfo;
            switch (this.AuthInfo.AuthenticationMode)
            {
            case CloudAuthenticationMode.AccessToken:
                Microsoft.Rest.TokenCredentials tokenCredentials =
                    new Microsoft.Rest.TokenCredentials(this.AuthInfo.AzureAccessToken);
                this.ServiceCredentials = tokenCredentials;
                break;

            case CloudAuthenticationMode.Certificate:
                X509Certificate2 cert = new X509Certificate2(this.AuthInfo.CertificateBytes, this.AuthInfo.PfxCertificatePassword,
                                                             X509KeyStorageFlags.MachineKeySet |
                                                             X509KeyStorageFlags.PersistKeySet |
                                                             X509KeyStorageFlags.Exportable);
                Microsoft.Rest.CertificateCredentials certificateCredentials =
                    new Microsoft.Rest.CertificateCredentials(cert);
                this.ServiceCredentials = certificateCredentials;
                break;

            case CloudAuthenticationMode.PublishingProfile:
                byte[]           managementCertificateBytes = Convert.FromBase64String(this.AuthInfo.ManagementCertificate);
                X509Certificate2 publishingCert             = new X509Certificate2(managementCertificateBytes, string.Empty,
                                                                                   X509KeyStorageFlags.MachineKeySet |
                                                                                   X509KeyStorageFlags.PersistKeySet |
                                                                                   X509KeyStorageFlags.Exportable);
                Microsoft.Rest.CertificateCredentials publishingCredentials = new CertificateCredentials(publishingCert);
                this.ServiceCredentials = publishingCredentials;
                break;
            }
        }
        private void ConfigureClientWithHost(string host, bool enforceTls = false, string pfxFilePath = null)
        {
            if (enforceTls && string.IsNullOrEmpty(pfxFilePath))
            {
                throw new InvalidOperationException("A PFX file with the TLS certificates must be provided to enforce TLS");
            }

            var hostUri = new Uri(host);
            DockerClientConfiguration clientConfig = null;

            if (!enforceTls)
            {
                clientConfig = new DockerClientConfiguration(hostUri);
            }
            else
            {
                var tlsCertificate = new SystemX509Certificate2(pfxFilePath);
                var credentials    = new CertificateCredentials(tlsCertificate);
                credentials.ServerCertificateValidationCallback += (o, c, ch, er) => true;

                clientConfig = new DockerClientConfiguration(hostUri, credentials);
            }
            var client = clientConfig.CreateClient();

            if (host.StartsWith("npipe") || host.StartsWith("unix"))
            {
                DockerHost = "localhost";
            }
            else
            {
                DockerHost = hostUri.Host;
            }
            ConfiguredClient = client;
        }
        /// <summary>
        /// Performs the playback of actions in this module.
        /// </summary>
        /// <remarks>You should not call this method directly, instead pass the module
        /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method
        /// that will in turn invoke this method.</remarks>
        void ITestModule.Run()
        {
            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

            DockerClient client = null;

            if (certFile.Length > 0)
            {
                var credentials = new CertificateCredentials(new X509Certificate2(certFile));
                client = new DockerClientConfiguration(new Uri(dockerURL), credentials).CreateClient();
            }
            else
            {
                client = new DockerClientConfiguration(new Uri(dockerURL)).CreateClient();
            }

            var id = TestSuite.CurrentTestContainer.Parameters["containerID"];

            var stopParams = new Docker.DotNet.Models.ContainerStopParameters()
            {
                WaitBeforeKillSeconds = 10
            };
            CancellationToken token = new CancellationToken();
            var stopTask            = client.Containers.StopContainerAsync(id, stopParams, token);

            stopTask.Wait();

            var remParams  = new Docker.DotNet.Models.ContainerRemoveParameters();
            var deleteTask = client.Containers.RemoveContainerAsync(id, remParams);

            deleteTask.Wait(new TimeSpan(0, 0, 15));
        }
        private async void button5_Click(object sender, EventArgs e)
        {
            int chooise = comboBox1.SelectedIndex;

            if (chooise == -1)
            {
                return;
            }
            List <string> getconn = DockerConnectionStrs[chooise];

            if (client != null)
            {
                client.Dispose();
            }
            if (getconn[2] == "false")
            {
                client      = new DockerClientConfiguration(new Uri(getconn[3])).CreateClient();
                label3.Text = "已经连接至" + comboBox1.SelectedItem.ToString();
            }
            else if (getconn[2] == "true")
            {
                var credentials = new CertificateCredentials(new X509Certificate2(getconn[4], getconn[5]));
                var config      = new DockerClientConfiguration(new Uri(getconn[3]), credentials);
                client      = config.CreateClient();
                label3.Text = "已经连接至" + comboBox1.SelectedItem.ToString();
            }
            else
            {
                label3.Text = "数据错误";
            }
            try
            {
                listBox1.Items.Clear();
                if (client != null)
                {
                    IList <ContainerListResponse> containers = await client.Containers.ListContainersAsync(
                        new ContainersListParameters()
                    {
                        Limit = 10,
                    });

                    foreach (ContainerListResponse c in containers)
                    {
                        listBox1.Items.Add(c.ID.Substring(0, 12));
                    }
                }
                else
                {
                    return;
                }
            }
            catch
            {
                MessageBox.Show("连接失败", "Error", MessageBoxButtons.OK);
                return;
            }
        }
Exemple #5
0
        async Task StartDockerClient()
        {
            await Task.Run(async() =>
            {
                //start docker connection
                switch (CurrentInstallerType)
                {
                case InstallerType.HYPER_V:
                    Log.Info("Starting HyperV Docker");

                    dockerclient = new DockerClientConfiguration(new Uri("npipe://./pipe/docker_engine")).CreateClient();
                    break;

                case InstallerType.NO_HYPER_V:
                    Log.Info("Starting Toolbox Docker");

                    var info = await Process.Start(new ProcessStartInfo("docker-machine", "env --shell=cmd")
                                                   //var info = await Process.Start(new ProcessStartInfo("cmd.exe","/C @FOR / f \"tokens=*\" % i IN('docker-machine env') DO @% i")
                    {
                        //var info = await Process.Start(new ProcessStartInfo("whoami") {
                        RedirectStandardError  = true,
                        RedirectStandardOutput = true,
                        UseShellExecute        = false,
                        CreateNoWindow         = true,
                        WindowStyle            = ProcessWindowStyle.Hidden
                    }).StandardOutput.ReadToEndAsync();

                    foreach (var line in info.Split('\n'))
                    {
                        if (line.Contains("="))
                        {
                            var parts = line.Split('=');
                            Environment.SetEnvironmentVariable(parts[0].Remove(0, 4), parts[1]);
                        }
                    }

                    var host = Environment.GetEnvironmentVariable("DOCKER_HOST");
                    var path = Environment.GetEnvironmentVariable("DOCKER_CERT_PATH");

                    byte[] certBuffer = Helpers.GetBytesFromPEM(File.ReadAllText(Path.Combine(path, "cert.pem")), PemStringType.Certificate);
                    byte[] keyBuffer  = Helpers.GetBytesFromPEM(File.ReadAllText(Path.Combine(path, "key.pem")), PemStringType.RsaPrivateKey);

                    X509Certificate2 certificate = new X509Certificate2(certBuffer);

                    RSACryptoServiceProvider prov = Crypto.DecodeRsaPrivateKey(keyBuffer);
                    certificate.PrivateKey        = prov;


                    ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

                    var credentials = new CertificateCredentials(certificate);

                    dockerclient = new DockerClientConfiguration(new Uri(host), credentials).CreateClient();
                    break;
                }
            });
        }
        public async Task connect(String host, int port, String user, String local_path, String remote_path, String password, TLS_MODE tls_mode, bool use_compression, String container)
        {
            cancel = new CancellationTokenSource();
            SetLocalPath(local_path);
            compress      = use_compression;
            this.tls_mode = tls_mode;
            if (String.IsNullOrWhiteSpace(remote_path))
            {
                remote_path = "";
            }
            else if (remote_path.EndsWith("/") == false && remote_path.EndsWith("\\") == false)
            {
                remote_path += "/";
            }
            this.remote_path = remote_path;
            this.container   = container;
            if (host.IndexOf("://") == -1)
            {
                host = "tcp://" + host;
            }
            host += ":" + port;
            Credentials creds     = new AnonymousCredentials();
            var         pswd_info = new FileInfo(password);

            if (pswd_info.Exists)
            {
                if (pswd_info.Attributes.HasFlag(FileAttributes.ReparsePoint))
                {
                    throw new Exception("Sysmlinks will crash this;0");
                }
                creds        = new CertificateCredentials(new X509Certificate2(password, ""));                              //warning sym links will throw an error here
                ca_cert_path = user;
                ((CertificateCredentials)creds).ServerCertificateValidationCallback += ServerCertificateValidationCallback; //not sure why cannot do this for basic auth
            }
            else if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(password))
            {
                creds = new BasicAuthCredentials(user, password, tls_mode != TLS_MODE.None);
            }
            var config = new DockerClientConfiguration(new Uri(host), creds);

            client = config.CreateClient();
            try {
                var stats = await client.Containers.InspectContainerAsync(container);

                if (!stats.State.Running)
                {
                    MainWindow.ShowMessage("Container is not running", "Unable to connect");
                }
                else
                {
                    connected = true;
                }
            } catch (Exception e) {
                HandleException(e);
            }
        }
 public DockerNode(string name, JoyOIManagementConfiguration.Node nodeInfo)
 {
     Name                   = name;
     NodeInfo               = nodeInfo;
     RunningJobs            = 0;
     RunningJobDescriptions = new ConcurrentDictionary <string, int>();
     ErrorFlags             = false;
     _credentials           = new CertificateCredentials(
         new X509Certificate2(nodeInfo.ClientCertificatePath, nodeInfo.ClientCertificatePassword));
     _dockerClientConfiguration = new DockerClientConfiguration(new Uri(nodeInfo.Address), _credentials);
     _client = _dockerClientConfiguration.CreateClient();
 }
Exemple #8
0
        /// <summary>
        ///     Convert Vault certificate credentials to an <see cref="X509Certificate2"/> (with private key, if present).
        /// </summary>
        /// <param name="certificateCredentials">
        ///     The Vault <see cref="CertificateCredentials"/> to convert.
        /// </param>
        /// <param name="keyStorageFlags">
        ///     Optional key-storage flags that control how the private key is persisted.
        /// </param>
        /// <returns>
        ///     The certificate, as an <see cref="X509Certificate2"/>.
        /// </returns>
        public static X509Certificate2 ToX509Certificate(this CertificateCredentials certificateCredentials, X509KeyStorageFlags keyStorageFlags = X509KeyStorageFlags.DefaultKeySet | X509KeyStorageFlags.Exportable)
        {
            if (certificateCredentials == null)
            {
                throw new ArgumentNullException(nameof(certificateCredentials));
            }

            // TODO: Use CRNG.
            string tempPassword = Guid.NewGuid().ToString("N");

            byte[] pfxData = certificateCredentials.ToPfx(tempPassword);

            return(new X509Certificate2(pfxData, tempPassword, keyStorageFlags));
        }
Exemple #9
0
        /// <summary>
        ///     Convert Vault certificate credentials to PFX / PKCS12 format (with private key, if present).
        /// </summary>
        /// <param name="certificateCredentials">
        ///     The Vault <see cref="CertificateCredentials"/> to convert.
        /// </param>
        /// <param name="password">
        ///     The password to use for protecting the exported data.
        /// </param>
        /// <returns>
        ///     A byte array containing the exported data.
        /// </returns>
        public static byte[] ToPfx(this CertificateCredentials certificateCredentials, string password)
        {
            if (certificateCredentials == null)
            {
                throw new ArgumentNullException(nameof(certificateCredentials));
            }

            if (String.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'password'.", nameof(password));
            }

            List <X509CertificateEntry> chain      = new List <X509CertificateEntry>();
            AsymmetricCipherKeyPair     privateKey = null;

            foreach (object pemObject in EnumeratePemObjects(password, certificateCredentials.CertificateContent, certificateCredentials.PrivateKey, certificateCredentials.IssuingCACertificateContent))
            {
                if (pemObject is X509Certificate certificate)
                {
                    chain.Add(new X509CertificateEntry(certificate));
                }
                else if (pemObject is AsymmetricCipherKeyPair keyPair)
                {
                    privateKey = keyPair;
                }
            }

            if (chain.Count == 0)
            {
                throw new CryptographicException("Cannot find X.509 certificate in PEM data.");
            }

            if (privateKey == null)
            {
                throw new CryptographicException("Cannot find private key in PEM data.");
            }

            string certificateSubject = chain[0].Certificate.SubjectDN.ToString();

            Pkcs12Store store = new Pkcs12StoreBuilder().Build();

            store.SetKeyEntry(certificateSubject, new AsymmetricKeyEntry(privateKey.Private), chain.ToArray());

            using (MemoryStream pfxData = new MemoryStream())
            {
                store.Save(pfxData, password.ToCharArray(), new SecureRandom());

                return(pfxData.ToArray());
            }
        }
Exemple #10
0
        public DockerMachine(string clientID, int?machineID = null)
        {
            _UserID  = clientID;
            _db      = DB.GetInstance();
            machines = _db.Select <Machine>("Docker", "=", new Dictionary <string, object>()
            {
                ["UserID"] = _UserID
            });
            if (machines.Count > 0)
            {
                var machine = machines.Any(x => x.MachineID == machineID) == false?machines.First() : machines.Find(x => x.MachineID == machineID);

                var credentials = new CertificateCredentials(new X509Certificate2(machine.CertPath, DecodeString(machine.Passwd)));
                _client = new DockerClientConfiguration(new Uri(machine.Url), credentials).CreateClient();
            }
        }
        private static X509Certificate2 CreateX509FromVaultCertificate(CertificateCredentials data)
        {
            var publicKeyBytes = Encoding.UTF8.GetBytes(data.CertificateContent);
            var publicKey      = new X509Certificate2(publicKeyBytes, string.Empty, X509KeyStorageFlags.EphemeralKeySet);

            // https://github.com/StefH/OpenSSL-X509Certificate2-Provider
            var decoder              = new OpenSSLPrivateKeyDecoder();
            var privateKey           = decoder.Decode(data.PrivateKeyContent);
            var privateKeyParameters = decoder.DecodeParameters(data.PrivateKeyContent);

            // Combine the public key & private key using the CopyWithPrivateKey extension method
            // https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.x509certificates.rsacertificateextensions.copywithprivatekey?view=netcore-2.2
            using (var certwithkey = publicKey.CopyWithPrivateKey(privateKey))
            {
                return(new X509Certificate2(certwithkey.Export(X509ContentType.Pkcs12)));
            }
        }
        /**
         * Instantiate a Docker client that will be used for Docker client related operations.
         * @param azure - instance of Azure
         * @param rgName - name of the Azure resource group to be used when creating a virtual machine
         * @param region - region to be used when creating a virtual machine
         * @return an instance of DockerClient
         */
        public static DockerClient CreateDockerClient(IAzure azure, String rgName, Region region)
        {
            string       envDockerHost     = Environment.GetEnvironmentVariable("DOCKER_HOST");
            string       envDockerCertPath = Environment.GetEnvironmentVariable("DOCKER_CERT_PATH");
            string       dockerHostUrl;
            DockerClient dockerClient;

            if (String.IsNullOrWhiteSpace(envDockerHost))
            {
                // Could not find a Docker environment; presume that there is no local Docker engine running and
                //    attempt to configure a Docker engine running inside a new    Azure virtual machine
                dockerClient = FromNewDockerVM(azure, rgName, region);
            }
            else
            {
                dockerHostUrl = envDockerHost;
                Utilities.Log("Using local settings to connect to a Docker service: " + dockerHostUrl);

                if (String.IsNullOrWhiteSpace(envDockerCertPath) || !File.Exists(envDockerCertPath + "/key.pfx"))
                {
                    // Could not find a Docker environment variable that is used to set the path to the certificate files
                    //    which are required when authenticating to a secured Docker service.
                    // Presume that no authentication is required to connect with this Docker service
                    dockerClient = new DockerClientConfiguration(new Uri(dockerHostUrl)).CreateClient();
                }
                else
                {
                    // Found environment variable pointing at the folder containing the certificate files required to
                    //    establish a secured connection to this Docker service.
                    // "key.pfx" file is required when connecting using the .Net client; to generate this certificate file
                    //    from standard .PEM certificate file execute the following command:
                    //
                    //    openssl pkcs12 -export -inkey key.pem -in cert.pem -out key.pfx -passout pass: -CAfile ca.pem
                    //
                    var credentials = new CertificateCredentials(new X509Certificate2(envDockerCertPath + "/key.pfx"));
                    credentials.ServerCertificateValidationCallback += (o, c, ch, er) => true;
                    dockerClient = new DockerClientConfiguration(new Uri(dockerHostUrl), credentials).CreateClient();
                }
            }
            Utilities.Log("List Docker host info");
            Utilities.Log("\tFound Docker version: " + dockerClient.Miscellaneous.GetVersionAsync().Result.Version);
            Utilities.Log("\tFound Docker server version: " + dockerClient.Miscellaneous.GetSystemInfoAsync().Result.ServerVersion);

            return(dockerClient);
        }
    public static DockerClient CreateClient(string HostAddress, string CertificateLocation)
    {
        HostAddress         = HostAddress ?? Environment.GetEnvironmentVariable("DOCKER_HOST") ?? "http://127.0.0.1:2375";
        CertificateLocation = CertificateLocation ?? Environment.GetEnvironmentVariable("DOCKER_CERT_PATH");

        Credentials cred = null;

        if (!string.IsNullOrEmpty(CertificateLocation))
        {
            //BUGBUG(swernli) - Remove this later in favor of something better.
            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

            // Try to find a certificate for secure connections.
            cred = new CertificateCredentials(
                new X509Certificate2(
                    System.IO.Path.Combine(CertificateLocation, KeyFileName),
                    certPass));
        }

        return(new DockerClientConfiguration(new Uri(HostAddress), cred).CreateClient(new Version(ApiVersion)));
    }
        public async Task Connect()
        {
            connected = true;

            string            userProfile   = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string            configPath    = Path.Combine(userProfile, @".docker\machine\machines", MachineName, "config.json");
            MachineConfigJson machineConfig = MachineConfigJson.Read(File.ReadAllBytes(configPath));

            string clientCertPath = machineConfig.HostOptions.AuthOptions.ClientCertPath;
            string clientKeyPath  = machineConfig.HostOptions.AuthOptions.ClientKeyPath;
            Uri    uri            = new Uri($"http://{machineConfig.Driver.IPAddress}:2376");

            X509Certificate2       cert        = CertificateUtils.ReadCertificateWithKey(clientCertPath, clientKeyPath, null);
            CertificateCredentials credentials = new CertificateCredentials(cert);

            DockerClientConfiguration config = new DockerClientConfiguration(uri, credentials);

            client = config.CreateClient();

            await Refresh();
        }
Exemple #15
0
        /// <summary>
        ///     Ensure that a Secret for data exists for the specified database server.
        /// </summary>
        /// <returns>
        ///     The Secret resource, as a <see cref="SecretV1"/>.
        /// </returns>
        public async Task <SecretV1> EnsureCredentialsSecretPresent()
        {
            RequireCurrentState();

            SecretV1 existingSecret = await FindCredentialsSecret();

            if (existingSecret != null)
            {
                Log.LogInformation("Found existing credentials secret {SecretName} for server {ServerId}.",
                                   existingSecret.Metadata.Name,
                                   State.Id
                                   );

                return(existingSecret);
            }

            Log.LogInformation("Creating credentials secret for server {ServerId}...",
                               State.Id
                               );

            Log.LogInformation("Requesting X.509 certificate...");

            CertificateCredentials serverCertificate = await RequestServerCertificate();

            SecretV1 createdSecret = await KubeClient.SecretsV1().Create(
                KubeResources.CredentialsSecret(State, serverCertificate,
                                                kubeNamespace: KubeOptions.KubeNamespace
                                                )
                );

            Log.LogInformation("Successfully created credentials secret {SecretName} for server {ServerId}.",
                               createdSecret.Metadata.Name,
                               State.Id
                               );

            return(createdSecret);
        }
Exemple #16
0
 public CertificateOpenIdAuthenticationStrategy(CertificateCredentials credentials, ICrypt cryptoProvider)
 {
     this.credentials    = credentials;
     this.cryptoProvider = cryptoProvider;
 }
        /**
         * Install Docker on a given virtual machine and return a DockerClient.
         * @param dockerHostIP - address (IP) of the Docker host machine
         * @param vmUserName - user name to connect with to the Docker host machine
         * @param vmPassword - password to connect with to the Docker host machine
         * @return an instance of DockerClient
         */
        public static DockerClient InstallDocker(string dockerHostIP, string vmUserName, string vmPassword)
        {
            int keyPfxBuffLength = 10000;

            byte[]   keyPfxContent        = new byte[keyPfxBuffLength]; // it stores the content of the key.pfx certificate file
            bool     dockerHostTlsEnabled = false;
            string   dockerHostUrl        = "tcp://" + dockerHostIP + ":2376";
            SSHShell sshShell             = null;

            try
            {
                using (sshShell = SSHShell.Open(dockerHostIP, 22, vmUserName, vmPassword))
                {
                    Utilities.Log("Copy Docker setup scripts to remote host: " + dockerHostIP);
                    sshShell.Upload(Encoding.ASCII.GetBytes(INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS),
                                    "INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh",
                                    ".azuredocker",
                                    true);

                    sshShell.Upload(Encoding.ASCII.GetBytes(CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.Replace("HOST_IP", dockerHostIP)),
                                    "CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh",
                                    ".azuredocker",
                                    true);
                    sshShell.Upload(Encoding.ASCII.GetBytes(INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU),
                                    "INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh",
                                    ".azuredocker",
                                    true);
                    sshShell.Upload(Encoding.ASCII.GetBytes(DEFAULT_DOCKERD_CONFIG_TLS_ENABLED),
                                    "dockerd_tls.config",
                                    ".azuredocker",
                                    true);
                    sshShell.Upload(Encoding.ASCII.GetBytes(CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED),
                                    "CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh",
                                    ".azuredocker",
                                    true);
                    sshShell.Upload(Encoding.ASCII.GetBytes(DEFAULT_DOCKERD_CONFIG_TLS_DISABLED),
                                    "dockerd_notls.config",
                                    ".azuredocker",
                                    true);
                    sshShell.Upload(Encoding.ASCII.GetBytes(CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED),
                                    "CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.sh",
                                    ".azuredocker",
                                    true);

                    Utilities.Log("Trying to install Docker host at: " + dockerHostIP);
                    string output = sshShell.ExecuteCommand("chmod +x ~/.azuredocker/INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh");
                    Utilities.Log(output);
                    output = sshShell.ExecuteCommand("bash -c ~/.azuredocker/INSTALL_DOCKER_FOR_UBUNTU_SERVER_16_04_LTS.sh");
                    Utilities.Log(output);

                    Utilities.Log("Trying to create OPENSSL certificates");
                    output = sshShell.ExecuteCommand("chmod +x ~/.azuredocker/CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh");
                    Utilities.Log(output);
                    output = sshShell.ExecuteCommand("bash -c ~/.azuredocker/CREATE_OPENSSL_TLS_CERTS_FOR_UBUNTU.sh");
                    Utilities.Log(output);

                    Utilities.Log("Trying to install TLS certificates");

                    output = sshShell.ExecuteCommand("chmod +x ~/.azuredocker/INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh");
                    Utilities.Log(output);
                    output = sshShell.ExecuteCommand("bash -c ~/.azuredocker/INSTALL_DOCKER_TLS_CERTS_FOR_UBUNTU.sh");
                    Utilities.Log(output);
                    Utilities.Log("Download Docker client TLS certificates from: " + dockerHostIP);
                    sshShell.Download(keyPfxContent, keyPfxBuffLength, "key.pfx", ".azuredocker/tls", true);

                    Utilities.Log("Trying to setup Docker config: " + dockerHostIP);

                    //// Setup Docker daemon to allow connection from any Docker clients
                    //output = sshShell.ExecuteCommand("bash -c ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_DISABLED.sh");
                    //Utilities.Log(output);
                    //string dockerHostPort = "2375"; // Default Docker port when secured connection is disabled
                    //dockerHostTlsEnabled = false;

                    // Setup Docker daemon to allow connection from authorized Docker clients only
                    output = sshShell.ExecuteCommand("chmod +x ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh");
                    output = sshShell.ExecuteCommand("bash -c ~/.azuredocker/CREATE_DEFAULT_DOCKERD_OPTS_TLS_ENABLED.sh");
                    Utilities.Log(output);
                    string dockerHostPort = "2376"; // Default Docker port when secured connection is enabled
                    dockerHostTlsEnabled = true;
                    SdkContext.DelayProvider.Delay(10000);

                    dockerHostUrl = "tcp://" + dockerHostIP + ":" + dockerHostPort;
                }
            }
            catch (Exception exception)
            {
                Utilities.Log(exception);
                return(null);
            }

            if (dockerHostTlsEnabled)
            {
                var credentials = new CertificateCredentials(new X509Certificate2(keyPfxContent));
                credentials.ServerCertificateValidationCallback += (o, c, ch, er) => true;
                return(new DockerClientConfiguration(new Uri(dockerHostUrl), credentials).CreateClient());
            }
            else
            {
                return(new DockerClientConfiguration(new Uri(dockerHostUrl)).CreateClient());
            }
        }
Exemple #18
0
        public override async Task <Wrapped.AuthenticationResult> Authenticate(string name, string pw, byte[][] certificates, string certhash, bool certstrong)
        {
            string fingerprint = null;
            long?  certSerial  = null;
            string subCN       = null;

            Org.BouncyCastle.X509.X509Certificate bouncyCert = null;
            if (certificates.Length > 0)
            {
                var certs    = certificates.Select(x => new X509Certificate2(x)).ToArray();
                var usercert = certs.Last();
                var chain    = new X509Chain();
                foreach (var cert in certs)
                {
                    chain.ChainPolicy.ExtraStore.Add(cert);
                }
                chain.ChainPolicy.RevocationMode    = X509RevocationMode.NoCheck;
                chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
                chain.Build(usercert);

                bouncyCert = new X509CertificateParser().ReadCertificate(certificates.Last());
                var subDN = bouncyCert.SubjectDN;
                subCN      = subDN.GetValueList()[subDN.GetOidList().IndexOf(X509ObjectIdentifiers.CommonName)] as string;
                certSerial = bouncyCert.SerialNumber.LongValue;

                fingerprint = usercert.Thumbprint;
            }
            else
            {
                // oh @moritzuehling y u do dis to me Q_Q
                // (no certs at all)
            }

            CertificateCredentials creds = null;

            if (certSerial.HasValue)
            {
                creds = new CertificateCredentials
                {
                    Fingerprint = fingerprint,
                    CertSerial  = certSerial.Value,
                }
            }
            ;


            User user;
            bool isGuest = false;

            using (var context = await FancyContext.Connect())
                using (var transact = context.Database.BeginTransaction(IsolationLevel.Serializable)) {
                    user = await context.Users.Include(x => x.Membership).Include(x => x.PersistentGuest)
                           .Include(x => x.PersistentGuest.Godfathers).SingleOrDefaultAsync(x => x.CertCredentials.Any(y => y.Fingerprint == fingerprint));

                    if (user != null)
                    {
                        // Known user. Why?
                        // * member
                        // * persistent guest
                        //
                        // As this is the /authenticator/, we can't query online users because that would deadlock murmur's main thread.
                        // As someone with CertificateCredentials is definitely allowed to connect, we just let them pass here and
                        // kick them in OnUserConnected if they're missing a godfather.
                    }
                    else
                    {
                        // Unknown user. Why?
                        // * temporary guest
                        // * new cert for existing user
                        // * new user
                        // * random person on the internet

                        // Let's first check for guest invites
                        pw = pw.Trim();
                        var invite = await context.Invites.SingleOrDefaultAsync(x => (x.Code == pw) && (x.ExpirationDate > DateTimeOffset.Now));

                        if (invite != null)
                        {
                            // Try to match by name.
                            user = await context.Users.Include(x => x.PersistentGuest).SingleOrDefaultAsync(x => x.Name == name);

                            if (user != null)
                            {
                                if (user.GuestInvite == null)
                                {
                                    // In case the name is already taken by a non-guest, we force them to a
                                    // random but different name so everyone can see they're a guest.
                                    name += "-guest-" + Guid.NewGuid().ToString();
                                    user  = null;
                                }
                                else
                                {
                                    // The account once belonged to a guest? Nice.
                                    // But adjust to the new guest invite.
                                    user.GuestInvite = invite;
                                    // (Note that we don't care about the edge case where guests get ghost-kicked
                                    //  by other guests because we simply don't care about guests.)
                                }
                            }

                            if (user == null)
                            {
                                // Create a new user for this name if we need to.
                                user = context.Users.Add(new User
                                {
                                    Name        = name,
                                    GuestInvite = invite,
                                });
                            }

                            isGuest = true;
                        }
                        else
                        {
                            // random person on the internet; has no signed or valid certificate
                            if (!certstrong)
                            {
                                return(Wrapped.AuthenticationResult.Forbidden());
                            }

                            // New cert for existing user?

                            /*
                             * not longer supported
                             * foreach (System.Collections.ICollection sans in bouncyCert.GetSubjectAlternativeNames())
                             * {
                             *  var enm = sans.GetEnumerator();
                             *  enm.MoveNext();
                             *  enm.MoveNext();
                             *  var val = enm.Current as string;
                             *  var match = Regex.Match(val ?? String.Empty, "^([^@]*)@user.mumble.ehvag.de$");
                             *  if (match.Success)
                             *  {
                             *      var oldName = match.Groups[1].Captures[0].Value;
                             *      var existingUser = await context.Users.Include(x => x.CertCredentials).SingleOrDefaultAsync(x => x.Name == oldName && x.CertCredentials.CertSerial < certSerial);
                             *      if (existingUser != null)
                             *      {
                             *          existingUser.Name = subCN;
                             *          existingUser.CertCredentials.CertSerial = certSerial.Value;
                             *          existingUser.CertCredentials.Fingerprint = fingerprint;
                             *          user = existingUser;
                             *          break;
                             *      }
                             *  }
                             * }
                             */

                            if (user == null)
                            {
                                // no existing user found, so create new user
                                user = context.Users.Add(new User
                                {
                                    Name            = subCN,
                                    CertCredentials = new List <CertificateCredentials> {
                                        creds
                                    },
                                    Membership = new Membership()
                                });
                            }
                        }
                    }

                    // As stated above, we can't query mumble for connected users to reject persistent guests.
                    // However, we can use the logs in the database as a heuristic to get currently connected users.
                    if (user.PersistentGuest != null && !isGuest)
                    {
                        var godfathersQuery = from usr in context.Users
                                              from godfathership in usr.Membership.Godfatherships
                                              where godfathership.UserId == user.Id
                                              join e in context.Logs.OfType <LogEntry.Connected>() on usr.Id equals e.Who.Id into connectEvents
                                              join e in context.Logs.OfType <LogEntry.Disconnected>() on usr.Id equals e.Who.Id into disconnectEvents
                                              select new { Con = connectEvents.Max(x => x.When), Dis = disconnectEvents.Max(x => x.When) };
                        var godfatherConnected = await godfathersQuery.AnyAsync(l => l.Con > l.Dis);

                        if (!godfatherConnected)
                        {
                            return(Wrapped.AuthenticationResult.Forbidden());
                        }
                    }

                    await context.SaveChangesAsync();

                    transact.Commit();
                }

            if (isGuest && (creds != null))
            {
                Fancyauth.GuestCredentials.AddOrUpdate(user.Id, creds, (k, c) => creds);
            }

            string[] groups = null;
            if (user.PersistentGuest != null)
            {
                groups = PersistentGuestGroups;
            }

            return(Wrapped.AuthenticationResult.Success(user.Id, user.Name, groups));
        }
        /// <summary>
        /// Performs the playback of actions in this module.
        /// </summary>
        /// <remarks>You should not call this method directly, instead pass the module
        /// instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method
        /// that will in turn invoke this method.</remarks>
        void ITestModule.Run()
        {
            // docker run --name wp1 -p 5556:80 --link mysql:mysql
            // -e WORDPRESS_DB_PASSWORD=pwd -e WORDPRESS_DB_NAME=wp1 -d wordpress

            ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;

            DockerClient client = null;

            if (certFile.Length > 0)
            {
                var credentials = new CertificateCredentials(new X509Certificate2(certFile));
                client = new DockerClientConfiguration(new Uri(dockerURL), credentials).CreateClient();
            }
            else
            {
                client = new DockerClientConfiguration(new Uri(dockerURL)).CreateClient();
            }



            Random r      = new Random();
            int    portNr = r.Next(1500, 8000);

            TestSuite.CurrentTestContainer.Parameters["URL"] = TestSuite.CurrentTestContainer.Parameters["URL"] + ":" + portNr.ToString();

            //Report.Info(portNr.ToString());
            //Report.Info(TestSuite.CurrentTestContainer.Parameters["URL"]);

            Docker.DotNet.Models.HostConfig hostConf = new Docker.DotNet.Models.HostConfig();
            hostConf.Links = new List <string>();
            hostConf.Links.Add("mysql");

            var portBindings = new Dictionary <string, IList <Docker.DotNet.Models.PortBinding> > {
                {
                    80.ToString(), new List <Docker.DotNet.Models.PortBinding> {
                        new Docker.DotNet.Models.PortBinding {
                            HostPort = portNr.ToString(),
                            HostIP   = "0.0.0.0"
                        }
                    }
                }
            };
            var exposedPorts = new Dictionary <string, object>()
            {
                { 80.ToString(), new { HostPort = portNr.ToString() } }
            };

            hostConf.PortBindings = portBindings;

            Docker.DotNet.Models.CreateContainerParameters createContainerParams = new Docker.DotNet.Models.CreateContainerParameters();
            createContainerParams.HostConfig = hostConf;
            createContainerParams.Image      = "a8f5a76ca5cd";

            createContainerParams.Env = new List <string>();
            createContainerParams.Env.Add("WORDPRESS_DB_PASSWORD=pwd");
            createContainerParams.Env.Add(String.Format("WORDPRESS_DB_NAME=wp{0}", portNr));


            createContainerParams.ExposedPorts = exposedPorts;

            var createTask = client.Containers.CreateContainerAsync(createContainerParams);

            createTask.Wait();
            var container = createTask.Result;

            TestSuite.CurrentTestContainer.Parameters["containerID"] = container.ID;

            var incpectTask = client.Containers.InspectContainerAsync(container.ID);

            incpectTask.Wait();
            var inspect = incpectTask.Result;

            var startParams = new Docker.DotNet.Models.ContainerStartParameters();
            var startTast   = client.Containers.StartContainerAsync(container.ID, startParams);

            startTast.Wait();
        }
Exemple #20
0
        /// <summary>
        ///     Create a new <see cref="SecretV1"/> for the specified database server's credentials.
        /// </summary>
        /// <param name="server">
        ///     A <see cref="DatabaseServer"/> representing the target server.
        /// </param>
        /// <param name="serverCertificate">
        ///     <see cref="CertificateCredentials"/> representing the server certificate.
        /// </param>
        /// <param name="kubeNamespace">
        ///     An optional target Kubernetes namespace.
        /// </param>
        /// <returns>
        ///     The configured <see cref="SecretV1"/>.
        /// </returns>
        public SecretV1 CredentialsSecret(DatabaseServer server, CertificateCredentials serverCertificate, string kubeNamespace = null)
        {
            if (server == null)
            {
                throw new ArgumentNullException(nameof(server));
            }

            if (serverCertificate == null)
            {
                throw new ArgumentNullException(nameof(serverCertificate));
            }

            var secretData = new Dictionary <string, string>();

            if (!String.IsNullOrWhiteSpace(serverCertificate.IssuingCACertificateContent))
            {
                secretData["ca.crt"] = Convert.ToBase64String(
                    Encoding.ASCII.GetBytes(serverCertificate.IssuingCACertificateContent)
                    );
            }

            secretData["server.crt"] = Convert.ToBase64String(
                Encoding.ASCII.GetBytes(serverCertificate.CertificateContent)
                );
            secretData["server.key"] = Convert.ToBase64String(
                Encoding.ASCII.GetBytes(serverCertificate.PrivateKey)
                );

            string pfxPassword;

            byte[] passwordBytes = new byte[16];
            using (RandomNumberGenerator random = RandomNumberGenerator.Create())
            {
                random.GetBytes(passwordBytes);
            }
            pfxPassword = Convert.ToBase64String(passwordBytes);

            secretData["server.pfx"] = Convert.ToBase64String(
                serverCertificate.ToPfx(pfxPassword)
                );
            secretData["pfx-password"] = Convert.ToBase64String(
                Encoding.ASCII.GetBytes(pfxPassword)
                );

            if (server.Settings is SqlServerSettings sqlServerSettings && !String.IsNullOrWhiteSpace(sqlServerSettings.AdminPassword))
            {
                secretData["sa-password"] = Convert.ToBase64String(
                    Encoding.ASCII.GetBytes(sqlServerSettings.AdminPassword)
                    );
            }

            return(CredentialsSecret(
                       name: Names.CredentialsSecret(server),
                       kubeNamespace: kubeNamespace,
                       data: secretData,
                       labels: new Dictionary <string, string>
            {
                ["k8s-app"] = Names.BaseName(server),
                ["cloud.dimensiondata.daas.server-id"] = server.Id,
                ["cloud.dimensiondata.daas.secret-type"] = "credentials"
            }
                       ));
        }
        public static IDataFactoryManagementClient GetRealClient(ExampleSecrets secrets)
        {
            IDataFactoryManagementClient client = null;

            if (secrets.Environment == "test")
            {
                string ArmTenant = secrets.TenantId;
                string ArmServicePrincipalIdentity = secrets.ClientId;
                string SubId = secrets.SubId;
                string Thumb = secrets.ClientSecret;
                // Use service principal with cert to authenticate against Azure
                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2           cert = store.Certificates.Find(X509FindType.FindByThumbprint, Thumb, false)[0];
                ClientAssertionCertificate cac  = new ClientAssertionCertificate(ArmServicePrincipalIdentity, cert);
                var context = new AuthenticationContext("https://login.windows-ppe.net/" + ArmTenant);
                AuthenticationResult     result = context.AcquireTokenAsync("https://management.core.windows.net/", cac).Result;
                ServiceClientCredentials creds  = new TokenCredentials(result.AccessToken);
                client = new DataFactoryManagementClient(creds)
                {
                    SubscriptionId = SubId
                };
                client.BaseUri = new Uri("https://api-dogfood.resources.windows-int.net/");
            }
            else if (secrets.Environment == "dogfood")
            {
                string ArmTenant = secrets.TenantId;
                string ArmServicePrincipalIdentity = secrets.ClientId;
                string SubId = secrets.SubId;
                // Use service principal with key to authenticate against Azure
                string secret  = secrets.ClientSecret;
                var    cac     = new ClientCredential(ArmServicePrincipalIdentity, secret);
                var    context = new AuthenticationContext("https://login.windows-ppe.net/" + ArmTenant);
                AuthenticationResult     result = context.AcquireTokenAsync("https://management.core.windows.net/", cac).Result;
                ServiceClientCredentials creds  = new TokenCredentials(result.AccessToken);
                client = new DataFactoryManagementClient(creds)
                {
                    SubscriptionId = SubId
                };
                client.BaseUri = new Uri("https://api-dogfood.resources.windows-int.net/");
            }
            else if (secrets.Environment == "prod")
            {
                // Use Service Principal to authenticate against Azure
                var context = new AuthenticationContext("https://login.windows.net/" + secrets.TenantId);
                ClientCredential         cc     = new ClientCredential(secrets.ClientId, secrets.ClientSecret);
                AuthenticationResult     result = context.AcquireTokenAsync("https://management.azure.com/", cc).Result;
                ServiceClientCredentials creds  = new TokenCredentials(result.AccessToken);
                client = new DataFactoryManagementClient(creds)
                {
                    SubscriptionId = secrets.SubId
                };
            }
            else if (secrets.Environment == "nightly")
            {
                // Use certificate for direct access to RP
                X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                store.Open(OpenFlags.ReadOnly);
                X509Certificate2       cert  = store.Certificates.Find(X509FindType.FindByThumbprint, "CF6DCEF6F6EB497A1B2A569319D157F875019A9E", false)[0];
                CertificateCredentials creds = new CertificateCredentials(cert);
                client = new DataFactoryManagementClient(creds)
                {
                    SubscriptionId = secrets.SubId
                };
                client.BaseUri = new Uri("https://adfrpnightly.svc.datafactory-test.azure.com");
            }
            else
            {
                throw new ArgumentException("Secrets environment must be test or prod, currently {0}", secrets.Environment);
            }
            return(client);
        }