From efc05ea1dec5a60c95763fc5158d60b45ef46d8f Mon Sep 17 00:00:00 2001 From: juju2013 Date: Tue, 22 Apr 2014 18:55:27 +0200 Subject: [PATCH] initial support for LDAP authentication/MSAD --- .gitignore | 1 + models/ldap.go | 38 ++++++++++++++++ models/user.go | 1 + modules/auth/ldap/README.md | 43 +++++++++++++++++++ modules/auth/ldap/ldap.go | 86 +++++++++++++++++++++++++++++++++++++ modules/base/conf.go | 44 ++++++++++++++++--- routers/user/user.go | 11 ++++- 7 files changed, 216 insertions(+), 8 deletions(-) create mode 100644 models/ldap.go create mode 100644 modules/auth/ldap/README.md create mode 100644 modules/auth/ldap/ldap.go diff --git a/.gitignore b/.gitignore index f8d8a286..65252f8c 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ public/img/avatar/ *.o *.a *.so +dev # Folders _obj diff --git a/models/ldap.go b/models/ldap.go new file mode 100644 index 00000000..cc905876 --- /dev/null +++ b/models/ldap.go @@ -0,0 +1,38 @@ +// Copyright github.com/juju2013. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package models + +import ( + "strings" + + "github.com/gogits/gogs/modules/auth/ldap" + "github.com/gogits/gogs/modules/log" +) + +// Query if name/passwd can login against the LDAP direcotry pool +// Create a local user if success +// Return the same LoginUserPlain semantic +func LoginUserLdap(name, passwd string) (*User, error) { + mail, logged := ldap.LoginUser(name, passwd) + if !logged { + // user not in LDAP, do nothing + return nil, ErrUserNotExist + } + // fake a local user creation + user := User{ + LowerName: strings.ToLower(name), + Name: strings.ToLower(name), + LoginType: 389, + IsActive: true, + Passwd: passwd, + Email: mail} + _, err := RegisterUser(&user) + if err != nil { + log.Debug("LDAP local user %s fond (%s) ", name, err) + } + // simulate local user login + localUser, err2 := GetUserByName(user.Name) + return localUser, err2 +} diff --git a/models/user.go b/models/user.go index ab43df7a..df1eb985 100644 --- a/models/user.go +++ b/models/user.go @@ -125,6 +125,7 @@ func GetUserSalt() string { // RegisterUser creates record of a new user. func RegisterUser(user *User) (*User, error) { + if !IsLegalName(user.Name) { return nil, ErrUserNameIllegal } diff --git a/modules/auth/ldap/README.md b/modules/auth/ldap/README.md new file mode 100644 index 00000000..8b508e0f --- /dev/null +++ b/modules/auth/ldap/README.md @@ -0,0 +1,43 @@ +LDAP authentication +=================== + +## Goal + +Authenticat user against LDAP directories + +It will bind with the user's login/pasword and query attributs ("mail" for instance) in a pool of directory servers + +The first OK wins. + +If there's connection error, the server will be disabled and won't be checked again + +## Usage + +In the [security] section, set +> LDAP_AUTH = true + +then for each LDAP source, set + +> [LdapSource-someuniquename] +> name=canonicalName +> host=hostname-or-ip +> port=3268 # or regular LDAP port +> # the following settings depend highly how you've configured your AD +> basedn=dc=ACME,dc=COM +> MSADSAFORMAT=%s@ACME.COM +> filter=(&(objectClass=user)(sAMAccountName=%s)) + +### Limitation + +Only tested on an MS 2008R2 DC, using global catalog (TCP/3268) + +This MSAD is a mess. + +The way how one checks the directory (CN, DN etc...) may be highly depending local custom configuration + +### Todo +* Define a timeout per server +* Check servers marked as "Disabled" when they'll come back online +* Find a more flexible way to define filter/MSADSAFORMAT/Attributes etc... maybe text/template ? +* Check OpenLDAP server +* SSL support ? \ No newline at end of file diff --git a/modules/auth/ldap/ldap.go b/modules/auth/ldap/ldap.go new file mode 100644 index 00000000..29773cda --- /dev/null +++ b/modules/auth/ldap/ldap.go @@ -0,0 +1,86 @@ +// Copyright github.com/juju2013. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +// package ldap provide functions & structure to query a LDAP ldap directory +// For now, it's mainly tested again an MS Active Directory service, see README.md for more information +package ldap + +import ( + "fmt" + "github.com/gogits/gogs/modules/log" + goldap "github.com/juju2013/goldap" +) + +// Basic LDAP authentication service +type ldapsource struct { + Name string // canonical name (ie. corporate.ad) + Host string // LDAP host + Port int // port number + BaseDN string // Base DN + Attributes string // Attribut to search + Filter string // Query filter to validate entry + MsAdSAFormat string // in the case of MS AD Simple Authen, the format to use (see: http://msdn.microsoft.com/en-us/library/cc223499.aspx) + Enabled bool // if this source is disabled +} + +//Global LDAP directory pool +var ( + Authensource []ldapsource +) + +// Add a new source (LDAP directory) to the global pool +func AddSource(name string, host string, port int, basedn string, attributes string, filter string, msadsaformat string) { + ldaphost := ldapsource{name, host, port, basedn, attributes, filter, msadsaformat, true} + Authensource = append(Authensource, ldaphost) +} + +//LoginUser : try to login an user to LDAP sources, return requested (attribut,true) if ok, ("",false) other wise +//First match wins +//Returns first attribute if exists +func LoginUser(name, passwd string) (a string, r bool) { + r = false + for _, ls := range Authensource { + a, r = ls.searchEntry(name, passwd) + if r { + return + } + } + return +} + +// searchEntry : search an LDAP source if an entry (name, passwd) is valide and in the specific filter +func (ls ldapsource) searchEntry(name, passwd string) (string, bool) { + l, err := goldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port)) + if err != nil { + log.Debug("LDAP Connect error, disabled source %s", ls.Host) + ls.Enabled = false + return "", false + } + defer l.Close() + + nx := fmt.Sprintf(ls.MsAdSAFormat, name) + err = l.Bind(nx, passwd) + if err != nil { + log.Debug("LDAP Authan failed for %s, reason: %s", nx, err.Error()) + return "", false + } + + search := goldap.NewSearchRequest( + ls.BaseDN, + goldap.ScopeWholeSubtree, goldap.NeverDerefAliases, 0, 0, false, + fmt.Sprintf(ls.Filter, name), + []string{ls.Attributes}, + nil) + sr, err := l.Search(search) + if err != nil { + log.Debug("LDAP Authen OK but not in filter %s", name) + return "", false + } + log.Debug("LDAP Authen OK: %s", name) + if len(sr.Entries) > 0 { + r := sr.Entries[0].GetAttributeValue(ls.Attributes) + return r, true + } + return "", true +} diff --git a/modules/base/conf.go b/modules/base/conf.go index abb67f6d..57245045 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -10,6 +10,7 @@ import ( "os/exec" "path" "path/filepath" + "regexp" "strings" "github.com/Unknwon/com" @@ -19,6 +20,7 @@ import ( "github.com/gogits/cache" "github.com/gogits/session" + "github.com/gogits/gogs/modules/auth/ldap" "github.com/gogits/gogs/modules/log" ) @@ -51,6 +53,7 @@ var ( Domain string SecretKey string RunUser string + LdapAuth bool RepoRootPath string ScriptType string @@ -83,13 +86,13 @@ var ( ) var Service struct { - RegisterEmailConfirm bool - DisableRegistration bool - RequireSignInView bool - EnableCacheAvatar bool - NotifyMail bool - ActiveCodeLives int - ResetPwdCodeLives int + RegisterEmailConfirm bool + DisableRegistration bool + RequireSignInView bool + EnableCacheAvatar bool + NotifyMail bool + ActiveCodeLives int + ResetPwdCodeLives int } func ExecDir() (string, error) { @@ -310,6 +313,33 @@ func NewConfigContext() { CookieUserName = Cfg.MustValue("security", "COOKIE_USERNAME") CookieRememberName = Cfg.MustValue("security", "COOKIE_REMEMBER_NAME") + // load LDAP authentication configuration if present + LdapAuth = Cfg.MustBool("security", "LDAP_AUTH", false) + if LdapAuth { + log.Debug("LDAP AUTHENTICATION activated") + nbsrc := 0 + for _, v := range Cfg.GetSectionList() { + if matched, _ := regexp.MatchString("(?i)^LDAPSOURCE.*", v); matched { + ldapname := Cfg.MustValue(v, "name", v) + ldaphost := Cfg.MustValue(v, "host") + ldapport := Cfg.MustInt(v, "port", 389) + ldapbasedn := Cfg.MustValue(v, "basedn", "dc=*,dc=*") + ldapattribute := Cfg.MustValue(v, "attribute", "mail") + ldapfilter := Cfg.MustValue(v, "filter", "(*)") + ldapmsadsaformat := Cfg.MustValue(v, "MSADSAFORMAT", "%s") + ldap.AddSource(ldapname, ldaphost, ldapport, ldapbasedn, ldapattribute, ldapfilter, ldapmsadsaformat) + nbsrc += 1 + log.Debug("%s added as LDAP source", ldapname) + } + } + if nbsrc == 0 { + log.Debug("No valide LDAP found, LDAP AUTHENTICATION NOT activated") + LdapAuth = false + } + } else { + log.Debug("LDAP AUTHENTICATION NOT activated") + } + PictureService = Cfg.MustValue("picture", "SERVICE") // Determine and create root git reposiroty path. diff --git a/routers/user/user.go b/routers/user/user.go index 7decd72d..75314237 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -89,7 +89,16 @@ func SignInPost(ctx *middleware.Context, form auth.LogInForm) { return } - user, err := models.LoginUserPlain(form.UserName, form.Password) + var user *models.User + var err error + // try to login against LDAP if defined + if base.LdapAuth { + user, err = models.LoginUserLdap(form.UserName, form.Password) + } + // try local if not LDAP or it's failed + if (!base.LdapAuth) || (err != nil) { + user, err = models.LoginUserPlain(form.UserName, form.Password) + } if err != nil { if err == models.ErrUserNotExist { log.Trace("%s Log in failed: %s/%s", ctx.Req.RequestURI, form.UserName, form.Password)