control.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package key
  4. import "encoding/json"
  5. // ControlPrivate is a Tailscale control plane private key.
  6. //
  7. // It is functionally equivalent to a MachinePrivate, but serializes
  8. // to JSON as a byte array rather than a typed string, because our
  9. // control plane database stores the key that way.
  10. //
  11. // Deprecated: this type should only be used in Tailscale's control
  12. // plane, where existing database serializations require this
  13. // less-good serialization format to persist. Other control plane
  14. // implementations can use MachinePrivate with no downsides.
  15. type ControlPrivate struct {
  16. mkey MachinePrivate // unexported so we can limit the API surface to only exactly what we need
  17. }
  18. // NewControl generates and returns a new control plane private key.
  19. func NewControl() ControlPrivate {
  20. return ControlPrivate{NewMachine()}
  21. }
  22. // IsZero reports whether k is the zero value.
  23. func (k ControlPrivate) IsZero() bool {
  24. return k.mkey.IsZero()
  25. }
  26. // Public returns the MachinePublic for k.
  27. // Panics if ControlPrivate is zero.
  28. func (k ControlPrivate) Public() MachinePublic {
  29. return k.mkey.Public()
  30. }
  31. // MarshalJSON implements json.Marshaler.
  32. func (k ControlPrivate) MarshalJSON() ([]byte, error) {
  33. return json.Marshal(k.mkey.k)
  34. }
  35. // UnmarshalJSON implements json.Unmarshaler.
  36. func (k *ControlPrivate) UnmarshalJSON(bs []byte) error {
  37. return json.Unmarshal(bs, &k.mkey.k)
  38. }
  39. // SealTo wraps cleartext into a NaCl box (see
  40. // golang.org/x/crypto/nacl) to p, authenticated from k, using a
  41. // random nonce.
  42. //
  43. // The returned ciphertext is a 24-byte nonce concatenated with the
  44. // box value.
  45. func (k ControlPrivate) SealTo(p MachinePublic, cleartext []byte) (ciphertext []byte) {
  46. return k.mkey.SealTo(p, cleartext)
  47. }
  48. // SharedKey returns the precomputed Nacl box shared key between k and p.
  49. func (k ControlPrivate) SharedKey(p MachinePublic) MachinePrecomputedSharedKey {
  50. return k.mkey.SharedKey(p)
  51. }
  52. // OpenFrom opens the NaCl box ciphertext, which must be a value
  53. // created by SealTo, and returns the inner cleartext if ciphertext is
  54. // a valid box from p to k.
  55. func (k ControlPrivate) OpenFrom(p MachinePublic, ciphertext []byte) (cleartext []byte, ok bool) {
  56. return k.mkey.OpenFrom(p, ciphertext)
  57. }