-
Notifications
You must be signed in to change notification settings - Fork 2
/
serve.go
280 lines (215 loc) · 8.24 KB
/
serve.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
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package main
import (
"errors"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"embed"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
"mvdan.cc/xurls/v2"
)
type (
serveHandle struct {
Config *config
OpenVPNConnectionConfig *openVPNConfig
TempDir string
SAMLResponse chan string
ServiceIPv4 string
ServiceHost string
}
)
//go:embed html/index.html
var welcomeHtmlFile embed.FS
//go:embed html/error.html
var errorHtmlFile embed.FS
func serveAction(c *cli.Context) error {
openVPNConfig := c.String("config")
tmpOpenVPNConfigDir := c.String("configTmpDir")
awsClientConfigFilename, err := searchConfigFilename()
if errors.Is(os.ErrNotExist, err) {
log.Fatal().Msg("failed loading " + appName + " config from working directory and user config folder! " + errorSuffix)
} else if err != nil {
log.Fatal().Err(err).Msg("unexpected error loading " + appName + " config! " + errorSuffix)
}
awsclientConfig, err := loadConfig(awsClientConfigFilename)
if err != nil {
log.Fatal().Str("config", awsClientConfigFilename).Err(err).Msg("unexpected error loading " + appName + " config! " + errorSuffix)
}
if !awsclientConfig.Debug {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
log.Debug().
Str("config", openVPNConfig).
Str("configOutDir", tmpOpenVPNConfigDir).
Msg("Parsing openvpn config and saving formatted version for openvpn")
connectionConfig, err := parseAndFormatOpenVPNConfig(openVPNConfig, tmpOpenVPNConfigDir)
if err != nil {
log.Fatal().
Str("config", openVPNConfig).
Str("configOut", tmpOpenVPNConfigDir).
Err(err).
Msg("Failed parsing or saving formatted version openvpn config! " + errorSuffix)
}
if connectionConfig.Formatted {
log.Info().Str("config", connectionConfig.Filename).Msg("Parsed and formatted openvpn configuration.")
} else {
log.Info().Msg("Parsed openvpn configuration.")
}
handle := &serveHandle{
Config: awsclientConfig,
OpenVPNConnectionConfig: connectionConfig,
SAMLResponse: make(chan string),
TempDir: tmpOpenVPNConfigDir,
}
log.Info().Msgf("Starting HTTP server at: %s", handle.Config.Server.Addr)
go startSAMLServer(handle)
startOpenVPNConnection(handle)
return nil
}
func startOpenVPNConnection(handle *serveHandle) {
connectionHostnameToken, err := generateRandomToken(12)
if err != nil {
log.Fatal().Err(err).Msg("Failed generating random token for remote hostname! " + errorSuffix)
}
handle.ServiceHost = connectionHostnameToken + "." + handle.OpenVPNConnectionConfig.Host
handle.ServiceIPv4, err = lookupIP(handle.ServiceHost)
if err != nil {
log.Fatal().Str("serviceHost", handle.ServiceHost).Err(err).Msg("Failed looking up ipv4 address of service hostname " + errorSuffix)
}
// Get the port of the SAML server for our password.
u, _ := url.Parse("http://" + handle.Config.Server.Addr)
// Save auth file for openvpn
tmpAuthConifg, err := saveOpenVPNAuthConfig(handle.TempDir, "ACS::"+u.Port())
if err != nil {
log.Fatal().Err(err).Msg("Failed saving openvpn auth config file! " + errorSuffix)
}
log.Info().
Str("config", handle.OpenVPNConnectionConfig.Filename).
Str("remote", handle.ServiceIPv4).
Msg("Fetching redirect URL from service...")
command := exec.Command(
handle.Config.Vpn.OpenVPN,
"--verb", "3",
"--config", handle.OpenVPNConnectionConfig.Filename,
"--proto", handle.OpenVPNConnectionConfig.Protocol,
"--remote", handle.ServiceIPv4, strconv.FormatInt(int64(handle.OpenVPNConnectionConfig.Port), 10),
"--auth-user-pass", tmpAuthConifg,
)
out, err := command.CombinedOutput()
removeErr := os.Remove(tmpAuthConifg)
if removeErr != nil {
log.Warn().Str("openvpnAuthConfig", tmpAuthConifg).Err(err).Msg("Failed deleting tmp openvpn auth config! " + errorSuffix)
}
log.Debug().Str("command", command.String()).Str("payload", string(out)).Msg("Executed command")
// Now are must extract the URL from the payload. We use xurls to do this since regex is hard.
rxStrict := xurls.Strict()
foundURLs := rxStrict.FindAllString(string(out), -1)
if len(foundURLs) == 0 {
log.Fatal().Err(err).Msg("No URLs found in payload from server! Please check the DEBUG logs for more information. " + errorSuffix)
}
if len(foundURLs) > 1 {
log.Fatal().Strs("foundURLs", foundURLs).Msg("More then one URL found in response payload! " + errorSuffix)
}
authUrl := foundURLs[len(foundURLs)-1]
log.Info().Msgf("open to authenticate into OpenVPN tunnel: %s", authUrl)
if handle.Config.Browser {
errOpenDefaultBrowser := openDefaultBrowser(handle.Config.Vpn.User, authUrl)
if errOpenDefaultBrowser != nil {
log.Warn().Err(err).Msg("Failed opening default browser. Please use the provided link in the output")
}
}
log.Info().Msg("Waiting for SAML response from 3rd party service...")
SAMLResponse := <-handle.SAMLResponse
log.Info().Msg("Received SAML response! Attempting to start OpenVPN client tunnel...")
// Save auth file for openvpn
SID, err := extractSIDFromOpenVPN(string(out))
if err != nil {
log.Fatal().Err(err).Msg("Failed finding SID in initial handshake! Please enable DEBUG mode to see payload. " + errorSuffix)
}
escapedSAMLResponse := url.QueryEscape(SAMLResponse)
log.Debug().Str("SAMLResponse", escapedSAMLResponse).Msgf("writing temp openvpn auth file")
tmpAuthConifg, err = saveOpenVPNAuthConfig(handle.TempDir, "CRV1::"+SID+"::"+escapedSAMLResponse)
if err != nil {
log.Fatal().Err(err).Msg("Failed saving auth config for OpenVPN tunnel! " + errorSuffix)
}
baseCommand := exec.Command(
handle.Config.Vpn.OpenVPN,
"--verb", "3",
"--config", handle.OpenVPNConnectionConfig.Filename,
"--proto", handle.OpenVPNConnectionConfig.Protocol,
"--remote", handle.ServiceIPv4, strconv.FormatInt(int64(handle.OpenVPNConnectionConfig.Port), 10),
"--script-security", "2",
"--auth-user-pass", tmpAuthConifg,
)
// If the user didn't provide a shell or we are already running as root.
// Non special hacks are needed to to run this step.
if handle.Config.Vpn.Shell == "" || isRoot() {
baseCommand.Env = os.Environ()
baseCommand.Stdout = os.Stdout
baseCommand.Stderr = os.Stderr
baseCommand.Stdin = os.Stdin
log.Debug().Str("command", baseCommand.String()).Msg("Executing OpenVPN tunnel.")
err = baseCommand.Start()
baseCommand.Wait()
} else {
args := append(handle.Config.Vpn.ShellArgs, handle.Config.Vpn.Sudo+" "+baseCommand.String())
shellCommand := exec.Command(
handle.Config.Vpn.Shell,
args...,
)
shellCommand.Env = os.Environ()
shellCommand.Stdout = os.Stdout
shellCommand.Stderr = os.Stderr
shellCommand.Stdin = os.Stdin
log.Debug().Str("command", shellCommand.String()).Msg("Executing OpenVPN tunnel in shell.")
err = shellCommand.Start()
shellCommand.Wait()
}
if err != nil {
log.Fatal().Err(err).Msg("Failed starting OpenVPN tunnel! " + errorSuffix)
}
}
func startSAMLServer(handle *serveHandle) {
http.HandleFunc("/", SAMLServer(handle))
http.ListenAndServe(handle.Config.Server.Addr, nil)
}
func writeEmbededHtmlFile(file embed.FS, filePath string, w http.ResponseWriter) {
content, err := file.ReadFile(filePath)
if err != nil {
log.Error().Msgf("failed loading HTML file: %s", filePath)
http.Error(w, "Could not load HTML file", http.StatusInternalServerError)
return
}
w.Write(content)
}
func SAMLServer(handle *serveHandle) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
switch r.Method {
case "POST":
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusBadRequest)
writeEmbededHtmlFile(errorHtmlFile, "html/error.html", w)
log.Error().Err(err).Msg("ParseForm() returned unexpected error")
return
}
SAMLResponse := r.FormValue("SAMLResponse")
if len(SAMLResponse) == 0 {
w.WriteHeader(http.StatusBadRequest)
writeEmbededHtmlFile(errorHtmlFile, "html/error.html", w)
log.Error().Msg("SAMLResponse field empty")
return
}
handle.SAMLResponse <- SAMLResponse
writeEmbededHtmlFile(welcomeHtmlFile, "html/index.html", w)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
writeEmbededHtmlFile(errorHtmlFile, "html/error.html", w)
log.Error().Msgf("Error: POST method expected, %s received", r.Method)
}
}
}