* feature (auth): required schema changes for auth ldap method (#2669) chore (auth/ldap): move schema changes to next avail migration number * feature (auth/ldap): define AuthMethod and all its value objects (#2703) * feature (auth/ldap): storage protos * feature (auth/ldap): define AuthMethod and all its value objects * feature (auth/ldap): add repo and reading an auth method (#2718) * feature (auth/ldap): add Repository.CreateAuthMethod(...) and Repository.DeleteAuthMethod(...) (#2724) * feature (auth/ldap): add Repository.UpdateAuthMethod(...) (#2739) * feature (auth/ldap): add Account * feature (auth/ldap): add AuthMethod.EnableGroups * fix (auth/ldap): refactor AuthMethod.oplog to enforce proper constraints * feature (auth/ldap): add Account repo functions * refactor (auth/ldap): remove entry attributes from account Realized the entry attributes could have absolutely anything in them (including binary data) and since we absolutely don't have to have them there's just no reason to take on the risk. * feature (auth/ldap): add AuthMethod.UseTokenGroups * feature (auth/ldap): add Authenticate(...) * refactor (auth/ldap): ensure options take a context as the 1st parameter * feature (auth/ldap): add Account attribute maps * chore (auth/ldap): make fmt deltas * feature (auth/ldap): add managed groups (#2760) * tests (auth/ldap): add missing unit test to Repository.DeleteAccount(...) Add bits to test the delete operation when you're not able to generate oplog metadata * feature (auth/ldap): add managed groups fixup! feature (auth/ldap): add managed groups (#2760) * feature (auth/ldap): service proto definition (#2761) * feature (handlers/authmethods): add handlers for ldap auth method operations (#2794) * feature (auth/ldap): add Account attribute maps * chore (auth/ldap): update cap/ldap to latest version * feature (auth/ldap): add ldap api generation definitions * feature (authmethods): add ldap repo NewService(...) * feature (authmethods/ldap): add proper mask_mapping to protobufs * feature (authmethods): add support to get an ldap auth method * refactor (auth/ldap): export TestGenerateCA(...) * feature (authmethods): add support to create an ldap auth method * feature (authmethods): add support to delete an ldap auth method * feature (authmethods): add support to list ldap auth methods * refactor (auth/ldap): make urls optional for NewAuthMethod(...) * refactor (auth/ldap): export ldap.TestInvalidPem * chore: make fmt changes * fix (auth/ldap): properly handle group search config Add constraints and tests to ensure when an ldap AuthMethod.EnableGroups is true, and UseTokenGroups is false; that there's a GroupDn configured for finding a user's associated groups * feature (authmethods): add support to update an ldap auth methods * chore (db/ldap): tmp mv migrations so there's no conflict with ongoing work * feature (verifier): add ldap auth method to verifier bits * fix (controller): prevent panic when controller stops when there's no listener * feature (authmethods): add support to authenticate via ldap auth methods * chore (migrations): fix whitespace in stmt * chore: fmt fixup * tests (auth/ldap): invalid err msg * feature (cli/authmethods): add support for ldap auth-methods CRUD and authenticate (#2810) * feature (authmethods): add CLI support for ldap auth methods CRUD * tests (api/auth): ldap auth method classification tests * feature (authmethods): add CLI support for ldap auth authenticate * feature (auth/ldap): set request timeouts for ldap server connections * feature (handlers/authmethods): handle u_anon listing properly. * feature (account/handers): ldap account and managed group CRUDL APIs (#2852) * feature (auth/ldap) add repository Listing of ManagedGroupMemberAccount * feature (controller/handlers): add ldapRepoFn to accounts service * feature (auth/ldap) register ldap managed group subtype * feature (account/handlers): ldap account CRUDL APIs * feature (controller/handlers): add ldapRepo to managed groups service * feature (account/handlers): ldap managed group CRUDL APIs * docs (domain): add LDAP accounts, auth-methods and managed groups (#2857) * feature (ldap/cli) add ldap accounts and managed groups CRUDL commands (#2856) * fix (handlers/authmethods): fix ldap authorized actions (#2892) * feature (cli/ldap/authenticate): use primary auth method if none is provided (#2890) * fix (auth/ldap): support setting the state attribute * feature (cli/ldap/authenticate): use primary auth method if none is provided * feature (wh/ldap) add tests for new ldap auth method and accounts (#2919) * refactor (migrations/ldap): mv to correct directory * chore: add copyright headers * fix (api/authmethods/ldap): renumber new LdapAuthMethodAttributes field * fix (auth/ldap): allow the auth method state to be updated (#2951) * chore: update sdk and api versions for llb - this is tmp until merging * tests (managed groups): add required errContains for new test
367 lines
13 KiB
Go
367 lines
13 KiB
Go
// Copyright (c) HashiCorp, Inc.
|
|
// SPDX-License-Identifier: MPL-2.0
|
|
|
|
package authmethods
|
|
|
|
import (
|
|
"context"
|
|
"crypto/x509"
|
|
"encoding/pem"
|
|
"fmt"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"github.com/hashicorp/boundary/internal/auth/ldap"
|
|
ldapstore "github.com/hashicorp/boundary/internal/auth/ldap/store"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/auth"
|
|
"github.com/hashicorp/boundary/internal/daemon/controller/handlers"
|
|
"github.com/hashicorp/boundary/internal/errors"
|
|
pbs "github.com/hashicorp/boundary/internal/gen/controller/api/services"
|
|
"github.com/hashicorp/boundary/internal/types/action"
|
|
pb "github.com/hashicorp/boundary/sdk/pbs/controller/api/resources/authmethods"
|
|
"google.golang.org/grpc/codes"
|
|
)
|
|
|
|
var ldapMaskManager handlers.MaskManager
|
|
|
|
func init() {
|
|
var err error
|
|
if ldapMaskManager, err = handlers.NewMaskManager(handlers.MaskDestination{&ldapstore.AuthMethod{}}, handlers.MaskSource{&pb.AuthMethod{}, &pb.LdapAuthMethodAttributes{}}); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
IdActions[ldap.Subtype] = action.ActionSet{
|
|
action.NoOp,
|
|
action.Read,
|
|
action.Update,
|
|
action.Delete,
|
|
action.Authenticate,
|
|
}
|
|
}
|
|
|
|
const (
|
|
urlsField = "attributes.urls"
|
|
bindDnField = "attributes.bind_dn"
|
|
bindPasswordField = "attributes.bind_password"
|
|
clientCertificateField = "attributes.client_certificate"
|
|
clientCertificateKeyField = "attributes.client_certificate_key"
|
|
certificatesField = "attributes.certificates"
|
|
accountAttributesMapField = "attributes.account_attribute_maps"
|
|
)
|
|
|
|
func (s Service) authenticateLdap(ctx context.Context, req *pbs.AuthenticateRequest, authResults *auth.VerifyResults) (*pbs.AuthenticateResponse, error) {
|
|
const op = "authmethod_service.(Service).authenticateLdap"
|
|
if req == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil request.")
|
|
}
|
|
if authResults == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "Nil auth results.")
|
|
}
|
|
reqAttrs := req.GetLdapLoginAttributes()
|
|
|
|
ldapRepo, err := s.ldapRepoFn()
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
ldapFn := func() (ldap.Authenticator, error) {
|
|
return ldapRepo, nil
|
|
}
|
|
|
|
iamRepo, err := s.iamRepoFn()
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
iamFn := func() (ldap.LookupUser, error) {
|
|
return iamRepo, nil
|
|
}
|
|
|
|
atRepo, err := s.atRepoFn()
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
atFn := func() (ldap.AuthTokenCreator, error) {
|
|
return atRepo, nil
|
|
}
|
|
|
|
rawTk, err := ldap.Authenticate(ctx, ldapFn, iamFn, atFn, req.GetAuthMethodId(), reqAttrs.GetLoginName(), reqAttrs.GetPassword())
|
|
if err != nil {
|
|
// let's not send back too much info about the error
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Unauthenticated, "Unable to authenticate.")
|
|
}
|
|
tk, err := s.ConvertInternalAuthTokenToApiAuthToken(
|
|
ctx,
|
|
rawTk,
|
|
)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
|
|
return s.convertToAuthenticateResponse(ctx, req, authResults, tk)
|
|
}
|
|
|
|
// createLdapInRepo creates an ldap auth method in a repo and returns the result.
|
|
// This method should never return a nil AuthMethod without returning an error.
|
|
func (s Service) createLdapInRepo(ctx context.Context, scopeId string, item *pb.AuthMethod) (*ldap.AuthMethod, error) {
|
|
u, err := toStorageLdapAuthMethod(ctx, scopeId, item)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
repo, err := s.ldapRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out, err := repo.CreateAuthMethod(ctx, u)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to create auth method: %w", err)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func (s Service) updateLdapInRepo(ctx context.Context, scopeId, id string, mask []string, item *pb.AuthMethod) (*ldap.AuthMethod, error) {
|
|
u, err := toStorageLdapAuthMethod(ctx, scopeId, item)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
version := item.GetVersion()
|
|
u.PublicId = id
|
|
|
|
dbMask := ldapMaskManager.Translate(mask)
|
|
if len(dbMask) == 0 {
|
|
return nil, handlers.InvalidArgumentErrorf("No valid fields included in the update mask.", map[string]string{"update_mask": "No valid fields provided in the update mask."})
|
|
}
|
|
|
|
repo, err := s.ldapRepoFn()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out, rowsUpdated, err := repo.UpdateAuthMethod(ctx, u, version, dbMask)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("unable to update auth method: %w", err)
|
|
}
|
|
if rowsUpdated == 0 {
|
|
return nil, handlers.NotFoundErrorf("AuthMethod %q doesn't exist or incorrect version provided or no changes were made to the existing AuthMethod.", id)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func toStorageLdapAuthMethod(ctx context.Context, scopeId string, in *pb.AuthMethod) (out *ldap.AuthMethod, err error) {
|
|
const op = "authmethod_service.toStorageLdapAuthMethod"
|
|
if in == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, "nil auth method.")
|
|
}
|
|
attrs := in.GetLdapAuthMethodsAttributes()
|
|
|
|
var opts []ldap.Option
|
|
if in.GetName() != nil {
|
|
opts = append(opts, ldap.WithName(ctx, in.GetName().GetValue()))
|
|
}
|
|
if in.GetDescription() != nil {
|
|
opts = append(opts, ldap.WithDescription(ctx, in.GetDescription().GetValue()))
|
|
}
|
|
var urls []*url.URL
|
|
if attrs != nil {
|
|
if attrs.GetState() != "" {
|
|
opts = append(opts, ldap.WithOperationalState(ctx, ldap.AuthMethodState(attrs.GetState())))
|
|
}
|
|
if attrs.StartTls {
|
|
opts = append(opts, ldap.WithStartTLS(ctx))
|
|
}
|
|
if attrs.InsecureTls {
|
|
opts = append(opts, ldap.WithInsecureTLS(ctx))
|
|
}
|
|
if attrs.DiscoverDn {
|
|
opts = append(opts, ldap.WithDiscoverDn(ctx))
|
|
}
|
|
if attrs.AnonGroupSearch {
|
|
opts = append(opts, ldap.WithAnonGroupSearch(ctx))
|
|
}
|
|
if attrs.UpnDomain.GetValue() != "" {
|
|
opts = append(opts, ldap.WithUpnDomain(ctx, attrs.UpnDomain.GetValue()))
|
|
}
|
|
if attrs.UserDn.GetValue() != "" {
|
|
opts = append(opts, ldap.WithUserDn(ctx, attrs.UserDn.GetValue()))
|
|
}
|
|
if attrs.UserAttr.GetValue() != "" {
|
|
opts = append(opts, ldap.WithUserAttr(ctx, attrs.UserAttr.GetValue()))
|
|
}
|
|
if attrs.UserFilter.GetValue() != "" {
|
|
opts = append(opts, ldap.WithUserFilter(ctx, attrs.UserFilter.GetValue()))
|
|
}
|
|
if attrs.EnableGroups {
|
|
opts = append(opts, ldap.WithEnableGroups(ctx))
|
|
}
|
|
if attrs.GroupDn.GetValue() != "" {
|
|
opts = append(opts, ldap.WithGroupDn(ctx, attrs.GroupDn.GetValue()))
|
|
}
|
|
if attrs.GroupAttr.GetValue() != "" {
|
|
opts = append(opts, ldap.WithGroupAttr(ctx, attrs.GroupAttr.GetValue()))
|
|
}
|
|
if attrs.GroupFilter.GetValue() != "" {
|
|
opts = append(opts, ldap.WithGroupFilter(ctx, attrs.GroupFilter.GetValue()))
|
|
}
|
|
if len(attrs.Certificates) > 0 {
|
|
certs, err := ldap.ParseCertificates(ctx, attrs.Certificates...)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
opts = append(opts, ldap.WithCertificates(ctx, certs...))
|
|
}
|
|
if attrs.ClientCertificate != nil || attrs.ClientCertificateKey != nil {
|
|
keyBlk, _ := pem.Decode([]byte(attrs.ClientCertificateKey.GetValue()))
|
|
if keyBlk == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unable to parse %s PEM", clientCertificateKeyField))
|
|
}
|
|
certBlk, _ := pem.Decode([]byte(attrs.ClientCertificate.GetValue()))
|
|
if certBlk == nil {
|
|
return nil, errors.New(ctx, errors.InvalidParameter, op, fmt.Sprintf("unable to parse %s PEM", clientCertificateField))
|
|
}
|
|
cc, err := x509.ParseCertificate(certBlk.Bytes)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse %s ASN.1 DER", clientCertificateField))
|
|
}
|
|
opts = append(opts, ldap.WithClientCertificate(ctx, keyBlk.Bytes, cc))
|
|
}
|
|
if attrs.BindDn.GetValue() != "" || attrs.BindPassword.GetValue() != "" {
|
|
opts = append(opts, ldap.WithBindCredential(ctx, attrs.BindDn.GetValue(), attrs.BindPassword.GetValue()))
|
|
}
|
|
if attrs.UseTokenGroups {
|
|
opts = append(opts, ldap.WithUseTokenGroups(ctx))
|
|
}
|
|
if len(attrs.AccountAttributeMaps) > 0 {
|
|
attribMaps, err := ldap.ParseAccountAttributeMaps(ctx, attrs.AccountAttributeMaps...)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse %s", accountAttributesMapField))
|
|
}
|
|
fromToMap := map[string]ldap.AccountToAttribute{}
|
|
for _, m := range attribMaps {
|
|
fromToMap[m.From] = ldap.AccountToAttribute(m.To)
|
|
}
|
|
opts = append(opts, ldap.WithAccountAttributeMap(ctx, fromToMap))
|
|
}
|
|
|
|
if len(attrs.GetUrls()) > 0 {
|
|
urls = make([]*url.URL, 0, len(attrs.GetUrls()))
|
|
for _, urlStr := range attrs.GetUrls() {
|
|
u, err := url.Parse(urlStr)
|
|
if err != nil {
|
|
return nil, errors.Wrap(ctx, err, op, errors.WithMsg("unable to parse %q into a url", urlStr))
|
|
}
|
|
urls = append(urls, u)
|
|
}
|
|
opts = append(opts, ldap.WithUrls(ctx, urls...))
|
|
}
|
|
}
|
|
u, err := ldap.NewAuthMethod(ctx, scopeId, opts...)
|
|
if err != nil {
|
|
switch {
|
|
case errors.Match(errors.T(errors.InvalidParameter), err):
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.InvalidArgument, err.Error())
|
|
default:
|
|
return nil, handlers.ApiErrorWithCodeAndMessage(codes.Internal, "Unable to build auth method: %v.", err)
|
|
}
|
|
}
|
|
return u, nil
|
|
}
|
|
|
|
// validateLdapAttributes implements a handlers.CustomValidatorFunc(...) to be
|
|
// used when validating requests with ldap attributes.
|
|
func validateLdapAttributes(ctx context.Context, attrs *pb.LdapAuthMethodAttributes, badFields map[string]string) {
|
|
if attrs == nil {
|
|
// LDAP attributes are required when creating an LDAP auth method.
|
|
// badFields[attributesField] = "Attributes are required for creating an LDAP auth method."
|
|
return
|
|
}
|
|
if len(attrs.GetUrls()) > 0 {
|
|
badUrlMsgs := []string{}
|
|
for _, rawUrl := range attrs.GetUrls() {
|
|
u, err := url.Parse(rawUrl)
|
|
if err != nil {
|
|
badUrlMsgs = append(badUrlMsgs, fmt.Sprintf("%q is not a valid url", rawUrl))
|
|
continue
|
|
}
|
|
if u.Scheme != "ldap" && u.Scheme != "ldaps" {
|
|
badUrlMsgs = append(badUrlMsgs, fmt.Sprintf("%s scheme in url %q is not either ldap or ldaps", u.Scheme, u.String()))
|
|
}
|
|
}
|
|
if len(badUrlMsgs) > 0 {
|
|
badFields[urlsField] = strings.Join(badUrlMsgs, " / ")
|
|
}
|
|
}
|
|
if len(attrs.GetCertificates()) > 0 {
|
|
if _, err := ldap.ParseCertificates(ctx, attrs.GetCertificates()...); err != nil {
|
|
badFields[certificatesField] = fmt.Sprintf("invalid %s: %s", certificatesField, err.Error())
|
|
}
|
|
}
|
|
if attrs.GetBindDn().GetValue() != "" && attrs.GetBindPassword().GetValue() == "" {
|
|
badFields[bindPasswordField] = fmt.Sprintf("%s is missing required %s field", bindDnField, bindPasswordField)
|
|
}
|
|
if attrs.GetBindPassword().GetValue() != "" && attrs.GetBindDn().GetValue() == "" {
|
|
badFields[bindDnField] = fmt.Sprintf("%s is missing required %s field", bindPasswordField, bindDnField)
|
|
}
|
|
if attrs.GetClientCertificate().GetValue() != "" && attrs.GetClientCertificateKey().GetValue() == "" {
|
|
badFields[clientCertificateKeyField] = fmt.Sprintf("%s is missing required %s field", clientCertificateField, clientCertificateKeyField)
|
|
}
|
|
if attrs.GetClientCertificateKey().GetValue() != "" && attrs.GetClientCertificate().GetValue() == "" {
|
|
badFields[clientCertificateField] = fmt.Sprintf("%s is missing required %s field", clientCertificateKeyField, clientCertificateField)
|
|
}
|
|
if attrs.GetClientCertificate().GetValue() != "" {
|
|
if _, err := ldap.ParseCertificates(ctx, attrs.GetClientCertificate().GetValue()); err != nil {
|
|
badFields[clientCertificateField] = fmt.Sprintf("invalid %s: %s", clientCertificateField, err.Error())
|
|
}
|
|
}
|
|
if attrs.GetClientCertificateKey().GetValue() != "" {
|
|
blk, _ := pem.Decode([]byte(attrs.GetClientCertificateKey().GetValue()))
|
|
if blk == nil || blk.Bytes == nil {
|
|
badFields[clientCertificateKeyField] = fmt.Sprintf("%s is not encoded as a valid pem", clientCertificateKeyField)
|
|
} else {
|
|
if _, err := x509.ParsePKCS8PrivateKey(blk.Bytes); err != nil {
|
|
badFields[clientCertificateKeyField] = fmt.Sprintf("%s is not a valid private key", clientCertificateKeyField)
|
|
}
|
|
}
|
|
}
|
|
if len(attrs.AccountAttributeMaps) > 0 {
|
|
if _, err := ldap.ParseAccountAttributeMaps(ctx, attrs.AccountAttributeMaps...); err != nil {
|
|
badFields[accountAttributesMapField] = fmt.Sprintf("invalid %s (unable to parse)", accountAttributesMapField)
|
|
}
|
|
}
|
|
}
|
|
|
|
func validateAuthenticateLdapRequest(req *pbs.AuthenticateRequest) error {
|
|
badFields := make(map[string]string)
|
|
|
|
attrs := req.GetLdapLoginAttributes()
|
|
switch {
|
|
case attrs == nil:
|
|
badFields["attributes"] = "This is a required field."
|
|
default:
|
|
if attrs.LoginName == "" {
|
|
badFields["attributes.login_name"] = "This is a required field."
|
|
}
|
|
if attrs.Password == "" {
|
|
badFields["attributes.password"] = "This is a required field."
|
|
}
|
|
if req.GetCommand() == "" {
|
|
// TODO: Eventually, require a command. For now, fall back to "login" for backwards compat.
|
|
req.Command = loginCommand
|
|
}
|
|
if req.Command != loginCommand {
|
|
badFields[commandField] = "Invalid command for this auth method type."
|
|
}
|
|
tokenType := req.GetType()
|
|
if tokenType == "" {
|
|
// Fall back to deprecated field if type is not set
|
|
tokenType = req.GetTokenType() //nolint:all
|
|
}
|
|
tType := strings.ToLower(strings.TrimSpace(tokenType))
|
|
if tType != "" && tType != "token" && tType != "cookie" {
|
|
badFields[tokenTypeField] = `The only accepted types are "token" and "cookie".`
|
|
}
|
|
}
|
|
|
|
if len(badFields) > 0 {
|
|
return handlers.InvalidArgumentErrorf("Invalid fields provided in request.", badFields)
|
|
}
|
|
return nil
|
|
}
|