-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathenroll.go
85 lines (70 loc) · 2.5 KB
/
enroll.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package cmd
import (
"crypto/x509"
"log"
"github.com/Diniboy1123/usque/api"
"github.com/Diniboy1123/usque/config"
"github.com/Diniboy1123/usque/models"
"github.com/spf13/cobra"
)
var enrollCmd = &cobra.Command{
Use: "enroll",
Short: "Enrolls a MASQUE private key and switches mode",
Long: "Enrolls a MASQUE private key and switches mode. Useful for ZeroTier where IPv6 address can change." +
" Or if you just want to deploy a new key.",
Run: func(cmd *cobra.Command, args []string) {
if !config.ConfigLoaded {
cmd.Println("Config not loaded. Please register first.")
return
}
configPath, err := cmd.Flags().GetString("config")
if err != nil {
log.Fatalf("Failed to get config path: %v", err)
}
if configPath == "" {
log.Fatalf("Config path is required")
}
deviceName, err := cmd.Flags().GetString("name")
if err != nil {
log.Fatalf("Failed to get device name: %v", err)
}
log.Printf("Enrolling device key...")
accountData := models.AccountData{
Token: config.AppConfig.AccessToken,
ID: config.AppConfig.ID,
}
privKey, err := config.AppConfig.GetEcPrivateKey()
if err != nil {
log.Fatalf("Failed to get private key: %v", err)
}
publicKey, err := x509.MarshalPKIXPublicKey(&privKey.PublicKey)
if err != nil {
log.Fatalf("Failed to marshal public key: %v", err)
}
updatedAccountData, err := api.EnrollKey(accountData, publicKey, deviceName)
if err != nil {
log.Fatalf("Failed to enroll device key: %v", err)
}
log.Printf("Successful registration. Saving config...")
config.AppConfig = config.Config{
PrivateKey: config.AppConfig.PrivateKey,
// TODO: proper endpoint parsing in utils
// strip :0
EndpointV4: updatedAccountData.Config.Peers[0].Endpoint.V4[:len(updatedAccountData.Config.Peers[0].Endpoint.V4)-2],
// strip [ from beginning and ]:0 from end
EndpointV6: updatedAccountData.Config.Peers[0].Endpoint.V6[1 : len(updatedAccountData.Config.Peers[0].Endpoint.V6)-3],
EndpointPubKey: updatedAccountData.Config.Peers[0].PublicKey,
License: updatedAccountData.Account.License,
ID: updatedAccountData.ID,
AccessToken: accountData.Token,
IPv4: updatedAccountData.Config.Interface.Addresses.V4,
IPv6: updatedAccountData.Config.Interface.Addresses.V6,
}
config.AppConfig.SaveConfig(configPath)
log.Printf("Config saved to %s", configPath)
},
}
func init() {
enrollCmd.Flags().StringP("name", "n", "", "Rename device a given name")
rootCmd.AddCommand(enrollCmd)
}