/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.KeyManagementService; using Amazon.KeyManagementService.Model; namespace Amazon.PowerShell.Cmdlets.KMS { /// /// Imports or reimports key material into an existing KMS key that was created without /// key material. ImportKeyMaterial also sets the expiration model and expiration /// date of the imported key material. /// /// /// /// By default, KMS keys are created with key material that KMS generates. This operation /// supports Importing /// key material, an advanced feature that lets you generate and import the cryptographic /// key material for a KMS key. For more information about importing key material into /// KMS, see Importing /// key material in the Key Management Service Developer Guide. /// /// After you successfully import key material into a KMS key, you can reimport /// the same key material into that KMS key, but you cannot import different key material. /// You might reimport key material to replace key material that expired or key material /// that you deleted. You might also reimport key material to change the expiration model /// or expiration date of the key material. Before reimporting key material, if necessary, /// call DeleteImportedKeyMaterial to delete the current imported key material. /// /// /// Each time you import key material into KMS, you can determine whether (ExpirationModel) /// and when (ValidTo) the key material expires. To change the expiration /// of your key material, you must import it again, either by calling ImportKeyMaterial /// or using the import /// features of the KMS console. /// /// Before calling ImportKeyMaterial: /// /// Then, in an ImportKeyMaterial request, you submit your encrypted key /// material and import token. When calling this operation, you must specify the following /// values: /// /// When this operation is successful, the key state of the KMS key changes from PendingImport /// to Enabled, and you can use the KMS key in cryptographic operations. /// /// If this operation fails, use the exception to help determine the problem. If the error /// is related to the key material, the import token, or wrapping key, use GetParametersForImport /// to get a new public key and import token for the KMS key and repeat the import procedure. /// For help, see How /// To Import Key Material in the Key Management Service Developer Guide. /// /// The KMS key that you use for this operation must be in a compatible key state. For /// details, see Key /// states of KMS keys in the Key Management Service Developer Guide. /// Cross-account use: No. You cannot perform this operation on a KMS key in a /// different Amazon Web Services account. /// Required permissions: kms:ImportKeyMaterial /// (key policy) /// Related operations: /// [Cmdlet("Import", "KMSKeyMaterial", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("None")] [AWSCmdlet("Calls the AWS Key Management Service ImportKeyMaterial API operation.", Operation = new[] {"ImportKeyMaterial"}, SelectReturnType = typeof(Amazon.KeyManagementService.Model.ImportKeyMaterialResponse))] [AWSCmdletOutput("None or Amazon.KeyManagementService.Model.ImportKeyMaterialResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.KeyManagementService.Model.ImportKeyMaterialResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class ImportKMSKeyMaterialCmdlet : AmazonKeyManagementServiceClientCmdlet, IExecutor { #region Parameter EncryptedKeyMaterial /// /// /// The encrypted key material to import. The key material must be encrypted under the /// public wrapping key that GetParametersForImport returned, using the wrapping /// algorithm that you specified in the same GetParametersForImport request. /// /// The cmdlet will automatically convert the supplied parameter of type string, string[], System.IO.FileInfo or System.IO.Stream to byte[] before supplying it to the service. /// #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [Amazon.PowerShell.Common.MemoryStreamParameterConverter] public byte[] EncryptedKeyMaterial { get; set; } #endregion #region Parameter ExpirationModel /// /// /// Specifies whether the key material expires. The default is KEY_MATERIAL_EXPIRES. /// For help with this choice, see Setting /// an expiration time in the Key Management Service Developer Guide.When the value of ExpirationModel is KEY_MATERIAL_EXPIRES, /// you must specify a value for the ValidTo parameter. When value is KEY_MATERIAL_DOES_NOT_EXPIRE, /// you must omit the ValidTo parameter.You cannot change the ExpirationModel or ValidTo values /// for the current import after the request completes. To change either value, you must /// reimport the key material. /// /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [AWSConstantClassSource("Amazon.KeyManagementService.ExpirationModelType")] public Amazon.KeyManagementService.ExpirationModelType ExpirationModel { get; set; } #endregion #region Parameter ImportToken /// /// /// The import token that you received in the response to a previous GetParametersForImport /// request. It must be from the same response that contained the public key that you /// used to encrypt the key material. /// /// The cmdlet will automatically convert the supplied parameter of type string, string[], System.IO.FileInfo or System.IO.Stream to byte[] before supplying it to the service. /// #if !MODULAR [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] #else [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] [Amazon.PowerShell.Common.MemoryStreamParameterConverter] public byte[] ImportToken { get; set; } #endregion #region Parameter KeyId /// /// /// The identifier of the KMS key that will be associated with the imported key material. /// This must be the same KMS key specified in the KeyID parameter of the /// corresponding GetParametersForImport request. The Origin of the /// KMS key must be EXTERNAL and its KeyState must be PendingImport. /// The KMS key can be a symmetric encryption KMS key, HMAC KMS key, asymmetric encryption /// KMS key, or asymmetric signing KMS key, including a multi-Region /// key of any supported type. You cannot perform this operation on a KMS key in a /// custom key store, or on a KMS key in a different Amazon Web Services account.Specify the key ID or key ARN of the KMS key.For example:To get the key ID and key ARN for a KMS key, use ListKeys or DescribeKey. /// /// #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String KeyId { get; set; } #endregion #region Parameter ValidTo /// /// /// The date and time when the imported key material expires. This parameter is required /// when the value of the ExpirationModel parameter is KEY_MATERIAL_EXPIRES. /// Otherwise it is not valid.The value of this parameter must be a future date and time. The maximum value is 365 /// days from the request date.When the key material expires, KMS deletes the key material from the KMS key. Without /// its key material, the KMS key is unusable. To use the KMS key in cryptographic operations, /// you must reimport the same key material.You cannot change the ExpirationModel or ValidTo values /// for the current import after the request completes. To change either value, you must /// delete (DeleteImportedKeyMaterial) and reimport the key material. /// /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.DateTime? ValidTo { get; set; } #endregion #region Parameter Select /// /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.KeyManagementService.Model.ImportKeyMaterialResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// /// Changes the cmdlet behavior to return the value passed to the KeyId parameter. /// The -PassThru parameter is deprecated, use -Select '^KeyId' instead. This parameter will be removed in a future version. /// [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^KeyId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { this._AWSSignerType = "v4"; base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.KeyId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Import-KMSKeyMaterial (ImportKeyMaterial)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.KeyId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.EncryptedKeyMaterial = this.EncryptedKeyMaterial; #if MODULAR if (this.EncryptedKeyMaterial == null && ParameterWasBound(nameof(this.EncryptedKeyMaterial))) { WriteWarning("You are passing $null as a value for parameter EncryptedKeyMaterial which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ExpirationModel = this.ExpirationModel; context.ImportToken = this.ImportToken; #if MODULAR if (this.ImportToken == null && ParameterWasBound(nameof(this.ImportToken))) { WriteWarning("You are passing $null as a value for parameter ImportToken which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.KeyId = this.KeyId; #if MODULAR if (this.KeyId == null && ParameterWasBound(nameof(this.KeyId))) { WriteWarning("You are passing $null as a value for parameter KeyId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif context.ValidTo = this.ValidTo; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { System.IO.MemoryStream _EncryptedKeyMaterialStream = null; System.IO.MemoryStream _ImportTokenStream = null; try { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.KeyManagementService.Model.ImportKeyMaterialRequest(); if (cmdletContext.EncryptedKeyMaterial != null) { _EncryptedKeyMaterialStream = new System.IO.MemoryStream(cmdletContext.EncryptedKeyMaterial); request.EncryptedKeyMaterial = _EncryptedKeyMaterialStream; } if (cmdletContext.ExpirationModel != null) { request.ExpirationModel = cmdletContext.ExpirationModel; } if (cmdletContext.ImportToken != null) { _ImportTokenStream = new System.IO.MemoryStream(cmdletContext.ImportToken); request.ImportToken = _ImportTokenStream; } if (cmdletContext.KeyId != null) { request.KeyId = cmdletContext.KeyId; } if (cmdletContext.ValidTo != null) { request.ValidTo = cmdletContext.ValidTo.Value; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } finally { if( _EncryptedKeyMaterialStream != null) { _EncryptedKeyMaterialStream.Dispose(); } if( _ImportTokenStream != null) { _ImportTokenStream.Dispose(); } } } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.KeyManagementService.Model.ImportKeyMaterialResponse CallAWSServiceOperation(IAmazonKeyManagementService client, Amazon.KeyManagementService.Model.ImportKeyMaterialRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Key Management Service", "ImportKeyMaterial"); try { #if DESKTOP return client.ImportKeyMaterial(request); #elif CORECLR return client.ImportKeyMaterialAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public byte[] EncryptedKeyMaterial { get; set; } public Amazon.KeyManagementService.ExpirationModelType ExpirationModel { get; set; } public byte[] ImportToken { get; set; } public System.String KeyId { get; set; } public System.DateTime? ValidTo { get; set; } public System.Func Select { get; set; } = (response, cmdlet) => null; } } }