summaryrefslogtreecommitdiff
path: root/cmd/cli/main.go
blob: e6be0bff23ad5361117a30a5a41d46ea13b7d1a0 (plain)
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"strings"

	eduvpn "github.com/jwijenbergh/eduvpn-common"
)

// Open a browser with xdg-open
func openBrowser(urlString string) {
	fmt.Printf("OAuth: Initialized with AuthURL %s\n", urlString)
	fmt.Println("OAuth: Opening browser with xdg-open...")
	exec.Command("xdg-open", urlString).Start()
}

// Taken from internal/server.go as it's an internal API for now
// These are used to parse the profile info
type ServerProfile struct {
	ID             string   `json:"profile_id"`
	DisplayName    string   `json:"display_name"`
	VPNProtoList   []string `json:"vpn_proto_list"`
	DefaultGateway bool     `json:"default_gateway"`
}
type ServerProfileInfo struct {
	Current string `json:"current_profile"`
	Info    struct {
		ProfileList []ServerProfile `json:"profile_list"`
	} `json:"info"`
}

// Ask for a profile in the command line
func sendProfile(state *eduvpn.VPNState, data string) {
	fmt.Printf("Multiple VPN profiles found. Please select a profile by entering e.g. 1")
	serverProfiles := &ServerProfileInfo{}

	jsonErr := json.Unmarshal([]byte(data), &serverProfiles)

	if jsonErr != nil {
		fmt.Println("\nFailed to get profile list", jsonErr)
		return
	}

	var profiles string

	for index, profile := range serverProfiles.Info.ProfileList {
		profiles += fmt.Sprintf("\n%d - %s", index+1, profile.DisplayName)
	}

	// Show the profiles
	fmt.Println(profiles)

	var chosenProfile int
	_, scanErr := fmt.Scanf("%d", &chosenProfile)

	if scanErr != nil || chosenProfile <= 0 || chosenProfile > len(serverProfiles.Info.ProfileList) {
		fmt.Println("invalid profile chosen, please retry")
		sendProfile(state, data)
		return
	}

	profile := serverProfiles.Info.ProfileList[chosenProfile-1]
	fmt.Println("Sending profile ID", profile.ID)
	profileErr := state.SetProfileID(profile.ID)

	if profileErr != nil {
		fmt.Println("Failed setting profile with error", profileErr)
	}
}

// The callback function
// If OAuth is started we open the browser with the Auth URL
// If we ask for a profile, we send the profile using command line input
// Note that this has an additional argument, the vpn state which was wrapped into this callback function below
func stateCallback(state *eduvpn.VPNState, oldState string, newState string, data string) {
	if newState == "OAuth_Started" {
		openBrowser(data)
	}

	if newState == "Ask_Profile" {
		sendProfile(state, data)
	}
}

// Get a config for Institute Access or Secure Internet Server
func getConfig(state *eduvpn.VPNState, url string, isInstitute bool) (string, string, error) {
	if !strings.HasPrefix(url, "https://") {
		url = "https://" + url
	}
	if !strings.HasSuffix(url, "/") {
		url += "/"
	}
	// Force TCP is set to False
	if isInstitute {
		return state.GetConfigInstituteAccess(url, false)
	}
	return state.GetConfigSecureInternet(url, false)
}

// A discovery entry for a server
type ServerDiscoEntry struct {
	ServerType string `json:"server_type"`
	BaseURL    string `json:"base_url"`
}

// Gets all different Secure Internet server by parsing the JSON from the discovery
func getAllSecureInternetServers(serverList string) ([]string, error) {
	var secureInternet []string

	discoEntries := []ServerDiscoEntry{}

	jsonErr := json.Unmarshal([]byte(serverList), &discoEntries)

	if jsonErr != nil {
		return nil, jsonErr
	}

	for _, entry := range discoEntries {
		if entry.ServerType == "secure_internet" {
			secureInternet = append(secureInternet, entry.BaseURL)
		}
	}

	return secureInternet, nil
}

// Store the Secure Internet config in a certificate folder
func storeSecureInternetConfig(state *eduvpn.VPNState, url string, directory string) {
	os.MkdirAll(directory, os.ModePerm)

	fmt.Println("Creating and storing cert for", url)

	config, _, configErr := getConfig(state, url, false)

	if configErr != nil {
		fmt.Printf("Failed obtaining config for url %s with error %v\n", url, configErr)
		return
	}

	cleanURL := filepath.Base(url)

	writeErr := os.WriteFile(path.Join(directory, cleanURL), []byte(config), 0o644)
	if writeErr != nil {
		fmt.Printf("Failed writing config for url %s with error %v\n", url, writeErr)
	}
}

// This is basically used to get a certificate for all Secure Internet servers
func getSecureInternetAll(homeURL string) {
	state := &eduvpn.VPNState{}

	state.Register("org.eduvpn.app.linux", "configs", func(old string, new string, data string) {
		stateCallback(state, old, new, data)
	}, true)

	defer state.Deregister()

	// Get the disco servers
	servers, serversErr := state.GetDiscoServers()

	if serversErr != nil {
		fmt.Println("Cannot obtain servers", serversErr)
		return
	}

	secureInternetURLs, secureInternetErr := getAllSecureInternetServers(servers)

	if secureInternetErr != nil {
		fmt.Println("Cannot parse secure internet servers", secureInternetErr)
		return
	}

	// Ensure that the directory exists
	directory := "certs"
	os.MkdirAll(directory, os.ModePerm)

	// Obtain config for home server
	storeSecureInternetConfig(state, homeURL, directory)

	for _, serverURL := range secureInternetURLs {
		if !strings.Contains(serverURL, homeURL) {
			storeSecureInternetConfig(state, serverURL, directory)
		}
	}

	fmt.Println("Done storing all certs in directory:", directory)
}

// Get a config for a single server, Institute Access or Secure Internet
func printConfig(url string, isInstitute bool) {
	state := &eduvpn.VPNState{}

	state.Register("org.eduvpn.app.linux", "configs", func(old string, new string, data string) {
		stateCallback(state, old, new, data)
	}, true)

	defer state.Deregister()

	config, _, configErr := getConfig(state, url, isInstitute)

	if configErr != nil {
		// Show the usage of tracebacks and causes
		fmt.Println("Error getting config:", state.GetErrorTraceback(configErr))
		fmt.Println("Error getting config, cause:", state.GetErrorCause(configErr))
		return
	}

	fmt.Println("Obtained config", config)
}

// The main function
// It parses the arguments and executes the correct functions
func main() {
	urlArg := flag.String("get-institute", "", "The url of an institute to connect to")
	secureInternet := flag.String("get-secure", "", "Gets secure internet servers.")
	secureInternetAll := flag.String("get-secure-all", "", "Gets certificates for all secure internet servers. It stores them in ./certs. Provide an URL for the home server e.g. nl.eduvpn.org.")
	flag.Parse()

	// Connect to a VPN by getting an Institute Access config
	urlString := *urlArg
	secureInternetString := *secureInternet
	secureInternetAllString := *secureInternetAll
	if urlString != "" {
		printConfig(urlString, true)
		return
	} else if secureInternetString != "" {
		printConfig(secureInternetString, false)
		return
	} else if secureInternetAllString != "" {
		getSecureInternetAll(secureInternetAllString)
		return
	}

	flag.PrintDefaults()
}