1
0

authkey.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package ganserv
  2. import (
  3. "errors"
  4. "log"
  5. "os"
  6. "runtime"
  7. "strings"
  8. )
  9. func TryLoadorAskUserForAuthkey() (string, error) {
  10. //Check for zt auth token
  11. value, exists := os.LookupEnv("ZT_AUTH")
  12. if !exists {
  13. log.Println("Environment variable ZT_AUTH not defined. Trying to load authtoken from file.")
  14. } else {
  15. return value, nil
  16. }
  17. authKey := ""
  18. if runtime.GOOS == "windows" {
  19. if isAdmin() {
  20. //Read the secret file directly
  21. b, err := os.ReadFile("C:\\ProgramData\\ZeroTier\\One\\authtoken.secret")
  22. if err == nil {
  23. log.Println("Zerotier authkey loaded")
  24. authKey = string(b)
  25. } else {
  26. log.Println("Unable to read authkey at C:\\ProgramData\\ZeroTier\\One\\authtoken.secret: ", err.Error())
  27. }
  28. } else {
  29. //Elavate the permission to admin
  30. ak, err := readAuthTokenAsAdmin()
  31. if err == nil {
  32. log.Println("Zerotier authkey loaded")
  33. authKey = ak
  34. } else {
  35. log.Println("Unable to read authkey at C:\\ProgramData\\ZeroTier\\One\\authtoken.secret: ", err.Error())
  36. }
  37. }
  38. } else if runtime.GOOS == "linux" {
  39. if isAdmin() {
  40. //Try to read from source using sudo
  41. ak, err := readAuthTokenAsAdmin()
  42. if err == nil {
  43. log.Println("Zerotier authkey loaded")
  44. authKey = strings.TrimSpace(ak)
  45. } else {
  46. log.Println("Unable to read authkey at /var/lib/zerotier-one/authtoken.secret: ", err.Error())
  47. }
  48. } else {
  49. //Try read from source
  50. b, err := os.ReadFile("/var/lib/zerotier-one/authtoken.secret")
  51. if err == nil {
  52. log.Println("Zerotier authkey loaded")
  53. authKey = string(b)
  54. } else {
  55. log.Println("Unable to read authkey at /var/lib/zerotier-one/authtoken.secret: ", err.Error())
  56. }
  57. }
  58. } else if runtime.GOOS == "darwin" {
  59. b, err := os.ReadFile("/Library/Application Support/ZeroTier/One/authtoken.secret")
  60. if err == nil {
  61. log.Println("Zerotier authkey loaded")
  62. authKey = string(b)
  63. } else {
  64. log.Println("Unable to read authkey at /Library/Application Support/ZeroTier/One/authtoken.secret ", err.Error())
  65. }
  66. }
  67. authKey = strings.TrimSpace(authKey)
  68. if authKey == "" {
  69. return "", errors.New("Unable to load authkey from file")
  70. }
  71. return authKey, nil
  72. }