identity.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 cli
  14. import (
  15. "encoding/hex"
  16. "fmt"
  17. "io/ioutil"
  18. "strings"
  19. "zerotier/pkg/zerotier"
  20. )
  21. func Identity(args []string) int {
  22. if len(args) > 0 {
  23. switch args[0] {
  24. case "new":
  25. idType := zerotier.IdentityTypeC25519
  26. if len(args) > 1 {
  27. if len(args) > 2 {
  28. Help()
  29. return 1
  30. }
  31. switch args[1] {
  32. case "c25519", "C25519", "0":
  33. idType = zerotier.IdentityTypeC25519
  34. case "p384", "P384", "1":
  35. idType = zerotier.IdentityTypeP384
  36. default:
  37. Help()
  38. return 1
  39. }
  40. }
  41. id, err := zerotier.NewIdentity(idType)
  42. if err != nil {
  43. pErr("internal error generating identity: %s", err.Error())
  44. return 1
  45. }
  46. fmt.Println(id.PrivateKeyString())
  47. return 0
  48. case "getpublic":
  49. if len(args) == 2 {
  50. fmt.Println(cliGetIdentityOrFatal(args[1]).String())
  51. return 0
  52. }
  53. pErr("no identity specified")
  54. return 1
  55. case "fingerprint":
  56. if len(args) == 2 {
  57. fmt.Println(cliGetIdentityOrFatal(args[1]).Fingerprint().String())
  58. return 0
  59. }
  60. pErr("no identity specified")
  61. return 1
  62. case "validate":
  63. if len(args) == 2 {
  64. if cliGetIdentityOrFatal(args[1]).LocallyValidate() {
  65. fmt.Println("VALID")
  66. return 0
  67. }
  68. fmt.Println("INVALID")
  69. return 1
  70. }
  71. case "sign", "verify":
  72. if len(args) > 2 {
  73. id := cliGetIdentityOrFatal(args[1])
  74. msg, err := ioutil.ReadFile(args[2])
  75. if err != nil {
  76. pErr("unable to read input file: %s", err.Error())
  77. return 1
  78. }
  79. if args[0] == "verify" {
  80. if len(args) == 4 {
  81. sig, err := hex.DecodeString(strings.TrimSpace(args[3]))
  82. if err != nil {
  83. fmt.Println("FAILED")
  84. return 1
  85. }
  86. if id.Verify(msg, sig) {
  87. fmt.Println("OK")
  88. return 0
  89. }
  90. }
  91. fmt.Println("FAILED")
  92. return 1
  93. } else {
  94. sig, err := id.Sign(msg)
  95. if err != nil {
  96. pErr("internal error signing message: %s", err.Error())
  97. return 1
  98. }
  99. fmt.Println(hex.EncodeToString(sig))
  100. return 0
  101. }
  102. }
  103. }
  104. }
  105. Help()
  106. return 1
  107. }