identity.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. /*
  2. * Copyright (C)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2025-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. package zerotier
  14. // #include "../../serviceiocore/GoGlue.h"
  15. import "C"
  16. import (
  17. "bytes"
  18. "encoding/hex"
  19. "encoding/json"
  20. "fmt"
  21. "runtime"
  22. "strings"
  23. "unsafe"
  24. )
  25. // TODO: export keys in ssh format?
  26. const (
  27. IdentityTypeC25519 = 0
  28. IdentityTypeP384 = 1
  29. IdentityTypeC25519PublicKeySize = 64
  30. IdentityTypeC25519PrivateKeySize = 64
  31. IdentityTypeP384PublicKeySize = 114
  32. IdentityTypeP384PrivateKeySize = 112
  33. )
  34. // Identity is precisely what it sounds like: the address and associated keys for a ZeroTier node
  35. type Identity struct {
  36. address Address
  37. idtype int
  38. publicKey []byte
  39. privateKey []byte
  40. cid unsafe.Pointer
  41. }
  42. func identityFinalizer(obj interface{}) {
  43. cid := obj.(*Identity).cid
  44. if cid != nil {
  45. C.ZT_Identity_delete(cid)
  46. }
  47. }
  48. // NewIdentity generates a new identity of the selected type.
  49. func NewIdentity(identityType int) (*Identity, error) {
  50. var cid unsafe.Pointer
  51. switch identityType {
  52. case C.ZT_IDENTITY_TYPE_C25519:
  53. cid = C.ZT_Identity_new(C.ZT_IDENTITY_TYPE_C25519)
  54. case C.ZT_IDENTITY_TYPE_P384:
  55. cid = C.ZT_Identity_new(C.ZT_IDENTITY_TYPE_P384)
  56. default:
  57. return nil, ErrInvalidParameter
  58. }
  59. id, err := newIdentityFromCIdentity(cid)
  60. if err != nil {
  61. return nil, err
  62. }
  63. id.cid = cid
  64. return id, nil
  65. }
  66. // NewIdentityFromString generates a new identity from its string representation.
  67. // The private key is imported as well if it is present.
  68. func NewIdentityFromString(s string) (*Identity, error) {
  69. ss := strings.Split(strings.TrimSpace(s), ":")
  70. if len(ss) < 3 {
  71. return nil, ErrInvalidParameter
  72. }
  73. var err error
  74. id := new(Identity)
  75. id.address, err = NewAddressFromString(ss[0])
  76. if err != nil {
  77. return nil, err
  78. }
  79. if ss[1] == "0" {
  80. id.idtype = 0
  81. } else if ss[1] == "1" {
  82. id.idtype = 1
  83. } else {
  84. return nil, ErrUnrecognizedIdentityType
  85. }
  86. switch id.idtype {
  87. case 0:
  88. id.publicKey, err = hex.DecodeString(ss[2])
  89. if err != nil {
  90. return nil, err
  91. }
  92. if len(ss) >= 4 {
  93. id.privateKey, err = hex.DecodeString(ss[3])
  94. if err != nil {
  95. return nil, err
  96. }
  97. }
  98. case 1:
  99. id.publicKey, err = Base32StdLowerCase.DecodeString(ss[2])
  100. if err != nil {
  101. return nil, err
  102. }
  103. if len(id.publicKey) != IdentityTypeP384PublicKeySize {
  104. return nil, ErrInvalidKey
  105. }
  106. if len(ss) >= 4 {
  107. id.privateKey, err = Base32StdLowerCase.DecodeString(ss[3])
  108. if err != nil {
  109. return nil, err
  110. }
  111. if len(id.privateKey) != IdentityTypeP384PrivateKeySize {
  112. return nil, ErrInvalidKey
  113. }
  114. }
  115. }
  116. return id, nil
  117. }
  118. func newIdentityFromCIdentity(cid unsafe.Pointer) (*Identity, error) {
  119. if cid == nil {
  120. return nil, ErrInvalidParameter
  121. }
  122. var idStrBuf [4096]byte
  123. idStr := C.ZT_Identity_toString(cid, (*C.char)(unsafe.Pointer(&idStrBuf[0])), 4096, 1)
  124. if uintptr(unsafe.Pointer(idStr)) == 0 {
  125. return nil, ErrInternal
  126. }
  127. id, err := NewIdentityFromString(C.GoString(idStr))
  128. if err != nil {
  129. return nil, err
  130. }
  131. runtime.SetFinalizer(id, identityFinalizer)
  132. return id, nil
  133. }
  134. func (id *Identity) cIdentity() unsafe.Pointer {
  135. if id.cid == nil {
  136. str := []byte(id.PrivateKeyString())
  137. if len(str) == 0 {
  138. str = []byte(id.String())
  139. }
  140. if len(str) == 0 {
  141. return nil
  142. }
  143. str = append(str, byte(0))
  144. id.cid = C.ZT_Identity_fromString((*C.char)(unsafe.Pointer(&str[0])))
  145. }
  146. return id.cid
  147. }
  148. // Address returns this identity's address.
  149. func (id *Identity) Address() Address { return id.address }
  150. // HasPrivate returns true if this identity has its own private portion.
  151. func (id *Identity) HasPrivate() bool { return len(id.privateKey) > 0 }
  152. // Fingerprint gets this identity's address plus hash of public key(s).
  153. func (id *Identity) Fingerprint() *Fingerprint {
  154. return newFingerprintFromCFingerprint(C.ZT_Identity_fingerprint(id.cIdentity()))
  155. }
  156. // PrivateKeyString returns the full identity.secret if the private key is set,
  157. // or an empty string if no private key is set.
  158. func (id *Identity) PrivateKeyString() string {
  159. switch id.idtype {
  160. case IdentityTypeC25519:
  161. if len(id.publicKey) == IdentityTypeC25519PublicKeySize && len(id.privateKey) == IdentityTypeC25519PrivateKeySize {
  162. return fmt.Sprintf("%.10x:0:%x:%x", uint64(id.address), id.publicKey, id.privateKey)
  163. }
  164. case IdentityTypeP384:
  165. if len(id.publicKey) == IdentityTypeP384PublicKeySize && len(id.privateKey) == IdentityTypeP384PrivateKeySize {
  166. return fmt.Sprintf("%.10x:1:%s:%s", uint64(id.address), Base32StdLowerCase.EncodeToString(id.publicKey), Base32StdLowerCase.EncodeToString(id.privateKey))
  167. }
  168. }
  169. return ""
  170. }
  171. // PublicKeyString returns the address and public key (identity.public contents).
  172. // An empty string is returned if this identity is invalid or not initialized.
  173. func (id *Identity) String() string {
  174. switch id.idtype {
  175. case IdentityTypeC25519:
  176. if len(id.publicKey) == IdentityTypeC25519PublicKeySize {
  177. return fmt.Sprintf("%.10x:0:%x", uint64(id.address), id.publicKey)
  178. }
  179. case IdentityTypeP384:
  180. if len(id.publicKey) == IdentityTypeP384PublicKeySize {
  181. return fmt.Sprintf("%.10x:1:%s", uint64(id.address), Base32StdLowerCase.EncodeToString(id.publicKey))
  182. }
  183. }
  184. return ""
  185. }
  186. // LocallyValidate performs local self-validation of this identity
  187. func (id *Identity) LocallyValidate() bool {
  188. return C.ZT_Identity_validate(id.cIdentity()) != 0
  189. }
  190. // Sign signs a message with this identity
  191. func (id *Identity) Sign(msg []byte) ([]byte, error) {
  192. var dataP unsafe.Pointer
  193. if len(msg) > 0 {
  194. dataP = unsafe.Pointer(&msg[0])
  195. }
  196. var sig [96]byte
  197. sigLen := C.ZT_Identity_sign(id.cIdentity(), dataP, C.uint(len(msg)), unsafe.Pointer(&sig[0]), 96)
  198. if sigLen <= 0 {
  199. return nil, ErrInvalidKey
  200. }
  201. return sig[0:uint(sigLen)], nil
  202. }
  203. // Verify verifies a signature
  204. func (id *Identity) Verify(msg, sig []byte) bool {
  205. if len(sig) == 0 {
  206. return false
  207. }
  208. var dataP unsafe.Pointer
  209. if len(msg) > 0 {
  210. dataP = unsafe.Pointer(&msg[0])
  211. }
  212. return C.ZT_Identity_verify(id.cIdentity(), dataP, C.uint(len(msg)), unsafe.Pointer(&sig[0]), C.uint(len(sig))) != 0
  213. }
  214. // Equals performs a deep equality test between this and another identity
  215. func (id *Identity) Equals(id2 *Identity) bool {
  216. if id2 == nil {
  217. return id == nil
  218. }
  219. if id == nil {
  220. return false
  221. }
  222. return id.address == id2.address && id.idtype == id2.idtype && bytes.Equal(id.publicKey, id2.publicKey) && bytes.Equal(id.privateKey, id2.privateKey)
  223. }
  224. func (id *Identity) MarshalJSON() ([]byte, error) {
  225. return []byte("\"" + id.String() + "\""), nil
  226. }
  227. func (id *Identity) UnmarshalJSON(j []byte) error {
  228. var s string
  229. err := json.Unmarshal(j, &s)
  230. if err != nil {
  231. return err
  232. }
  233. nid, err := NewIdentityFromString(s)
  234. if err != nil {
  235. return err
  236. }
  237. *id = *nid
  238. return nil
  239. }