package server import ( "context" "crypto/tls" "crypto/x509" "database/sql" "encoding/base64" "errors" "fmt" "log" "net" "net/http" "net/url" "strings" "time" "unicode/utf8" ldap "github.com/go-ldap/ldap/v3" "pageswiki/internal/store" ) type ldapDirectory interface { Bind(string, string) error Search(*ldap.SearchRequest) (*ldap.SearchResult, error) Close() error } type ldapDialFunc func(context.Context, store.AuthProviderConfig) (ldapDirectory, error) type ldapIdentity struct { Subject, Username, Email, DisplayName, DN string } func ldapTLSConfig(config store.AuthProviderConfig) (*tls.Config, error) { parsed, err := url.Parse(config.LDAPURL) if err != nil { return nil, err } tlsConfig := &tls.Config{ // #nosec G402 -- opt-out is an explicit administrator setting. MinVersion: tls.VersionTLS12, ServerName: parsed.Hostname(), InsecureSkipVerify: config.LDAPSkipTLSVerify, } if config.LDAPCAPEM != "" { pool, poolErr := x509.SystemCertPool() if poolErr != nil || pool == nil { pool = x509.NewCertPool() } if !pool.AppendCertsFromPEM([]byte(config.LDAPCAPEM)) { return nil, errors.New("LDAP CA PEM contains no certificate") } tlsConfig.RootCAs = pool } return tlsConfig, nil } func dialLDAPDirectory(_ context.Context, config store.AuthProviderConfig) (ldapDirectory, error) { if err := store.ValidateLDAPProviderConfig(config); err != nil { return nil, err } tlsConfig, err := ldapTLSConfig(config) if err != nil { return nil, err } conn, err := ldap.DialURL(config.LDAPURL, ldap.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}), ldap.DialWithTLSConfig(tlsConfig), ) if err != nil { return nil, err } conn.SetTimeout(8 * time.Second) if config.LDAPStartTLS { if err = conn.StartTLS(tlsConfig); err != nil { conn.Close() return nil, err } } return conn, nil } func ldapStableSubject(raw []byte) (string, error) { if len(raw) == 0 || len(raw) > 4096 { return "", errors.New("LDAP immutable UID is missing or too large") } return "attr:" + base64.RawURLEncoding.EncodeToString(raw), nil } func (s *Server) authenticateLDAPDirectory(ctx context.Context, config store.AuthProviderConfig, login, password string) (ldapIdentity, error) { login = strings.TrimSpace(login) if login == "" || len(login) > 512 || password == "" || len(password) > 4096 || config.UUID == "" { return ldapIdentity{}, store.ErrAccessDenied } if err := store.ValidateLDAPProviderConfig(config); err != nil || !config.Enabled { return ldapIdentity{}, store.ErrAccessDenied } dial := s.ldapDial if dial == nil { dial = dialLDAPDirectory } directory, err := dial(ctx, config) if err != nil { return ldapIdentity{}, err } defer func() { _ = directory.Close() }() if config.LDAPBindDN != "" { if config.LDAPBindPassword == "" { return ldapIdentity{}, errors.New("LDAP service bind password is unavailable") } if err = directory.Bind(config.LDAPBindDN, config.LDAPBindPassword); err != nil { return ldapIdentity{}, fmt.Errorf("LDAP service bind: %w", err) } } attributes := []string{config.LDAPUIDAttribute, config.LDAPUsernameAttribute, config.LDAPEmailAttribute, config.LDAPDisplayAttribute} unique := make([]string, 0, len(attributes)) seen := map[string]bool{} for _, attribute := range attributes { key := strings.ToLower(attribute) if !seen[key] { seen[key] = true unique = append(unique, attribute) } } filter := strings.ReplaceAll(config.LDAPSearchFilter, "{{username}}", ldap.EscapeFilter(login)) request := ldap.NewSearchRequest(config.LDAPSearchBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 2, 6, false, filter, unique, nil) result, err := directory.Search(request) if err != nil { return ldapIdentity{}, fmt.Errorf("LDAP user search: %w", err) } if len(result.Entries) != 1 || result.Entries[0].DN == "" { return ldapIdentity{}, store.ErrAccessDenied } entry := result.Entries[0] subject, err := ldapStableSubject(entry.GetEqualFoldRawAttributeValue(config.LDAPUIDAttribute)) if err != nil { return ldapIdentity{}, err } identity := ldapIdentity{ Subject: subject, DN: entry.DN, Username: strings.ToLower(strings.TrimSpace(entry.GetEqualFoldAttributeValue(config.LDAPUsernameAttribute))), Email: strings.ToLower(strings.TrimSpace(entry.GetEqualFoldAttributeValue(config.LDAPEmailAttribute))), DisplayName: strings.TrimSpace(entry.GetEqualFoldAttributeValue(config.LDAPDisplayAttribute)), } if identity.Username == "" || !utf8.ValidString(identity.Username) || !utf8.ValidString(identity.DisplayName) || !utf8.ValidString(identity.Email) { return ldapIdentity{}, errors.New("LDAP identity attributes are invalid") } // The successful user bind is the password proof. Never retain or log the // supplied password, and do not accept a search result alone as login. if err = directory.Bind(entry.DN, password); err != nil { return ldapIdentity{}, store.ErrAccessDenied } return identity, nil } func (s *Server) authenticateLDAPPrincipal(ctx context.Context, domainUUID, login, password string) (*store.Principal, error) { config, err := s.store.AuthProviderConfig(domainUUID, "ldap") if err != nil || !config.Enabled { return nil, store.ErrAccessDenied } identity, err := s.authenticateLDAPDirectory(ctx, config, login, password) if err != nil { return nil, err } attributes := map[string]string{"dn": identity.DN, "username": identity.Username, "email": identity.Email, "display_name": identity.DisplayName} principal, err := s.store.PrincipalByExternalIdentity(domainUUID, "ldap", config.UUID, "", identity.Subject) if err == nil { if bindErr := s.store.BindExternalIdentity(principal.UUID, "ldap", config.UUID, "", identity.Subject, attributes); bindErr != nil { return nil, bindErr } return principal, nil } if !errors.Is(err, sql.ErrNoRows) { return nil, err } switch config.LDAPMatchBy { case "email": principal, err = s.store.PrincipalByVerifiedEmail(domainUUID, identity.Email) default: principal, err = s.store.PrincipalByExternalUsername(domainUUID, identity.Username) } if err == nil { if err = s.store.BindExternalIdentityIfProviderUnbound(domainUUID, principal.UUID, "ldap", config.UUID, "", identity.Subject, attributes); err != nil { return nil, err } return principal, nil } if !errors.Is(err, store.ErrAccessDenied) || !config.LDAPAutoProvision { return nil, store.ErrAccessDenied } return s.store.ProvisionExternalAccount(domainUUID, identity.Username, identity.DisplayName, identity.Email, "ldap", config.UUID, "", identity.Subject, attributes) } func (s *Server) handleLDAPLogin(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.Header().Set("Allow", http.MethodPost) http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } w.Header().Set("Cache-Control", "no-store") r.Body = http.MaxBytesReader(w, r.Body, 64<<10) if err := r.ParseForm(); err != nil { http.Error(w, "invalid sign-in request", http.StatusBadRequest) return } returnPath := safeReturnPath(r.FormValue("return")) select { case s.ldapSlots <- struct{}{}: defer func() { <-s.ldapSlots }() default: http.Error(w, "directory authentication is busy", http.StatusServiceUnavailable) return } ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second) defer cancel() domainUUID := s.domainUUIDForRequest(r) principal, err := s.authenticateLDAPPrincipal(ctx, domainUUID, r.FormValue("username"), r.FormValue("password")) if err != nil { log.Printf("LDAP login failed domain=%s error=%v", domainUUID, err) s.renderAuthPage(w, r, map[string]any{"Error": translate(s.getLocale(domainUUID), "auth.invalid_credentials"), "Return": returnPath}) return } if s.store.HasTOTP(principal.UUID) { challenge, challengeErr := s.store.CreateTOTPLoginChallengeForLogin(domainUUID, principal.UUID, r.PostForm.Get("remember") == "1") if challengeErr != nil { http.Error(w, "authentication unavailable", http.StatusServiceUnavailable) return } if strings.Contains(r.Header.Get("Accept"), "application/json") { writeEventJSON(w, http.StatusUnauthorized, map[string]any{"mfa_required": true, "challenge_token": challenge, "method": "totp"}) return } http.SetCookie(w, &http.Cookie{Name: mfaChallengeCookieName, Value: challenge, Path: "/_/auth/", HttpOnly: true, Secure: requestIsHTTPS(r), SameSite: http.SameSiteStrictMode, MaxAge: 300}) s.renderAuthPage(w, r, map[string]any{"MFA": true, "Return": returnPath}) return } token, lifetime, err := s.store.CreateLoginSession(domainUUID, principal.UUID, 0, !strings.Contains(r.Header.Get("Accept"), "application/json"), r.PostForm.Get("remember") == "1") if err != nil { http.Error(w, "authentication unavailable", http.StatusServiceUnavailable) return } if strings.Contains(r.Header.Get("Accept"), "application/json") { writeEventJSON(w, http.StatusOK, map[string]any{"access_token": token, "token_type": "Bearer", "expires_in": int(lifetime.Seconds())}) return } s.setAuthCookieForSeconds(w, r, token, int(lifetime.Seconds())) http.Redirect(w, r, returnPath, http.StatusSeeOther) }