-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
257 lines (210 loc) · 10.5 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Azure.Identity;
using Azure.Security.KeyVault.Keys;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.KeyVault.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Samples.Common;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Newtonsoft.Json;
namespace ManageSqlServerKeysWithAzureKeyVaultKey
{
public class Program
{
private static string Azure_SP_ClientId;
private static string Azure_SP_Secret;
private static readonly string sqlServerName = SdkContext.RandomResourceName("sqlserver", 20);
private static readonly string rgName = SdkContext.RandomResourceName("rgsql", 20);
private static readonly string administratorLogin = "sqladmin3423";
private static readonly string administratorPassword = Utilities.CreatePassword();
private static readonly string vaultName = SdkContext.RandomResourceName("sqlkv", 20);
private static readonly string keyName = SdkContext.RandomResourceName("sqlkey", 20);
/**
* Azure SQL sample for managing SQL secrets (Server Keys) using Azure Key Vault -
* - Create a SQL Server with "system assigned" managed service identity.
* - Create an Azure Key Vault with giving access to the SQL Server
* - Create, get, list and delete SQL Server Keys
* - Delete SQL Server
*/
public static async Task RunSample(IAzure azure)
{
try
{
// ============================================================
// Create a SQL Server with system assigned managed service identity.
Utilities.Log("Creating a SQL Server with system assigned managed service identity");
var sqlServer = azure.SqlServers.Define(sqlServerName)
.WithRegion(Region.USSouthCentral)
.WithNewResourceGroup(rgName)
.WithAdministratorLogin(administratorLogin)
.WithAdministratorPassword(administratorPassword)
.WithSystemAssignedManagedServiceIdentity()
.Create();
Utilities.PrintSqlServer(sqlServer);
// ============================================================
// Create an Azure Key Vault and set the access policies.
Utilities.Log("Creating an Azure Key Vault and set the access policies");
InitializeCredentials(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
if (Azure_SP_ClientId == null || Azure_SP_Secret == null)
{
throw new ArgumentNullException("Missing Client ID and Secret");
}
var vault = azure.Vaults.Define(vaultName)
.WithRegion(Region.USSouthCentral)
.WithExistingResourceGroup(rgName)
.DefineAccessPolicy()
.ForObjectId(sqlServer.SystemAssignedManagedServiceIdentityPrincipalId)
.AllowKeyPermissions(KeyPermissions.WrapKey, KeyPermissions.UnwrapKey, KeyPermissions.Get, KeyPermissions.List)
.Attach()
.DefineAccessPolicy()
.ForServicePrincipal(Azure_SP_ClientId)
.AllowKeyAllPermissions()
.Attach()
.Create();
SdkContext.DelayProvider.Delay(3 * 60 * 1000);
// ============================================================
// Create a SQL server key with Azure Key Vault key.
Utilities.Log("Creating a SQL server key with Azure Key Vault key");
var kvClient = new KeyClient(new Uri(vault.VaultUri), new DefaultAzureCredential());
var keyBundle = await kvClient.CreateKeyAsync(keyName, KeyType.Rsa);
string keyUri = keyBundle.Value.Key.Id;
// Work around for SQL server key name must be formatted as "vault_key_version"
string serverKeyName = $"{vaultName}_{keyName}_" +
keyUri.Substring(keyUri.LastIndexOf("/") + 1);
var sqlServerKey = sqlServer.ServerKeys.Define()
.WithAzureKeyVaultKey(keyUri)
.Create();
Utilities.PrintSqlServerKey(sqlServerKey);
// Validate key exists by getting key
Utilities.Log("Validating key exists by getting the key");
sqlServerKey = sqlServer.ServerKeys.Get(serverKeyName);
Utilities.PrintSqlServerKey(sqlServerKey);
// Validate key exists by listing keys
Utilities.Log("Validating key exists by listing keys");
var serverKeys = sqlServer.ServerKeys.List();
foreach (var item in serverKeys)
{
Utilities.PrintSqlServerKey(item);
}
// Delete key
Utilities.Log("Deleting the key");
azure.SqlServers.ServerKeys.DeleteBySqlServer(rgName, sqlServerName, serverKeyName);
// Delete the SQL Server.
Utilities.Log("Deleting a Sql Server");
azure.SqlServers.DeleteById(sqlServer.Id);
}
finally
{
try
{
Utilities.Log("Deleting Resource Group: " + rgName);
azure.ResourceGroups.DeleteByName(rgName);
Utilities.Log("Deleted Resource Group: " + rgName);
}
catch (Exception e)
{
Utilities.Log(e);
}
}
}
public async static Task Main(string[] args)
{
try
{
//=================================================================
// Authenticate
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Microsoft.Azure.Management.Fluent.Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
// Print selected subscription
Utilities.Log("Selected subscription: " + azure.SubscriptionId);
await RunSample(azure);
}
catch (Exception e)
{
Utilities.Log(e.ToString());
}
}
//the method that will be provided to the KeyVaultClient
public static async Task<string> GetToken(string authority, string resource, string scope)
{
//=================================================================
// Authenticate
var authContext = new AuthenticationContext(authority);
ClientCredential clientCred = new ClientCredential(Azure_SP_ClientId, Azure_SP_Secret);
AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);
if (result == null)
throw new InvalidOperationException("Failed to obtain the JWT token");
return result.AccessToken;
}
public static void InitializeCredentials(string authFile)
{
var config = new Dictionary<string, string>()
{
{ "authurl", AzureEnvironment.AzureGlobalCloud.AuthenticationEndpoint },
{ "baseurl", AzureEnvironment.AzureGlobalCloud.ResourceManagerEndpoint },
{ "managementuri", AzureEnvironment.AzureGlobalCloud.ManagementEndpoint },
{ "graphurl", AzureEnvironment.AzureGlobalCloud.GraphEndpoint }
};
var lines = File.ReadLines(authFile);
if (lines.First().Trim().StartsWith("{"))
{
string json = string.Join("", lines);
AuthFile jsonConfig = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<AuthFile>(json);
jsonConfig.GetType()
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic)
.ToList()
.ForEach(info => config[info.Name] = (string)info.GetValue(jsonConfig));
}
else
{
lines.All(line =>
{
if (line.Trim().StartsWith("#"))
return true; // Ignore comments
var keyVal = line.Trim().Split(new char[] { '=' }, 2);
if (keyVal.Length < 2)
return true; // Ignore lines that don't look like $$$=$$$
config[keyVal[0].ToLowerInvariant()] = keyVal[1];
return true;
});
}
Azure_SP_ClientId = config["client"];
Azure_SP_Secret = config["key"];
}
private class AuthFile
{
[JsonProperty("clientId")]
private string client;
[JsonProperty("tenantId")]
private string tenant;
[JsonProperty("clientSecret")]
private string key;
[JsonProperty("clientCertificate")]
private string certificate;
[JsonProperty("clientCertificatePassword")]
private string certificatepassword;
[JsonProperty("subscriptionId")]
private string subscription;
[JsonProperty("activeDirectoryEndpointUrl")]
private string authurl;
[JsonProperty("resourceManagerEndpointUrl")]
private string baseurl;
[JsonProperty("managementEndpointUrl")]
private string managementuri;
[JsonProperty("activeDirectoryGraphResourceId")]
private string graphurl;
}
}
}