Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PAM authentication implemented #48

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,14 +256,15 @@ The web interface itself cannot add administrative users.
`Authenticators.Issuer`: TOTP issuer, the name that will get added to the TOTP app
`Authenticators.DomainURL`: Full url of the vpn authentication endpoint, required for `webauthn` and `oidc`
`Authenticators.DefaultMethod`: String, default method the user will be presented, if not specified a list of methods is displayed to the user (possible values: `webauth`, `totp`, `oidc`)
`Authenticators.Methods`: String array, enabled authentication methods, e.g ["totp","webauthn","oidc"]
`Authenticators.Methods`: String array, enabled authentication methods, e.g ["totp","webauthn","oidc", "pam"]

`Authenticators.OIDC`: Object that contains `OIDC` specific configuration options
`Authenticators.OIDC.IssuerURL`: Identity provider endpoint, e.g `http://localhost:8080/realms/account`
`Authenticators.OIDC.ClientID`: OIDC identifier for application
`Authenticators.OIDC.ClientSecret`: OIDC secret
`Authenticators.OIDC.GroupsClaimName`: Not yet used.

`Authenticators.PAM.ServiceName`: Name of PAM-Auth file in `/etc/pam.d/`

`Wireguard`: Object that contains the wireguard device configuration
`Wireguard.DevName`: The wireguard device to attach or to create if it does not exist, will automatically add peers (no need to configure peers with `wg-quick`)
`Wireguard.ListenPort`: Port that wireguard will listen on
Expand Down Expand Up @@ -315,13 +316,16 @@ Full config example
"Issuer": "vpn.test",
"DomainURL": "https://vpn.test:8080",
"DefaultMethod":"webauthn",
"Methods":["totp","webauthn", "oidc"],
"Methods":["totp","webauthn", "oidc", "pam"],
"OIDC": {
"IssuerURL": "http://localhost:8080/",
"ClientSecret": "<OMITTED>",
"ClientID": "account",
"GroupsClaimName": "groups"
}
},
"PAM": {
"ServiceName": "vpncheckpass"
},
},
"Wireguard": {
"DevName": "wg0",
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ require (
github.com/mdlayher/genetlink v1.3.2 // indirect
github.com/mdlayher/socket v0.4.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/msteinert/pam v1.1.0 // indirect
github.com/x448/float16 v0.8.4 // indirect
golang.org/x/oauth2 v0.8.0 // indirect
golang.org/x/sync v0.2.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrk
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/msteinert/pam v1.1.0 h1:VhLun/0n0kQYxiRBJJvVpC2jR6d21SWJFjpvUVj20Kc=
github.com/msteinert/pam v1.1.0/go.mod h1:M4FPeAW8g2ITO68W8gACDz13NDJyOQM9IQsQhrR6TOI=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
Expand Down
11 changes: 11 additions & 0 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,10 @@ type Config struct {
GroupsClaimName string `json:",omitempty"`
} `json:",omitempty"`

PAM struct {
ServiceName string
} `json:",omitempty"`

//Not externally configurable
Webauthn *webauthn.WebAuthn `json:"-"`
}
Expand Down Expand Up @@ -680,6 +684,13 @@ func load(path string) (c Config, err error) {
return c, errors.New("could not configure webauthn domain: " + err.Error())
}

case "pam":
if c.Authenticators.PAM.ServiceName == "" {
return c, errors.New("Authenticators.PAM.ServiceName unset, needed for PAM authentication")
}

settings["ServiceName"] = c.Authenticators.PAM.ServiceName

}

if err := resultMFAMap[method].Init(settings); err != nil {
Expand Down
1 change: 1 addition & 0 deletions internal/webserver/authenticators/authenticators.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const (
TotpMFA = "totp"
WebauthnMFA = "webauthn"
OidcMFA = "oidc"
PamMFA = "pam"
)

type Authenticator interface {
Expand Down
1 change: 1 addition & 0 deletions internal/webserver/authenticators/methods/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func init() {
authenticators.MFA[authenticators.TotpMFA] = new(Totp)
authenticators.MFA[authenticators.WebauthnMFA] = new(Webauthn)
authenticators.MFA[authenticators.OidcMFA] = new(Oidc)
authenticators.MFA[authenticators.PamMFA] = new(Pam)
}

func resultMessage(err error) (string, int) {
Expand Down
193 changes: 193 additions & 0 deletions internal/webserver/authenticators/methods/pam.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
package methods

import (
"errors"
"log"
"net/http"

"github.com/NHAS/wag/internal/config"
"github.com/NHAS/wag/internal/data"
"github.com/NHAS/wag/internal/router"
"github.com/NHAS/wag/internal/users"
"github.com/NHAS/wag/internal/utils"
"github.com/NHAS/wag/internal/webserver/authenticators"
"github.com/NHAS/wag/internal/webserver/resources"
"github.com/msteinert/pam"
)

// Supported is true when built with PAM
var Supported = true
var serviceName = ""

type Pam struct {
}

func (t *Pam) Init(settings map[string]string) error {
serviceName = settings["ServiceName"]
return nil
}

func (t *Pam) Type() string {
return authenticators.PamMFA
}

func (t *Pam) FriendlyName() string {
return "Pam OTP"
}

func (t *Pam) RegistrationAPI(w http.ResponseWriter, r *http.Request) {
clientTunnelIp := utils.GetIPFromRequest(r)

if router.IsAuthed(clientTunnelIp.String()) {
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
resources.Render("success.html", w, nil)
return
}

user, err := users.GetUserFromAddress(clientTunnelIp)
if err != nil {
log.Println("unknown", clientTunnelIp, "could not get associated device:", err)
http.Error(w, "Bad request", 400)
return
}

if user.IsEnforcingMFA() {
log.Println(user.Username, clientTunnelIp, "tried to re-register mfa despite already being registered")

http.Error(w, "Bad request", 400)
return
}

switch r.Method {
case "GET":
err = data.SetUserMfa(user.Username, "PAMauth", authenticators.PamMFA)
if err != nil {
log.Println(user.Username, clientTunnelIp, "unable to save PAM key to db:", err)
http.Error(w, "Unknown error", 500)
return
}

jsonResponse(w, user.Username, 200)

case "POST":
err = user.Authenticate(clientTunnelIp.String(), t.Type(), t.AuthoriseFunc(w, r))
msg, status := resultMessage(err)
jsonResponse(w, msg, status)

if err != nil {
log.Println(user.Username, clientTunnelIp, "failed to authorise: ", err.Error())
return
}

log.Println(user.Username, clientTunnelIp, "authorised")
user.EnforceMFA()

default:
http.NotFound(w, r)
return
}
}

func (t *Pam) AuthorisationAPI(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.NotFound(w, r)
return
}

clientTunnelIp := utils.GetIPFromRequest(r)

if router.IsAuthed(clientTunnelIp.String()) {
w.Header().Set("Content-Type", "text/html; charset=UTF-8")
resources.Render("success.html", w, nil)
return
}

user, err := users.GetUserFromAddress(clientTunnelIp)
if err != nil {
log.Println("unknown", clientTunnelIp, "could not get associated device:", err)
http.Error(w, "Bad request", 400)
return
}

if !user.IsEnforcingMFA() {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}

err = user.Authenticate(clientTunnelIp.String(), t.Type(), t.AuthoriseFunc(w, r))

msg, status := resultMessage(err)
jsonResponse(w, msg, status)

if err != nil {
log.Println(user.Username, clientTunnelIp, "failed to authorise: ", err.Error())
return
}

log.Println(user.Username, clientTunnelIp, "authorised")

}

func (t *Pam) AuthoriseFunc(w http.ResponseWriter, r *http.Request) authenticators.AuthenticatorFunc {
return func(mfaSecret, username string) error {
err := r.ParseForm()
if err != nil {
http.Error(w, "Bad request", 400)
return err
}

passwd := r.FormValue("code")

t, err := pam.StartFunc(serviceName, username, func(s pam.Style, msg string) (string, error) {
switch s {
case pam.PromptEchoOff:
return passwd, nil
case pam.PromptEchoOn, pam.ErrorMsg, pam.TextInfo:
return "", nil
}
return "", errors.New("unrecognized PAM message style")
})
if err != nil {
return errors.New("PAM start failed")
}

if err = t.Authenticate(0); err != nil {
return errors.New("PAM authentication failed")
}

if err = t.AcctMgmt(0); err != nil {
return errors.New("PAM account failed")
}

// PAM login names might suffer transformations in the PAM stack.
// We should take whatever the PAM stack returns for it.
user, err := t.GetItem(pam.User)
if err != nil {
return errors.New("PAM get user '" + user + "' failed")
} else {
return nil
}
}
}

func (t *Pam) MFAPromptUI(w http.ResponseWriter, r *http.Request, username, ip string) {
if err := resources.Render("prompt_mfa_pam.html", w, &resources.Msg{
HelpMail: config.Values().HelpMail,
NumMethods: len(authenticators.MFA),
}); err != nil {
log.Println(username, ip, "unable to render pam prompt template: ", err)
}
}

func (t *Pam) RegistrationUI(w http.ResponseWriter, r *http.Request, username, ip string) {
if err := resources.Render("register_mfa_pam.html", w, &resources.Msg{
HelpMail: config.Values().HelpMail,
NumMethods: len(authenticators.MFA),
}); err != nil {
log.Println(username, ip, "unable to render pam mfa template: ", err)
}
}

func (t *Pam) LogoutPath() string {
return "/"
}
84 changes: 84 additions & 0 deletions internal/webserver/resources/static/js/pam.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
document.addEventListener('DOMContentLoaded', function () {
let location = '/authorise/pam/';
if (document.getElementById("registration") !== null) {
location = "/register_mfa/pam/";
populatePamDetails()
}

document.getElementById('loginForm').onsubmit = function () {
loginUser(location);
return false;
};
}, false);

async function populatePamDetails() {
const response = await fetch("/register_mfa/pam/", {
method: 'GET',
mode: 'same-origin',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow'
});

if (response.ok) {

let details;
try {
details = await response.json();
} catch (e) {
document.getElementById("error").hidden = false;
return
}

document.getElementById("AccountName").textContent = details;

}
}

async function loginUser(location) {

try {
const send = await fetch(location, {
method: 'POST',
mode: 'same-origin',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: new URLSearchParams({
"code": document.getElementById("mfaCode").value
})
});

document.getElementById("mfaCode").value = "";

if (!send.ok) {
console.log("failed to send pam code")

let response;
try {
response = await send.json();
} catch (e) {
console.log("logging in failed")

document.getElementById("error").hidden = false;
return
}

document.getElementById("errorMsg").textContent = response;
document.getElementById("error").hidden = false;
return
}
} catch (e) {
console.log("logging in user failed")
document.getElementById("errorMsg").textContent = e.message;
document.getElementById("error").hidden = false;
return
}


window.location.href = "/";
}
Loading