From 727065e3c3222ab44b9498765e12c660c44ae7b7 Mon Sep 17 00:00:00 2001 From: shibayan Date: Wed, 26 Sep 2018 17:51:19 +0900 Subject: [PATCH] Adding project --- AzureKeyVault.LetsEncrypt.sln | 25 ++ AzureKeyVault.LetsEncrypt/.gitignore | 264 +++++++++++++ AzureKeyVault.LetsEncrypt/AccountKey.cs | 39 ++ AzureKeyVault.LetsEncrypt/AddCertificate.cs | 38 ++ .../AzureKeyVault.LetsEncrypt.csproj | 23 ++ .../RenewCertificates.cs | 50 +++ AzureKeyVault.LetsEncrypt/Settings.cs | 28 ++ AzureKeyVault.LetsEncrypt/SharedFunctions.cs | 358 ++++++++++++++++++ AzureKeyVault.LetsEncrypt/host.json | 3 + LICENSE | 2 +- 10 files changed, 829 insertions(+), 1 deletion(-) create mode 100644 AzureKeyVault.LetsEncrypt.sln create mode 100644 AzureKeyVault.LetsEncrypt/.gitignore create mode 100644 AzureKeyVault.LetsEncrypt/AccountKey.cs create mode 100644 AzureKeyVault.LetsEncrypt/AddCertificate.cs create mode 100644 AzureKeyVault.LetsEncrypt/AzureKeyVault.LetsEncrypt.csproj create mode 100644 AzureKeyVault.LetsEncrypt/RenewCertificates.cs create mode 100644 AzureKeyVault.LetsEncrypt/Settings.cs create mode 100644 AzureKeyVault.LetsEncrypt/SharedFunctions.cs create mode 100644 AzureKeyVault.LetsEncrypt/host.json diff --git a/AzureKeyVault.LetsEncrypt.sln b/AzureKeyVault.LetsEncrypt.sln new file mode 100644 index 00000000..dcaf0262 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.28010.2036 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AzureKeyVault.LetsEncrypt", "AzureKeyVault.LetsEncrypt\AzureKeyVault.LetsEncrypt.csproj", "{81F62D09-D16D-4B0C-9DAE-C075580F5021}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {81F62D09-D16D-4B0C-9DAE-C075580F5021}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {81F62D09-D16D-4B0C-9DAE-C075580F5021}.Debug|Any CPU.Build.0 = Debug|Any CPU + {81F62D09-D16D-4B0C-9DAE-C075580F5021}.Release|Any CPU.ActiveCfg = Release|Any CPU + {81F62D09-D16D-4B0C-9DAE-C075580F5021}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {84335610-C357-42B9-BC67-393B987B1632} + EndGlobalSection +EndGlobal diff --git a/AzureKeyVault.LetsEncrypt/.gitignore b/AzureKeyVault.LetsEncrypt/.gitignore new file mode 100644 index 00000000..ff5b00c5 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/.gitignore @@ -0,0 +1,264 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# Azure Functions localsettings file +local.settings.json + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +#*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc \ No newline at end of file diff --git a/AzureKeyVault.LetsEncrypt/AccountKey.cs b/AzureKeyVault.LetsEncrypt/AccountKey.cs new file mode 100644 index 00000000..ab11fff8 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/AccountKey.cs @@ -0,0 +1,39 @@ +using System; + +using ACMESharp.Crypto.JOSE; + +namespace AzureKeyVault.LetsEncrypt +{ + internal class AccountKey + { + public string KeyType { get; set; } + public string KeyExport { get; set; } + + public IJwsTool GenerateSigner() + { + if (KeyType.StartsWith("ES")) + { + var tool = new ACMESharp.Crypto.JOSE.Impl.ESJwsTool + { + HashSize = int.Parse(KeyType.Substring(2)) + }; + tool.Init(); + tool.Import(KeyExport); + return tool; + } + + if (KeyType.StartsWith("RS")) + { + var tool = new ACMESharp.Crypto.JOSE.Impl.RSJwsTool + { + KeySize = int.Parse(KeyType.Substring(2)) + }; + tool.Init(); + tool.Import(KeyExport); + return tool; + } + + throw new Exception($"Unknown or unsupported KeyType [{KeyType}]"); + } + } +} \ No newline at end of file diff --git a/AzureKeyVault.LetsEncrypt/AddCertificate.cs b/AzureKeyVault.LetsEncrypt/AddCertificate.cs new file mode 100644 index 00000000..1b7f39b5 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/AddCertificate.cs @@ -0,0 +1,38 @@ +using System.Net.Http; +using System.Threading.Tasks; + +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; +using Microsoft.Extensions.Logging; + +namespace AzureKeyVault.LetsEncrypt +{ + public static class AddCertificate + { + [FunctionName("AddCertificate_HttpStart")] + public static async Task HttpStart( + [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequestMessage req, + [OrchestrationClient] DurableOrchestrationClient starter, + ILogger log) + { + var request = await req.Content.ReadAsAsync(); + + if (request.Domains == null || request.Domains.Length == 0) + { + return req.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, $"{nameof(request.Domains)} is empty."); + } + + // Function input comes from the request content. + var instanceId = await starter.StartNewAsync(nameof(SharedFunctions.IssueCertificate), request.Domains); + + log.LogInformation($"Started orchestration with ID = '{instanceId}'."); + + return starter.CreateCheckStatusResponse(req, instanceId); + } + } + + public class AddCertificateRequest + { + public string[] Domains { get; set; } + } +} \ No newline at end of file diff --git a/AzureKeyVault.LetsEncrypt/AzureKeyVault.LetsEncrypt.csproj b/AzureKeyVault.LetsEncrypt/AzureKeyVault.LetsEncrypt.csproj new file mode 100644 index 00000000..03857a35 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/AzureKeyVault.LetsEncrypt.csproj @@ -0,0 +1,23 @@ + + + netstandard2.0 + v2 + + + + + + + + + + + + PreserveNewest + + + PreserveNewest + Never + + + \ No newline at end of file diff --git a/AzureKeyVault.LetsEncrypt/RenewCertificates.cs b/AzureKeyVault.LetsEncrypt/RenewCertificates.cs new file mode 100644 index 00000000..529543f8 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/RenewCertificates.cs @@ -0,0 +1,50 @@ +using System.Collections.Generic; +using System.Threading.Tasks; + +using Microsoft.Azure.KeyVault.Models; +using Microsoft.Azure.WebJobs; +using Microsoft.Extensions.Logging; + +namespace AzureKeyVault.LetsEncrypt +{ + public static class RenewCertificates + { + [FunctionName("RenewCertificates")] + public static async Task RunOrchestrator([OrchestrationTrigger] DurableOrchestrationContext context, ILogger log) + { + // 期限切れまで 30 日以内の証明書を取得する + var certificates = await context.CallActivityAsync>(nameof(SharedFunctions.GetCertificates), context.CurrentUtcDateTime); + + // 更新対象となる証明書がない場合は終わる + if (certificates.Count == 0) + { + log.LogInformation("Certificates is not found"); + + return; + } + + var tasks = new List(); + + // 証明書の更新を行う + foreach (var certificate in certificates) + { + log.LogInformation($"{certificate.Id} - {certificate.Attributes.Expires}"); + + // 証明書の更新処理を開始 + tasks.Add(context.CallSubOrchestratorAsync(nameof(SharedFunctions.IssueCertificate), certificate.Policy.X509CertificateProperties.SubjectAlternativeNames.DnsNames)); + } + + // サブオーケストレーターの完了を待つ + await Task.WhenAll(tasks); + } + + [FunctionName("RenewCertificates_Timer")] + public static async Task TimerStart([TimerTrigger("0 0 0 * * *")] TimerInfo timer, [OrchestrationClient] DurableOrchestrationClient starter, ILogger log) + { + // Function input comes from the request content. + var instanceId = await starter.StartNewAsync("RenewCertificates", null); + + log.LogInformation($"Started orchestration with ID = '{instanceId}'."); + } + } +} \ No newline at end of file diff --git a/AzureKeyVault.LetsEncrypt/Settings.cs b/AzureKeyVault.LetsEncrypt/Settings.cs new file mode 100644 index 00000000..a23ce4ee --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/Settings.cs @@ -0,0 +1,28 @@ +using Microsoft.Extensions.Configuration; + +namespace AzureKeyVault.LetsEncrypt +{ + internal class Settings + { + public Settings() + { + var builder = new ConfigurationBuilder() + .AddJsonFile("local.settings.json", true) + .AddEnvironmentVariables(); + + _configuration = builder.Build(); + _section = _configuration.GetSection("LetsEncrypt"); + } + + private readonly IConfiguration _configuration; + private readonly IConfiguration _section; + + public string Contacts => _section[nameof(Contacts)]; + + public string SubscriptionId => _section[nameof(SubscriptionId)]; + + public string VaultBaseUrl => _section[nameof(VaultBaseUrl)]; + + public static Settings Default { get; } = new Settings(); + } +} diff --git a/AzureKeyVault.LetsEncrypt/SharedFunctions.cs b/AzureKeyVault.LetsEncrypt/SharedFunctions.cs new file mode 100644 index 00000000..e72ea887 --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/SharedFunctions.cs @@ -0,0 +1,358 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net.Http; +using System.Security.Cryptography.X509Certificates; +using System.Threading.Tasks; + +using ACMESharp.Authorizations; +using ACMESharp.Protocol; +using ACMESharp.Protocol.Resources; + +using Microsoft.Azure.KeyVault; +using Microsoft.Azure.KeyVault.Models; +using Microsoft.Azure.Management.Dns; +using Microsoft.Azure.Management.Dns.Models; +using Microsoft.Azure.Services.AppAuthentication; +using Microsoft.Azure.WebJobs; +using Microsoft.Extensions.Logging; +using Microsoft.Rest; + +using Newtonsoft.Json; + +namespace AzureKeyVault.LetsEncrypt +{ + public static class SharedFunctions + { + private static readonly HttpClient _httpClient = new HttpClient(); + private static readonly HttpClient _acmeHttpClient = new HttpClient { BaseAddress = new Uri("https://acme-v02.api.letsencrypt.org/") }; + //private static readonly HttpClient _acmeHttpClient = new HttpClient { BaseAddress = new Uri("https://acme-staging-v02.api.letsencrypt.org/") }; + + [FunctionName(nameof(IssueCertificate))] + public static async Task IssueCertificate([OrchestrationTrigger] DurableOrchestrationContext context, ILogger log) + { + var dnsNames = context.GetInput(); + + // 前提条件をチェック + await context.CallActivityAsync(nameof(Dns01Precondition), dnsNames); + + // 新しく ACME Order を作成する + var orderDetails = await context.CallActivityAsync(nameof(Order), dnsNames); + + // 複数の Authorizations を処理する + var challenges = new List(); + + foreach (var authorization in orderDetails.Payload.Authorizations) + { + // ACME Challenge を実行 + challenges.Add(await context.CallActivityAsync(nameof(Dns01Authorization), authorization)); + } + + // Order status が ready になるまで待つ + await context.CallActivityAsync(nameof(AnswerChallenges), (orderDetails, challenges)); + + await context.CallActivityAsync(nameof(FinalizeOrder), (dnsNames, orderDetails)); + } + + [FunctionName(nameof(GetCertificates))] + public static async Task> GetCertificates([ActivityTrigger] DurableActivityContext context, ILogger log) + { + var currentDateTime = context.GetInput(); + + var keyVaultClient = CreateKeyVaultClient(); + + var certificates = await keyVaultClient.GetCertificatesAsync(Settings.Default.VaultBaseUrl); + + var list = certificates.Where(x => x.Tags.TryGetValue("Issuer", out var issuer) && issuer == "letsencrypt.org") + .Where(x => (x.Attributes.Expires.Value - currentDateTime).TotalDays < 30) + .ToArray(); + + var bundles = new List(); + + foreach (var item in list) + { + bundles.Add(await keyVaultClient.GetCertificateAsync(item.Id)); + } + + return bundles; + } + + [FunctionName(nameof(Order))] + public static async Task Order([ActivityTrigger] DurableActivityContext context, ILogger log) + { + var hostNames = context.GetInput(); + + var acme = await CreateAcmeClientAsync(); + + return await acme.CreateOrderAsync(hostNames); + } + + [FunctionName(nameof(Dns01Precondition))] + public static async Task Dns01Precondition([ActivityTrigger] DurableActivityContext context, ILogger log) + { + var hostNames = context.GetInput(); + + var dnsClient = await CreateDnsManagementClientAsync(); + + // Azure DNS が存在するか確認 + var zones = await dnsClient.Zones.ListAsync(); + + foreach (var hostName in hostNames) + { + if (!zones.Any(x => hostName.EndsWith(x.Name))) + { + log.LogError($"Azure DNS zone \"{hostNames}\" is not found"); + + throw new InvalidOperationException(); + } + } + } + + [FunctionName(nameof(Dns01Authorization))] + public static async Task Dns01Authorization([ActivityTrigger] DurableActivityContext context, ILogger log) + { + var authzUrl = context.GetInput(); + + var acme = await CreateAcmeClientAsync(); + + var authz = await acme.GetAuthorizationDetailsAsync(authzUrl); + + // DNS-01 Challenge の情報を拾う + var challenge = authz.Challenges.First(x => x.Type == "dns-01"); + + var challengeValidationDetails = AuthorizationDecoder.ResolveChallengeForDns01(authz, challenge, acme.Signer); + + // Azure DNS の TXT レコードを書き換え + var dnsClient = await CreateDnsManagementClientAsync(); + + var zone = (await dnsClient.Zones.ListAsync()).First(x => challengeValidationDetails.DnsRecordName.EndsWith(x.Name)); + + var resourceId = ParseResourceId(zone.Id); + + // Challenge の詳細から Azure DNS 向けにレコード名を作成 + var acmeDnsRecordName = challengeValidationDetails.DnsRecordName.Replace("." + zone.Name, ""); + + RecordSet recordSet; + + try + { + recordSet = await dnsClient.RecordSets.GetAsync(resourceId["resourceGroups"], zone.Name, acmeDnsRecordName, RecordType.TXT); + } + catch + { + recordSet = null; + } + + if (recordSet != null) + { + if (recordSet.Metadata == null || !recordSet.Metadata.TryGetValue(nameof(context.InstanceId), out var instanceId) || instanceId != context.InstanceId) + { + recordSet.Metadata = new Dictionary + { + { nameof(context.InstanceId), context.InstanceId } + }; + + recordSet.TxtRecords.Clear(); + } + + // 既存の TXT レコードに値を追加する + recordSet.TxtRecords.Add(new TxtRecord(new[] { challengeValidationDetails.DnsRecordValue })); + } + else + { + // 新しく TXT レコードを作成する + recordSet = new RecordSet + { + TTL = 60, + Metadata = new Dictionary + { + { nameof(context.InstanceId), context.InstanceId } + }, + TxtRecords = new[] + { + new TxtRecord(new[] { challengeValidationDetails.DnsRecordValue }) + } + }; + } + + await dnsClient.RecordSets.CreateOrUpdateAsync(resourceId["resourceGroups"], zone.Name, acmeDnsRecordName, RecordType.TXT, recordSet); + + return challenge; + } + + [FunctionName(nameof(AnswerChallenges))] + public static async Task AnswerChallenges([ActivityTrigger] DurableActivityContext context, ILogger log) + { + var (orderDetails, challenges) = context.GetInput<(OrderDetails, IList)>(); + + var acme = await CreateAcmeClientAsync(); + + // Answer の準備が出来たことを通知 + foreach (var challenge in challenges) + { + await acme.AnswerChallengeAsync(challenge.Url); + } + + // Order のステータスが ready になるまで 60 秒待機 + for (int i = 0; i < 12; i++) + { + orderDetails = await acme.GetOrderDetailsAsync(orderDetails.OrderUrl, orderDetails); + + if (orderDetails.Payload.Status == "ready") + { + return; + } + + await Task.Delay(TimeSpan.FromSeconds(5)); + } + + log.LogError($"Timeout ACME challenge status : {orderDetails.Payload.Status}"); + + if (orderDetails.Payload.Error != null) + { + log.LogError($"{orderDetails.Payload.Error.Type},{orderDetails.Payload.Error.Status},{orderDetails.Payload.Error.Detail}"); + } + + throw new InvalidOperationException(); + } + + [FunctionName(nameof(FinalizeOrder))] + public static async Task FinalizeOrder([ActivityTrigger] DurableActivityContext context, ILogger log) + { + var (hostNames, orderDetails) = context.GetInput<(string[], OrderDetails)>(); + + var certificateName = hostNames[0].Replace(".", "-"); + + var keyVaultClient = CreateKeyVaultClient(); + + // Key Vault を使って CSR を作成 + var request = await keyVaultClient.CreateCertificateAsync(Settings.Default.VaultBaseUrl, certificateName, new CertificatePolicy + { + X509CertificateProperties = new X509CertificateProperties + { + SubjectAlternativeNames = new SubjectAlternativeNames(dnsNames: hostNames) + } + }, tags: new Dictionary + { + { "Issuer", "letsencrypt.org" } + }); + + var acme = await CreateAcmeClientAsync(); + + // Order の最終処理を実行し、証明書を作成 + var finalize = await acme.FinalizeOrderAsync(orderDetails.Payload.Finalize, request.Csr); + + var certificateData = await _httpClient.GetByteArrayAsync(finalize.Payload.Certificate); + + // X509Certificate2 を作成 + var certificate = new X509Certificate2(certificateData); + + await keyVaultClient.MergeCertificateAsync(Settings.Default.VaultBaseUrl, certificateName, new X509Certificate2Collection(certificate)); + } + + private static async Task CreateAcmeClientAsync() + { + var account = default(AccountDetails); + var accountKey = default(AccountKey); + var acmeDir = default(ServiceDirectory); + + LoadState(ref account, "account.json"); + LoadState(ref accountKey, "account_key.json"); + LoadState(ref acmeDir, "directory.json"); + + var acme = new AcmeProtocolClient(_acmeHttpClient, acmeDir, account, accountKey?.GenerateSigner()); + + if (acmeDir == null) + { + acmeDir = await acme.GetDirectoryAsync(); + + SaveState(acmeDir, "directory.json"); + + acme.Directory = acmeDir; + } + + await acme.GetNonceAsync(); + + if (account == null || accountKey == null) + { + account = await acme.CreateAccountAsync(new[] { "mailto:" + Settings.Default.Contacts }, true); + + accountKey = new AccountKey + { + KeyType = acme.Signer.JwsAlg, + KeyExport = acme.Signer.Export() + }; + + SaveState(account, "account.json"); + SaveState(accountKey, "account_key.json"); + + acme.Account = account; + } + + return acme; + } + + private static void LoadState(ref T value, string path) + { + var fullPath = Environment.ExpandEnvironmentVariables(@"%HOME%\.acme\" + path); + + if (!File.Exists(fullPath)) + { + return; + } + + var json = File.ReadAllText(fullPath); + + value = JsonConvert.DeserializeObject(json); + } + + private static void SaveState(T value, string path) + { + var fullPath = Environment.ExpandEnvironmentVariables(@"%HOME%\.acme\" + path); + var directoryPath = Path.GetDirectoryName(fullPath); + + if (!Directory.Exists(directoryPath)) + { + Directory.CreateDirectory(directoryPath); + } + + var json = JsonConvert.SerializeObject(value, Formatting.Indented); + + File.WriteAllText(fullPath, json); + } + + private static async Task CreateDnsManagementClientAsync() + { + var tokenProvider = new AzureServiceTokenProvider(); + + var accessToken = await tokenProvider.GetAccessTokenAsync("https://management.azure.com/"); + + var dnsClient = new DnsManagementClient(new TokenCredentials(accessToken)) + { + SubscriptionId = Settings.Default.SubscriptionId + }; + + return dnsClient; + } + + private static KeyVaultClient CreateKeyVaultClient() + { + var tokenProvider = new AzureServiceTokenProvider(); + + return new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback)); + } + + private static IDictionary ParseResourceId(string resourceId) + { + var values = resourceId.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); + + return new Dictionary + { + { "subscriptions", values[1] }, + { "resourceGroups", values[3] }, + { "providers", values[5] } + }; + } + } +} \ No newline at end of file diff --git a/AzureKeyVault.LetsEncrypt/host.json b/AzureKeyVault.LetsEncrypt/host.json new file mode 100644 index 00000000..b9f92c0d --- /dev/null +++ b/AzureKeyVault.LetsEncrypt/host.json @@ -0,0 +1,3 @@ +{ + "version": "2.0" +} \ No newline at end of file diff --git a/LICENSE b/LICENSE index 989e2c59..41764dd7 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ Apache License same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright [yyyy] [name of copyright owner] + Copyright 2018 Tatsuro Shibamura Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.