refactoring. convert for go module; totp auth
This commit is contained in:
parent
8ca2faa468
commit
9e5553eff6
10 changed files with 534 additions and 391 deletions
47
README.md
47
README.md
|
@ -1,7 +1,7 @@
|
||||||
# openvpn-user
|
# openvpn-user
|
||||||
|
|
||||||
## Disclaimer
|
## Disclaimer
|
||||||
```diff
|
```
|
||||||
- Not tested in production environments!
|
- Not tested in production environments!
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -12,12 +12,12 @@ Use it on your own risk =)
|
||||||
A simple tool to use with openvpn when you need to use `–auth-user-pass-verify` or wherever you want
|
A simple tool to use with openvpn when you need to use `–auth-user-pass-verify` or wherever you want
|
||||||
|
|
||||||
### Example
|
### Example
|
||||||
make sure `openvpn-user` binary available through `PATH` variable and you have `auth.sh` script with `+x` rights available to openvpn server
|
make sure `openvpn-user` binary available through `PATH` variable and you have [auth.sh](https://github.com/pashcovich/openvpn-user/blob/master/auth.sh) or [auth_totp.sh](https://github.com/pashcovich/openvpn-user/blob/master/auth_totp.sh) script with `+x` rights available to openvpn server
|
||||||
|
|
||||||
i.e. put binary to `/usr/local/sbin/` and auth script to `/etc/openvpn/scripts/` dir
|
i.e. put binary to `/usr/local/sbin/` and auth script to `/etc/openvpn/scripts/` dir
|
||||||
|
|
||||||
part of openvpn server config
|
part of openvpn server config
|
||||||
```bash
|
```
|
||||||
script-security 2
|
script-security 2
|
||||||
auth-user-pass-verify /etc/openvpn/scripts/auth.sh via-file
|
auth-user-pass-verify /etc/openvpn/scripts/auth.sh via-file
|
||||||
```
|
```
|
||||||
|
@ -30,50 +30,85 @@ usage: openvpn-user [<flags>] <command> [<args> ...]
|
||||||
Flags:
|
Flags:
|
||||||
--help Show context-sensitive help (also try --help-long and --help-man).
|
--help Show context-sensitive help (also try --help-long and --help-man).
|
||||||
--db.path="./openvpn-user.db" path do openvpn-user db
|
--db.path="./openvpn-user.db" path do openvpn-user db
|
||||||
--debug Enable debug mode.
|
|
||||||
--version Show application version.
|
|
||||||
|
|
||||||
Commands:
|
Commands:
|
||||||
help [<command>...]
|
help [<command>...]
|
||||||
Show help.
|
Show help.
|
||||||
|
|
||||||
|
|
||||||
db-init
|
db-init
|
||||||
Init db.
|
Init db.
|
||||||
|
|
||||||
|
|
||||||
db-migrate
|
db-migrate
|
||||||
STUB: Migrate db.
|
STUB: Migrate db.
|
||||||
|
|
||||||
|
|
||||||
create --user=USER --password=PASSWORD
|
create --user=USER --password=PASSWORD
|
||||||
Create user.
|
Create user.
|
||||||
|
|
||||||
|
--user=USER Username.
|
||||||
|
--password=PASSWORD Password.
|
||||||
|
|
||||||
delete --user=USER [<flags>]
|
delete --user=USER [<flags>]
|
||||||
Delete user.
|
Delete user.
|
||||||
|
|
||||||
|
-f, --force delete from db.
|
||||||
|
-u, --user=USER Username.
|
||||||
|
|
||||||
revoke --user=USER
|
revoke --user=USER
|
||||||
Revoke user.
|
Revoke user.
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
|
||||||
restore --user=USER
|
restore --user=USER
|
||||||
Restore user.
|
Restore user.
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
|
||||||
list [<flags>]
|
list [<flags>]
|
||||||
List active users.
|
List active users.
|
||||||
|
|
||||||
|
-a, --all Show all users include revoked and deleted.
|
||||||
|
|
||||||
check --user=USER
|
check --user=USER
|
||||||
check user existent.
|
check user existent.
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
|
||||||
auth --user=USER [<flags>]
|
auth --user=USER [<flags>]
|
||||||
Auth user.
|
Auth user.
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
-p, --password=PASSWORD Password.
|
||||||
|
-t, --totp=TOTP TOTP code.
|
||||||
|
|
||||||
change-password --user=USER --password=PASSWORD
|
change-password --user=USER --password=PASSWORD
|
||||||
Change password
|
Change password
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
-p, --password=PASSWORD Password.
|
||||||
|
|
||||||
update-secret --user=USER [<flags>]
|
update-secret --user=USER [<flags>]
|
||||||
update OTP secret
|
update OTP secret
|
||||||
|
|
||||||
register-app --user=USER
|
-u, --user=USER Username.
|
||||||
|
-s, --secret="generate" Secret.
|
||||||
|
|
||||||
|
register-app --user=USER --totp=TOTP
|
||||||
register 2FA application
|
register 2FA application
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
-t, --totp=TOTP TOTP.
|
||||||
|
|
||||||
|
check-app --user=USER
|
||||||
|
check 2FA application
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
|
||||||
get-secret --user=USER
|
get-secret --user=USER
|
||||||
get OTP secret
|
get OTP secret
|
||||||
|
|
||||||
|
-u, --user=USER Username.
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
3
auth.sh
3
auth.sh
|
@ -2,11 +2,12 @@
|
||||||
|
|
||||||
PATH=$PATH:/usr/local/bin
|
PATH=$PATH:/usr/local/bin
|
||||||
set -e
|
set -e
|
||||||
|
|
||||||
auth_usr=$(head -1 $1)
|
auth_usr=$(head -1 $1)
|
||||||
auth_passwd=$(tail -1 $1)
|
auth_passwd=$(tail -1 $1)
|
||||||
|
|
||||||
if [ $common_name = ${auth_usr} ]; then
|
if [ $common_name = ${auth_usr} ]; then
|
||||||
openvpn-user auth --user ${auth_usr} --password ${auth_passwd}
|
openvpn-user auth --user ${auth_usr} --password ${auth_passwd} # --db.path /etc/openvpn/easyrsa/pki/users.db
|
||||||
else
|
else
|
||||||
echo "Authorization failed"
|
echo "Authorization failed"
|
||||||
exit 1
|
exit 1
|
||||||
|
|
14
auth_totp.sh
Normal file
14
auth_totp.sh
Normal file
|
@ -0,0 +1,14 @@
|
||||||
|
#!/usr/bin/env sh
|
||||||
|
|
||||||
|
PATH=$PATH:/usr/local/bin
|
||||||
|
set -e
|
||||||
|
|
||||||
|
auth_usr=$(head -1 $1)
|
||||||
|
auth_token=$(tail -1 $1)
|
||||||
|
|
||||||
|
if [ $common_name = ${auth_usr} ]; then
|
||||||
|
openvpn-user auth --user ${auth_usr} --totp ${auth_token} # --db.path /etc/openvpn/easyrsa/pki/users.db
|
||||||
|
else
|
||||||
|
echo "Authorization failed"
|
||||||
|
exit 1
|
||||||
|
fi
|
6
go.mod
6
go.mod
|
@ -1,4 +1,4 @@
|
||||||
module openvpn-user
|
module github.com/pashcovich/openvpn-user
|
||||||
|
|
||||||
go 1.14
|
go 1.14
|
||||||
|
|
||||||
|
@ -6,8 +6,8 @@ require (
|
||||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
|
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
|
||||||
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 // indirect
|
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 // indirect
|
||||||
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3
|
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3
|
||||||
github.com/mattn/go-sqlite3 v1.14.6
|
github.com/mattn/go-sqlite3 v1.14.16
|
||||||
github.com/stretchr/testify v1.7.0 // indirect
|
github.com/sirupsen/logrus v1.9.0
|
||||||
golang.org/x/crypto v0.2.0
|
golang.org/x/crypto v0.2.0
|
||||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6
|
gopkg.in/alecthomas/kingpin.v2 v2.2.6
|
||||||
)
|
)
|
||||||
|
|
11
go.sum
11
go.sum
|
@ -2,14 +2,17 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 h1:JYp7IbQjafo
|
||||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 h1:EBTWhcAX7rNQ80RLwLCpHZBBrJuzallFHnF+yMXo928=
|
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4 h1:EBTWhcAX7rNQ80RLwLCpHZBBrJuzallFHnF+yMXo928=
|
||||||
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
|
github.com/alecthomas/units v0.0.0-20201120081800-1786d5ef83d4/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE=
|
||||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3 h1:AqeKSZIG/NIC75MNQlPy/LM3LxfpLwahICJBHwSMFNc=
|
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3 h1:AqeKSZIG/NIC75MNQlPy/LM3LxfpLwahICJBHwSMFNc=
|
||||||
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3/go.mod h1:hEfFauPHz7+NnjR/yHJGhrKo1Za+zStgwUETx3yzqgY=
|
github.com/dgryski/dgoogauth v0.0.0-20190221195224-5a805980a5f3/go.mod h1:hEfFauPHz7+NnjR/yHJGhrKo1Za+zStgwUETx3yzqgY=
|
||||||
github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg=
|
github.com/mattn/go-sqlite3 v1.14.16 h1:yOQRA0RpS5PFz/oikGwBEqvAWhWg5ufRz4ETLjwpU1Y=
|
||||||
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
github.com/mattn/go-sqlite3 v1.14.16/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
|
||||||
|
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||||
|
@ -30,7 +33,9 @@ golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5h
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A=
|
||||||
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
|
445
openvpn-user.go
445
openvpn-user.go
|
@ -1,22 +1,16 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/base32"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"github.com/dgryski/dgoogauth"
|
|
||||||
_ "github.com/mattn/go-sqlite3"
|
_ "github.com/mattn/go-sqlite3"
|
||||||
"golang.org/x/crypto/bcrypt"
|
"github.com/pashcovich/openvpn-user/src"
|
||||||
"gopkg.in/alecthomas/kingpin.v2"
|
"gopkg.in/alecthomas/kingpin.v2"
|
||||||
"log"
|
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
|
||||||
"text/tabwriter"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
version = "1.0.5"
|
version = "1.0.6"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
|
@ -30,83 +24,77 @@ var (
|
||||||
createCommandPasswordFlag = createCommand.Flag("password", "Password.").Required().String()
|
createCommandPasswordFlag = createCommand.Flag("password", "Password.").Required().String()
|
||||||
|
|
||||||
deleteCommand = kingpin.Command("delete", "Delete user.")
|
deleteCommand = kingpin.Command("delete", "Delete user.")
|
||||||
deleteCommandUserForceFlag = deleteCommand.Flag("force", "delete from db.").Default("false").Bool()
|
deleteCommandUserForceFlag = deleteCommand.Flag("force", "delete from db.").Short('f').Default("false").Bool()
|
||||||
deleteCommandUserFlag = deleteCommand.Flag("user", "Username.").Required().String()
|
deleteCommandUserFlag = deleteCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
|
||||||
revokeCommand = kingpin.Command("revoke", "Revoke user.")
|
revokeCommand = kingpin.Command("revoke", "Revoke user.")
|
||||||
revokeCommandUserFlag = revokeCommand.Flag("user", "Username.").Required().String()
|
revokeCommandUserFlag = revokeCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
|
||||||
restoreCommand = kingpin.Command("restore", "Restore user.")
|
restoreCommand = kingpin.Command("restore", "Restore user.")
|
||||||
restoreCommandUserFlag = restoreCommand.Flag("user", "Username.").Required().String()
|
restoreCommandUserFlag = restoreCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
|
||||||
listCommand = kingpin.Command("list", "List active users.")
|
listCommand = kingpin.Command("list", "List active users.")
|
||||||
listAll = listCommand.Flag("all", "Show all users include revoked and deleted.").Default("false").Bool()
|
listCommandAllFlag = listCommand.Flag("all", "Show all users include revoked and deleted.").Short('a').Default("false").Bool()
|
||||||
|
|
||||||
checkCommand = kingpin.Command("check", "check user existent.")
|
checkCommand = kingpin.Command("check", "check user existent.")
|
||||||
checkCommandUserFlag = checkCommand.Flag("user", "Username.").Required().String()
|
checkCommandUserFlag = checkCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
|
||||||
authCommand = kingpin.Command("auth", "Auth user.")
|
authCommand = kingpin.Command("auth", "Auth user.")
|
||||||
authCommandUserFlag = authCommand.Flag("user", "Username.").Required().String()
|
authCommandUserFlag = authCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
authCommandPasswordFlag = authCommand.Flag("password", "Password.").String()
|
authCommandPasswordFlag = authCommand.Flag("password", "Password.").Short('p').String()
|
||||||
authCommandTotpFlag = authCommand.Flag("totp", "TOTP code.").String()
|
authCommandTotpFlag = authCommand.Flag("totp", "TOTP code.").Short('t').String()
|
||||||
//authCommandHotpFlag = authCommand.Flag("hotp", "HOTP code.").String()
|
|
||||||
|
|
||||||
changePasswordCommand = kingpin.Command("change-password", "Change password")
|
changePasswordCommand = kingpin.Command("change-password", "Change password")
|
||||||
changePasswordCommandUserFlag = changePasswordCommand.Flag("user", "Username.").Required().String()
|
changePasswordCommandUserFlag = changePasswordCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
changePasswordCommandPasswordFlag = changePasswordCommand.Flag("password", "Password.").Required().String()
|
changePasswordCommandPasswordFlag = changePasswordCommand.Flag("password", "Password.").Short('p').Required().String()
|
||||||
|
|
||||||
updateSecretCommand = kingpin.Command("update-secret", "update OTP secret")
|
updateSecretCommand = kingpin.Command("update-secret", "update OTP secret")
|
||||||
updateSecretCommandUserFlag = updateSecretCommand.Flag("user", "Username.").Required().String()
|
updateSecretCommandUserFlag = updateSecretCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
updateSecretCommandSecretFlag = updateSecretCommand.Flag("secret", "Secret.").Default("generate").String()
|
updateSecretCommandSecretFlag = updateSecretCommand.Flag("secret", "Secret.").Short('s').Default("generate").String()
|
||||||
|
|
||||||
registerAppCommand = kingpin.Command("register-app", "register 2FA application")
|
registerAppCommand = kingpin.Command("register-app", "register 2FA application")
|
||||||
registerAppCommandUserFlag = registerAppCommand.Flag("user", "Username.").Required().String()
|
registerAppCommandUserFlag = registerAppCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
registerAppCommandTotpFlag = registerAppCommand.Flag("totp", "TOTP.").Short('t').Required().String()
|
||||||
|
|
||||||
|
checkAppCommand = kingpin.Command("check-app", "check 2FA application")
|
||||||
|
checkAppCommandUserFlag = checkAppCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
|
||||||
getSecretCommand = kingpin.Command("get-secret", "get OTP secret")
|
getSecretCommand = kingpin.Command("get-secret", "get OTP secret")
|
||||||
getSecretCommandUserFlag = getSecretCommand.Flag("user", "Username.").Required().String()
|
getSecretCommandUserFlag = getSecretCommand.Flag("user", "Username.").Short('u').Required().String()
|
||||||
|
|
||||||
debug = kingpin.Flag("debug", "Enable debug mode.").Default("false").Bool()
|
|
||||||
)
|
|
||||||
|
|
||||||
type Migration struct {
|
|
||||||
id int64
|
|
||||||
name string
|
|
||||||
sql string
|
|
||||||
}
|
|
||||||
|
|
||||||
type User struct {
|
|
||||||
id int64
|
|
||||||
name string
|
|
||||||
password string
|
|
||||||
revoked bool
|
|
||||||
deleted bool
|
|
||||||
secret string
|
|
||||||
appConfigured bool
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
migrations []Migration
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
migrations = append(migrations, Migration{name: "users_add_secret_column_2022_11_10", sql: "ALTER TABLE users ADD COLUMN secret string"})
|
args := kingpin.Parse()
|
||||||
migrations = append(migrations, Migration{name: "users_add_2fa_column_2022_11_11", sql: "ALTER TABLE users ADD COLUMN app_configured integer default 0"})
|
|
||||||
|
|
||||||
kingpin.Version(version)
|
db, err := sql.Open("sqlite3", *dbPath)
|
||||||
switch kingpin.Parse() {
|
if err != nil {
|
||||||
|
kingpin.Fatalf(err.Error())
|
||||||
|
}
|
||||||
|
defer func(db *sql.DB) {
|
||||||
|
err = db.Close()
|
||||||
|
if err != nil {
|
||||||
|
kingpin.Fatalf(err.Error())
|
||||||
|
}
|
||||||
|
}(db)
|
||||||
|
|
||||||
|
openvpnUser := src.OpenvpnUser{Database: db}
|
||||||
|
|
||||||
|
kingpin.Version(version).VersionFlag.Short('v')
|
||||||
|
|
||||||
|
switch args {
|
||||||
case createCommand.FullCommand():
|
case createCommand.FullCommand():
|
||||||
createUser(*createCommandUserFlag, *createCommandPasswordFlag)
|
wrap(openvpnUser.CreateUser(*createCommandUserFlag, *createCommandPasswordFlag))
|
||||||
case deleteCommand.FullCommand():
|
case deleteCommand.FullCommand():
|
||||||
deleteUser(*deleteCommandUserFlag)
|
wrap(openvpnUser.DeleteUser(*deleteCommandUserFlag, *deleteCommandUserForceFlag))
|
||||||
case revokeCommand.FullCommand():
|
case revokeCommand.FullCommand():
|
||||||
revokedUser(*revokeCommandUserFlag)
|
wrap(openvpnUser.RevokedUser(*revokeCommandUserFlag))
|
||||||
case restoreCommand.FullCommand():
|
case restoreCommand.FullCommand():
|
||||||
restoreUser(*restoreCommandUserFlag)
|
wrap(openvpnUser.RestoreUser(*restoreCommandUserFlag))
|
||||||
case listCommand.FullCommand():
|
case listCommand.FullCommand():
|
||||||
printUsers()
|
openvpnUser.PrintUsers(*listCommandAllFlag)
|
||||||
case checkCommand.FullCommand():
|
case checkCommand.FullCommand():
|
||||||
_ = checkUserExistent(*checkCommandUserFlag)
|
_ = openvpnUser.CheckUserExistent(*checkCommandUserFlag)
|
||||||
case authCommand.FullCommand():
|
case authCommand.FullCommand():
|
||||||
provideAuthType := 0
|
provideAuthType := 0
|
||||||
if *authCommandPasswordFlag != "" {
|
if *authCommandPasswordFlag != "" {
|
||||||
|
@ -115,341 +103,44 @@ func main() {
|
||||||
if *authCommandTotpFlag != "" {
|
if *authCommandTotpFlag != "" {
|
||||||
provideAuthType += 1
|
provideAuthType += 1
|
||||||
}
|
}
|
||||||
//if *authCommandHotpFlag != "" {
|
|
||||||
// provideAuthType += 1
|
|
||||||
//}
|
|
||||||
if provideAuthType == 1 {
|
if provideAuthType == 1 {
|
||||||
authUser(*authCommandUserFlag, *authCommandPasswordFlag, *authCommandTotpFlag)
|
authSuccessful, authErr := openvpnUser.AuthUser(*authCommandUserFlag, *authCommandPasswordFlag, *authCommandTotpFlag)
|
||||||
|
if authErr != nil {
|
||||||
|
kingpin.Fatalf(authErr.Error())
|
||||||
|
} else if authSuccessful {
|
||||||
|
fmt.Println("Authorization successful")
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("Please provide only one type of auth paswword")
|
fmt.Println("Please provide only one type of auth flag")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
case changePasswordCommand.FullCommand():
|
case changePasswordCommand.FullCommand():
|
||||||
changeUserPassword(*changePasswordCommandUserFlag, *changePasswordCommandPasswordFlag)
|
wrap(openvpnUser.ChangeUserPassword(*changePasswordCommandUserFlag, *changePasswordCommandPasswordFlag))
|
||||||
case updateSecretCommand.FullCommand():
|
case updateSecretCommand.FullCommand():
|
||||||
registerOtpSecret(*updateSecretCommandUserFlag, *updateSecretCommandSecretFlag)
|
wrap(openvpnUser.RegisterOtpSecret(*updateSecretCommandUserFlag, *updateSecretCommandSecretFlag))
|
||||||
case registerAppCommand.FullCommand():
|
case registerAppCommand.FullCommand():
|
||||||
registerOtpApplication(*registerAppCommandUserFlag)
|
wrap(openvpnUser.RegisterOtpApplication(*registerAppCommandUserFlag, *registerAppCommandTotpFlag))
|
||||||
|
case checkAppCommand.FullCommand():
|
||||||
|
appConfigured, appErr := openvpnUser.IsSecondFactorEnabled(*checkAppCommandUserFlag)
|
||||||
|
if appErr != nil {
|
||||||
|
kingpin.Fatalf(appErr.Error())
|
||||||
|
} else if appConfigured {
|
||||||
|
fmt.Println("App configured")
|
||||||
|
}
|
||||||
case getSecretCommand.FullCommand():
|
case getSecretCommand.FullCommand():
|
||||||
getUserOtpSecret(*getSecretCommandUserFlag)
|
wrap(openvpnUser.GetUserOtpSecret(*getSecretCommandUserFlag))
|
||||||
|
|
||||||
case dbInitCommand.FullCommand():
|
case dbInitCommand.FullCommand():
|
||||||
initDb()
|
openvpnUser.InitDb()
|
||||||
case dbMigrateCommand.FullCommand():
|
case dbMigrateCommand.FullCommand():
|
||||||
migrateDb()
|
openvpnUser.MigrateDb()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getDb() *sql.DB {
|
func wrap(msg string, err error) {
|
||||||
db, err := sql.Open("sqlite3", *dbPath)
|
|
||||||
checkErr(err)
|
|
||||||
if db == nil {
|
|
||||||
panic("db is nil")
|
|
||||||
}
|
|
||||||
return db
|
|
||||||
}
|
|
||||||
|
|
||||||
func initDb() {
|
|
||||||
// boolean fields are integer because of sqlite does not support boolean: 1 = true, 0 = false
|
|
||||||
_, err := getDb().Exec("CREATE TABLE IF NOT EXISTS users(id integer not null primary key autoincrement, username string UNIQUE, password string, revoked integer default 0, deleted integer default 0)")
|
|
||||||
checkErr(err)
|
|
||||||
_, err = getDb().Exec("CREATE TABLE IF NOT EXISTS migrations(id integer not null primary key autoincrement, name string)")
|
|
||||||
checkErr(err)
|
|
||||||
fmt.Printf("Database initialized at %s\n", *dbPath)
|
|
||||||
}
|
|
||||||
|
|
||||||
func migrateDb() {
|
|
||||||
var c int
|
|
||||||
for _, migration := range migrations {
|
|
||||||
c = -1
|
|
||||||
err := getDb().QueryRow("SELECT count(*) FROM migrations WHERE name = $1", migration.name).Scan(&c)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if err == sql.ErrNoRows {
|
kingpin.Fatalf(err.Error())
|
||||||
continue
|
|
||||||
}
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
if c == 0 {
|
|
||||||
fmt.Printf("Migrating database with new migration %s\n", migration.name)
|
|
||||||
_, err := getDb().Exec(migration.sql)
|
|
||||||
checkErr(err)
|
|
||||||
_, err = getDb().Exec("INSERT INTO migrations(name) VALUES ($1)", migration.name)
|
|
||||||
checkErr(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fmt.Println("Migrations are up to date")
|
|
||||||
}
|
|
||||||
|
|
||||||
func createUser(username, password string) {
|
|
||||||
if !checkUserExistent(username) {
|
|
||||||
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
|
||||||
_, err := getDb().Exec("INSERT INTO users(username, password) VALUES ($1, $2)", username, string(hash))
|
|
||||||
checkErr(err)
|
|
||||||
fmt.Printf("User %s created\n", username)
|
|
||||||
} else {
|
} else {
|
||||||
fmt.Printf("ERROR: User %s already registered\n", username)
|
fmt.Println(msg)
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func deleteUser(username string) {
|
|
||||||
deleteQuery := "UPDATE users SET deleted = 1 WHERE username = $1"
|
|
||||||
if *deleteCommandUserForceFlag {
|
|
||||||
deleteQuery = "DELETE FROM users WHERE username = $1"
|
|
||||||
}
|
|
||||||
res, err := getDb().Exec(deleteQuery, username)
|
|
||||||
checkErr(err)
|
|
||||||
if rowsAffected, rowsErr := res.RowsAffected(); rowsErr != nil {
|
|
||||||
if rowsAffected == 1 {
|
|
||||||
fmt.Printf("User %s deleted\n", username)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if *debug {
|
|
||||||
fmt.Printf("ERROR: due deleting user %s: %s\n", username, rowsErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func revokedUser(username string) {
|
|
||||||
if !userDeleted(username) {
|
|
||||||
res, err := getDb().Exec("UPDATE users SET revoked = 1 WHERE username = $1", username)
|
|
||||||
checkErr(err)
|
|
||||||
if rowsAffected, rowsErr := res.RowsAffected(); rowsErr != nil {
|
|
||||||
if rowsAffected == 1 {
|
|
||||||
fmt.Printf("User %s revoked\n", username)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if *debug {
|
|
||||||
fmt.Printf("ERROR: due reoking user %s: %s\n", username, rowsErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func restoreUser(username string) {
|
|
||||||
if !userDeleted(username) {
|
|
||||||
res, err := getDb().Exec("UPDATE users SET revoked = 0 WHERE username = $1", username)
|
|
||||||
checkErr(err)
|
|
||||||
if rowsAffected, rowsErr := res.RowsAffected(); rowsErr != nil {
|
|
||||||
if rowsAffected == 1 {
|
|
||||||
fmt.Printf("User %s restored\n", username)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if *debug {
|
|
||||||
fmt.Printf("ERROR: due restoring user %s: %s\n", username, rowsErr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkUserExistent(username string) bool {
|
|
||||||
// we need to check if there is already such a user
|
|
||||||
// return true if user exist
|
|
||||||
var c int
|
|
||||||
_ = getDb().QueryRow("SELECT count(*) FROM users WHERE username = $1", username).Scan(&c)
|
|
||||||
if c == 1 {
|
|
||||||
fmt.Printf("User %s exist\n", username)
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func userDeleted(username string) bool {
|
|
||||||
// return true if user marked as deleted
|
|
||||||
u := User{}
|
|
||||||
_ = getDb().QueryRow("SELECT deleted FROM users WHERE username = $1", username).Scan(&u.deleted)
|
|
||||||
if u.deleted {
|
|
||||||
fmt.Printf("User %s marked as deleted\n", username)
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func userIsActive(username string) bool {
|
|
||||||
// return true if user exist and not deleted and revoked
|
|
||||||
u := User{}
|
|
||||||
err := getDb().QueryRow("SELECT revoked,deleted FROM users WHERE username = $1", username).Scan(&u.revoked, &u.deleted)
|
|
||||||
if err != nil {
|
|
||||||
if err == sql.ErrNoRows {
|
|
||||||
fmt.Println("User not found")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !u.revoked && !u.deleted {
|
|
||||||
if *debug {
|
|
||||||
fmt.Printf("User %s is active\n", username)
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
} else {
|
|
||||||
fmt.Println("User may be deleted or revoked")
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func listUsers() []User {
|
|
||||||
condition := "WHERE deleted = 0 AND revoked = 0"
|
|
||||||
var users []User
|
|
||||||
if *listAll {
|
|
||||||
condition = ""
|
|
||||||
}
|
|
||||||
query := "SELECT id, username, password, revoked, deleted FROM users " + condition
|
|
||||||
rows, err := getDb().Query(query)
|
|
||||||
checkErr(err)
|
|
||||||
|
|
||||||
for rows.Next() {
|
|
||||||
u := User{}
|
|
||||||
err := rows.Scan(&u.id, &u.name, &u.password, &u.revoked, &u.deleted)
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
users = append(users, u)
|
|
||||||
}
|
|
||||||
|
|
||||||
return users
|
|
||||||
}
|
|
||||||
|
|
||||||
func printUsers() {
|
|
||||||
ul := listUsers()
|
|
||||||
if len(ul) > 0 {
|
|
||||||
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.TabIndent|tabwriter.Debug)
|
|
||||||
_, _ = fmt.Fprintln(w, "id\t username\t revoked\t deleted")
|
|
||||||
for _, u := range ul {
|
|
||||||
fmt.Fprintf(w, "%d\t %s\t %v\t %v\n", u.id, u.name, u.revoked, u.deleted)
|
|
||||||
}
|
|
||||||
_ = w.Flush()
|
|
||||||
} else {
|
|
||||||
fmt.Println("No users created yet")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func changeUserPassword(username, password string) {
|
|
||||||
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
|
||||||
_, err := getDb().Exec("UPDATE users SET password = $1 WHERE username = $2", hash, username)
|
|
||||||
checkErr(err)
|
|
||||||
|
|
||||||
fmt.Println("Password changed")
|
|
||||||
}
|
|
||||||
|
|
||||||
func registerOtpSecret(username, secret string) {
|
|
||||||
if userIsActive(username) {
|
|
||||||
if secret == "generate" {
|
|
||||||
randomStr := randStr(6, "alphanum")
|
|
||||||
|
|
||||||
secret = base32.StdEncoding.EncodeToString([]byte(randomStr))
|
|
||||||
if *debug {
|
|
||||||
fmt.Printf("new generated secret for user %s: %s\n", username, secret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_, err := getDb().Exec("UPDATE users SET secret = $1 WHERE username = $2", secret, username)
|
|
||||||
checkErr(err)
|
|
||||||
|
|
||||||
fmt.Println("Secret updated")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func registerOtpApplication(username string) {
|
|
||||||
if userIsActive(username) {
|
|
||||||
|
|
||||||
_, err := getDb().Exec("UPDATE users SET app_configured = 1 WHERE username = $2")
|
|
||||||
checkErr(err)
|
|
||||||
|
|
||||||
fmt.Printf("OTP application for user %s configured\n", username)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func getUserOtpSecret(username string) {
|
|
||||||
if userIsActive(username) {
|
|
||||||
u := User{}
|
|
||||||
_ = getDb().QueryRow("SELECT secret FROM users WHERE username = $1", username).Scan(&u.secret)
|
|
||||||
|
|
||||||
fmt.Println(u.secret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func authUser(username, password, totp string) {
|
|
||||||
|
|
||||||
row := getDb().QueryRow("SELECT id, username, password, revoked, deleted, secret, app_configured FROM users WHERE username = $1", username)
|
|
||||||
u := User{}
|
|
||||||
err := row.Scan(&u.id, &u.name, &u.password, &u.revoked, &u.deleted, &u.secret, &u.appConfigured)
|
|
||||||
checkErr(err)
|
|
||||||
|
|
||||||
if userIsActive(username) {
|
|
||||||
if password == "" && len(totp) > 0 {
|
|
||||||
otpConfig := &dgoogauth.OTPConfig{
|
|
||||||
Secret: strings.TrimSpace(u.secret),
|
|
||||||
WindowSize: 3,
|
|
||||||
HotpCounter: 0,
|
|
||||||
}
|
|
||||||
|
|
||||||
// get rid of the extra \n from the token string
|
|
||||||
// otherwise the validation will fail
|
|
||||||
trimmedToken := strings.TrimSpace(totp)
|
|
||||||
|
|
||||||
// Validate token
|
|
||||||
ok, err := otpConfig.Authenticate(trimmedToken)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println(err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
if ok {
|
|
||||||
fmt.Println("Authorization successful")
|
|
||||||
os.Exit(0)
|
|
||||||
} else {
|
|
||||||
fmt.Println("Token mismatched")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
} else if len(password) > 0 && totp == "" {
|
|
||||||
|
|
||||||
err = bcrypt.CompareHashAndPassword([]byte(u.password), []byte(password))
|
|
||||||
if err != nil {
|
|
||||||
fmt.Println("Authorization failed")
|
|
||||||
if *debug {
|
|
||||||
fmt.Println("Passwords mismatched")
|
|
||||||
}
|
|
||||||
os.Exit(1)
|
|
||||||
} else {
|
|
||||||
fmt.Println("Authorization successful")
|
|
||||||
os.Exit(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
fmt.Println("Authorization failed")
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
func randStr(strSize int, randType string) string {
|
|
||||||
|
|
||||||
var dictionary string
|
|
||||||
|
|
||||||
if randType == "alphanum" {
|
|
||||||
dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
||||||
}
|
|
||||||
|
|
||||||
if randType == "alpha" {
|
|
||||||
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
||||||
}
|
|
||||||
|
|
||||||
if randType == "number" {
|
|
||||||
dictionary = "0123456789"
|
|
||||||
}
|
|
||||||
|
|
||||||
var bytes = make([]byte, strSize)
|
|
||||||
rand.Read(bytes)
|
|
||||||
for k, v := range bytes {
|
|
||||||
bytes[k] = dictionary[v%byte(len(dictionary))]
|
|
||||||
}
|
|
||||||
return string(bytes)
|
|
||||||
}
|
|
||||||
|
|
||||||
func checkErr(err error) {
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
331
src/commands.go
Normal file
331
src/commands.go
Normal file
|
@ -0,0 +1,331 @@
|
||||||
|
package src
|
||||||
|
|
||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"encoding/base32"
|
||||||
|
"fmt"
|
||||||
|
"github.com/dgryski/dgoogauth"
|
||||||
|
log "github.com/sirupsen/logrus"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
"text/tabwriter"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) InitDb() {
|
||||||
|
// boolean fields are integer because of sqlite does not support boolean: 1 = true, 0 = false
|
||||||
|
_, err := oUser.Database.Exec("CREATE TABLE IF NOT EXISTS users(id integer not null primary key autoincrement, username string UNIQUE, password string, revoked integer default 0, deleted integer default 0)")
|
||||||
|
checkErr(err)
|
||||||
|
_, err = oUser.Database.Exec("CREATE TABLE IF NOT EXISTS migrations(id integer not null primary key autoincrement, name string)")
|
||||||
|
checkErr(err)
|
||||||
|
log.Infof("Database initialized at %v", oUser.Database.Driver())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) CreateUser(username, password string) (string, error) {
|
||||||
|
if !oUser.CheckUserExistent(username) {
|
||||||
|
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
||||||
|
_, err := oUser.Database.Exec("INSERT INTO users(username, password, secret, revoked, deleted, app_configured) VALUES ($1, $2, $3, 0, 0, 0)", username, string(hash), "")
|
||||||
|
checkErr(err)
|
||||||
|
return "User created", nil
|
||||||
|
} else {
|
||||||
|
return "", userAlreadyExistError
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) DeleteUser(username string, force bool) (string, error) {
|
||||||
|
deleteQuery := "UPDATE users SET deleted = 1 WHERE username = $1"
|
||||||
|
if force {
|
||||||
|
deleteQuery = "DELETE FROM users WHERE username = $1"
|
||||||
|
}
|
||||||
|
res, err := oUser.Database.Exec(deleteQuery, username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if rowsAffected == 0 {
|
||||||
|
return "", userDeleteError
|
||||||
|
}
|
||||||
|
return "User deleted", nil
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) RevokedUser(username string) (string, error) {
|
||||||
|
if !oUser.userDeleted(username) {
|
||||||
|
res, err := oUser.Database.Exec("UPDATE users SET revoked = 1 WHERE username = $1", username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if rowsAffected == 0 {
|
||||||
|
return "", userRevokeError
|
||||||
|
}
|
||||||
|
return "User revoked", nil
|
||||||
|
}
|
||||||
|
return "", userDeletedError
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) RestoreUser(username string) (string, error) {
|
||||||
|
if !oUser.userDeleted(username) {
|
||||||
|
res, err := oUser.Database.Exec("UPDATE users SET revoked = 0 WHERE username = $1", username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
rowsAffected, err := res.RowsAffected()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
if rowsAffected == 0 {
|
||||||
|
return "", userRestoreError
|
||||||
|
}
|
||||||
|
return "User restored", nil
|
||||||
|
}
|
||||||
|
return "", userDeletedError
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) CheckUserExistent(username string) bool {
|
||||||
|
c := 0
|
||||||
|
_ = oUser.Database.QueryRow("SELECT count(*) FROM users WHERE username = $1", username).Scan(&c)
|
||||||
|
if c == 1 {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) userDeleted(username string) bool {
|
||||||
|
u := User{}
|
||||||
|
_ = oUser.Database.QueryRow("SELECT deleted FROM users WHERE username = $1", username).Scan(&u.deleted)
|
||||||
|
if u.deleted {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) userIsActive(username string) bool {
|
||||||
|
// return true if user exist and not deleted or revoked
|
||||||
|
u := User{}
|
||||||
|
err := oUser.Database.QueryRow("SELECT revoked,deleted FROM users WHERE username = $1", username).Scan(&u.revoked, &u.deleted)
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if !u.revoked && !u.deleted {
|
||||||
|
return true
|
||||||
|
} else {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) listUsers(all bool) []User {
|
||||||
|
var users []User
|
||||||
|
condition := "WHERE deleted = 0 AND revoked = 0"
|
||||||
|
|
||||||
|
if all {
|
||||||
|
condition = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
query := "SELECT id, username, password, revoked, deleted, app_configured FROM users " + condition
|
||||||
|
|
||||||
|
rows, err := oUser.Database.Query(query)
|
||||||
|
checkErr(err)
|
||||||
|
|
||||||
|
for rows.Next() {
|
||||||
|
u := User{}
|
||||||
|
err = rows.Scan(&u.id, &u.name, &u.password, &u.revoked, &u.deleted, &u.appConfigured)
|
||||||
|
if err != nil {
|
||||||
|
//log.Error(err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
users = append(users, u)
|
||||||
|
}
|
||||||
|
|
||||||
|
return users
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) PrintUsers(all bool) {
|
||||||
|
ul := oUser.listUsers(all)
|
||||||
|
if len(ul) > 0 {
|
||||||
|
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.TabIndent|tabwriter.Debug)
|
||||||
|
_, _ = fmt.Fprintln(w, "id\t username\t revoked\t deleted\t app_configured")
|
||||||
|
for _, u := range ul {
|
||||||
|
_, _ = fmt.Fprintf(w, "%d\t %s\t %v\t %v\t %v\n", u.id, u.name, u.revoked, u.deleted, u.appConfigured)
|
||||||
|
}
|
||||||
|
_ = w.Flush()
|
||||||
|
} else {
|
||||||
|
log.Print("No users created yet")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) ChangeUserPassword(username, password string) (string, error) {
|
||||||
|
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
|
||||||
|
_, err := oUser.Database.Exec("UPDATE users SET password = $1 WHERE username = $2", hash, username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Password changed", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) RegisterOtpSecret(username, secret string) (string, error) {
|
||||||
|
if oUser.userIsActive(username) {
|
||||||
|
if secret == "generate" {
|
||||||
|
randomStr := randStr(6, "alphanum")
|
||||||
|
|
||||||
|
secret = base32.StdEncoding.EncodeToString([]byte(randomStr))
|
||||||
|
log.Debug("new generated secret for user %s: %s", username, secret)
|
||||||
|
}
|
||||||
|
|
||||||
|
_, err := oUser.Database.Exec("UPDATE users SET secret = $1 WHERE username = $2", secret, username)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
|
||||||
|
return "Secret updated", nil
|
||||||
|
}
|
||||||
|
return "", userIsNotActiveError
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) RegisterOtpApplication(username, totp string) (string, error) {
|
||||||
|
if oUser.userIsActive(username) {
|
||||||
|
|
||||||
|
appConfigured, appErr := oUser.IsSecondFactorEnabled(username)
|
||||||
|
if appErr != nil {
|
||||||
|
return "", appErr
|
||||||
|
}
|
||||||
|
if !appConfigured {
|
||||||
|
|
||||||
|
authOk, authErr := oUser.AuthUser(username, "", totp)
|
||||||
|
if authErr != nil {
|
||||||
|
return "", authErr
|
||||||
|
}
|
||||||
|
if authOk {
|
||||||
|
_, err := oUser.Database.Exec("UPDATE users SET app_configured = 1 WHERE username = $2")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
return "OTP application configured", nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "OTP application already configured", nil
|
||||||
|
}
|
||||||
|
return "", userIsNotActiveError
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) GetUserOtpSecret(username string) (string, error) {
|
||||||
|
if oUser.userIsActive(username) {
|
||||||
|
u := User{}
|
||||||
|
_ = oUser.Database.QueryRow("SELECT secret FROM users WHERE username = $1", username).Scan(&u.secret)
|
||||||
|
|
||||||
|
return u.secret, nil
|
||||||
|
}
|
||||||
|
return "", userIsNotActiveError
|
||||||
|
}
|
||||||
|
func (oUser *OpenvpnUser) IsSecondFactorEnabled(username string) (bool, error) {
|
||||||
|
if oUser.userIsActive(username) {
|
||||||
|
u := User{}
|
||||||
|
_ = oUser.Database.QueryRow("SELECT username, appConfigured FROM users WHERE username = $1", username).Scan(&u.name, &u.appConfigured)
|
||||||
|
if u.name == username {
|
||||||
|
return u.appConfigured, nil
|
||||||
|
}
|
||||||
|
return false, checkAppError
|
||||||
|
}
|
||||||
|
return false, userIsNotActiveError
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) AuthUser(username, password, totp string) (bool, error) {
|
||||||
|
|
||||||
|
row := oUser.Database.QueryRow("SELECT id, username, password, revoked, deleted, secret, app_configured FROM users WHERE username = $1", username)
|
||||||
|
u := User{}
|
||||||
|
err := row.Scan(&u.id, &u.name, &u.password, &u.revoked, &u.deleted, &u.secret, &u.appConfigured)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if oUser.userIsActive(username) {
|
||||||
|
if password == "" && len(totp) > 0 {
|
||||||
|
if len(u.secret) == 0 {
|
||||||
|
return false, userSecretDoesNotExistError
|
||||||
|
}
|
||||||
|
|
||||||
|
otpConfig := &dgoogauth.OTPConfig{
|
||||||
|
Secret: strings.TrimSpace(u.secret),
|
||||||
|
WindowSize: 3,
|
||||||
|
HotpCounter: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
trimmedToken := strings.TrimSpace(totp)
|
||||||
|
|
||||||
|
ok, err := otpConfig.Authenticate(trimmedToken)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Error(err)
|
||||||
|
}
|
||||||
|
if ok {
|
||||||
|
return true, nil
|
||||||
|
} else {
|
||||||
|
return false, tokenMismatchedError
|
||||||
|
}
|
||||||
|
|
||||||
|
} else if len(password) > 0 && totp == "" {
|
||||||
|
err = bcrypt.CompareHashAndPassword([]byte(u.password), []byte(password))
|
||||||
|
if err != nil {
|
||||||
|
return false, passwordMismatchedError
|
||||||
|
} else {
|
||||||
|
return true, nil
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false, userIsNotActiveError
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
func (oUser *OpenvpnUser) MigrateDb() {
|
||||||
|
var c int
|
||||||
|
var migrations []Migration
|
||||||
|
|
||||||
|
migrations = append(migrations, Migration{name: "users_add_secret_column_2022_11_10", sql: "ALTER TABLE users ADD COLUMN secret string"})
|
||||||
|
migrations = append(migrations, Migration{name: "users_add_2fa_column_2022_11_11", sql: "ALTER TABLE users ADD COLUMN app_configured integer default 0"})
|
||||||
|
|
||||||
|
for _, migration := range migrations {
|
||||||
|
c = -1
|
||||||
|
err := oUser.Database.QueryRow("SELECT count(*) FROM migrations WHERE name = $1", migration.name).Scan(&c)
|
||||||
|
if err != nil {
|
||||||
|
if err == sql.ErrNoRows {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
if c == 0 {
|
||||||
|
log.Info("Migrating database with new migration %s\n", migration.name)
|
||||||
|
_, err = oUser.Database.Exec(migration.sql)
|
||||||
|
checkErr(err)
|
||||||
|
_, err = oUser.Database.Exec("INSERT INTO migrations(name) VALUES ($1)", migration.name)
|
||||||
|
checkErr(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.Info("Migrations are up to date")
|
||||||
|
}
|
||||||
|
|
||||||
|
func checkErr(err error) {
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
}
|
||||||
|
}
|
16
src/errors.go
Normal file
16
src/errors.go
Normal file
|
@ -0,0 +1,16 @@
|
||||||
|
package src
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
var (
|
||||||
|
userSecretDoesNotExistError = errors.New("user secret does not exist")
|
||||||
|
userAlreadyExistError = errors.New("user already exist")
|
||||||
|
userDeletedError = errors.New("user marked as deleted")
|
||||||
|
userRestoreError = errors.New("failed to restore user")
|
||||||
|
userRevokeError = errors.New("failed to revoke user")
|
||||||
|
userDeleteError = errors.New("failed to delete user")
|
||||||
|
userIsNotActiveError = errors.New("user is not active")
|
||||||
|
passwordMismatchedError = errors.New("password mismatched")
|
||||||
|
tokenMismatchedError = errors.New("token mismatched")
|
||||||
|
checkAppError = errors.New("failed to check 2FA app")
|
||||||
|
)
|
23
src/models.go
Normal file
23
src/models.go
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
package src
|
||||||
|
|
||||||
|
import "database/sql"
|
||||||
|
|
||||||
|
type OpenvpnUser struct {
|
||||||
|
Database *sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
type Migration struct {
|
||||||
|
id int64
|
||||||
|
name string
|
||||||
|
sql string
|
||||||
|
}
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
id int64
|
||||||
|
name string
|
||||||
|
password string
|
||||||
|
revoked bool
|
||||||
|
deleted bool
|
||||||
|
secret string
|
||||||
|
appConfigured bool
|
||||||
|
}
|
27
src/utils.go
Normal file
27
src/utils.go
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
package src
|
||||||
|
|
||||||
|
import "crypto/rand"
|
||||||
|
|
||||||
|
func randStr(strSize int, randType string) string {
|
||||||
|
|
||||||
|
var dictionary string
|
||||||
|
|
||||||
|
if randType == "alphanum" {
|
||||||
|
dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||||
|
}
|
||||||
|
|
||||||
|
if randType == "alpha" {
|
||||||
|
dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
||||||
|
}
|
||||||
|
|
||||||
|
if randType == "number" {
|
||||||
|
dictionary = "0123456789"
|
||||||
|
}
|
||||||
|
|
||||||
|
var bytes = make([]byte, strSize)
|
||||||
|
rand.Read(bytes)
|
||||||
|
for k, v := range bytes {
|
||||||
|
bytes[k] = dictionary[v%byte(len(dictionary))]
|
||||||
|
}
|
||||||
|
return string(bytes)
|
||||||
|
}
|
Loading…
Reference in a new issue