Skip to content

Commit

Permalink
Merge pull request #3605 from dougm/crypto-key-status
Browse files Browse the repository at this point in the history
api: add crypto.ManagerKmip.QueryCryptoKeyStatus
  • Loading branch information
dougm authored Oct 29, 2024
2 parents def262d + 5c54c3f commit bbb6349
Show file tree
Hide file tree
Showing 8 changed files with 497 additions and 4 deletions.
62 changes: 59 additions & 3 deletions crypto/manager_kmip.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ import (
"github.com/vmware/govmomi/vim25/types"
)

const (
CheckKeyAvailable = int32(0x01)
CheckKeyUsedByVms = int32(0x02)
CheckKeyUsedByHosts = int32(0x04)
CheckKeyUsedByOther = int32(0x08)
)

type ManagerKmip struct {
object.Common
}
Expand Down Expand Up @@ -313,6 +320,24 @@ func (m ManagerKmip) RemoveKmipServer(
return nil
}

func (m ManagerKmip) QueryCryptoKeyStatus(
ctx context.Context,
ids []types.CryptoKeyId,
check int32) ([]types.CryptoManagerKmipCryptoKeyStatus, error) {

req := types.QueryCryptoKeyStatus{
This: m.Reference(),
KeyIds: ids,
CheckKeyBitMap: check,
}

res, err := methods.QueryCryptoKeyStatus(ctx, m.Client(), &req)
if err != nil {
return nil, err
}
return res.Returnval, nil
}

func (m ManagerKmip) ListKeys(
ctx context.Context,
limit *int32) ([]types.CryptoKeyId, error) {
Expand All @@ -328,17 +353,33 @@ func (m ManagerKmip) ListKeys(
return res.Returnval, nil
}

const keyStateNotActiveOrEnabled = string(types.CryptoManagerKmipCryptoKeyStatusKeyUnavailableReasonKeyStateNotActiveOrEnabled)

// IsValidKey returns true if QueryCryptoKeyStatus results indicate the key is available or unavailable reason is `KeyStateNotActiveOrEnabled`.
// This method is only valid for standard providers and will always return false for native providers.
func (m ManagerKmip) IsValidKey(
ctx context.Context,
providerID,
keyID string) (bool, error) {

keys, err := m.ListKeys(ctx, nil)
id := []types.CryptoKeyId{{
KeyId: keyID,
ProviderId: &types.KeyProviderId{
Id: providerID,
}},
}

res, err := m.QueryCryptoKeyStatus(ctx, id, CheckKeyAvailable)
if err != nil {
return false, err
}

for i := range keys {
if keys[i].KeyId == keyID {
for _, status := range res {
if status.KeyAvailable != nil && *status.KeyAvailable {
return true, nil
}

if status.Reason == keyStateNotActiveOrEnabled {
return true, nil
}
}
Expand Down Expand Up @@ -413,6 +454,21 @@ func (m ManagerKmip) GenerateKey(
return res.Returnval.KeyId.KeyId, nil
}

func (m ManagerKmip) RemoveKeys(
ctx context.Context,
ids []types.CryptoKeyId,
force bool) error {

req := types.RemoveKeys{
This: m.Reference(),
Keys: ids,
Force: force,
}

_, err := methods.RemoveKeys(ctx, m.Client(), &req)
return err
}

type generateKeyError struct {
types.LocalizedMethodFault
reason string
Expand Down
2 changes: 1 addition & 1 deletion crypto/manager_kmip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -987,7 +987,7 @@ func TestCryptoManagerKmip(t *testing.T) {
assert.NoError(t, err)
assert.NotEmpty(t, keyID)

ok, err := m.IsValidKey(ctx, keyID)
ok, err := m.IsValidKey(ctx, providerID, keyID)
assert.NoError(t, err)
assert.True(t, ok)
})
Expand Down
77 changes: 77 additions & 0 deletions govc/kms/key/create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
Copyright (c) 2024-2024 VMware, Inc. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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.
*/

package key

import (
"context"
"flag"
"fmt"

"github.com/vmware/govmomi/crypto"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
)

type create struct {
*flags.ClientFlag
}

func init() {
cli.Register("kms.key.create", &create{}, true)
}

func (cmd *create) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
}

func (cmd *create) Usage() string {
return "ID"
}

func (cmd *create) Description() string {
return `Generate crypto key.
Examples:
govc kms.key.create my-kp`
}

func (cmd *create) Run(ctx context.Context, f *flag.FlagSet) error {
id := f.Arg(0)
if id == "" {
return flag.ErrHelp
}

c, err := cmd.Client()
if err != nil {
return err
}

m, err := crypto.GetManagerKmip(c)
if err != nil {
return err
}

key, err := m.GenerateKey(ctx, id)
if err != nil {
return err
}

fmt.Println(key)

return nil
}
182 changes: 182 additions & 0 deletions govc/kms/key/info.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/*
Copyright (c) 2024-2024 VMware, Inc. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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.
*/

package key

import (
"context"
"flag"
"fmt"
"io"
"strconv"
"text/tabwriter"

"github.com/vmware/govmomi/crypto"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/govc/cli"
"github.com/vmware/govmomi/govc/flags"
"github.com/vmware/govmomi/vim25"
"github.com/vmware/govmomi/vim25/types"
)

type info struct {
*flags.ClientFlag
*flags.OutputFlag

provider string

avail, vms, hosts, other bool
}

func init() {
cli.Register("kms.key.info", &info{}, true)
}

func (cmd *info) Register(ctx context.Context, f *flag.FlagSet) {
cmd.ClientFlag, ctx = flags.NewClientFlag(ctx)
cmd.ClientFlag.Register(ctx, f)
cmd.OutputFlag, ctx = flags.NewOutputFlag(ctx)
cmd.OutputFlag.Register(ctx, f)

f.StringVar(&cmd.provider, "p", "", "Provider ID")
f.BoolVar(&cmd.avail, "a", true, "Show key availability")
f.BoolVar(&cmd.vms, "vms", false, "Show VMs using keys")
f.BoolVar(&cmd.hosts, "hosts", false, "Show hosts using keys")
f.BoolVar(&cmd.other, "other", false, "Show 3rd party using keys")
}

func (cmd *info) Process(ctx context.Context) error {
if err := cmd.ClientFlag.Process(ctx); err != nil {
return err
}
return cmd.OutputFlag.Process(ctx)
}

func (cmd *info) Usage() string {
return "ID..."
}

func (cmd *info) Description() string {
return `Crypto key info.
Examples:
govc kms.key.info -p my-kp ID
govc kms.key.info -p my-kp -vms ID`
}

type infoResult struct {
Status []types.CryptoManagerKmipCryptoKeyStatus `json:"status"`
ctx context.Context
c *vim25.Client
}

func (r *infoResult) writeObj(w io.Writer, refs []types.ManagedObjectReference) {
for _, ref := range refs {
p, err := find.InventoryPath(r.ctx, r.c, ref)
if err != nil {
p = ref.String()
}
fmt.Fprintf(w, " %s\t%s\n", ref.Value, p)
}
}

func (r *infoResult) Write(w io.Writer) error {
tw := tabwriter.NewWriter(w, 2, 0, 2, ' ', 0)

for _, s := range r.Status {
avail := "-"
reason := s.Reason
if s.KeyAvailable != nil {
avail = strconv.FormatBool(*s.KeyAvailable)
if *s.KeyAvailable && reason == "" {
reason = "KeyStateAvailable"
}
}
pid := ""
if p := s.KeyId.ProviderId; p != nil {
pid = p.Id
}
fmt.Fprintf(tw, "%s\t%s\t%s\t%s\n",
pid, s.KeyId.KeyId, avail, reason)
r.writeObj(tw, s.EncryptedVMs)
r.writeObj(tw, s.AffectedHosts)
}

return tw.Flush()
}

func argsToKeys(p string, args []string) []types.CryptoKeyId {
ids := make([]types.CryptoKeyId, len(args))

var provider *types.KeyProviderId

if p != "" {
provider = &types.KeyProviderId{Id: p}
}

for i, id := range args {
ids[i] = types.CryptoKeyId{
KeyId: id,
ProviderId: provider,
}
}

return ids
}

func (cmd *info) Run(ctx context.Context, f *flag.FlagSet) error {
n := f.NArg()
if n == 0 {
return flag.ErrHelp
}

ids := argsToKeys(cmd.provider, f.Args())

c, err := cmd.Client()
if err != nil {
return err
}

m, err := crypto.GetManagerKmip(c)
if err != nil {
return err
}

check := int32(0)

opts := []struct {
enabled bool
val int32
}{
{cmd.avail, crypto.CheckKeyAvailable},
{cmd.vms, crypto.CheckKeyUsedByVms},
{cmd.hosts, crypto.CheckKeyUsedByHosts},
{cmd.other, crypto.CheckKeyUsedByOther},
}

for _, opt := range opts {
if opt.enabled {
check = check | opt.val
}
}

res, err := m.QueryCryptoKeyStatus(ctx, ids, check)
if err != nil {
return err
}

return cmd.WriteResult(&infoResult{res, ctx, c})
}
Loading

0 comments on commit bbb6349

Please sign in to comment.