Exemplo n.º 1
0
        public static void Run([TimerTrigger("0 */30 * * * *")] TimerInfo myTimer, TraceWriter log)
        {
            AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
            KeyVaultClient            kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            //signedPermissions: Allowed values: (a)dd(c)reate(d)elete(l)ist(p)rocess(r)ead(u)pdate(w)rite
            //signedServices: Allowed values: (b)lob(f)ile(q)ueue(t)able
            //signedResourceTypes: Allowed values: (s)ervice(c)ontainer(o)bject
            string _sasName = "blobrwu4hours";
            Dictionary <string, string> _sasProperties = new Dictionary <string, string>()
            {
                { "sasType", "account" },
                { "signedProtocols", "https" },
                { "signedServices", "b" },
                { "signedResourceTypes", "sco" },
                { "signedPermissions", "rwu" },
                { "signedVersion", "2017-11-09" },
                { "validityPeriod", "PT4H" }
            };
            SasDefinitionAttributes _sasDefinitionAttributes = new SasDefinitionAttributes(enabled: true);

            try
            {
                //Sas definition create/update should be in a different function
                var setSas = Task.Run(
                    () => kv.SetSasDefinitionAsync(_vaultBaseUrl, _storageAccountName, _sasName, _sasProperties, _sasDefinitionAttributes))
                             .ConfigureAwait(false).GetAwaiter().GetResult();
                log.Info("Sas definition created!");

                secret = Task.Run(
                    () => kv.GetSecretAsync(_vaultBaseUrl, $"{_storageAccountName}-{_sasName}"))
                         .ConfigureAwait(false).GetAwaiter().GetResult();

                base64sas = Convert.ToBase64String(Encoding.UTF8.GetBytes(secret.Value));

                log.Info($"Here there is the base 64 encoded secret: {secret.Value}");

                sshPrivateKey = Task.Run(
                    () => kv.GetSecretAsync(_vaultBaseUrl, $"privatekey"))
                                .ConfigureAwait(false).GetAwaiter().GetResult();
                log.Info($"Retrieved {sshPrivateKey.Id}");
            }
            catch (Exception ex)
            {
                log.Info($"Something went wrong with KeyVault: {ex.Message}");
            }

            try
            {
                //By choice we do not have passphrase for the key stored in Key Vault
                PrivateKeyFile privKey = new PrivateKeyFile(new MemoryStream(Encoding.UTF8.GetBytes(sshPrivateKey.Value)));

                using (var client = new SshClient(host, 22, sshUsername, privKey))
                {
                    byte[] expectedFingerPrint = StringToByteArray(sshPubKeyFingerprint);
                    client.HostKeyReceived += (sender, e) =>
                    {
                        if (expectedFingerPrint.Length == e.FingerPrint.Length)
                        {
                            for (var i = 0; i < expectedFingerPrint.Length; i++)
                            {
                                if (expectedFingerPrint[i] != e.FingerPrint[i])
                                {
                                    e.CanTrust = false;
                                    break;
                                }
                            }
                        }
                        else
                        {
                            e.CanTrust = false;
                        }
                    };
                    client.Connect();
                    var delete = client.CreateCommand($"kubectl delete secret {kubernetesSecretName}").Execute();
                    log.Info(delete);
                    var create = client.CreateCommand($"kubectl create secret generic {kubernetesSecretName} --from-literal=secretKey={base64sas}").Execute();
                    log.Info(create);
                    client.Disconnect();
                }
            }
            catch (Exception ex)
            {
                log.Error($"Something went wrong with Kubernetes: {ex.Message}");
            }
        }
Exemplo n.º 2
0
    private static async Task <string> GetOrCreateSasDefinitionAsync(
        ManagedStorageRestClient storageClient,
        string storageAccountName,
        string sasTemplate,
        int days,
        bool readOnly)
    {
        const string Tag = "ShareLinkSample";

        // Format the duration using ISO 8601.
        string duration = days > 0 ? XmlConvert.ToString(TimeSpan.FromDays(days)) : null;

        // Try to find an existing definition based on the template and duration, since the formatted name may have changed.
        for (SasDefinitionListResult result = await storageClient.GetSasDefinitionsAsync(storageAccountName, cancellationToken: s_cancellationTokenSource.Token); ;
             result = await storageClient.GetSasDefinitionsNextPageAsync(result.NextLink, storageAccountName, cancellationToken: s_cancellationTokenSource.Token))
        {
            foreach (SasDefinitionItem sasDefinitionInfo in result.Value.Where(d => d.Tags.ContainsKey(Tag)))
            {
                // The SAS definition name is the segment of the Id.
                int    pos  = sasDefinitionInfo.Id.AsSpan().TrimEnd('/').LastIndexOf('/');
                string name = sasDefinitionInfo.Id.Substring(pos + 1);

                SasDefinitionBundle foundSasDefinition = await storageClient.GetSasDefinitionAsync(storageAccountName, name, cancellationToken : s_cancellationTokenSource.Token);

                if (string.Equals(sasTemplate, foundSasDefinition.TemplateUri, StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(duration, foundSasDefinition.ValidityPeriod, StringComparison.OrdinalIgnoreCase))
                {
                    return(name);
                }
            }

            if (result.NextLink is null)
            {
                // No more results.
                break;
            }
        }

        // Create a new SAS definition since we didn't find an existing definition.
        string sasDefinitionName = BuildSasDefinitionName(Tag, readOnly, duration);
        SasDefinitionAttributes sasDefinitionAttributes = new SasDefinitionAttributes
        {
            Enabled = true,
        };

        Dictionary <string, string> tags = new Dictionary <string, string>
        {
            [Tag] = "1",
        };

        SasDefinitionBundle createdSasDefinition = await storageClient.SetSasDefinitionAsync(
            storageAccountName,
            sasDefinitionName,
            sasTemplate,
            SasTokenType.Account,
            duration,
            sasDefinitionAttributes,
            tags,
            s_cancellationTokenSource.Token);

        return(sasDefinitionName);
    }