Skip to content

[KeyVault] Supported getting random number from managed HSM by Get-AzKeyVaultRandomNumber #17778

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/KeyVault/KeyVault/Az.KeyVault.psd1
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ CmdletsToExport = 'Add-AzKeyVaultCertificate', 'Update-AzKeyVaultCertificate',
'New-AzKeyVaultRoleDefinition', 'Remove-AzKeyVaultRoleDefinition',
'Remove-AzKeyVaultRoleAssignment', 'Remove-AzKeyVaultAccessPolicy',
'Set-AzKeyVaultAccessPolicy', 'Backup-AzKeyVaultKey',
'Get-AzKeyVaultKey', 'Get-AzKeyVaultSecret',
'Get-AzKeyVaultKey', 'Get-AzKeyVaultSecret', 'Get-AzKeyVaultRandomNumber',
'Undo-AzKeyVaultKeyRemoval', 'Undo-AzKeyVaultSecretRemoval',
'Add-AzKeyVaultKey', 'Remove-AzKeyVaultKey', 'Update-AzKeyVault',
'New-AzKeyVaultNetworkRuleSetObject', 'Remove-AzKeyVaultSecret',
Expand Down
1 change: 1 addition & 0 deletions src/KeyVault/KeyVault/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Additional information about change #1
-->
## Upcoming Release
* Supported getting random number from managed HSM by `Get-AzKeyVaultRandomNumber`
* Skipped subscription connection status validation for Az.KeyVault.Extension [#17712]
* Enabled public network access setting

Expand Down
97 changes: 97 additions & 0 deletions src/KeyVault/KeyVault/Commands/Key/GetAzKeyVaultRandomNumber.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using Microsoft.Azure.Commands.KeyVault.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Internal.Resources.Utilities.Models;

using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Text;

namespace Microsoft.Azure.Commands.KeyVault.Commands.Key
{
[Cmdlet("Get", ResourceManager.Common.AzureRMConstants.AzurePrefix + "KeyVaultRandomNumber", DefaultParameterSetName = GetByHsmNameParameterSet)]
[OutputType(typeof(string), typeof(byte))]
public class GetAzKeyVaultRandomNumber: KeyVaultCmdletBase
{
#region Parameter Set Names

private const string GetByHsmNameParameterSet = "GetByHsmName";
private const string GetByHsmInputObjectNameParameterSet = "GetByHsmInputObject";
private const string GetByHsmResourceIdParameterSet = "GetByHsmResourceId";

#endregion

#region Input Parameter Definitions

/// <summary>
/// HSM Name
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = GetByHsmNameParameterSet,
HelpMessage = "HSM name. Cmdlet constructs the FQDN of a managed HSM based on the name and currently selected environment.")]
[ResourceNameCompleter("Microsoft.KeyVault/managedHSMs", "FakeResourceGroupName")]
[ValidateNotNullOrEmpty]
public string HsmName;

/// <summary>
/// HSM Input Object
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ParameterSetName = GetByHsmInputObjectNameParameterSet,
HelpMessage = "HSM object.")]
[ValidateNotNullOrEmpty]
public PSManagedHsm InputObject;

/// <summary>
/// HSM Resource Id
/// </summary>
[Parameter(Mandatory = true,
Position = 0,
ParameterSetName = GetByHsmResourceIdParameterSet,
ValueFromPipelineByPropertyName = true,
HelpMessage = "HSM resource id.")]
[ValidateNotNullOrEmpty]
public string ResourceId { get; set; }

[Parameter(Mandatory = true,
HelpMessage = "The requested number of random bytes.")]
[ValidateRange(1, 128)]
public int Count;

[Parameter(Mandatory = false,
HelpMessage = "If specified, return random number as base-64 digit. By default, this command retruns random number as byte array.")]
public SwitchParameter AsBase64String;

#endregion

public override void ExecuteCmdlet()
{
NormalizeKeySourceParameters();
var result = Track2DataClient.GetManagedHsmRandomNumber(HsmName, Count);
if(AsBase64String.IsPresent)
{
this.WriteObject(Convert.ToBase64String(result));
}
else
{
this.WriteObject(result, true);
}
}

private void NormalizeKeySourceParameters()
{
if (InputObject != null)
{
HsmName = InputObject.Name;
}
else if (ResourceId != null)
{
var resourceIdentifier = new ResourceIdentifier(ResourceId);
HsmName = resourceIdentifier.ResourceName;
}
}
}
}
2 changes: 2 additions & 0 deletions src/KeyVault/KeyVault/Models/IKeyVaultDataServiceClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ public interface IKeyVaultDataServiceClient

PSKeyVaultKey RestoreManagedHsmKey(string managedHsmName, string inputBlobPath);

byte[] GetManagedHsmRandomNumber(string managedHsmName, int count);

#region Key rotation
PSKeyVaultKey RotateManagedHsmKey(string managedHsmName, string keyName);

Expand Down
5 changes: 5 additions & 0 deletions src/KeyVault/KeyVault/Models/KeyVaultDataServiceClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2204,6 +2204,11 @@ public PSKeyOperationResult ManagedHsmWrapKey(string managedHsmName, string keyN
throw new NotImplementedException("Wrapping keys on managed HSM is only possible in track 2 SDK.");
}

public byte[] GetManagedHsmRandomNumber(string managedHsmName, int count)
{
throw new NotImplementedException("Getting random number on managed HSM is only possible in track 2 SDK.");
}

#region Key rotation
public PSKeyVaultKey RotateManagedHsmKey(string managedHsmName, string keyName)
{
Expand Down
10 changes: 10 additions & 0 deletions src/KeyVault/KeyVault/Track2Models/Track2HsmClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,16 @@ internal void PurgeKey(string managedHsmName, string keyName)
throw GetInnerException(ex);
}
}

public byte[] GetRandomNumberBytes(string managedHsmName, int count)
{
if (string.IsNullOrEmpty(managedHsmName))
throw new ArgumentNullException(nameof(managedHsmName));

var client = CreateKeyClient(managedHsmName);
return client.GetRandomBytes(count);
}

#endregion

#region Key rotation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,11 @@ public PSKeyVaultKey RestoreKey(string vaultName, string inputBlobPath)
throw new NotImplementedException();
}

public byte[] GetRandomNumber()
{
throw new NotImplementedException();
}

#region Key rotation
public PSKeyVaultKey RotateKey(string vaultName, string keyName)
{
Expand Down Expand Up @@ -576,6 +581,12 @@ public PSKeyVaultKey RestoreManagedHsmKey(string managedHsmName, string inputBlo
{
return HsmClient.RestoreKey(managedHsmName, inputBlobPath);
}

public byte[] GetManagedHsmRandomNumber(string managedHsmName, int count)
{
return HsmClient.GetRandomNumberBytes(managedHsmName, count);
}

#endregion

#region Key rotation
Expand Down
199 changes: 199 additions & 0 deletions src/KeyVault/KeyVault/help/Get-AzKeyVaultRandomNumber.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
---
external help file: Microsoft.Azure.PowerShell.Cmdlets.KeyVault.dll-Help.xml
Module Name: Az.KeyVault
online version: https://docs.microsoft.com/powershell/module/az.keyvault/get-azkeyvaultrandomnumber
schema: 2.0.0
---

# Get-AzKeyVaultRandomNumber

## SYNOPSIS
Get the requested number of bytes containing random values from a managed HSM.

## SYNTAX

### GetByHsmName (Default)
```
Get-AzKeyVaultRandomNumber [-DefaultProfile <IAzureContextContainer>] [-HsmName] <String> -Count <Int32>
[-AsBase64String] [<CommonParameters>]
```

### GetByHsmResourceId
```
Get-AzKeyVaultRandomNumber [-ResourceId] <String> [-DefaultProfile <IAzureContextContainer>] -Count <Int32>
[-AsBase64String] [<CommonParameters>]
```

### GetByHsmInputObject
```
Get-AzKeyVaultRandomNumber [-DefaultProfile <IAzureContextContainer>] [-InputObject] <PSManagedHsm>
-Count <Int32> [-AsBase64String] [<CommonParameters>]
```

## DESCRIPTION
Get the requested number of bytes containing random values from a managed HSM.

## EXAMPLES

### Example 1: Get requested number of random bytes by managed HSM name
```powershell
Get-AzKeyVaultRandomNumber -HsmName testmhsm -Count 10
```

```output
158
171
96
142
109
28
1
85
178
201
```

This command gets 10 random bytes from managed HSM "testmhsm"

### Example 2: Get random number as base64 string by piping
```powershell
Get-AzKeyVaultManagedHsm -HsmName bezmhsm2022 | Get-AzKeyVaultRandomNumber -Count 10 -AsBase64String
```

```output
G1CsEqa9yUp/EA==
```

This command gets 10 random bytes as base-64 string from managed HSM "testmhsm"

### Example 3: Get random number by resource id
```powershell
Get-AzKeyVaultRandomNumber -ResourceId /subscriptions/0b1fxxxx-xxxx-xxxx-aec3-xxxx72f09590/resourceGroups/test-rg/provders/Microsoft.KeyVault/managedHSMs/testhsm -Count 10
```

```output
158
171
96
142
109
28
1
85
178
201
```

This command gets 10 random bytes from managed HSM with specified resource id

## PARAMETERS

### -AsBase64String
If specified, return random number as base-64 digit.
By default, this command retruns random number as byte array.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Count
The requested number of random bytes.

```yaml
Type: System.Int32
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with Azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzContext, AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -HsmName
HSM name. Cmdlet constructs the FQDN of a managed HSM based on the name and currently selected environment.

```yaml
Type: System.String
Parameter Sets: GetByHsmName
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -InputObject
HSM object.

```yaml
Type: Microsoft.Azure.Commands.KeyVault.Models.PSManagedHsm
Parameter Sets: GetByHsmInputObject
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByValue)
Accept wildcard characters: False
```

### -ResourceId
HSM resource id.

```yaml
Type: System.String
Parameter Sets: GetByHsmResourceId
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### System.String

### Microsoft.Azure.Commands.KeyVault.Models.PSManagedHsm

## OUTPUTS

### System.String

### System.Byte

## NOTES

## RELATED LINKS