working prototype
This commit is contained in:
parent
a82131c8c8
commit
9eff9ce803
|
@ -1,3 +1,2 @@
|
|||
test.sh
|
||||
openvpn-mgt
|
||||
openvpn-dm-mgt-server.conf
|
||||
bindata_assetfs.go
|
||||
|
|
|
@ -0,0 +1,21 @@
|
|||
all: build
|
||||
build: fmt lint gobuild
|
||||
deps: godeps
|
||||
fmt: gofmt
|
||||
lint: golint
|
||||
test: gotest
|
||||
|
||||
gobuild:
|
||||
statik -src=./web/
|
||||
go build
|
||||
|
||||
godeps:
|
||||
go get -v -u -t ./...
|
||||
go get github.com/rakyll/statik
|
||||
|
||||
gofmt:
|
||||
go fmt ./...
|
||||
golint:
|
||||
go vet ./...
|
||||
gotest:
|
||||
go test ./...
|
|
@ -15,7 +15,10 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
func (s *OpenVpnMgt) getServerList() error {
|
||||
type ExpressVPN struct {
|
||||
}
|
||||
|
||||
func (s *ExpressVPN) ServerList() (error, *[]string) {
|
||||
var mux sync.Mutex
|
||||
requestCount := 0
|
||||
VPNNames := map[string]bool{}
|
||||
|
@ -28,12 +31,12 @@ func (s *OpenVpnMgt) getServerList() error {
|
|||
// Make request
|
||||
resp, err := client.Get("https://www.expressvpn.com/vpn-server")
|
||||
if err != nil {
|
||||
return err
|
||||
return err, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != 200 {
|
||||
return errors.New(fmt.Sprintf("Server List URL is not valid (%d)\n", resp.StatusCode))
|
||||
return errors.New(fmt.Sprintf("Server List URL is not valid (%d)\n", resp.StatusCode)), nil
|
||||
}
|
||||
|
||||
buf := bufio.NewReader(bufio.NewReader(resp.Body))
|
||||
|
@ -84,7 +87,7 @@ func (s *OpenVpnMgt) getServerList() error {
|
|||
}
|
||||
|
||||
if len(VPNNames) == 0 {
|
||||
return errors.New("Can't get a list of VPN endpoints")
|
||||
return errors.New("Can't get a list of VPN endpoints"), nil
|
||||
}
|
||||
|
||||
// add the right values
|
||||
|
@ -93,8 +96,5 @@ func (s *OpenVpnMgt) getServerList() error {
|
|||
keys = append(keys, k)
|
||||
}
|
||||
|
||||
s.Lock()
|
||||
s.VpnRemotes = keys
|
||||
s.Unlock()
|
||||
return nil
|
||||
return nil, &keys
|
||||
}
|
||||
|
|
5
go.mod
5
go.mod
|
@ -1,9 +1,6 @@
|
|||
module gitlab.dm.gg/vwf/openvpn-dm-mgt-server
|
||||
|
||||
require (
|
||||
github.com/mattevans/pwned-passwords v0.0.0-20190611210716-1da592be4a34
|
||||
github.com/onsi/gomega v1.5.0 // indirect
|
||||
github.com/pyke369/golang-support v0.0.0-20190703174728-34ca97aa79e9
|
||||
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d // indirect
|
||||
gopkg.in/ldap.v2 v2.5.1
|
||||
github.com/rakyll/statik v0.1.6
|
||||
)
|
||||
|
|
35
go.sum
35
go.sum
|
@ -1,34 +1,5 @@
|
|||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/mattevans/pwned-passwords v0.0.0-20190611210716-1da592be4a34 h1:cl/axA6OJFqTmZ573VUw9TTQ6/vbb+DIBFNFNPRFNaw=
|
||||
github.com/mattevans/pwned-passwords v0.0.0-20190611210716-1da592be4a34/go.mod h1:lTBNMS5Uc86U2A2Cps0gWoo091FA0YH5FMXhTvL0ZPI=
|
||||
github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo=
|
||||
github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
git.euclide.org/euclide/openvpn-mgt v0.0.0-20190815091940-a82131c8c881 h1:HXhjoWj3DcY1M5O077Q7kxNhMJmbK6qC8QUSifIUIpU=
|
||||
github.com/pyke369/golang-support v0.0.0-20190703174728-34ca97aa79e9 h1:H1vjQ+Mfc8dFAOTuF541/tScdKoynzll9iKuWgaLLxM=
|
||||
github.com/pyke369/golang-support v0.0.0-20190703174728-34ca97aa79e9/go.mod h1:0XGrzgrEp0fa/+JSV8XZePUwyjnU6C3bMc7Xz2bHHKI=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d h1:TxyelI5cVkbREznMhfzycHdkp5cLA7DpE+GKjSslYhM=
|
||||
gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d/go.mod h1:cuepJuh7vyXfUyUwEgHQXw849cJrilpS5NeIjOWESAw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/ldap.v2 v2.5.1 h1:wiu0okdNfjlBzg6UWvd1Hn8Y+Ux17/u/4nlk4CQr6tU=
|
||||
gopkg.in/ldap.v2 v2.5.1/go.mod h1:oI0cpe/D7HRtBQl8aTg+ZmzFUAvu4lsv3eLXMLGFxWk=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
github.com/rakyll/statik v0.1.6 h1:uICcfUXpgqtw2VopbIncslhAmE5hwc4g20TEyEENBNs=
|
||||
github.com/rakyll/statik v0.1.6/go.mod h1:OEi9wJV/fMUAGx1eNjq75DKDsJVuEv1U0oYdX6GX8Zs=
|
||||
|
|
18
httpd.go
18
httpd.go
|
@ -7,6 +7,9 @@ import (
|
|||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
_ "git.euclide.org/euclide/openvpn-mgt/statik"
|
||||
"github.com/rakyll/statik/fs"
|
||||
)
|
||||
|
||||
type jsonInput struct {
|
||||
|
@ -71,6 +74,7 @@ func (h *HttpServer) ajaxHandler(w http.ResponseWriter, r *http.Request) {
|
|||
http.Error(w, "Invalid request", 500)
|
||||
return
|
||||
}
|
||||
h.ovpn.Debug(req)
|
||||
|
||||
switch req.Action {
|
||||
case "get-remotes":
|
||||
|
@ -78,6 +82,8 @@ func (h *HttpServer) ajaxHandler(w http.ResponseWriter, r *http.Request) {
|
|||
case "set-remote":
|
||||
err = h.ovpn.SetRemote(req.Params.Server, req.Params.Session)
|
||||
jsonStr = []byte("{\"status\": \"ok\"}")
|
||||
case "get-sessions":
|
||||
jsonStr, err = json.Marshal(h.ovpn)
|
||||
case "version":
|
||||
err, version := h.ovpn.Version()
|
||||
if err != nil {
|
||||
|
@ -85,7 +91,12 @@ func (h *HttpServer) ajaxHandler(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
jsonStr, err = json.Marshal(version)
|
||||
case "stats":
|
||||
case "restart":
|
||||
err = h.ovpn.Restart(req.Params.Session)
|
||||
jsonStr = []byte("{\"status\": \"ok\"}")
|
||||
case "kill":
|
||||
err = h.ovpn.Kill(req.Params.Session)
|
||||
jsonStr = []byte("{\"status\": \"ok\"}")
|
||||
default:
|
||||
err = errors.New("Invalid request")
|
||||
}
|
||||
|
@ -105,8 +116,13 @@ func NewHTTPServer(port string, s *OpenVpnMgt) {
|
|||
ovpn: s,
|
||||
}
|
||||
|
||||
statikFS, err := fs.New()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
http.HandleFunc("/ajax", h.ajaxHandler)
|
||||
http.HandleFunc("/", h.handler)
|
||||
http.Handle("/", http.FileServer(statikFS))
|
||||
|
||||
log.Fatal(http.ListenAndServe(port, nil))
|
||||
}
|
||||
|
|
2
main.go
2
main.go
|
@ -15,7 +15,7 @@ func main() {
|
|||
var err error
|
||||
var config *uconfig.UConfig
|
||||
// default configuration file is /etc/openvpn/dm-mgt-server.conf
|
||||
configFile := flag.String("config", "/etc/openvpn/dm-mgt-server.conf", "configuration file")
|
||||
configFile := flag.String("config", "/etc/openvpn/vpn-mgt.conf", "configuration file")
|
||||
logToSyslog := flag.Bool("syslog", false, "Log to syslog")
|
||||
debug := flag.Bool("debug", false, "log every message received")
|
||||
flag.Parse()
|
||||
|
|
|
@ -1,152 +0,0 @@
|
|||
config
|
||||
{
|
||||
profiles:
|
||||
{
|
||||
###################################################################
|
||||
### Security Model ###
|
||||
### ###
|
||||
### +-1-> CONTRACT ###
|
||||
### | ###
|
||||
### start-here +---5---> DATACENTER ###
|
||||
### | | ###
|
||||
### +-2-> CORP -----4------> DEV -6---> ADMINS ###
|
||||
### | ^ ###
|
||||
### 3 4 ###
|
||||
### | | ###
|
||||
### +--> IT-AND-SEC ---+ ###
|
||||
### ###
|
||||
### CORP/IT-AND-SEC have the same IPs but not the API access ###
|
||||
### ADMINS/DATACENTER have the same IPs but not the API access ###
|
||||
### ###
|
||||
### at each step: ###
|
||||
### attributes[0] must match validGroups ###
|
||||
### attributes[1] is the login for the next security checks ###
|
||||
### attributes[2] is used as a salt for mfa generation ###
|
||||
### ###
|
||||
### Security Checks: ###
|
||||
### ###
|
||||
### 1/2: check AD groups and password. get mail address ###
|
||||
### 3: user must be in some AD security group (IT or SEC) ###
|
||||
### 4: mail must be in infra LDAP. User must have a ssh key ###
|
||||
### 5: user must be in the datacenter group in infra ldap ###
|
||||
### 6: user must be in the infra/net groups in infra ldap ###
|
||||
### ###
|
||||
### mfa setup is set according the mfa attribute of the final ###
|
||||
### group reached ###
|
||||
### ###
|
||||
###################################################################
|
||||
CONTRACT:
|
||||
{
|
||||
servers: [ "dc-11.office.daily","dc-12.office.daily","dc-13.office.daily" ]
|
||||
baseDN: "ou=Users_External,OU=Dailymotion,DC=office,DC=daily",
|
||||
bindCn: "CN=VPN Service,OU=Services,OU=Dailymotion,DC=office,DC=daily",
|
||||
bindPw: "********************",
|
||||
searchFilter: "(&(sAMAccountName=%s))"
|
||||
attributes: [ "memberOf", "mail", "extensionAttribute8" ]
|
||||
validGroups:
|
||||
[
|
||||
"CN=SEC_VPN_Users_External,OU=Security,OU=Groups,OU=Dailymotion,DC=office,DC=daily",
|
||||
]
|
||||
mfa: "internal"
|
||||
IPRange: "192.168.207.1 - 192.168.207.254",
|
||||
routes:
|
||||
[
|
||||
"10.189.10.9 255.255.255.255",
|
||||
"10.190.32.2 255.255.255.255",
|
||||
"10.190.32.20 255.255.255.255",
|
||||
"10.190.22.1 255.255.255.255",
|
||||
"10.190.22.2 255.255.255.255",
|
||||
"188.65.124.35 255.255.255.255",
|
||||
"195.8.215.129 255.255.255.255",
|
||||
"195.8.215.140 255.255.255.255",
|
||||
"10.190.52.100 255.255.255.255",
|
||||
"10.190.62.150 255.255.255.255",
|
||||
]
|
||||
}
|
||||
CORP:
|
||||
{
|
||||
servers: [ "dc-11.office.daily","dc-12.office.daily","dc-13.office.daily" ]
|
||||
baseDN: "OU=Dailymotion,DC=office,DC=daily",
|
||||
bindCn: "CN=VPN Service,OU=Services,OU=Dailymotion,DC=office,DC=daily",
|
||||
bindPw: "********************",
|
||||
searchFilter: "(&(sAMAccountName=%s))"
|
||||
attributes: [ "memberOf", "mail", "extensionAttribute8" ]
|
||||
validGroups:
|
||||
[
|
||||
"CN=SEC_VPN,OU=Security,OU=Groups,OU=Dailymotion,DC=office,DC=daily",
|
||||
]
|
||||
mfa: ""
|
||||
IPRange: "192.168.201.1-192.168.203.254"
|
||||
}
|
||||
IT-AND-SEC:
|
||||
{
|
||||
servers: [ "dc-11.office.daily","dc-12.office.daily","dc-13.office.daily" ]
|
||||
baseDN: "OU=Dailymotion,DC=office,DC=daily",
|
||||
bindCn: "CN=VPN Service,OU=Services,OU=Dailymotion,DC=office,DC=daily",
|
||||
bindPw: "********************",
|
||||
searchFilter: "(&(mail=%s))"
|
||||
attributes: [ "memberOf", "mail", "extensionAttribute8" ]
|
||||
upgradeFrom: [ "CORP" ]
|
||||
validGroups:
|
||||
[
|
||||
"CN=IT-Office,OU=Security,OU=Groups,OU=Dailymotion,DC=office,DC=daily",
|
||||
"CN=Security,OU=Security,OU=Groups,OU=Dailymotion,DC=office,DC=daily",
|
||||
]
|
||||
mfa: ""
|
||||
IPRange: "192.168.201.1-192.168.203.254"
|
||||
}
|
||||
|
||||
DEV:
|
||||
{
|
||||
servers: [ "ldap-auth.vip.dailymotion.com" ]
|
||||
baseDN: "dc=dailymotion,dc=com"
|
||||
bindCn: "cn=readonly,dc=dailymotion,dc=com"
|
||||
bindPw: "**********"
|
||||
searchFilter: "(&(mail=%s))"
|
||||
attributes: [ "description", "sshPublicKey" ]
|
||||
upgradeFrom: [ "CORP", "IT-AND-SEC" ]
|
||||
mfa: ""
|
||||
IPRange: "192.168.204.1-192.168.206.254"
|
||||
}
|
||||
ADMINS:
|
||||
{
|
||||
validGroups:
|
||||
[
|
||||
"infra",
|
||||
"net",
|
||||
]
|
||||
upgradeFrom: [ "DEV" ]
|
||||
mfa: "internal"
|
||||
IPRange: "192.168.200.2-192.168.200.254"
|
||||
}
|
||||
DATACENTER:
|
||||
{
|
||||
validGroups:
|
||||
[
|
||||
"datacenter",
|
||||
]
|
||||
upgradeFrom: [ "DEV" ]
|
||||
mfa: "internal"
|
||||
IPRange: "192.168.200.2-192.168.200.254"
|
||||
}
|
||||
}
|
||||
openvpnPort: "127.0.0.1:4000"
|
||||
http:
|
||||
{
|
||||
port: ":8443"
|
||||
ca: "/usr/local/share/ca-certificates/Dailymotion.crt"
|
||||
key: "/etc/ssl/private/server-key.pem"
|
||||
cert: "/etc/ssl/certs/server-bundle.pem"
|
||||
startAuth: "CORP"
|
||||
reqAuth: [ "ADMINS", "IP-AND-SEC" ]
|
||||
}
|
||||
cacheDir: "/var/run/openvpn/"
|
||||
authCa: "/usr/local/share/ca-certificates/Dailymotion.crt"
|
||||
masterSecrets: [ "********************************" ]
|
||||
vpnLogUrl: "https://install.dm.gg/vpn-log.php"
|
||||
mailRelay: "mailrelay.dailymotion.com:25"
|
||||
mailFrom: "engineering-infra@dailymotion.com"
|
||||
ccPwnPassword: "security-incident-report@dailymotion.com"
|
||||
pwnTemplate: "Mime-Version: 1.0;\nContent-Type: text/html; charset=\"ISO-8859-1\";\nContent-Transfer-Encoding: 7bit;\nFrom: {{.MailFrom}}\nSubject: [Dailymotion] Your current okta password is compromised\nTo: {{.Mail}}\nCc: {{.CcPwnPassword}}\n\n<html><body>Hello<br>\n<br>\nWe have detected that you recently connected to the dailymotion's corporate VPN with login {{.Login}} and a password which was part a password-related breach - possibly related to your own account on a third party website - and which is now widely known to hackers.<br>\n<br>\nPlease contact the security team and go to the Okta homepage to change your password immediately : <a href=\"https://dailymotion.okta.com\">https://dailymotion.okta.com</a>/<br>\n<br>\nIf you were using the same unsafe password anywhere else, you should change it everywhere and make sure you use a unique password for every service (password managers make this feasible).<br>\n<br>\nWe remind you that you should always keep your passwords strong and strictly unique, especially when it comes to your dailymotion accounts. A robust password can, for example, be generated using an easily remembered phrase and retaining certain letters: for example, the phrase \"a bird in the hand is worth two in the bush\" would give the password \"1bitH=2itB\" (this example must not be used as a password).<br>\n<br>\nRegards,<br>\n<br>\n--<br>\nThe Dailymotion Security Team</body></html>"
|
||||
newAsTemplate: "From: {{.MailFrom}}\nSubject: A new connection from you to the Dailymotion VPN\nTo: {{.Mail}}\n\nHello\n\nWe have detected a new connection to the vpn from {{.Login}}.\nIt was detected the {{.Time}} coming from the ip {{.IP}} ({{.AsName}}).\n\nIt's not the usual internet provider you connect to the Dailymotion VPN from.\nOr maybe it's the first time you use the VPN from this location.\n\nIf you think there is something suspicious, please contact {{.CcPwnPassword}}\nIf it's you who connected to the VPN, we are sorry for the spam. You won't receive another mail if you connect from this location.\n\nRegards,\n\n--\nThe Dailymotion Infra and Security Teams"
|
||||
}
|
176
openvpn.go
176
openvpn.go
|
@ -2,112 +2,188 @@ package main
|
|||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"sync"
|
||||
|
||||
"github.com/pyke369/golang-support/rcache"
|
||||
)
|
||||
|
||||
type OpenVpnSrv struct {
|
||||
Remote string `json:"active-vpn"`
|
||||
Status string `json:"status"`
|
||||
hold bool
|
||||
chanHold chan bool
|
||||
m sync.RWMutex
|
||||
ret chan []string
|
||||
buf *bufio.ReadWriter
|
||||
Remote string `json:"active-vpn"`
|
||||
Status string `json:"status"`
|
||||
Provider string `json:"provider"`
|
||||
Identifier string `json:"identifier"`
|
||||
chanHold chan bool
|
||||
m sync.RWMutex
|
||||
ret chan []string
|
||||
buf *bufio.ReadWriter
|
||||
mgt *OpenVpnMgt
|
||||
hold bool
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) Lock() {
|
||||
s.m.Lock()
|
||||
func (v *OpenVpnSrv) Lock() {
|
||||
v.m.Lock()
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) Unlock() {
|
||||
s.m.Unlock()
|
||||
func (v *OpenVpnSrv) Unlock() {
|
||||
v.m.Unlock()
|
||||
}
|
||||
|
||||
func NewOpenVpnSrv(conn net.Conn) *OpenVpnSrv {
|
||||
func NewOpenVpnSrv(conn net.Conn, mgt *OpenVpnMgt) *OpenVpnSrv {
|
||||
return &OpenVpnSrv{
|
||||
buf: bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn)),
|
||||
hold: false,
|
||||
chanHold: make(chan bool),
|
||||
ret: make(chan []string),
|
||||
mgt: mgt,
|
||||
hold: false,
|
||||
}
|
||||
}
|
||||
|
||||
// send a command to the server. Set the channel to receive the response
|
||||
func (s *OpenVpnSrv) sendCommand(msg []string) (error, []string) {
|
||||
func (v *OpenVpnSrv) sendCommand(msg []string) (error, []string) {
|
||||
v.Lock()
|
||||
for _, line := range msg {
|
||||
if _, err := s.buf.WriteString(line + "\r\n"); err != nil {
|
||||
if _, err := v.buf.WriteString(line + "\r\n"); err != nil {
|
||||
v.Unlock()
|
||||
return err, nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.buf.Flush(); err != nil {
|
||||
if err := v.buf.Flush(); err != nil {
|
||||
return err, nil
|
||||
}
|
||||
v.Unlock()
|
||||
|
||||
// wait for the response
|
||||
ret := <-s.ret
|
||||
ret := <-v.ret
|
||||
|
||||
return nil, ret
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) Response(response []string) {
|
||||
s.Lock()
|
||||
s.ret <- response
|
||||
s.Unlock()
|
||||
func (v *OpenVpnSrv) Signal(signal string) error {
|
||||
for _, valid := range []string{"SIGHUP", "SIGTERM"} {
|
||||
if signal == valid {
|
||||
err, _ := v.sendCommand([]string{fmt.Sprintf("signal %s", signal)})
|
||||
return err
|
||||
}
|
||||
}
|
||||
return errors.New("unknown signal")
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) GetLine() (string, error) {
|
||||
return s.buf.ReadString('\n')
|
||||
func (v *OpenVpnSrv) GetPid() error {
|
||||
err, infos := v.sendCommand([]string{"pid"})
|
||||
if err != nil {
|
||||
v.mgt.Debug(err)
|
||||
return err
|
||||
}
|
||||
pidRegexp := rcache.Get("^SUCCESS: pid=([0-9]+)$")
|
||||
for _, line := range infos {
|
||||
match := pidRegexp.FindStringSubmatch(line)
|
||||
if len(match) == 0 {
|
||||
continue
|
||||
}
|
||||
if len(match) == 2 {
|
||||
pid, err := strconv.Atoi(match[1])
|
||||
if err == nil {
|
||||
v.mgt.SetPid(v, pid)
|
||||
v.mgt.Debug("Found PID", pid)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
v.mgt.Debug("Can't find PID")
|
||||
return errors.New("Can't find PID")
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) ValidRemote(server, port, proto string) {
|
||||
if s.Remote != "" {
|
||||
s.sendCommand([]string{fmt.Sprintf("remote MOD %s %s %s", s.Remote, port, proto)})
|
||||
s.Status = "Connected"
|
||||
func (v *OpenVpnSrv) GetEcho() {
|
||||
err, infos := v.sendCommand([]string{"echo all"})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.Remote = server
|
||||
s.sendCommand([]string{"remote ACCEPT"})
|
||||
echoRegexp := rcache.Get("^[0-9]+,([A-Za-z0-9-]*):([A-Za-z0-9-]*)$")
|
||||
for _, line := range infos {
|
||||
match := echoRegexp.FindStringSubmatch(line)
|
||||
if len(match) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
switch match[1] {
|
||||
case "vpnidentifier":
|
||||
v.Identifier = match[2]
|
||||
case "vpnprovider":
|
||||
if err := v.mgt.getServerList(match[2]); err != nil {
|
||||
v.mgt.Debug(err)
|
||||
|
||||
continue
|
||||
}
|
||||
v.Provider = match[2]
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) Kill() {
|
||||
func (v *OpenVpnSrv) Response(response []string) {
|
||||
v.Lock()
|
||||
v.ret <- response
|
||||
v.Unlock()
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) Version() (error, []string) {
|
||||
return s.sendCommand([]string{"version"})
|
||||
func (v *OpenVpnSrv) GetLine() (string, error) {
|
||||
return v.buf.ReadString('\n')
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) SetRemote(server string) error {
|
||||
func (v *OpenVpnSrv) ValidRemote(server, port, proto string) {
|
||||
if v.Remote != "" {
|
||||
v.sendCommand([]string{fmt.Sprintf("remote MOD %s %s %s", v.Remote, port, proto)})
|
||||
v.Status = "Connected"
|
||||
return
|
||||
}
|
||||
v.Remote = server
|
||||
v.sendCommand([]string{"remote ACCEPT"})
|
||||
}
|
||||
|
||||
func (v *OpenVpnSrv) Version() (error, []string) {
|
||||
return v.sendCommand([]string{"version"})
|
||||
}
|
||||
|
||||
func (v *OpenVpnSrv) SetRemote(server string) error {
|
||||
// already the active server, do nothing
|
||||
if s.Remote == server {
|
||||
if v.Remote == server {
|
||||
return nil
|
||||
}
|
||||
|
||||
if s.Remote != "" {
|
||||
s.Kill()
|
||||
if v.Remote != "" {
|
||||
v.Remote = server
|
||||
v.Signal("SIGHUP")
|
||||
v.Status = "Reloaded"
|
||||
}
|
||||
|
||||
s.Remote = server
|
||||
v.Remote = server
|
||||
|
||||
// release Hold if necessary
|
||||
s.ReleaseHold()
|
||||
v.ReleaseHold()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) waitForRelase() {
|
||||
s.hold = true
|
||||
s.Status = "Hold"
|
||||
<-s.chanHold
|
||||
s.sendCommand([]string{"hold release"})
|
||||
}
|
||||
|
||||
func (s *OpenVpnSrv) ReleaseHold() {
|
||||
if !s.hold {
|
||||
func (v *OpenVpnSrv) waitForRelase() {
|
||||
v.Status = "Hold"
|
||||
if v.hold {
|
||||
return
|
||||
}
|
||||
s.hold = false
|
||||
s.chanHold <- true
|
||||
s.Status = "Waiting for connexion"
|
||||
v.hold = true
|
||||
<-v.chanHold
|
||||
v.sendCommand([]string{"hold release"})
|
||||
v.sendCommand([]string{"hold off"})
|
||||
}
|
||||
|
||||
func (v *OpenVpnSrv) ReleaseHold() {
|
||||
if !v.hold {
|
||||
return
|
||||
}
|
||||
v.hold = false
|
||||
v.chanHold <- true
|
||||
v.Status = "Waiting for connexion"
|
||||
}
|
||||
|
|
File diff suppressed because one or more lines are too long
1
utils.go
1
utils.go
|
@ -16,7 +16,6 @@ func inArray(search, list []string) bool {
|
|||
i := sort.Search(len(list), func(i int) bool { return list[i] >= g })
|
||||
if i < len(list) && list[i] == g {
|
||||
return true
|
||||
break
|
||||
}
|
||||
}
|
||||
return false
|
||||
|
|
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2014 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,216 @@
|
|||
// Copyright 2014 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package fs contains an HTTP file system that works with zip contents.
|
||||
package fs
|
||||
|
||||
import (
|
||||
"archive/zip"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var zipData string
|
||||
|
||||
// file holds unzipped read-only file contents and file metadata.
|
||||
type file struct {
|
||||
os.FileInfo
|
||||
data []byte
|
||||
fs *statikFS
|
||||
}
|
||||
|
||||
type statikFS struct {
|
||||
files map[string]file
|
||||
dirs map[string][]string
|
||||
}
|
||||
|
||||
// Register registers zip contents data, later used to initialize
|
||||
// the statik file system.
|
||||
func Register(data string) {
|
||||
zipData = data
|
||||
}
|
||||
|
||||
// New creates a new file system with the registered zip contents data.
|
||||
// It unzips all files and stores them in an in-memory map.
|
||||
func New() (http.FileSystem, error) {
|
||||
if zipData == "" {
|
||||
return nil, errors.New("statik/fs: no zip data registered")
|
||||
}
|
||||
zipReader, err := zip.NewReader(strings.NewReader(zipData), int64(len(zipData)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files := make(map[string]file, len(zipReader.File))
|
||||
dirs := make(map[string][]string)
|
||||
fs := &statikFS{files: files, dirs: dirs}
|
||||
for _, zipFile := range zipReader.File {
|
||||
fi := zipFile.FileInfo()
|
||||
f := file{FileInfo: fi, fs: fs}
|
||||
f.data, err = unzip(zipFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("statik/fs: error unzipping file %q: %s", zipFile.Name, err)
|
||||
}
|
||||
files["/"+zipFile.Name] = f
|
||||
}
|
||||
for fn := range files {
|
||||
// go up directories recursively in order to care deep directory
|
||||
for dn := path.Dir(fn); dn != fn; {
|
||||
if _, ok := files[dn]; !ok {
|
||||
files[dn] = file{FileInfo: dirInfo{dn}, fs: fs}
|
||||
} else {
|
||||
break
|
||||
}
|
||||
fn, dn = dn, path.Dir(dn)
|
||||
}
|
||||
}
|
||||
for fn := range files {
|
||||
dn := path.Dir(fn)
|
||||
if fn != dn {
|
||||
fs.dirs[dn] = append(fs.dirs[dn], path.Base(fn))
|
||||
}
|
||||
}
|
||||
for _, s := range fs.dirs {
|
||||
sort.Strings(s)
|
||||
}
|
||||
return fs, nil
|
||||
}
|
||||
|
||||
var _ = os.FileInfo(dirInfo{})
|
||||
|
||||
type dirInfo struct {
|
||||
name string
|
||||
}
|
||||
|
||||
func (di dirInfo) Name() string { return path.Base(di.name) }
|
||||
func (di dirInfo) Size() int64 { return 0 }
|
||||
func (di dirInfo) Mode() os.FileMode { return 0755 | os.ModeDir }
|
||||
func (di dirInfo) ModTime() time.Time { return time.Time{} }
|
||||
func (di dirInfo) IsDir() bool { return true }
|
||||
func (di dirInfo) Sys() interface{} { return nil }
|
||||
|
||||
func unzip(zf *zip.File) ([]byte, error) {
|
||||
rc, err := zf.Open()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rc.Close()
|
||||
return ioutil.ReadAll(rc)
|
||||
}
|
||||
|
||||
// Open returns a file matching the given file name, or os.ErrNotExists if
|
||||
// no file matching the given file name is found in the archive.
|
||||
// If a directory is requested, Open returns the file named "index.html"
|
||||
// in the requested directory, if that file exists.
|
||||
func (fs *statikFS) Open(name string) (http.File, error) {
|
||||
name = strings.Replace(name, "//", "/", -1)
|
||||
if f, ok := fs.files[name]; ok {
|
||||
return newHTTPFile(f), nil
|
||||
}
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
|
||||
func newHTTPFile(file file) *httpFile {
|
||||
if file.IsDir() {
|
||||
return &httpFile{file: file, isDir: true}
|
||||
}
|
||||
return &httpFile{file: file, reader: bytes.NewReader(file.data)}
|
||||
}
|
||||
|
||||
// httpFile represents an HTTP file and acts as a bridge
|
||||
// between file and http.File.
|
||||
type httpFile struct {
|
||||
file
|
||||
|
||||
reader *bytes.Reader
|
||||
isDir bool
|
||||
dirIdx int
|
||||
}
|
||||
|
||||
// Read reads bytes into p, returns the number of read bytes.
|
||||
func (f *httpFile) Read(p []byte) (n int, err error) {
|
||||
if f.reader == nil && f.isDir {
|
||||
return 0, io.EOF
|
||||
}
|
||||
return f.reader.Read(p)
|
||||
}
|
||||
|
||||
// Seek seeks to the offset.
|
||||
func (f *httpFile) Seek(offset int64, whence int) (ret int64, err error) {
|
||||
return f.reader.Seek(offset, whence)
|
||||
}
|
||||
|
||||
// Stat stats the file.
|
||||
func (f *httpFile) Stat() (os.FileInfo, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// IsDir returns true if the file location represents a directory.
|
||||
func (f *httpFile) IsDir() bool {
|
||||
return f.isDir
|
||||
}
|
||||
|
||||
// Readdir returns an empty slice of files, directory
|
||||
// listing is disabled.
|
||||
func (f *httpFile) Readdir(count int) ([]os.FileInfo, error) {
|
||||
var fis []os.FileInfo
|
||||
if !f.isDir {
|
||||
return fis, nil
|
||||
}
|
||||
di, ok := f.FileInfo.(dirInfo)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("failed to read directory: %q", f.Name())
|
||||
}
|
||||
|
||||
// If count is positive, the specified number of files will be returned,
|
||||
// and if negative, all remaining files will be returned.
|
||||
// The reading position of which file is returned is held in dirIndex.
|
||||
fnames := f.file.fs.dirs[di.name]
|
||||
flen := len(fnames)
|
||||
|
||||
// If dirIdx reaches the end and the count is a positive value,
|
||||
// an io.EOF error is returned.
|
||||
// In other cases, no error will be returned even if, for example,
|
||||
// you specified more counts than the number of remaining files.
|
||||
start := f.dirIdx
|
||||
if start >= flen && count > 0 {
|
||||
return fis, io.EOF
|
||||
}
|
||||
var end int
|
||||
if count < 0 {
|
||||
end = flen
|
||||
} else {
|
||||
end = start + count
|
||||
}
|
||||
if end > flen {
|
||||
end = flen
|
||||
}
|
||||
for i := start; i < end; i++ {
|
||||
fis = append(fis, f.file.fs.files[path.Join(di.name, fnames[i])].FileInfo)
|
||||
}
|
||||
f.dirIdx += len(fis)
|
||||
return fis, nil
|
||||
}
|
||||
|
||||
func (f *httpFile) Close() error {
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,79 @@
|
|||
// Copyright 2014 Google Inc. All Rights Reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"net/http"
|
||||
"path"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Walk walks the file tree rooted at root,
|
||||
// calling walkFn for each file or directory in the tree, including root.
|
||||
// All errors that arise visiting files and directories are filtered by walkFn.
|
||||
//
|
||||
// As with filepath.Walk, if the walkFn returns filepath.SkipDir, then the directory is skipped.
|
||||
func Walk(hfs http.FileSystem, root string, walkFn filepath.WalkFunc) error {
|
||||
dh, err := hfs.Open(root)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
di, err := dh.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fis, err := dh.Readdir(-1)
|
||||
dh.Close()
|
||||
if err = walkFn(root, di, err); err != nil {
|
||||
if err == filepath.SkipDir {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
for _, fi := range fis {
|
||||
fn := path.Join(root, fi.Name())
|
||||
if fi.IsDir() {
|
||||
if err = Walk(hfs, fn, walkFn); err != nil {
|
||||
if err == filepath.SkipDir {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err = walkFn(fn, fi, nil); err != nil {
|
||||
if err == filepath.SkipDir {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadFile reads the contents of the file of hfs specified by name.
|
||||
// Just as ioutil.ReadFile does.
|
||||
func ReadFile(hfs http.FileSystem, name string) ([]byte, error) {
|
||||
fh, err := hfs.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var buf bytes.Buffer
|
||||
_, err = io.Copy(&buf, fh)
|
||||
fh.Close()
|
||||
return buf.Bytes(), err
|
||||
}
|
|
@ -1,9 +1,5 @@
|
|||
# github.com/mattevans/pwned-passwords v0.0.0-20190611210716-1da592be4a34
|
||||
github.com/mattevans/pwned-passwords
|
||||
# github.com/pyke369/golang-support v0.0.0-20190703174728-34ca97aa79e9
|
||||
github.com/pyke369/golang-support/rcache
|
||||
github.com/pyke369/golang-support/uconfig
|
||||
# gopkg.in/asn1-ber.v1 v1.0.0-20181015200546-f715ec2f112d
|
||||
gopkg.in/asn1-ber.v1
|
||||
# gopkg.in/ldap.v2 v2.5.1
|
||||
gopkg.in/ldap.v2
|
||||
# github.com/rakyll/statik v0.1.6
|
||||
github.com/rakyll/statik/fs
|
||||
|
|
|
@ -0,0 +1,8 @@
|
|||
config
|
||||
{
|
||||
openvpnPort: "127.0.0.1:4000"
|
||||
http:
|
||||
{
|
||||
port: ":8080"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,22 @@
|
|||
package main
|
||||
|
||||
type VpnProvider interface {
|
||||
ServerList() (error, *[]string)
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) getServerList(provider string) error {
|
||||
var err error
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
|
||||
if _, ok := s.VpnRemotes[provider]; ok {
|
||||
return nil
|
||||
}
|
||||
switch provider {
|
||||
case "expressvpn":
|
||||
list := ExpressVPN{}
|
||||
err, s.VpnRemotes[provider] = list.ServerList()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
132
vpnserver.go
132
vpnserver.go
|
@ -6,9 +6,9 @@ import (
|
|||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pyke369/golang-support/rcache"
|
||||
)
|
||||
|
@ -18,8 +18,9 @@ type OpenVpnMgt struct {
|
|||
port string
|
||||
m sync.RWMutex
|
||||
debug bool
|
||||
VpnRemotes []string `json:"remotes"`
|
||||
vpnServers map[int]*OpenVpnSrv `json:"sessions"`
|
||||
VpnRemotes map[string]*[]string `json:"remotes"`
|
||||
VpnServers map[int]*OpenVpnSrv `json:"sessions"`
|
||||
LastChange time.Time `json:"last_change"`
|
||||
}
|
||||
|
||||
// NewServer returns a pointer to a new server
|
||||
|
@ -27,7 +28,8 @@ func NewVPNServer(port string, debug bool) *OpenVpnMgt {
|
|||
return &OpenVpnMgt{
|
||||
port: port,
|
||||
debug: debug,
|
||||
vpnServers: make(map[int]*OpenVpnSrv),
|
||||
VpnServers: make(map[int]*OpenVpnSrv),
|
||||
VpnRemotes: make(map[string]*[]string),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -39,15 +41,18 @@ func (s *OpenVpnMgt) Unlock() {
|
|||
s.m.Unlock()
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) Change() {
|
||||
s.LastChange = time.Now().Round(time.Second)
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) Debug(v ...interface{}) {
|
||||
if s.debug {
|
||||
log.Println(v...)
|
||||
}
|
||||
}
|
||||
|
||||
// Run starts a the server
|
||||
func (s *OpenVpnMgt) Run() {
|
||||
|
||||
// get the endpoint list
|
||||
if err := s.getServerList(); err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Resolve the passed port into an address
|
||||
addrs, err := net.ResolveTCPAddr("tcp", s.port)
|
||||
if err != nil {
|
||||
|
@ -73,38 +78,82 @@ func (s *OpenVpnMgt) Run() {
|
|||
}
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) GetSession(remote int) (error, *OpenVpnSrv) {
|
||||
if vpnServer, ok := s.vpnServers[remote]; ok {
|
||||
return nil, vpnServer
|
||||
func (s *OpenVpnMgt) GetSession(pid int) (error, *OpenVpnSrv) {
|
||||
if openvpn, ok := s.VpnServers[pid]; ok {
|
||||
return nil, openvpn
|
||||
}
|
||||
return errors.New(fmt.Sprintf("unknown session %d", vpnServers)), nil
|
||||
return errors.New(fmt.Sprintf("unknown session %d", pid)), nil
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) SetRemote(server string, remote int) error {
|
||||
func (s *OpenVpnMgt) Restart(pid int) error {
|
||||
// check if the session is valid
|
||||
err, session := s.GetSession(remote)
|
||||
err, session := s.GetSession(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
session.Signal("SIGHUP")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) Kill(pid int) error {
|
||||
// check if the session is valid
|
||||
err, session := s.GetSession(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
session.Signal("SIGTERM")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) SetRemote(server string, pid int) error {
|
||||
// check if the session is valid
|
||||
err, session := s.GetSession(pid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
for _, r := range s.VpnRemotes {
|
||||
if session.Provider == "" {
|
||||
return errors.New("No server list for this config")
|
||||
}
|
||||
if _, ok := s.VpnRemotes[session.Provider]; !ok {
|
||||
return errors.New("No server list for this provider")
|
||||
}
|
||||
|
||||
for _, r := range *(s.VpnRemotes[session.Provider]) {
|
||||
if r != server {
|
||||
continue
|
||||
}
|
||||
return session.SetRemote(server)
|
||||
}
|
||||
|
||||
return errors.New(fmt.Sprintf("unknown remote %s", server))
|
||||
return errors.New(fmt.Sprintf("unknown session %s", server))
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) SetPid(openvpn *OpenVpnSrv, pid int) {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
s.VpnServers[pid] = openvpn
|
||||
}
|
||||
|
||||
func (s *OpenVpnMgt) Remove(openvpn *OpenVpnSrv) {
|
||||
for pid, v := range s.VpnServers {
|
||||
if v == openvpn {
|
||||
delete(s.VpnServers, pid)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// send the version command on all vpn servers. Kind of useless
|
||||
func (s *OpenVpnMgt) Version() (error, map[int][]string) {
|
||||
var err error
|
||||
ret := make(map[int][]string)
|
||||
for remote, srv := range s.vpnServers {
|
||||
for pid, srv := range s.VpnServers {
|
||||
err, msg := srv.Version()
|
||||
if err == nil {
|
||||
ret[remote] = msg
|
||||
ret[pid] = msg
|
||||
}
|
||||
}
|
||||
return err, ret
|
||||
|
@ -113,19 +162,17 @@ func (s *OpenVpnMgt) Version() (error, map[int][]string) {
|
|||
// main loop for a given openvpn server
|
||||
func (s *OpenVpnMgt) handleConn(conn net.Conn) {
|
||||
remote := conn.RemoteAddr().String()
|
||||
pidRegexp := rcache.Get("^SUCCESS: pid=([0-9]+)$")
|
||||
// >REMOTE:vpn.example.com,1194,udp
|
||||
remoteRegexp := rcache.Get("^>REMOTE:(.*),([0-9]*),(.*)$")
|
||||
|
||||
defer conn.Close()
|
||||
|
||||
vpnServer := NewOpenVpnSrv(conn)
|
||||
openvpn := NewOpenVpnSrv(conn, s)
|
||||
defer s.Remove(openvpn)
|
||||
|
||||
// most response are multilined, use response to concatenate them
|
||||
response := []string{}
|
||||
|
||||
// remove bogus clients
|
||||
line, err := vpnServer.session.GetLine()
|
||||
line, err := openvpn.GetLine()
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
return
|
||||
|
@ -137,24 +184,27 @@ func (s *OpenVpnMgt) handleConn(conn net.Conn) {
|
|||
|
||||
log.Printf("Valid openvpn connected from %s\n", remote)
|
||||
|
||||
go session.sendCommand([]string{"pid"})
|
||||
go openvpn.GetEcho()
|
||||
go openvpn.GetPid()
|
||||
s.Change()
|
||||
defer s.Change()
|
||||
|
||||
for {
|
||||
line, err := session.GetLine()
|
||||
line, err := openvpn.GetLine()
|
||||
|
||||
// manage basic errors
|
||||
switch {
|
||||
case err == io.EOF:
|
||||
log.Println("Reached EOF - close this connection.\n")
|
||||
log.Println("Reached EOF - close this connection")
|
||||
return
|
||||
case err != nil:
|
||||
log.Println("Error reading line. Got: '"+line+"'\n", err)
|
||||
log.Printf("Error reading line. Got: '"+line+"'\n", err)
|
||||
return
|
||||
}
|
||||
line = strings.Trim(line, "\n\r ")
|
||||
|
||||
if s.debug && strings.Index(line, "password") == -1 {
|
||||
log.Print(line)
|
||||
if strings.Index(line, "password") == -1 {
|
||||
s.Debug(line)
|
||||
}
|
||||
|
||||
// manage exit commands
|
||||
|
@ -165,22 +215,13 @@ func (s *OpenVpnMgt) handleConn(conn net.Conn) {
|
|||
}
|
||||
}
|
||||
|
||||
// get the PID
|
||||
match := pidRegexp.FindStringSubmatch(line)
|
||||
if len(match) == 2 {
|
||||
pid, _ := strconv.Atoi(match[1])
|
||||
s.Lock()
|
||||
s.vpnServers[pid] = vpnServer
|
||||
s.Unlock()
|
||||
defer delete(s.vpnServers, pid)
|
||||
}
|
||||
|
||||
// manage all "terminator" lines
|
||||
for _, terminator := range []string{"END", ">CLIENT:ENV,END", "SUCCESS", "ERROR"} {
|
||||
if strings.HasPrefix(line, terminator) {
|
||||
vpnServer.Response(response)
|
||||
openvpn.Response(append(response, line))
|
||||
response = nil
|
||||
line = ""
|
||||
s.Change()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
@ -188,11 +229,10 @@ func (s *OpenVpnMgt) handleConn(conn net.Conn) {
|
|||
remoteMatch := remoteRegexp.FindStringSubmatch(line)
|
||||
switch {
|
||||
// command successfull, we can ignore
|
||||
case strings.HasPrefix(line, ">SUCCESS: client-deny command succeeded"):
|
||||
case strings.HasPrefix(line, ">HOLD"):
|
||||
go vpnServer.waitForRelase()
|
||||
go openvpn.waitForRelase()
|
||||
case len(remoteMatch) > 0:
|
||||
go vpnServer.ValidRemote(remoteMatch[1], remoteMatch[2], remoteMatch[3])
|
||||
go openvpn.ValidRemote(remoteMatch[1], remoteMatch[2], remoteMatch[3])
|
||||
default:
|
||||
response = append(response, line)
|
||||
}
|
||||
|
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
@ -0,0 +1,206 @@
|
|||
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>OpenVPN Manager</title>
|
||||
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
|
||||
<script language="javascript" type="text/javascript" src="jquery.min.js"></script>
|
||||
<script language="javascript" type="text/javascript" src="bootstrap.min.js"></script>
|
||||
<link rel="stylesheet" href="bootstrap.min.css" />
|
||||
<style>
|
||||
body
|
||||
{
|
||||
padding: 0px 10px 10px 10px;
|
||||
}
|
||||
|
||||
.hidden {
|
||||
display:none;
|
||||
}
|
||||
|
||||
#background
|
||||
{
|
||||
position: fixed;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background-position: bottom right;
|
||||
background-repeat: no-repeat;
|
||||
}
|
||||
.container
|
||||
{
|
||||
margin-top: 10px;
|
||||
}
|
||||
.section
|
||||
{
|
||||
position: relative;
|
||||
width: 930px;
|
||||
padding: 30px 0px 10px 10px;
|
||||
border: 1px solid #cccccc;
|
||||
border-radius: 4px;
|
||||
}
|
||||
.section_title
|
||||
{
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
padding: 3px 7px 3px 7px;
|
||||
border-bottom: 1px solid #cccccc;
|
||||
border-right: 1px solid #cccccc;
|
||||
border-bottom-right-radius: 4px;
|
||||
border-top-left-radius: 4px;
|
||||
color: #989898;
|
||||
font-size: 12px;
|
||||
font-weight: bold;
|
||||
background-color: #f5f5f5;
|
||||
}
|
||||
.alert
|
||||
{
|
||||
float: left;
|
||||
padding-bottom: 14px;
|
||||
margin: 4px 0px 0px 0px;
|
||||
width: 867px;
|
||||
}
|
||||
.btn
|
||||
{
|
||||
font-weight: bold;
|
||||
}
|
||||
.btn.active, .btn:active
|
||||
{
|
||||
background-color: rgb(47, 150, 180);
|
||||
color: white;
|
||||
text-shadow: 0px 0px 0px;
|
||||
}
|
||||
|
||||
table {
|
||||
border-style: solid none solid solid;
|
||||
border-width: 1px;
|
||||
border-spacing:0;
|
||||
margin: 1em;
|
||||
border-collapse:collapse;
|
||||
}
|
||||
|
||||
|
||||
th {
|
||||
padding: 5px 2em 5px 2em;
|
||||
border-style: solid solid none none;
|
||||
border-width: 1px;
|
||||
text-align: left;
|
||||
font-weight:bold;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 5px 2em 5px 2em;
|
||||
border-style: solid solid none none;
|
||||
border-width: 1px;
|
||||
vertical-align: middle;
|
||||
height: 16px;
|
||||
}
|
||||
|
||||
select.interface {
|
||||
width: 5em;
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
last_change="";
|
||||
$(function() {
|
||||
server = "localhost:8080";
|
||||
ajax(server, {"action":"get-remotes"} );
|
||||
});
|
||||
|
||||
function ajax(server, action){
|
||||
$.ajax({
|
||||
type: 'post',
|
||||
url: 'http://'+server+'/ajax',
|
||||
data: JSON.stringify(action),
|
||||
error:function(msg){
|
||||
console.log( 'Error !: (' + msg.responseText + ')' );
|
||||
},
|
||||
success:function(data){
|
||||
if (action["action"] == "get-remotes") {
|
||||
refresh(server, data);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function vpn_restart(pid) {
|
||||
if(confirm("are you sure you want to restart this session ?")) {
|
||||
ajax(server, {action: 'restart', params: {session: pid}});
|
||||
}
|
||||
}
|
||||
|
||||
function vpn_kill(pid) {
|
||||
if(confirm("are you sure you want to kill this openvpn client ?")) {
|
||||
ajax(server, {action: 'kill', params: {session: pid}});
|
||||
}
|
||||
}
|
||||
|
||||
function server_change(pid) {
|
||||
ajax(server, {action: 'set-remote', params: {server: $('#server_'+pid).val() , session: pid}});
|
||||
}
|
||||
|
||||
function refresh(server, data) {
|
||||
setTimeout(function(){ ajax(server, {"action":"get-remotes"} )}, 3000);
|
||||
if (data["last_change"] == last_change) {
|
||||
return;
|
||||
}
|
||||
last_change = data["last_change"];
|
||||
$('#result>tbody').remove();
|
||||
$('#result').append('<tbody></ybody>');
|
||||
remote = []
|
||||
$.each(data, function(index, infos) {
|
||||
if (!infos) {
|
||||
return;
|
||||
} else if (index == "remotes") {
|
||||
remotes = infos;
|
||||
} else if (index == "sessions") {
|
||||
$.each(infos, function(pid, infos) {
|
||||
line = '<tr>';
|
||||
line +='<td>'+infos['identifier']+'</td>';
|
||||
line +='<td>'+infos['provider']+'</td>';
|
||||
if (possible=remotes[infos['provider']]) {
|
||||
possible.sort();
|
||||
line += '<td><select id="server_'+pid+'" onchange="server_change('+pid+')">'
|
||||
if (infos['active-vpn']=="") {
|
||||
line += '<option value="">----------------</option>'
|
||||
}
|
||||
$.each(possible, function(i, remote) {
|
||||
line += '<option value="'+remote+'"';
|
||||
if(remote == infos['active-vpn']) {
|
||||
line += ' selected ';
|
||||
}
|
||||
line += '>'+remote+'</option>';
|
||||
});
|
||||
line+='</select></td>'
|
||||
} else {
|
||||
line +='<td>'+infos['active-vpn']+'</td>';
|
||||
}
|
||||
line +='<td>'+infos['status']+'</td>';
|
||||
|
||||
line +='<td><a href="javascript:vpn_restart('+pid+')">Reload</a></td>';
|
||||
line +='<td><a href="javascript:vpn_kill('+pid+')">Kill</a></td>';
|
||||
line += '</tr>\n';
|
||||
$('#result>tbody').append(line);
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<h1>VPN Sessions</h1>
|
||||
<table id="result">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>VPN Identifier</th>
|
||||
<th>Provider</th>
|
||||
<th>VPN Server</th>
|
||||
<th>Status</th>
|
||||
<th colspan="2"> </th>
|
||||
</tr>
|
||||
</thead>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
File diff suppressed because one or more lines are too long
Loading…
Reference in New Issue