|
| 1 | +// ---------------------------------------------------------------------------------- |
| 2 | +// |
| 3 | +// Copyright Microsoft Corporation |
| 4 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +// you may not use this file except in compliance with the License. |
| 6 | +// You may obtain a copy of the License at |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | +// ---------------------------------------------------------------------------------- |
| 14 | + |
| 15 | +using Microsoft.WindowsAzure.Management; |
| 16 | +using Microsoft.WindowsAzure.Management.EventSources; |
| 17 | +using Security.Cryptography; |
| 18 | +using Security.Cryptography.X509Certificates; |
| 19 | +using System; |
| 20 | +using System.Collections.Generic; |
| 21 | +using System.Linq; |
| 22 | +using System.Security.Cryptography; |
| 23 | +using System.Security.Cryptography.X509Certificates; |
| 24 | +using System.Text; |
| 25 | +using System.Threading.Tasks; |
| 26 | + |
| 27 | +namespace Microsoft.Azure.Commands.AzureBackup.Cmdlets |
| 28 | +{ |
| 29 | + /// <summary> |
| 30 | + /// Certificate utility methods |
| 31 | + /// </summary> |
| 32 | + public class CertUtils |
| 33 | + { |
| 34 | + public const string MsEnhancedProv = "Microsoft Enhanced Cryptographic Provider v1.0"; |
| 35 | + public const string DefaultIssuer = "CN=Windows Azure Tools"; |
| 36 | + |
| 37 | + public const string DefaultPassword = ""; |
| 38 | + public const string OIDClientAuthValue = "1.3.6.1.5.5.7.3.2"; |
| 39 | + public const string OIDClientAuthFriendlyName = "Client Authentication"; |
| 40 | + public const int KeySize2048 = 2048; |
| 41 | + |
| 42 | + /// <summary> |
| 43 | + /// Windows Azure Service Management API requires 2048bit RSA keys. |
| 44 | + /// The private key needs to be exportable so we can save it to .pfx for sharing with team members. |
| 45 | + /// </summary> |
| 46 | + /// <returns>A 2048 bit RSA key</returns> |
| 47 | + private static CngKey Create2048RsaKey() |
| 48 | + { |
| 49 | + var keyCreationParameters = new CngKeyCreationParameters |
| 50 | + { |
| 51 | + ExportPolicy = CngExportPolicies.AllowExport, |
| 52 | + KeyCreationOptions = CngKeyCreationOptions.None, |
| 53 | + KeyUsage = CngKeyUsages.AllUsages, |
| 54 | + Provider = new CngProvider(MsEnhancedProv) |
| 55 | + }; |
| 56 | + |
| 57 | + keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(KeySize2048), CngPropertyOptions.None)); |
| 58 | + |
| 59 | + return CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters); |
| 60 | + } |
| 61 | + |
| 62 | + /// <summary> |
| 63 | + /// Creates a new self-signed X509 certificate |
| 64 | + /// </summary> |
| 65 | + /// <param name="issuer">The certificate issuer</param> |
| 66 | + /// <param name="friendlyName">Human readable name</param> |
| 67 | + /// <param name="password">The certificate's password</param> |
| 68 | + /// <param name="startTime">Certificate creation date & time</param> |
| 69 | + /// <param name="endTime">Certificate expiry date & time</param> |
| 70 | + /// <returns>An X509Certificate2</returns> |
| 71 | + public static X509Certificate2 CreateSelfSignedCert(string issuer, string friendlyName, string password, DateTime startTime, DateTime endTime) |
| 72 | + { |
| 73 | + string distinguishedNameString = issuer; |
| 74 | + var key = Create2048RsaKey(); |
| 75 | + |
| 76 | + var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(distinguishedNameString)) |
| 77 | + { |
| 78 | + TakeOwnershipOfKey = true, |
| 79 | + StartTime = startTime, |
| 80 | + EndTime = endTime |
| 81 | + }; |
| 82 | + |
| 83 | + // adding client authentication, -eku = 1.3.6.1.5.5.7.3.2, |
| 84 | + // This is mandatory for the upload to be successful |
| 85 | + OidCollection oidCollection = new OidCollection(); |
| 86 | + oidCollection.Add(new Oid(OIDClientAuthValue, OIDClientAuthFriendlyName)); |
| 87 | + creationParams.Extensions.Add(new X509EnhancedKeyUsageExtension(oidCollection, false)); |
| 88 | + |
| 89 | + // Documentation of CreateSelfSignedCertificate states: |
| 90 | + // If creationParameters have TakeOwnershipOfKey set to true, the certificate |
| 91 | + // generated will own the key and the input CngKey will be disposed to ensure |
| 92 | + // that the caller doesn't accidentally use it beyond its lifetime (which is |
| 93 | + // now controlled by the certificate object). |
| 94 | + // We don't dispose it ourselves in this case. |
| 95 | + var cert = key.CreateSelfSignedCertificate(creationParams); |
| 96 | + key = null; |
| 97 | + cert.FriendlyName = friendlyName; |
| 98 | + |
| 99 | + // X509 certificate needs PersistKeySet flag set. |
| 100 | + // Reload a new X509Certificate2 instance from exported bytes in order to set the PersistKeySet flag. |
| 101 | + var bytes = cert.Export(X509ContentType.Pfx, password); |
| 102 | + |
| 103 | + // NOTE: PfxValidation is not done here because these are newly created certs and assumed valid. |
| 104 | + |
| 105 | + ICommonEventSource evtSource = null; |
| 106 | + return X509Certificate2Helper.NewX509Certificate2(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable, evtSource, doPfxValidation: false); |
| 107 | + } |
| 108 | + |
| 109 | + /// <summary> |
| 110 | + /// Returns serialized certificate - Base64 encoded based on the content type |
| 111 | + /// </summary> |
| 112 | + /// <param name="cert">The certificate provided</param> |
| 113 | + /// <param name="contentType">Cert content type</param> |
| 114 | + /// <returns>The serialized cert value in string</returns> |
| 115 | + public static string SerializeCert(X509Certificate2 cert, X509ContentType contentType) |
| 116 | + { |
| 117 | + return Convert.ToBase64String(cert.Export(contentType)); |
| 118 | + } |
| 119 | + |
| 120 | + /// <summary> |
| 121 | + /// Generates friendly name |
| 122 | + /// </summary> |
| 123 | + /// <param name="subscriptionId">Subscription id</param> |
| 124 | + /// <param name="prefix">Prefix, likely resource name</param> |
| 125 | + /// <returns>Friendly name</returns> |
| 126 | + public static string GenerateCertFriendlyName(string subscriptionId, string prefix = "") |
| 127 | + { |
| 128 | + return string.Format("{0}{1}-{2}-vaultcredentials", prefix, subscriptionId, DateTime.Now.ToString("M-d-yyyy")); |
| 129 | + } |
| 130 | + } |
| 131 | +} |
0 commit comments