ldap.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package ldap provide functions & structure to query a LDAP ldap directory
  5. // For now, it's mainly tested again an MS Active Directory service, see README.md for more information
  6. package ldap
  7. import (
  8. "crypto/tls"
  9. "fmt"
  10. "strings"
  11. log "gopkg.in/clog.v1"
  12. "gopkg.in/ldap.v2"
  13. )
  14. type SecurityProtocol int
  15. // Note: new type must be added at the end of list to maintain compatibility.
  16. const (
  17. SECURITY_PROTOCOL_UNENCRYPTED SecurityProtocol = iota
  18. SECURITY_PROTOCOL_LDAPS
  19. SECURITY_PROTOCOL_START_TLS
  20. )
  21. // Basic LDAP authentication service
  22. type Source struct {
  23. Name string // canonical name (ie. corporate.ad)
  24. Host string // LDAP host
  25. Port int // port number
  26. SecurityProtocol SecurityProtocol
  27. SkipVerify bool
  28. BindDN string // DN to bind with
  29. BindPassword string // Bind DN password
  30. UserBase string // Base search path for users
  31. UserDN string // Template for the DN of the user for simple auth
  32. AttributeUsername string // Username attribute
  33. AttributeName string // First name attribute
  34. AttributeSurname string // Surname attribute
  35. AttributeMail string // E-mail attribute
  36. AttributesInBind bool // fetch attributes in bind context (not user)
  37. Filter string // Query filter to validate entry
  38. AdminFilter string // Query filter to check if user is admin
  39. GroupEnabled bool // if the group checking is enabled
  40. GroupDN string // Group Search Base
  41. GroupFilter string // Group Name Filter
  42. GroupMemberUID string // Group Attribute containing array of UserUID
  43. UserUID string // User Attribute listed in Group
  44. Enabled bool // if this source is disabled
  45. }
  46. func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
  47. // See http://tools.ietf.org/search/rfc4515
  48. badCharacters := "\x00()*\\"
  49. if strings.ContainsAny(username, badCharacters) {
  50. log.Trace("LDAP: Username contains invalid query characters: %s", username)
  51. return "", false
  52. }
  53. return fmt.Sprintf(ls.Filter, username), true
  54. }
  55. func (ls *Source) sanitizedUserDN(username string) (string, bool) {
  56. // See http://tools.ietf.org/search/rfc4514: "special characters"
  57. badCharacters := "\x00()*\\,='\"#+;<>"
  58. if strings.ContainsAny(username, badCharacters) || strings.HasPrefix(username, " ") || strings.HasSuffix(username, " ") {
  59. log.Trace("LDAP: Username contains invalid query characters: %s", username)
  60. return "", false
  61. }
  62. return fmt.Sprintf(ls.UserDN, username), true
  63. }
  64. func (ls *Source) sanitizedGroupFilter(group string) (string, bool) {
  65. // See http://tools.ietf.org/search/rfc4515
  66. badCharacters := "\x00*\\"
  67. if strings.ContainsAny(group, badCharacters) {
  68. log.Trace("LDAP: Group filter invalid query characters: %s", group)
  69. return "", false
  70. }
  71. return group, true
  72. }
  73. func (ls *Source) sanitizedGroupDN(groupDn string) (string, bool) {
  74. // See http://tools.ietf.org/search/rfc4514: "special characters"
  75. badCharacters := "\x00()*\\'\"#+;<>"
  76. if strings.ContainsAny(groupDn, badCharacters) || strings.HasPrefix(groupDn, " ") || strings.HasSuffix(groupDn, " ") {
  77. log.Trace("LDAP: Group DN contains invalid query characters: %s", groupDn)
  78. return "", false
  79. }
  80. return groupDn, true
  81. }
  82. func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  83. log.Trace("Search for LDAP user: %s", name)
  84. if ls.BindDN != "" && ls.BindPassword != "" {
  85. err := l.Bind(ls.BindDN, ls.BindPassword)
  86. if err != nil {
  87. log.Trace("LDAP: Failed to bind as BindDN '%s': %v", ls.BindDN, err)
  88. return "", false
  89. }
  90. log.Trace("LDAP: Bound as BindDN: %s", ls.BindDN)
  91. } else {
  92. log.Trace("LDAP: Proceeding with anonymous LDAP search")
  93. }
  94. // A search for the user.
  95. userFilter, ok := ls.sanitizedUserQuery(name)
  96. if !ok {
  97. return "", false
  98. }
  99. log.Trace("LDAP: Searching for DN using filter '%s' and base '%s'", userFilter, ls.UserBase)
  100. search := ldap.NewSearchRequest(
  101. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  102. false, userFilter, []string{}, nil)
  103. // Ensure we found a user
  104. sr, err := l.Search(search)
  105. if err != nil || len(sr.Entries) < 1 {
  106. log.Trace("LDAP: Failed search using filter '%s': %v", userFilter, err)
  107. return "", false
  108. } else if len(sr.Entries) > 1 {
  109. log.Trace("LDAP: Filter '%s' returned more than one user", userFilter)
  110. return "", false
  111. }
  112. userDN := sr.Entries[0].DN
  113. if userDN == "" {
  114. log.Error(2, "LDAP: Search was successful, but found no DN!")
  115. return "", false
  116. }
  117. return userDN, true
  118. }
  119. func dial(ls *Source) (*ldap.Conn, error) {
  120. log.Trace("LDAP: Dialing with security protocol '%v' without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
  121. tlsCfg := &tls.Config{
  122. ServerName: ls.Host,
  123. InsecureSkipVerify: ls.SkipVerify,
  124. }
  125. if ls.SecurityProtocol == SECURITY_PROTOCOL_LDAPS {
  126. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
  127. }
  128. conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  129. if err != nil {
  130. return nil, fmt.Errorf("Dial: %v", err)
  131. }
  132. if ls.SecurityProtocol == SECURITY_PROTOCOL_START_TLS {
  133. if err = conn.StartTLS(tlsCfg); err != nil {
  134. conn.Close()
  135. return nil, fmt.Errorf("StartTLS: %v", err)
  136. }
  137. }
  138. return conn, nil
  139. }
  140. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  141. log.Trace("Binding with userDN: %s", userDN)
  142. err := l.Bind(userDN, passwd)
  143. if err != nil {
  144. log.Trace("LDAP authentication failed for '%s': %v", userDN, err)
  145. return err
  146. }
  147. log.Trace("Bound successfully with userDN: %s", userDN)
  148. return err
  149. }
  150. // searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  151. func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  152. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  153. if len(passwd) == 0 {
  154. log.Trace("authentication failed for '%s' with empty password")
  155. return "", "", "", "", false, false
  156. }
  157. l, err := dial(ls)
  158. if err != nil {
  159. log.Error(2, "LDAP connect failed for '%s': %v", ls.Host, err)
  160. ls.Enabled = false
  161. return "", "", "", "", false, false
  162. }
  163. defer l.Close()
  164. var userDN string
  165. if directBind {
  166. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  167. var ok bool
  168. userDN, ok = ls.sanitizedUserDN(name)
  169. if !ok {
  170. return "", "", "", "", false, false
  171. }
  172. } else {
  173. log.Trace("LDAP will use BindDN")
  174. var found bool
  175. userDN, found = ls.findUserDN(l, name)
  176. if !found {
  177. return "", "", "", "", false, false
  178. }
  179. }
  180. if directBind || !ls.AttributesInBind {
  181. // binds user (checking password) before looking-up attributes in user context
  182. err = bindUser(l, userDN, passwd)
  183. if err != nil {
  184. return "", "", "", "", false, false
  185. }
  186. }
  187. userFilter, ok := ls.sanitizedUserQuery(name)
  188. if !ok {
  189. return "", "", "", "", false, false
  190. }
  191. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v' with filter '%s' and base '%s'",
  192. ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.UserUID, userFilter, userDN)
  193. search := ldap.NewSearchRequest(
  194. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  195. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.UserUID},
  196. nil)
  197. sr, err := l.Search(search)
  198. if err != nil {
  199. log.Error(2, "LDAP: User search failed: %v", err)
  200. return "", "", "", "", false, false
  201. } else if len(sr.Entries) < 1 {
  202. if directBind {
  203. log.Trace("LDAP: User filter inhibited user login")
  204. } else {
  205. log.Trace("LDAP: User search failed: 0 entries")
  206. }
  207. return "", "", "", "", false, false
  208. }
  209. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  210. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  211. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  212. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  213. uid := sr.Entries[0].GetAttributeValue(ls.UserUID)
  214. // Check group membership
  215. if ls.GroupEnabled {
  216. groupFilter, ok := ls.sanitizedGroupFilter(ls.GroupFilter)
  217. if !ok {
  218. return "", "", "", "", false, false
  219. }
  220. groupDN, ok := ls.sanitizedGroupDN(ls.GroupDN)
  221. if !ok {
  222. return "", "", "", "", false, false
  223. }
  224. log.Trace("LDAP: Fetching groups '%v' with filter '%s' and base '%s'", ls.GroupMemberUID, groupFilter, groupDN)
  225. groupSearch := ldap.NewSearchRequest(
  226. groupDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, groupFilter,
  227. []string{ls.GroupMemberUID},
  228. nil)
  229. srg, err := l.Search(groupSearch)
  230. if err != nil {
  231. log.Error(2, "LDAP: Group search failed: %v", err)
  232. return "", "", "", "", false, false
  233. } else if len(sr.Entries) < 1 {
  234. log.Error(2, "LDAP: Group search failed: 0 entries")
  235. return "", "", "", "", false, false
  236. }
  237. isMember := false
  238. for _, group := range srg.Entries {
  239. for _, member := range group.GetAttributeValues(ls.GroupMemberUID) {
  240. if member == uid {
  241. isMember = true
  242. }
  243. }
  244. }
  245. if !isMember {
  246. log.Trace("LDAP: Group membership test failed [username: %s, group_member_uid: %s, user_uid: %s", username, ls.GroupMemberUID, uid)
  247. return "", "", "", "", false, false
  248. }
  249. }
  250. isAdmin := false
  251. if len(ls.AdminFilter) > 0 {
  252. log.Trace("Checking admin with filter '%s' and base '%s'", ls.AdminFilter, userDN)
  253. search = ldap.NewSearchRequest(
  254. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  255. []string{ls.AttributeName},
  256. nil)
  257. sr, err = l.Search(search)
  258. if err != nil {
  259. log.Error(2, "LDAP: Admin search failed: %v", err)
  260. } else if len(sr.Entries) < 1 {
  261. log.Error(2, "LDAP: Admin search failed: 0 entries")
  262. } else {
  263. isAdmin = true
  264. }
  265. }
  266. if !directBind && ls.AttributesInBind {
  267. // binds user (checking password) after looking-up attributes in BindDN context
  268. err = bindUser(l, userDN, passwd)
  269. if err != nil {
  270. return "", "", "", "", false, false
  271. }
  272. }
  273. return username, firstname, surname, mail, isAdmin, true
  274. }