Skip to content
Open
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
43 changes: 43 additions & 0 deletions services/idp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,46 @@ clients:




### Two-Factor Authentication

Users can protect their account with a second factor: a time-based one-time password (TOTP, RFC 6238) from an authenticator app like Google Authenticator, Microsoft Authenticator or FreeOTP.

The feature is built in and available by default, nothing needs to be configured. It is optional per user: only users who turn it on in their account settings are asked for a code. It is offered with the identity managers `ldap` (the default) and `cs3` and when `IDP_ENCRYPTION_SECRET_FILE` is set, which it is by default. To switch it off for the whole instance set:

```
IDP_MFA_ENABLED=false
```

#### How it Works for Users

Users find "Two-factor authentication" in their account settings in the web UI. It opens the page `/signin/v1/mfa` of the login service, for example `https://cloud.example.com/signin/v1/mfa`:

1. The user confirms the password and scans a QR code with the authenticator app.
2. The user enters a code from the app to confirm the setup.
3. The user gets ten recovery codes. Each one can be used once instead of a code from the app, for example when the phone is lost.

From then on the login page asks for a code after the password. This applies to all clients as web, desktop and mobile apps use the same login page. Sessions that exist when two-factor authentication is turned on stay valid.

To turn two-factor authentication off or to get new recovery codes, a code from the app or a recovery code is required.

#### Lost Authenticator App

When users lose their authenticator app and their recovery codes, an administrator can turn two-factor authentication off for them. They can log in with their password again and set it up anew.

```bash
# list the users with two-factor authentication
opencloud idp mfa list

# turn it off for a user, identified by username or user id
opencloud idp mfa disable alan
```

#### Things to Know

* The secrets are kept in the store configured with `IDP_MFA_STORE` (default: `nats-js-kv`). They are encrypted with a key that is derived from the content of `IDP_ENCRYPTION_SECRET_FILE`. When this file is lost or replaced, the secrets cannot be read anymore. Logins of users with two-factor authentication fail until an administrator turns it off for them with the command above. In deployments with more than one `idp` instance all instances need the same file.
* Recovery codes are only stored as hashes.
* The `idp` service needs to reach the store. When the store cannot be reached, nobody can log in, because it is not known who needs a second factor. In deployments where the `idp` service runs separately, set `IDP_MFA_STORE_NODES` (or `OC_PERSISTENT_STORE_NODES`) or switch the feature off.
* After five wrong codes in a row no codes are accepted for five minutes. Every further five wrong codes double the wait, up to a day, until a correct code is entered. An administrator can end it earlier with the command above. A one-time code is accepted once.
* Setting `IDP_MFA_ENABLED=false` turns the check off for all users. Their secrets stay in the store and apply again when it is enabled again.
* The second factor is checked by the login page of the builtin IDP only. Other ways to authenticate are not affected: app tokens of the `auth-app` service and basic auth (`PROXY_ENABLE_BASIC_AUTH`, disabled by default) work with the password or token only. With an external IDP like Keycloak, configure two-factor authentication there.
1 change: 1 addition & 0 deletions services/idp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
"i18next": "^26.5.4",
"i18next-browser-languagedetector": "^8.2.1",
"i18next-resources-to-backend": "^1.2.3",
"qrcode.react": "^4.2.0",
"query-string": "^9.5.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
Expand Down
29 changes: 22 additions & 7 deletions services/idp/pkg/backends/cs3/bootstrap/cs3.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (

"github.com/libregraph/lico/bootstrap"
"github.com/libregraph/lico/identifier"
"github.com/libregraph/lico/identifier/backends"
"github.com/libregraph/lico/identity"
"github.com/libregraph/lico/identity/managers"

Expand All @@ -34,20 +35,26 @@ const (
identityManagerName = "cs3"
)

// Register adds the CS3 identity manager to the lico bootstrap
func Register() error {
return bootstrap.RegisterIdentityManager(identityManagerName, NewIdentityManager)
// BackendWrapper decorates the identifier backend, e.g. to add a second factor to the logon.
type BackendWrapper func(backends.Backend) backends.Backend

// Register adds the CS3 identity manager to the lico bootstrap. If wrap is not nil the
// identifier backend is passed through it.
func Register(wrap BackendWrapper) error {
return bootstrap.RegisterIdentityManager(identityManagerName, func(bs bootstrap.Bootstrap) (identity.Manager, error) {
return NewIdentityManager(bs, wrap)
})
}

// MustRegister adds the CS3 identity manager to the lico bootstrap or panics
func MustRegister() {
if err := Register(); err != nil {
func MustRegister(wrap BackendWrapper) {
if err := Register(wrap); err != nil {
panic(err)
}
}

// NewIdentityManager produces a CS3 backed identity manager instance for the idp
func NewIdentityManager(bs bootstrap.Bootstrap) (identity.Manager, error) {
func NewIdentityManager(bs bootstrap.Bootstrap, wrap BackendWrapper) (identity.Manager, error) {
config := bs.Config()

logger := config.Config.Logger
Expand Down Expand Up @@ -82,6 +89,11 @@ func NewIdentityManager(bs bootstrap.Bootstrap) (identity.Manager, error) {
return nil, fmt.Errorf("failed to create identifier backend: %v", identifierErr)
}

var activeBackend backends.Backend = identifierBackend
if wrap != nil {
activeBackend = wrap(activeBackend)
}

fullAuthorizationEndpointURL := bootstrap.WithSchemeAndHost(config.AuthorizationEndpointURI, config.IssuerIdentifierURI)
fullSignInFormURL := bootstrap.WithSchemeAndHost(config.SignInFormURI, config.IssuerIdentifierURI)
fullSignedOutEndpointURL := bootstrap.WithSchemeAndHost(config.SignedOutURI, config.IssuerIdentifierURI)
Expand Down Expand Up @@ -110,7 +122,7 @@ func NewIdentityManager(bs bootstrap.Bootstrap) (identity.Manager, error) {
DefaultUsernameHintText: config.IdentifierDefaultUsernameHintText,
UILocales: config.IdentifierUILocales,

Backend: identifierBackend,
Backend: activeBackend,
})
if err != nil {
return nil, fmt.Errorf("failed to create identifier: %v", err)
Expand All @@ -120,6 +132,9 @@ func NewIdentityManager(bs bootstrap.Bootstrap) (identity.Manager, error) {
return nil, fmt.Errorf("invalid --encryption-secret parameter value for identifier: %v", err)
}

// Expose the identifier in the managers registry like the other lico backends do.
bs.Managers().Set("identifier", activeIdentifier)

identityManagerConfig := &identity.Config{
SignInFormURI: fullSignInFormURL,
SignedOutURI: fullSignedOutEndpointURL,
Expand Down
201 changes: 201 additions & 0 deletions services/idp/pkg/backends/ldap/bootstrap/ldap.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
/*
* Copyright 2017-2019 Kopano and its licensors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

// Package bootstrap provides the LDAP identity manager of lico with the option to wrap
// the identifier backend. It is a copy of
// github.com/libregraph/lico/bootstrap/backends/ldap which creates the backend
// internally and offers no way to decorate it.
package bootstrap

import (
"crypto/x509"
"fmt"
"os"
"strings"

"github.com/libregraph/lico/bootstrap"
"github.com/libregraph/lico/identifier"
"github.com/libregraph/lico/identifier/backends"
"github.com/libregraph/lico/identifier/backends/ldap"
"github.com/libregraph/lico/identity"
"github.com/libregraph/lico/identity/managers"
)

// Identity managers.
const (
identityManagerName = "ldap"
)

// BackendWrapper decorates the identifier backend, e.g. to add a second factor to the logon.
type BackendWrapper func(backends.Backend) backends.Backend

// Register adds the LDAP identity manager to the lico bootstrap. The identifier backend
// is passed through wrap.
func Register(wrap BackendWrapper) error {
return bootstrap.RegisterIdentityManager(identityManagerName, func(bs bootstrap.Bootstrap) (identity.Manager, error) {
return NewIdentityManager(bs, wrap)
})
}

// MustRegister adds the LDAP identity manager to the lico bootstrap or panics
func MustRegister(wrap BackendWrapper) {
if err := Register(wrap); err != nil {
panic(err)
}
}

// NewIdentityManager produces a LDAP backed identity manager instance for the idp
func NewIdentityManager(bs bootstrap.Bootstrap, wrap BackendWrapper) (identity.Manager, error) {
config := bs.Config()

logger := config.Config.Logger

if config.AuthorizationEndpointURI.String() != "" {
return nil, fmt.Errorf("ldap backend is incompatible with authorization-endpoint-uri parameter")
}
config.AuthorizationEndpointURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/identifier/_/authorize")

if config.EndSessionEndpointURI.String() != "" {
return nil, fmt.Errorf("ldap backend is incompatible with endsession-endpoint-uri parameter")
}
config.EndSessionEndpointURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/identifier/_/endsession")

if config.SignInFormURI.EscapedPath() == "" {
config.SignInFormURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/identifier")
}

if config.SignedOutURI.EscapedPath() == "" {
config.SignedOutURI.Path = bs.MakeURIPath(bootstrap.APITypeSignin, "/goodbye")
}

// Default LDAP attribute mappings.
attributeMapping := map[string]string{
ldap.AttributeLogin: os.Getenv("LDAP_LOGIN_ATTRIBUTE"),
ldap.AttributeEmail: os.Getenv("LDAP_EMAIL_ATTRIBUTE"),
ldap.AttributeName: os.Getenv("LDAP_NAME_ATTRIBUTE"),
ldap.AttributeFamilyName: os.Getenv("LDAP_FAMILY_NAME_ATTRIBUTE"),
ldap.AttributeGivenName: os.Getenv("LDAP_GIVEN_NAME_ATTRIBUTE"),
ldap.AttributeUUID: os.Getenv("LDAP_UUID_ATTRIBUTE"),
fmt.Sprintf("%s_type", ldap.AttributeUUID): os.Getenv("LDAP_UUID_ATTRIBUTE_TYPE"),
}
// Add optional LDAP attribute mappings.
if numericUIDAttribute := os.Getenv("LDAP_UIDNUMBER_ATTRIBUTE"); numericUIDAttribute != "" {
attributeMapping[ldap.AttributeNumericUID] = numericUIDAttribute
}
// Sub from LDAP attribute mappings.
var subMapping []string
if subMappingString := os.Getenv("LDAP_SUB_ATTRIBUTES"); subMappingString != "" {
subMapping = strings.Split(subMappingString, " ")
}

// Use a clone here to avoid changing the config of other possible users of the config.
tlsConfig := config.TLSClientConfig.Clone()
if caCertFile := os.Getenv("LDAP_TLS_CACERT"); caCertFile != "" {
// the path is part of the configuration of the service, it is not user input
// nosemgrep
if pemBytes, err := os.ReadFile(caCertFile); err == nil {
rpool, _ := x509.SystemCertPool()
if rpool.AppendCertsFromPEM(pemBytes) {
tlsConfig.RootCAs = rpool
} else {
return nil, fmt.Errorf("failed to append CA certificate(s) from '%s' to pool", caCertFile)
}
} else {
return nil, fmt.Errorf("failed to read CA certificate(s) from '%s': %w", caCertFile, err)
}
}

identifierBackend, identifierErr := ldap.NewLDAPIdentifierBackend(
config.Config,
tlsConfig,
os.Getenv("LDAP_URI"),
os.Getenv("LDAP_BINDDN"),
os.Getenv("LDAP_BINDPW"),
os.Getenv("LDAP_BASEDN"),
os.Getenv("LDAP_SCOPE"),
os.Getenv("LDAP_FILTER"),
subMapping,
attributeMapping,
)
if identifierErr != nil {
return nil, fmt.Errorf("failed to create identifier backend: %v", identifierErr)
}

var activeBackend backends.Backend = identifierBackend
if wrap != nil {
activeBackend = wrap(activeBackend)
}

fullAuthorizationEndpointURL := bootstrap.WithSchemeAndHost(config.AuthorizationEndpointURI, config.IssuerIdentifierURI)
fullSignInFormURL := bootstrap.WithSchemeAndHost(config.SignInFormURI, config.IssuerIdentifierURI)
fullSignedOutEndpointURL := bootstrap.WithSchemeAndHost(config.SignedOutURI, config.IssuerIdentifierURI)

activeIdentifier, err := identifier.NewIdentifier(&identifier.Config{
Config: config.Config,

BaseURI: config.IssuerIdentifierURI,
PathPrefix: bs.MakeURIPath(bootstrap.APITypeSignin, ""),
StaticFolder: config.IdentifierClientPath,
ScopesConf: config.IdentifierScopesConf,
WebAppDisabled: config.IdentifierClientDisabled,

LogonCookieName: "__Secure-KKT", // Kopano-Konnect-Token
LogonCookieSameSite: config.CookieSameSite,

ConsentCookieSameSite: config.CookieSameSite,

StateCookieSameSite: config.CookieSameSite,

AuthorizationEndpointURI: fullAuthorizationEndpointURL,
SignedOutEndpointURI: fullSignedOutEndpointURL,

DefaultBannerLogo: config.IdentifierDefaultBannerLogo,
DefaultBannerLogoHeight: config.IdentifierDefaultBannerLogoHeight,
DefaultSignInPageText: config.IdentifierDefaultSignInPageText,
DefaultSignInPageLogoURI: config.IdentifierDefaultLogoTargetURI,
DefaultUsernameHintText: config.IdentifierDefaultUsernameHintText,
UILocales: config.IdentifierUILocales,

Backend: activeBackend,
})
if err != nil {
return nil, fmt.Errorf("failed to create identifier: %v", err)
}
err = activeIdentifier.SetKey(config.EncryptionSecret)
if err != nil {
return nil, fmt.Errorf("invalid --encryption-secret parameter value for identifier: %v", err)
}

// Expose the identifier in the managers registry so other managers (e.g.
// signedlogin) can access it without creating a second instance.
bs.Managers().Set("identifier", activeIdentifier)

identityManagerConfig := &identity.Config{
SignInFormURI: fullSignInFormURL,
SignedOutURI: fullSignedOutEndpointURL,

Logger: logger,

ScopesSupported: config.Config.AllowedScopes,
AllowSignedLogin: config.Config.AllowClientSignedLogins,
}

identifierIdentityManager := managers.NewIdentifierIdentityManager(identityManagerConfig, activeIdentifier)
logger.Infoln("using identifier backed identity manager")

return identifierIdentityManager, nil
}
Loading