Compare commits
8 commits
c98fe735ad
...
2cf22d678a
| Author | SHA1 | Date | |
|---|---|---|---|
| 2cf22d678a | |||
| e62ac9f3d0 | |||
| 6c4b1ea9c0 | |||
| 30990e5892 | |||
| c671d26205 | |||
| 3ec3d2649f | |||
| a9eae79414 | |||
| daab7bf699 |
18 changed files with 98 additions and 460 deletions
41
addy.go
41
addy.go
|
|
@ -3,13 +3,13 @@ package main
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"crypto/hmac"
|
"crypto/hmac"
|
||||||
"crypto/rand"
|
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"encoding/base32"
|
"encoding/base32"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
"math/rand"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
@ -76,7 +76,7 @@ func addyAliasAPIAuth(r *http.Request) (*string, error) {
|
||||||
// Decode header
|
// Decode header
|
||||||
authorization, err := base32.StdEncoding.DecodeString(fields[1])
|
authorization, err := base32.StdEncoding.DecodeString(fields[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Printf("Invalid Authorization header: %s", err.Error())
|
log.Println("Invalid Authorization header: %s", err.Error())
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -89,11 +89,6 @@ func addyAliasAPIAuth(r *http.Request) (*string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func addyAliasAPI(w http.ResponseWriter, r *http.Request) {
|
func addyAliasAPI(w http.ResponseWriter, r *http.Request) {
|
||||||
if !aliasLimiter.Allow(remoteIP(r)) {
|
|
||||||
http.Error(w, "Too many requests", http.StatusTooManyRequests)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := addyAliasAPIAuth(r)
|
user, err := addyAliasAPIAuth(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusUnauthorized)
|
http.Error(w, err.Error(), http.StatusUnauthorized)
|
||||||
|
|
@ -129,23 +124,6 @@ func addyAliasAPI(w http.ResponseWriter, r *http.Request) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Validate domain against allowlist
|
|
||||||
if len(allowedAliasDomains) == 0 {
|
|
||||||
http.Error(w, "Alias creation is not configured", http.StatusServiceUnavailable)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
domainAllowed := false
|
|
||||||
for _, d := range allowedAliasDomains {
|
|
||||||
if body.Domain == d {
|
|
||||||
domainAllowed = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !domainAllowed {
|
|
||||||
http.Error(w, "Domain not allowed", http.StatusBadRequest)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(body.Alias) == 0 {
|
if len(body.Alias) == 0 {
|
||||||
body.Alias = generateRandomString(10)
|
body.Alias = generateRandomString(10)
|
||||||
}
|
}
|
||||||
|
|
@ -184,11 +162,6 @@ func addyAliasAPI(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func addyAliasAPIDelete(w http.ResponseWriter, r *http.Request) {
|
func addyAliasAPIDelete(w http.ResponseWriter, r *http.Request) {
|
||||||
if !aliasLimiter.Allow(remoteIP(r)) {
|
|
||||||
http.Error(w, "Too many requests", http.StatusTooManyRequests)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
user, err := addyAliasAPIAuth(r)
|
user, err := addyAliasAPIAuth(r)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusUnauthorized)
|
http.Error(w, err.Error(), http.StatusUnauthorized)
|
||||||
|
|
@ -230,14 +203,10 @@ func addyAliasAPIDelete(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func generateRandomString(length int) string {
|
func generateRandomString(length int) string {
|
||||||
const charset = "abcdefghijklmnopqrstuvwxyz0123456789"
|
charset := "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
result := make([]byte, length)
|
result := make([]byte, length)
|
||||||
buf := make([]byte, length)
|
for i := range result {
|
||||||
if _, err := rand.Read(buf); err != nil {
|
result[i] = charset[rand.Intn(len(charset))]
|
||||||
panic("crypto/rand unavailable: " + err.Error())
|
|
||||||
}
|
|
||||||
for i, b := range buf {
|
|
||||||
result[i] = charset[int(b)%len(charset)]
|
|
||||||
}
|
}
|
||||||
return string(result)
|
return string(result)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
27
altcha.go
27
altcha.go
|
|
@ -1,27 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
goaltcha "github.com/k42-software/go-altcha"
|
|
||||||
altchahttp "github.com/k42-software/go-altcha/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func serveAltchaJS(w http.ResponseWriter, r *http.Request) {
|
|
||||||
altchahttp.ServeJavascript(w, r)
|
|
||||||
}
|
|
||||||
|
|
||||||
func serveAltchaChallenge(w http.ResponseWriter, r *http.Request) {
|
|
||||||
challenge := goaltcha.NewChallenge()
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
w.Header().Set("Cache-Control", "private, no-cache, no-store, must-revalidate")
|
|
||||||
_, _ = w.Write([]byte(challenge.Encode()))
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateAltcha(r *http.Request) bool {
|
|
||||||
encoded := r.PostFormValue("altcha")
|
|
||||||
if encoded == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return goaltcha.ValidateResponse(encoded, true)
|
|
||||||
}
|
|
||||||
66
change.go
66
change.go
|
|
@ -4,90 +4,46 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"unicode"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func checkPasswdConstraint(password string) error {
|
func checkPasswdConstraint(password string) error {
|
||||||
if len(password) < 12 {
|
if len(password) < 8 {
|
||||||
return errors.New("too short, please choose a password at least 12 characters long")
|
return errors.New("too short, please choose a password at least 8 characters long.")
|
||||||
}
|
|
||||||
|
|
||||||
var hasUpper, hasLower, hasDigit bool
|
|
||||||
for _, r := range password {
|
|
||||||
switch {
|
|
||||||
case unicode.IsUpper(r):
|
|
||||||
hasUpper = true
|
|
||||||
case unicode.IsLower(r):
|
|
||||||
hasLower = true
|
|
||||||
case unicode.IsDigit(r):
|
|
||||||
hasDigit = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hasUpper || !hasLower || !hasDigit {
|
|
||||||
return errors.New("password must contain at least one uppercase letter, one lowercase letter, and one digit")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func changePassword(w http.ResponseWriter, r *http.Request) {
|
func changePassword(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == "POST" && !changeLimiter.Allow(remoteIP(r)) {
|
|
||||||
csrfToken, _ := setCSRFToken(w)
|
|
||||||
displayTmplError(w, http.StatusTooManyRequests, "change.html", map[string]interface{}{"error": "Too many requests. Please try again later.", "csrf_token": csrfToken})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.Method != "POST" {
|
if r.Method != "POST" {
|
||||||
csrfToken, err := setCSRFToken(w)
|
displayTmpl(w, "change.html", map[string]interface{}{})
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
displayTmpl(w, "change.html", map[string]interface{}{"csrf_token": csrfToken})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !validateCSRF(r) {
|
|
||||||
csrfToken, _ := setCSRFToken(w)
|
|
||||||
displayTmplError(w, http.StatusForbidden, "change.html", map[string]interface{}{"error": "Invalid or missing CSRF token. Please try again.", "csrf_token": csrfToken})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !validateAltcha(r) {
|
|
||||||
csrfToken, _ := setCSRFToken(w)
|
|
||||||
displayTmplError(w, http.StatusForbidden, "change.html", map[string]interface{}{"error": "Invalid or missing altcha response. Please try again.", "csrf_token": csrfToken})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
renderError := func(status int, msg string) {
|
|
||||||
csrfToken, _ := setCSRFToken(w)
|
|
||||||
displayTmplError(w, status, "change.html", map[string]interface{}{"error": msg, "csrf_token": csrfToken})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check the two new passwords are identical
|
// Check the two new passwords are identical
|
||||||
if r.PostFormValue("newpassword") != r.PostFormValue("new2password") {
|
if r.PostFormValue("newpassword") != r.PostFormValue("new2password") {
|
||||||
renderError(http.StatusNotAcceptable, "New passwords are not identical. Please retry.")
|
displayTmplError(w, http.StatusNotAcceptable, "change.html", map[string]interface{}{"error": "New passwords are not identical. Please retry."})
|
||||||
} else if len(r.PostFormValue("login")) == 0 {
|
} else if len(r.PostFormValue("login")) == 0 {
|
||||||
renderError(http.StatusNotAcceptable, "Please provide a valid login")
|
displayTmplError(w, http.StatusNotAcceptable, "change.html", map[string]interface{}{"error": "Please provide a valid login"})
|
||||||
} else if err := checkPasswdConstraint(r.PostFormValue("newpassword")); err != nil {
|
} else if err := checkPasswdConstraint(r.PostFormValue("newpassword")); err != nil {
|
||||||
renderError(http.StatusNotAcceptable, "The password you chose doesn't respect all constraints: "+err.Error())
|
displayTmplError(w, http.StatusNotAcceptable, "change.html", map[string]interface{}{"error": "The password you chose doesn't respect all constraints: " + err.Error()})
|
||||||
} else {
|
} else {
|
||||||
conn, err := myLDAP.Connect()
|
conn, err := myLDAP.Connect()
|
||||||
if err != nil || conn == nil {
|
if err != nil || conn == nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusInternalServerError, "Unable to process your request. Please try again later.")
|
displayTmplError(w, http.StatusInternalServerError, "change.html", map[string]interface{}{"error": err.Error()})
|
||||||
} else if err := conn.ServiceBind(); err != nil {
|
} else if err := conn.ServiceBind(); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusInternalServerError, "Unable to process your request. Please try again later.")
|
displayTmplError(w, http.StatusInternalServerError, "change.html", map[string]interface{}{"error": err.Error()})
|
||||||
} else if dn, err := conn.SearchDN(r.PostFormValue("login"), true); err != nil {
|
} else if dn, err := conn.SearchDN(r.PostFormValue("login"), true); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusUnauthorized, "Invalid login or password.")
|
displayTmplError(w, http.StatusInternalServerError, "change.html", map[string]interface{}{"error": err.Error()})
|
||||||
} else if err := conn.Bind(dn, r.PostFormValue("password")); err != nil {
|
} else if err := conn.Bind(dn, r.PostFormValue("password")); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusUnauthorized, "Invalid login or password.")
|
displayTmplError(w, http.StatusUnauthorized, "change.html", map[string]interface{}{"error": err.Error()})
|
||||||
} else if err := conn.ChangePassword(dn, r.PostFormValue("newpassword")); err != nil {
|
} else if err := conn.ChangePassword(dn, r.PostFormValue("newpassword")); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusInternalServerError, "Unable to process your request. Please try again later.")
|
displayTmplError(w, http.StatusInternalServerError, "change.html", map[string]interface{}{"error": err.Error()})
|
||||||
} else {
|
} else {
|
||||||
displayMsg(w, "Password successfully changed!", http.StatusOK)
|
displayMsg(w, "Password successfully changed!", http.StatusOK)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
40
csrf.go
40
csrf.go
|
|
@ -1,40 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/rand"
|
|
||||||
"encoding/base64"
|
|
||||||
"net/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
func generateCSRFToken() (string, error) {
|
|
||||||
b := make([]byte, 32)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return base64.URLEncoding.EncodeToString(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func setCSRFToken(w http.ResponseWriter) (string, error) {
|
|
||||||
token, err := generateCSRFToken()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
http.SetCookie(w, &http.Cookie{
|
|
||||||
Name: "csrf_token",
|
|
||||||
Value: token,
|
|
||||||
Path: "/",
|
|
||||||
HttpOnly: false, // must be readable via form hidden field comparison
|
|
||||||
SameSite: http.SameSiteStrictMode,
|
|
||||||
Secure: !devMode,
|
|
||||||
})
|
|
||||||
return token, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func validateCSRF(r *http.Request) bool {
|
|
||||||
cookie, err := r.Cookie("csrf_token")
|
|
||||||
if err != nil || cookie.Value == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
formToken := r.PostFormValue("csrf_token")
|
|
||||||
return formToken != "" && cookie.Value == formToken
|
|
||||||
}
|
|
||||||
2
go.mod
2
go.mod
|
|
@ -14,8 +14,6 @@ require (
|
||||||
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
|
||||||
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
|
github.com/go-asn1-ber/asn1-ber v1.5.8-0.20250403174932-29230038a667 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/k42-software/go-altcha v0.1.1
|
|
||||||
github.com/pkg/errors v0.9.1 // indirect
|
|
||||||
golang.org/x/crypto v0.36.0 // indirect
|
golang.org/x/crypto v0.36.0 // indirect
|
||||||
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
|
||||||
)
|
)
|
||||||
|
|
|
||||||
4
go.sum
4
go.sum
|
|
@ -41,10 +41,6 @@ github.com/jcmturner/gokrb5/v8 v8.4.4 h1:x1Sv4HaTpepFkXbt2IkL29DXRf8sOfZXo8eRKh6
|
||||||
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
github.com/jcmturner/gokrb5/v8 v8.4.4/go.mod h1:1btQEpgT6k+unzCwX1KdWMEwPPkkgBtP+F6aCACiMrs=
|
||||||
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
github.com/jcmturner/rpc/v2 v2.0.3 h1:7FXXj8Ti1IaVFpSAziCZWNzbNuZmnvw/i6CqLNdWfZY=
|
||||||
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
github.com/jcmturner/rpc/v2 v2.0.3/go.mod h1:VUJYCIDm3PVOEHw8sgt091/20OJjskO/YJki3ELg/Hc=
|
||||||
github.com/k42-software/go-altcha v0.1.1 h1:vfA+0+0gr7jK4vp21Q7xvEpIjDsx8PqzxS0obgIToQs=
|
|
||||||
github.com/k42-software/go-altcha v0.1.1/go.mod h1:2aX+0PkUSI0YPDVfjapZeuGELWt8ugEXkg8gr6QejMU=
|
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
|
||||||
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/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
|
|
||||||
5
ldap.go
5
ldap.go
|
|
@ -23,7 +23,6 @@ type LDAP struct {
|
||||||
MailPort int
|
MailPort int
|
||||||
MailUser string
|
MailUser string
|
||||||
MailPassword string
|
MailPassword string
|
||||||
MailFrom string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (l LDAP) Connect() (*LDAPConn, error) {
|
func (l LDAP) Connect() (*LDAPConn, error) {
|
||||||
|
|
@ -75,7 +74,7 @@ func (l LDAPConn) SearchDN(username string, person bool) (string, error) {
|
||||||
searchRequest := ldap.NewSearchRequest(
|
searchRequest := ldap.NewSearchRequest(
|
||||||
l.BaseDN,
|
l.BaseDN,
|
||||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||||
fmt.Sprintf("(&(objectClass=%s)(uid=%s))", ldap.EscapeFilter(objectClass), ldap.EscapeFilter(username)),
|
fmt.Sprintf("(&(objectClass=%s)(uid=%s))", objectClass, username),
|
||||||
[]string{"dn"},
|
[]string{"dn"},
|
||||||
nil,
|
nil,
|
||||||
)
|
)
|
||||||
|
|
@ -148,7 +147,7 @@ func (l LDAPConn) SearchMailAlias(address string) (int, error) {
|
||||||
searchRequest := ldap.NewSearchRequest(
|
searchRequest := ldap.NewSearchRequest(
|
||||||
l.BaseDN,
|
l.BaseDN,
|
||||||
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
|
||||||
fmt.Sprintf("(&(objectClass=*)(mailAlias=%s))", ldap.EscapeFilter(address)),
|
fmt.Sprintf("(&(objectClass=*)(mailAlias=%s))", address),
|
||||||
[]string{"dn"},
|
[]string{"dn"},
|
||||||
nil,
|
nil,
|
||||||
)
|
)
|
||||||
|
|
|
||||||
36
login.go
36
login.go
|
|
@ -2,11 +2,9 @@ package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"html"
|
|
||||||
"html/template"
|
"html/template"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/go-ldap/ldap/v3"
|
"github.com/go-ldap/ldap/v3"
|
||||||
|
|
@ -48,16 +46,6 @@ func tryLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !authLimiter.Allow(remoteIP(r)) {
|
|
||||||
displayTmplError(w, http.StatusTooManyRequests, "login.html", map[string]interface{}{"error": "Too many login attempts. Please try again later."})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !validateAltcha(r) {
|
|
||||||
displayTmplError(w, http.StatusForbidden, "login.html", map[string]interface{}{"error": "Invalid or missing altcha response. Please try again."})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if entries, err := login(r.PostFormValue("login"), r.PostFormValue("password")); err != nil {
|
if entries, err := login(r.PostFormValue("login"), r.PostFormValue("password")); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
displayTmplError(w, http.StatusInternalServerError, "login.html", map[string]interface{}{"error": err.Error()})
|
displayTmplError(w, http.StatusInternalServerError, "login.html", map[string]interface{}{"error": err.Error()})
|
||||||
|
|
@ -67,34 +55,20 @@ func tryLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
cnt := "<ul>"
|
cnt := "<ul>"
|
||||||
for _, e := range entries {
|
for _, e := range entries {
|
||||||
for i, v := range e.Values {
|
for i, v := range e.Values {
|
||||||
safeName := html.EscapeString(e.Name)
|
|
||||||
safeVal := html.EscapeString(v)
|
|
||||||
elemID := fmt.Sprintf("mailAlias-%d", i)
|
|
||||||
if e.Name == "userPassword" || e.Name == "krbPrincipalKey" {
|
if e.Name == "userPassword" || e.Name == "krbPrincipalKey" {
|
||||||
cnt += "<li><strong>" + safeName + ":</strong> <em>[...]</em></li>"
|
cnt += "<li><strong>" + e.Name + ":</strong> <em>[...]</em></li>"
|
||||||
} else if e.Name == "mailAlias" && len(strings.SplitN(v, "@", 2)[0]) == 10 {
|
} else if e.Name == "mailAlias" && len(strings.SplitN(v, "@", 2)[0]) == 10 {
|
||||||
safeURL := url.PathEscape(v)
|
cnt += "<li id='" + fmt.Sprintf("mailAlias-%d", i) + "'><strong>" + e.Name + ":</strong> " + v + `<button type="button" class="mx-1 btn btn-sm btn-danger" onclick="fetch('/api/v1/aliases/` + v + `', {'method': 'delete', 'headers': {'Authorization': 'Bearer ` + apiToken + `'}}).then((res) => { if (res.ok) document.getElementById('` + fmt.Sprintf("mailAlias-%d", i) + `').remove(); });">Supprimer</a></li>`
|
||||||
safeToken := html.EscapeString(apiToken)
|
|
||||||
safeElemID := html.EscapeString(elemID)
|
|
||||||
cnt += `<li id="` + safeElemID + `"><strong>` + safeName + `:</strong> ` + safeVal +
|
|
||||||
`<button type="button" class="mx-1 btn btn-sm btn-danger" data-alias="` + safeURL + `" data-token="` + safeToken + `" data-elem="` + safeElemID + `" onclick="(function(b){fetch('/api/v1/aliases/'+b.dataset.alias,{'method':'delete','headers':{'Authorization':'Bearer '+b.dataset.token}}).then(function(r){if(r.ok)document.getElementById(b.dataset.elem).remove();})})(this)">Supprimer</button></li>`
|
|
||||||
} else {
|
} else {
|
||||||
cnt += "<li><strong>" + safeName + ":</strong> " + safeVal + "</li>"
|
cnt += "<li><strong>" + e.Name + ":</strong> " + v + "</li>"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
displayTmpl(w, "message.html", map[string]interface{}{"details": template.HTML(`Login ok<br><br>Here are the information we have about you:` + cnt + "</ul><p>To use our Addy.io compatible API, use the following token: <code>" + html.EscapeString(apiToken) + "</code></p>")})
|
displayTmpl(w, "message.html", map[string]interface{}{"details": template.HTML(`Login ok<br><br>Here are the information we have about you:` + cnt + "</ul><p>To use our Addy.io compatible API, use the following token: <code>" + apiToken + "</code></p>")})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func httpBasicAuth(w http.ResponseWriter, r *http.Request) {
|
func httpBasicAuth(w http.ResponseWriter, r *http.Request) {
|
||||||
if !authLimiter.Allow(remoteIP(r)) {
|
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="nemunai.re restricted"`)
|
|
||||||
w.WriteHeader(http.StatusTooManyRequests)
|
|
||||||
w.Write([]byte("Too many requests"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if user, pass, ok := r.BasicAuth(); ok {
|
if user, pass, ok := r.BasicAuth(); ok {
|
||||||
if entries, err := login(user, pass); err != nil {
|
if entries, err := login(user, pass); err != nil {
|
||||||
w.Header().Set("WWW-Authenticate", `Basic realm="nemunai.re restricted"`)
|
w.Header().Set("WWW-Authenticate", `Basic realm="nemunai.re restricted"`)
|
||||||
|
|
@ -113,7 +87,7 @@ func httpBasicAuth(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else if dockerRegistrySecret != "" && r.Header.Get("X-Special-Auth") == dockerRegistrySecret {
|
} else if v := r.Header.Get("X-Special-Auth"); v == "docker-registry" {
|
||||||
method := r.Header.Get("X-Original-Method")
|
method := r.Header.Get("X-Original-Method")
|
||||||
uri := r.Header.Get("X-Original-URI")
|
uri := r.Header.Get("X-Original-URI")
|
||||||
|
|
||||||
|
|
|
||||||
121
lost.go
121
lost.go
|
|
@ -1,64 +1,54 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
"crypto/sha512"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
|
"encoding/binary"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"gopkg.in/gomail.v2"
|
"gopkg.in/gomail.v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
type resetTokenEntry struct {
|
func (l LDAPConn) genToken(dn string, previous bool) string {
|
||||||
dn string
|
hour := time.Now()
|
||||||
expiresAt time.Time
|
// Generate the previous token?
|
||||||
}
|
if previous {
|
||||||
|
hour.Add(time.Hour * -1)
|
||||||
var resetTokenStore = struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
tokens map[string]resetTokenEntry
|
|
||||||
}{tokens: make(map[string]resetTokenEntry)}
|
|
||||||
|
|
||||||
func generateResetToken() (string, error) {
|
|
||||||
b := make([]byte, 32)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
}
|
||||||
return base64.URLEncoding.EncodeToString(b), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func storeResetToken(token string, dn string) {
|
b := make([]byte, binary.MaxVarintLen64)
|
||||||
resetTokenStore.mu.Lock()
|
binary.PutVarint(b, hour.Round(time.Hour).Unix())
|
||||||
defer resetTokenStore.mu.Unlock()
|
|
||||||
|
|
||||||
// Clean expired tokens
|
// Search the email address and current password
|
||||||
now := time.Now()
|
entries, err := l.GetEntry(dn)
|
||||||
for t, e := range resetTokenStore.tokens {
|
if err != nil {
|
||||||
if now.After(e.expiresAt) {
|
log.Println("Unable to generate token:", err)
|
||||||
delete(resetTokenStore.tokens, t)
|
return "#err"
|
||||||
|
}
|
||||||
|
|
||||||
|
email := ""
|
||||||
|
curpasswd := ""
|
||||||
|
for _, e := range entries {
|
||||||
|
if e.Name == "mail" {
|
||||||
|
email += e.Values[0]
|
||||||
|
} else if e.Name == "userPassword" {
|
||||||
|
curpasswd += e.Values[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
resetTokenStore.tokens[token] = resetTokenEntry{
|
|
||||||
dn: dn,
|
|
||||||
expiresAt: now.Add(time.Hour),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func consumeResetToken(token string) (string, bool) {
|
// Hash that
|
||||||
resetTokenStore.mu.Lock()
|
hash := sha512.New()
|
||||||
defer resetTokenStore.mu.Unlock()
|
hash.Write(b)
|
||||||
entry, ok := resetTokenStore.tokens[token]
|
hash.Write([]byte(dn))
|
||||||
if !ok || time.Now().After(entry.expiresAt) {
|
hash.Write([]byte(email))
|
||||||
delete(resetTokenStore.tokens, token)
|
hash.Write([]byte(curpasswd))
|
||||||
return "", false
|
|
||||||
}
|
return base64.StdEncoding.EncodeToString(hash.Sum(nil)[:])
|
||||||
delete(resetTokenStore.tokens, token)
|
|
||||||
return entry.dn, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func lostPasswordToken(conn *LDAPConn, login string) (string, string, error) {
|
func lostPasswordToken(conn *LDAPConn, login string) (string, string, error) {
|
||||||
|
|
@ -74,41 +64,15 @@ func lostPasswordToken(conn *LDAPConn, login string) (string, string, error) {
|
||||||
return "", "", err
|
return "", "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate a cryptographically random token
|
// Generate the token
|
||||||
token, err := generateResetToken()
|
token := conn.genToken(dn, false)
|
||||||
if err != nil {
|
|
||||||
return "", "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
// Store token server-side with expiration
|
|
||||||
storeResetToken(token, dn)
|
|
||||||
|
|
||||||
return token, dn, nil
|
return token, dn, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func lostPassword(w http.ResponseWriter, r *http.Request) {
|
func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == "POST" && !lostLimiter.Allow(remoteIP(r)) {
|
|
||||||
displayTmplError(w, http.StatusTooManyRequests, "lost.html", map[string]interface{}{"error": "Too many requests. Please try again later."})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if r.Method != "POST" {
|
if r.Method != "POST" {
|
||||||
csrfToken, err := setCSRFToken(w)
|
displayTmpl(w, "lost.html", map[string]interface{}{})
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
displayTmpl(w, "lost.html", map[string]interface{}{"csrf_token": csrfToken})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !validateCSRF(r) {
|
|
||||||
displayTmplError(w, http.StatusForbidden, "lost.html", map[string]interface{}{"error": "Invalid or missing CSRF token. Please try again."})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !validateAltcha(r) {
|
|
||||||
displayTmplError(w, http.StatusForbidden, "lost.html", map[string]interface{}{"error": "Invalid or missing altcha response. Please try again."})
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -116,7 +80,7 @@ func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
conn, err := myLDAP.Connect()
|
conn, err := myLDAP.Connect()
|
||||||
if err != nil || conn == nil {
|
if err != nil || conn == nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": "Unable to process your request. Please try again later."})
|
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -124,8 +88,7 @@ func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
token, dn, err := lostPasswordToken(conn, r.PostFormValue("login"))
|
token, dn, err := lostPasswordToken(conn, r.PostFormValue("login"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
// Return generic message to avoid user enumeration
|
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": err.Error()})
|
||||||
displayMsg(w, "If an account with that login exists, a password recovery email has been sent.", http.StatusOK)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -133,7 +96,7 @@ func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
entries, err := conn.GetEntry(dn)
|
entries, err := conn.GetEntry(dn)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
displayMsg(w, "If an account with that login exists, a password recovery email has been sent.", http.StatusOK)
|
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -150,16 +113,16 @@ func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
if email == "" {
|
if email == "" {
|
||||||
log.Println("Unable to find a valid adress for user " + dn)
|
log.Println("Unable to find a valid adress for user " + dn)
|
||||||
displayMsg(w, "If an account with that login exists, a password recovery email has been sent.", http.StatusOK)
|
displayTmplError(w, http.StatusBadRequest, "lost.html", map[string]interface{}{"error": "We were unable to find a valid email address associated with your account. Please contact an administrator."})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send the email
|
// Send the email
|
||||||
m := gomail.NewMessage()
|
m := gomail.NewMessage()
|
||||||
m.SetHeader("From", myLDAP.MailFrom)
|
m.SetHeader("From", "noreply@nemunai.re")
|
||||||
m.SetHeader("To", email)
|
m.SetHeader("To", email)
|
||||||
m.SetHeader("Subject", "SSO nemunai.re: password recovery")
|
m.SetHeader("Subject", "SSO nemunai.re: password recovery")
|
||||||
m.SetBody("text/plain", "Hello "+cn+"!\n\nSomeone, and we hope it's you, requested to reset your account password. \nIn order to continue, go to:\n"+myPublicURL+"/reset?l="+r.PostFormValue("login")+"&t="+token+"\n\nThis link expires in 1 hour and can only be used once.\n\nBest regards,\n-- \nnemunai.re SSO")
|
m.SetBody("text/plain", "Hello "+cn+"!\n\nSomeone, and we hope it's you, requested to reset your account password. \nIn order to continue, go to:\n"+BASEURL+"/reset?l="+r.PostFormValue("login")+"&t="+token+"\n\nBest regards,\n-- \nnemunai.re SSO")
|
||||||
|
|
||||||
var s gomail.Sender
|
var s gomail.Sender
|
||||||
if myLDAP.MailHost != "" {
|
if myLDAP.MailHost != "" {
|
||||||
|
|
@ -167,7 +130,7 @@ func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
s, err = d.Dial()
|
s, err = d.Dial()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println("Unable to connect to email server: " + err.Error())
|
log.Println("Unable to connect to email server: " + err.Error())
|
||||||
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": "Unable to send password recovery email. Please try again later."})
|
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": "Unable to connect to email server: " + err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|
@ -202,7 +165,7 @@ func lostPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
|
|
||||||
if err := gomail.Send(s, m); err != nil {
|
if err := gomail.Send(s, m); err != nil {
|
||||||
log.Println("Unable to send email: " + err.Error())
|
log.Println("Unable to send email: " + err.Error())
|
||||||
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": "Unable to send password recovery email. Please try again later."})
|
displayTmplError(w, http.StatusInternalServerError, "lost.html", map[string]interface{}{"error": "Unable to send email: " + err.Error()})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
51
main.go
51
main.go
|
|
@ -17,23 +17,13 @@ import (
|
||||||
"syscall"
|
"syscall"
|
||||||
)
|
)
|
||||||
|
|
||||||
var myPublicURL = "https://ldap.nemunai.re"
|
const BASEURL = "https://ldap.nemunai.re"
|
||||||
var devMode bool
|
|
||||||
|
|
||||||
// dockerRegistrySecret is required for X-Special-Auth anonymous access.
|
|
||||||
// If empty, the feature is disabled.
|
|
||||||
var dockerRegistrySecret string
|
|
||||||
|
|
||||||
// allowedAliasDomains is the allowlist of domains users may create aliases under.
|
|
||||||
// If empty, alias creation is disabled.
|
|
||||||
var allowedAliasDomains []string
|
|
||||||
|
|
||||||
var myLDAP = LDAP{
|
var myLDAP = LDAP{
|
||||||
Host: "localhost",
|
Host: "localhost",
|
||||||
Port: 389,
|
Port: 389,
|
||||||
BaseDN: "dc=example,dc=com",
|
BaseDN: "dc=example,dc=com",
|
||||||
MailPort: 587,
|
MailPort: 587,
|
||||||
MailFrom: "noreply@nemunai.re",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ResponseWriterPrefix struct {
|
type ResponseWriterPrefix struct {
|
||||||
|
|
@ -80,16 +70,8 @@ func main() {
|
||||||
var bind = flag.String("bind", "127.0.0.1:8080", "Bind port/socket")
|
var bind = flag.String("bind", "127.0.0.1:8080", "Bind port/socket")
|
||||||
var baseURL = flag.String("baseurl", "/", "URL prepended to each URL")
|
var baseURL = flag.String("baseurl", "/", "URL prepended to each URL")
|
||||||
var configfile = flag.String("config", "", "path to the configuration file")
|
var configfile = flag.String("config", "", "path to the configuration file")
|
||||||
var publicURL = flag.String("public-url", myPublicURL, "Public base URL used in password reset emails")
|
|
||||||
var dev = flag.Bool("dev", false, "Development mode: disables HSTS and cookie Secure flag for local HTTP testing")
|
|
||||||
flag.Parse()
|
flag.Parse()
|
||||||
|
|
||||||
myPublicURL = *publicURL
|
|
||||||
devMode = *dev
|
|
||||||
if devMode {
|
|
||||||
log.Println("WARNING: running in development mode — security features relaxed, do not use in production")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Sanitize options
|
// Sanitize options
|
||||||
log.Println("Checking paths...")
|
log.Println("Checking paths...")
|
||||||
if *baseURL != "/" {
|
if *baseURL != "/" {
|
||||||
|
|
@ -159,31 +141,9 @@ func main() {
|
||||||
if val, ok := os.LookupEnv("SMTP_USER"); ok {
|
if val, ok := os.LookupEnv("SMTP_USER"); ok {
|
||||||
myLDAP.MailUser = val
|
myLDAP.MailUser = val
|
||||||
}
|
}
|
||||||
if val, ok := os.LookupEnv("SMTP_PASSWORD_FILE"); ok {
|
if val, ok := os.LookupEnv("SMTP_PASSWORD"); ok {
|
||||||
if fd, err := os.Open(val); err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
} else if cnt, err := os.ReadFile(val); err != nil {
|
|
||||||
fd.Close()
|
|
||||||
log.Fatal(err)
|
|
||||||
} else {
|
|
||||||
fd.Close()
|
|
||||||
myLDAP.MailPassword = string(cnt)
|
|
||||||
}
|
|
||||||
} else if val, ok := os.LookupEnv("SMTP_PASSWORD"); ok {
|
|
||||||
myLDAP.MailPassword = val
|
myLDAP.MailPassword = val
|
||||||
}
|
}
|
||||||
if val, ok := os.LookupEnv("SMTP_FROM"); ok {
|
|
||||||
myLDAP.MailFrom = val
|
|
||||||
}
|
|
||||||
if val, ok := os.LookupEnv("PUBLIC_URL"); ok {
|
|
||||||
myPublicURL = val
|
|
||||||
}
|
|
||||||
if val, ok := os.LookupEnv("DOCKER_REGISTRY_SECRET"); ok {
|
|
||||||
dockerRegistrySecret = val
|
|
||||||
}
|
|
||||||
if val, ok := os.LookupEnv("ALIAS_ALLOWED_DOMAINS"); ok && val != "" {
|
|
||||||
allowedAliasDomains = strings.Split(val, ",")
|
|
||||||
}
|
|
||||||
|
|
||||||
if flag.NArg() > 0 {
|
if flag.NArg() > 0 {
|
||||||
switch flag.Arg(0) {
|
switch flag.Arg(0) {
|
||||||
|
|
@ -204,7 +164,7 @@ func main() {
|
||||||
log.Fatal(err.Error())
|
log.Fatal(err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("Reset link for %s: %s/reset?l=%s&t=%s", dn, myPublicURL, login, token)
|
fmt.Printf("Reset link for %s: %s/reset?l=%s&t=%s", dn, BASEURL, login, token)
|
||||||
return
|
return
|
||||||
case "serve":
|
case "serve":
|
||||||
case "server":
|
case "server":
|
||||||
|
|
@ -219,8 +179,6 @@ func main() {
|
||||||
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
|
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
|
||||||
|
|
||||||
// Register handlers
|
// Register handlers
|
||||||
http.HandleFunc(fmt.Sprintf("GET %s/altcha.min.js", *baseURL), serveAltchaJS)
|
|
||||||
http.HandleFunc(fmt.Sprintf("GET %s/altcha-challenge", *baseURL), serveAltchaChallenge)
|
|
||||||
http.HandleFunc(fmt.Sprintf("%s/{$}", *baseURL), changePassword)
|
http.HandleFunc(fmt.Sprintf("%s/{$}", *baseURL), changePassword)
|
||||||
http.HandleFunc(fmt.Sprintf("POST %s/api/v1/aliases", *baseURL), addyAliasAPI)
|
http.HandleFunc(fmt.Sprintf("POST %s/api/v1/aliases", *baseURL), addyAliasAPI)
|
||||||
http.HandleFunc(fmt.Sprintf("DELETE %s/api/v1/aliases/{alias}", *baseURL), addyAliasAPIDelete)
|
http.HandleFunc(fmt.Sprintf("DELETE %s/api/v1/aliases/{alias}", *baseURL), addyAliasAPIDelete)
|
||||||
|
|
@ -231,8 +189,7 @@ func main() {
|
||||||
http.HandleFunc(fmt.Sprintf("%s/lost", *baseURL), lostPassword)
|
http.HandleFunc(fmt.Sprintf("%s/lost", *baseURL), lostPassword)
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: *bind,
|
Addr: *bind,
|
||||||
Handler: securityHeaders(http.DefaultServeMux),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serve content
|
// Serve content
|
||||||
|
|
|
||||||
63
ratelimit.go
63
ratelimit.go
|
|
@ -1,63 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/http"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type rateLimiter struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
counts map[string][]time.Time
|
|
||||||
limit int
|
|
||||||
window time.Duration
|
|
||||||
}
|
|
||||||
|
|
||||||
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
|
|
||||||
return &rateLimiter{
|
|
||||||
counts: make(map[string][]time.Time),
|
|
||||||
limit: limit,
|
|
||||||
window: window,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rl *rateLimiter) Allow(key string) bool {
|
|
||||||
rl.mu.Lock()
|
|
||||||
defer rl.mu.Unlock()
|
|
||||||
|
|
||||||
now := time.Now()
|
|
||||||
windowStart := now.Add(-rl.window)
|
|
||||||
|
|
||||||
timestamps := rl.counts[key]
|
|
||||||
filtered := timestamps[:0]
|
|
||||||
for _, t := range timestamps {
|
|
||||||
if t.After(windowStart) {
|
|
||||||
filtered = append(filtered, t)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(filtered) >= rl.limit {
|
|
||||||
rl.counts[key] = filtered
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
rl.counts[key] = append(filtered, now)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
var (
|
|
||||||
authLimiter = newRateLimiter(20, time.Minute)
|
|
||||||
changeLimiter = newRateLimiter(10, time.Minute)
|
|
||||||
lostLimiter = newRateLimiter(5, time.Minute)
|
|
||||||
resetLimiter = newRateLimiter(10, time.Minute)
|
|
||||||
aliasLimiter = newRateLimiter(30, time.Minute)
|
|
||||||
)
|
|
||||||
|
|
||||||
func remoteIP(r *http.Request) string {
|
|
||||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
||||||
if err != nil {
|
|
||||||
return r.RemoteAddr
|
|
||||||
}
|
|
||||||
return host
|
|
||||||
}
|
|
||||||
73
reset.go
73
reset.go
|
|
@ -3,66 +3,32 @@ package main
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
func resetPassword(w http.ResponseWriter, r *http.Request) {
|
func resetPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == "POST" && !resetLimiter.Allow(remoteIP(r)) {
|
|
||||||
http.Error(w, "Too many requests. Please try again later.", http.StatusTooManyRequests)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(r.URL.Query().Get("l")) == 0 || len(r.URL.Query().Get("t")) == 0 {
|
if len(r.URL.Query().Get("l")) == 0 || len(r.URL.Query().Get("t")) == 0 {
|
||||||
http.Redirect(w, r, "lost", http.StatusFound)
|
http.Redirect(w, r, "lost", http.StatusFound)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
base := map[string]interface{}{
|
base := map[string]interface{}{
|
||||||
"login": r.URL.Query().Get("l"),
|
"login": r.URL.Query().Get("l"),
|
||||||
"token": r.URL.Query().Get("t"),
|
"token": strings.Replace(r.URL.Query().Get("t"), " ", "+", -1),
|
||||||
}
|
}
|
||||||
|
|
||||||
if r.Method != "POST" {
|
if r.Method != "POST" {
|
||||||
csrfToken, err := setCSRFToken(w)
|
|
||||||
if err != nil {
|
|
||||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
base["csrf_token"] = csrfToken
|
|
||||||
displayTmpl(w, "reset.html", base)
|
displayTmpl(w, "reset.html", base)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
renderError := func(status int, msg string) {
|
|
||||||
csrfToken, _ := setCSRFToken(w)
|
|
||||||
base["error"] = msg
|
|
||||||
base["csrf_token"] = csrfToken
|
|
||||||
displayTmplError(w, status, "reset.html", base)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !validateCSRF(r) {
|
|
||||||
renderError(http.StatusForbidden, "Invalid or missing CSRF token. Please try again.")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !validateAltcha(r) {
|
|
||||||
renderError(http.StatusForbidden, "Invalid or missing altcha response. Please try again.")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check the two new passwords are identical
|
// Check the two new passwords are identical
|
||||||
if r.PostFormValue("newpassword") != r.PostFormValue("new2password") {
|
if r.PostFormValue("newpassword") != r.PostFormValue("new2password") {
|
||||||
renderError(http.StatusNotAcceptable, "New passwords are not identical. Please retry.")
|
base["error"] = "New passwords are not identical. Please retry."
|
||||||
|
displayTmplError(w, http.StatusNotAcceptable, "reset.html", base)
|
||||||
return
|
return
|
||||||
} else if err := checkPasswdConstraint(r.PostFormValue("newpassword")); err != nil {
|
} else if err := checkPasswdConstraint(r.PostFormValue("newpassword")); err != nil {
|
||||||
renderError(http.StatusNotAcceptable, "The password you chose doesn't respect all constraints: "+err.Error())
|
base["error"] = "The password you chose doesn't respect all constraints: " + err.Error()
|
||||||
return
|
displayTmplError(w, http.StatusNotAcceptable, "reset.html", base)
|
||||||
}
|
|
||||||
|
|
||||||
// Validate and consume the token (single-use, server-side)
|
|
||||||
token := r.PostFormValue("token")
|
|
||||||
dn, ok := consumeResetToken(token)
|
|
||||||
if !ok {
|
|
||||||
renderError(http.StatusNotAcceptable, "Token invalid or expired, please retry the lost password procedure. Tokens expire after 1 hour.")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -70,22 +36,41 @@ func resetPassword(w http.ResponseWriter, r *http.Request) {
|
||||||
conn, err := myLDAP.Connect()
|
conn, err := myLDAP.Connect()
|
||||||
if err != nil || conn == nil {
|
if err != nil || conn == nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusInternalServerError, "Unable to process your request. Please try again later.")
|
base["error"] = err.Error()
|
||||||
|
displayTmplError(w, http.StatusInternalServerError, "reset.html", base)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bind as service to perform the password change
|
// Bind as service to perform the search
|
||||||
err = conn.ServiceBind()
|
err = conn.ServiceBind()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusInternalServerError, "Unable to process your request. Please try again later.")
|
base["error"] = err.Error()
|
||||||
|
displayTmplError(w, http.StatusInternalServerError, "reset.html", base)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search the dn of the given user
|
||||||
|
dn, err := conn.SearchDN(r.PostFormValue("login"), true)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
base["error"] = err.Error()
|
||||||
|
displayTmplError(w, http.StatusInternalServerError, "reset.html", base)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check token validity (allow current token + last one)
|
||||||
|
if conn.genToken(dn, false) != r.PostFormValue("token") && conn.genToken(dn, true) != r.PostFormValue("token") {
|
||||||
|
base["error"] = "Token invalid, please retry the lost password procedure. Please note that our token expires after 1 hour."
|
||||||
|
displayTmplError(w, http.StatusNotAcceptable, "reset.html", base)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// Replace the password by the new given
|
// Replace the password by the new given
|
||||||
if err := conn.ChangePassword(dn, r.PostFormValue("newpassword")); err != nil {
|
if err := conn.ChangePassword(dn, r.PostFormValue("newpassword")); err != nil {
|
||||||
log.Println(err)
|
log.Println(err)
|
||||||
renderError(http.StatusInternalServerError, "Unable to process your request. Please try again later.")
|
base["error"] = err.Error()
|
||||||
|
displayTmplError(w, http.StatusInternalServerError, "reset.html", base)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
13
static.go
13
static.go
|
|
@ -7,19 +7,6 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
func securityHeaders(next http.Handler) http.Handler {
|
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
w.Header().Set("X-Frame-Options", "DENY")
|
|
||||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
||||||
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
|
|
||||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; script-src 'self' 'wasm-unsafe-eval' 'unsafe-inline' https://stackpath.bootstrapcdn.com; style-src https://stackpath.bootstrapcdn.com; img-src 'self'; font-src https://stackpath.bootstrapcdn.com")
|
|
||||||
if !devMode {
|
|
||||||
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
|
|
||||||
}
|
|
||||||
next.ServeHTTP(w, r)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
//go:embed all:static
|
//go:embed all:static
|
||||||
var assets embed.FS
|
var assets embed.FS
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@
|
||||||
|
|
||||||
<form method="post" action="change">
|
<form method="post" action="change">
|
||||||
{{if .error}}<div class="alert alert-danger" role="alert">{{.error}}</div>{{end}}
|
{{if .error}}<div class="alert alert-danger" role="alert">{{.error}}</div>{{end}}
|
||||||
<input type="hidden" name="csrf_token" value="{{ .csrf_token }}">
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<input name="login" required="" class="form-control" id="input_0" type="text" placeholder="Login" autofocus>
|
<input name="login" required="" class="form-control" id="input_0" type="text" placeholder="Login" autofocus>
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -40,9 +39,6 @@
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
|
||||||
<altcha-widget challengeurl="altcha-challenge"></altcha-widget>
|
|
||||||
</div>
|
|
||||||
<button class="btn btn-primary" type="submit">Change my password</button>
|
<button class="btn btn-primary" type="submit">Change my password</button>
|
||||||
<a href="/lost" class="btn btn-outline-secondary">Forgot your password?</a>
|
<a href="/lost" class="btn btn-outline-secondary">Forgot your password?</a>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,6 @@
|
||||||
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
|
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
|
||||||
|
|
||||||
<title>nemunai.re password change</title>
|
<title>nemunai.re password change</title>
|
||||||
<script src="altcha.min.js" async defer></script>
|
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class="container">
|
<div class="container">
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,6 @@
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<input name="password" required="" class="form-control" id="input_1" type="password" placeholder="Current password">
|
<input name="password" required="" class="form-control" id="input_1" type="password" placeholder="Current password">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
|
||||||
<altcha-widget challengeurl="altcha-challenge"></altcha-widget>
|
|
||||||
</div>
|
|
||||||
<button class="btn btn-primary" type="submit">Sign in</button>
|
<button class="btn btn-primary" type="submit">Sign in</button>
|
||||||
<a href="/lost" class="btn btn-outline-secondary">Forgot your password?</a>
|
<a href="/lost" class="btn btn-outline-secondary">Forgot your password?</a>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -3,13 +3,9 @@
|
||||||
|
|
||||||
<form method="post" action="lost">
|
<form method="post" action="lost">
|
||||||
{{if .error}}<div class="alert alert-danger" role="alert">{{.error}}</div>{{end}}
|
{{if .error}}<div class="alert alert-danger" role="alert">{{.error}}</div>{{end}}
|
||||||
<input type="hidden" name="csrf_token" value="{{ .csrf_token }}">
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<input name="login" required="" class="form-control" id="input_0" type="text" placeholder="Login" autofocus>
|
<input name="login" required="" class="form-control" id="input_0" type="text" placeholder="Login" autofocus>
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
|
||||||
<altcha-widget challengeurl="altcha-challenge"></altcha-widget>
|
|
||||||
</div>
|
|
||||||
<button class="btn btn-primary" type="submit">Reset my password</button>
|
<button class="btn btn-primary" type="submit">Reset my password</button>
|
||||||
<a href="/change" class="btn btn-outline-success">Just want to change your password?</a>
|
<a href="/change" class="btn btn-outline-success">Just want to change your password?</a>
|
||||||
</form>
|
</form>
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,8 @@
|
||||||
{{template "header"}}
|
{{template "header"}}
|
||||||
<h1 class="display-4">Forgot your password? <small class="text-muted">Define a new one!</small></h1>
|
<h1 class="display-4">Forgot your password? <small class="text-muted">Define a new one!</small></h1>
|
||||||
|
|
||||||
<form method="post" action="reset">
|
<form method="post" action="reset?l={{ .login }}&t={{ .token }}">
|
||||||
{{if .error}}<div class="alert alert-danger" role="alert">{{.error}}</div>{{end}}
|
{{if .error}}<div class="alert alert-danger" role="alert">{{.error}}</div>{{end}}
|
||||||
<input type="hidden" name="csrf_token" value="{{ .csrf_token }}">
|
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<input required="" class="form-control" id="input_0" type="text" placeholder="Email" value="{{ .login }}" disabled="">
|
<input required="" class="form-control" id="input_0" type="text" placeholder="Email" value="{{ .login }}" disabled="">
|
||||||
</div>
|
</div>
|
||||||
|
|
@ -15,9 +14,6 @@
|
||||||
<div class="form-group">
|
<div class="form-group">
|
||||||
<input name="new2password" required="" class="form-control" id="input_3" type="password" placeholder="Retype new password">
|
<input name="new2password" required="" class="form-control" id="input_3" type="password" placeholder="Retype new password">
|
||||||
</div>
|
</div>
|
||||||
<div class="form-group">
|
|
||||||
<altcha-widget challengeurl="altcha-challenge"></altcha-widget>
|
|
||||||
</div>
|
|
||||||
<button class="btn btn-primary" type="submit">Reset my password</button>
|
<button class="btn btn-primary" type="submit">Reset my password</button>
|
||||||
</form>
|
</form>
|
||||||
{{template "footer"}}
|
{{template "footer"}}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue