lightvpn/main.go
Patrick MARIE 66f02634ab Fix version used.
It seems like using an older version breaks things, as the server will
only return AUTH_FAILED.

Making a bigger channel so the tool does not block after the preflight
query.
2023-02-09 18:19:55 +01:00

116 lines
2.5 KiB
Go

package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/exec"
)
type Token struct {
Email string
Token string
}
var ovpnFile string
var logFile string = "/tmp/openvpn-avx.log"
var samlCorpUrl string = "https://prod.aviatrixsystems.com/flask/saml/login/azureapp"
func init() {
flag.StringVar(&ovpnFile, "ovpn", "corp-saml-aviatrix-vpn.ovpn", "The OpenVPN configuration file")
}
func checkOpenVPNFile() error {
if _, err := os.Stat(ovpnFile); errors.Is(err, os.ErrNotExist) {
fmt.Fprintf(os.Stderr, "Given OpenVPN file [%s] could not be found.\n", ovpnFile)
return err
}
fmt.Printf("Using configuration file is [%s].\n", ovpnFile)
return nil
}
func writeTempCredentials(token Token) (string, error) {
f, err := os.CreateTemp("", "vpn")
if err != nil {
return "", err
}
fileContent := fmt.Sprintf("%s\n%s", token.Email, token.Token)
if _, err := f.Write([]byte(fileContent)); err != nil {
return "", err
}
if err := f.Close(); err != nil {
return "", err
}
return f.Name(), nil
}
func localServer(tokenChannel chan<- Token) {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var token Token
err := json.Unmarshal([]byte(r.URL.Path[1:]), &token)
if err != nil {
log.Fatalf("Could not decode http response: %s (Reason: %s)\n", r.URL.Path[1:], err)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
fmt.Fprintf(w, "SuccessAviatrix")
tokenChannel <- token
})
log.Fatal(http.ListenAndServe("127.0.0.1:15395", nil))
}
func main() {
flag.Parse()
if checkOpenVPNFile() != nil {
return
}
// Make a some big room for the channel.
tokenChannel := make(chan Token, 65535)
// Open a quick local httpd before redirecting user to go to saml auth page.
go localServer(tokenChannel)
fmt.Printf("Please now go to %s.\n", samlCorpUrl)
token := <-tokenChannel
tmpCredentialsFile, err := writeTempCredentials(token)
if err != nil {
log.Fatal(err)
}
defer os.Remove(tmpCredentialsFile)
fmt.Printf("Got your token! Email is: %s\n", token.Email)
fmt.Printf("Launching OpenVPN. Check log file: %s\n", logFile)
cmd := exec.Command(
"/usr/sbin/openvpn",
"--config", ovpnFile,
"--auth-user-pass", tmpCredentialsFile,
"--script-security", "2", "--up-restart", "--up", "scripts/linux.sh", "--down", "scripts/linux.sh",
"--setenv", "IV_PLAT", "linux", "--setenv", "IV_GUI_VER", "AVPNC-2.16.42", "--push-peer-info", "--log", logFile,
)
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Println("Bye!")
}