ldap.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 len(ls.BindDN) > 0 && len(ls.BindPassword) > 0 {
  85. // Replace placeholders with username
  86. bindDN := strings.Replace(ls.BindDN, "%s", name, -1)
  87. err := l.Bind(bindDN, ls.BindPassword)
  88. if err != nil {
  89. log.Trace("LDAP: Failed to bind as BindDN '%s': %v", bindDN, err)
  90. return "", false
  91. }
  92. log.Trace("LDAP: Bound as BindDN: %s", bindDN)
  93. } else {
  94. log.Trace("LDAP: Proceeding with anonymous LDAP search")
  95. }
  96. // A search for the user.
  97. userFilter, ok := ls.sanitizedUserQuery(name)
  98. if !ok {
  99. return "", false
  100. }
  101. log.Trace("LDAP: Searching for DN using filter '%s' and base '%s'", userFilter, ls.UserBase)
  102. search := ldap.NewSearchRequest(
  103. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  104. false, userFilter, []string{}, nil)
  105. // Ensure we found a user
  106. sr, err := l.Search(search)
  107. if err != nil || len(sr.Entries) < 1 {
  108. log.Trace("LDAP: Failed search using filter '%s': %v", userFilter, err)
  109. return "", false
  110. } else if len(sr.Entries) > 1 {
  111. log.Trace("LDAP: Filter '%s' returned more than one user", userFilter)
  112. return "", false
  113. }
  114. userDN := sr.Entries[0].DN
  115. if userDN == "" {
  116. log.Error(2, "LDAP: Search was successful, but found no DN!")
  117. return "", false
  118. }
  119. return userDN, true
  120. }
  121. func dial(ls *Source) (*ldap.Conn, error) {
  122. log.Trace("LDAP: Dialing with security protocol '%v' without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
  123. tlsCfg := &tls.Config{
  124. ServerName: ls.Host,
  125. InsecureSkipVerify: ls.SkipVerify,
  126. }
  127. if ls.SecurityProtocol == SECURITY_PROTOCOL_LDAPS {
  128. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
  129. }
  130. conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  131. if err != nil {
  132. return nil, fmt.Errorf("Dial: %v", err)
  133. }
  134. if ls.SecurityProtocol == SECURITY_PROTOCOL_START_TLS {
  135. if err = conn.StartTLS(tlsCfg); err != nil {
  136. conn.Close()
  137. return nil, fmt.Errorf("StartTLS: %v", err)
  138. }
  139. }
  140. return conn, nil
  141. }
  142. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  143. log.Trace("Binding with userDN: %s", userDN)
  144. err := l.Bind(userDN, passwd)
  145. if err != nil {
  146. log.Trace("LDAP authentication failed for '%s': %v", userDN, err)
  147. return err
  148. }
  149. log.Trace("Bound successfully with userDN: %s", userDN)
  150. return err
  151. }
  152. // searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  153. func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  154. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  155. if len(passwd) == 0 {
  156. log.Trace("authentication failed for '%s' with empty password")
  157. return "", "", "", "", false, false
  158. }
  159. l, err := dial(ls)
  160. if err != nil {
  161. log.Error(2, "LDAP connect failed for '%s': %v", ls.Host, err)
  162. ls.Enabled = false
  163. return "", "", "", "", false, false
  164. }
  165. defer l.Close()
  166. var userDN string
  167. if directBind {
  168. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  169. var ok bool
  170. userDN, ok = ls.sanitizedUserDN(name)
  171. if !ok {
  172. return "", "", "", "", false, false
  173. }
  174. } else {
  175. log.Trace("LDAP will use BindDN")
  176. var found bool
  177. userDN, found = ls.findUserDN(l, name)
  178. if !found {
  179. return "", "", "", "", false, false
  180. }
  181. }
  182. if directBind || !ls.AttributesInBind {
  183. // binds user (checking password) before looking-up attributes in user context
  184. err = bindUser(l, userDN, passwd)
  185. if err != nil {
  186. return "", "", "", "", false, false
  187. }
  188. }
  189. userFilter, ok := ls.sanitizedUserQuery(name)
  190. if !ok {
  191. return "", "", "", "", false, false
  192. }
  193. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v' with filter '%s' and base '%s'",
  194. ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.UserUID, userFilter, userDN)
  195. search := ldap.NewSearchRequest(
  196. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  197. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.UserUID},
  198. nil)
  199. sr, err := l.Search(search)
  200. if err != nil {
  201. log.Error(2, "LDAP: User search failed: %v", err)
  202. return "", "", "", "", false, false
  203. } else if len(sr.Entries) < 1 {
  204. if directBind {
  205. log.Trace("LDAP: User filter inhibited user login")
  206. } else {
  207. log.Trace("LDAP: User search failed: 0 entries")
  208. }
  209. return "", "", "", "", false, false
  210. }
  211. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  212. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  213. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  214. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  215. uid := sr.Entries[0].GetAttributeValue(ls.UserUID)
  216. // Check group membership
  217. if ls.GroupEnabled {
  218. groupFilter, ok := ls.sanitizedGroupFilter(ls.GroupFilter)
  219. if !ok {
  220. return "", "", "", "", false, false
  221. }
  222. groupDN, ok := ls.sanitizedGroupDN(ls.GroupDN)
  223. if !ok {
  224. return "", "", "", "", false, false
  225. }
  226. log.Trace("LDAP: Fetching groups '%v' with filter '%s' and base '%s'", ls.GroupMemberUID, groupFilter, groupDN)
  227. groupSearch := ldap.NewSearchRequest(
  228. groupDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, groupFilter,
  229. []string{ls.GroupMemberUID},
  230. nil)
  231. srg, err := l.Search(groupSearch)
  232. if err != nil {
  233. log.Error(2, "LDAP: Group search failed: %v", err)
  234. return "", "", "", "", false, false
  235. } else if len(sr.Entries) < 1 {
  236. log.Error(2, "LDAP: Group search failed: 0 entries")
  237. return "", "", "", "", false, false
  238. }
  239. isMember := false
  240. for _, group := range srg.Entries {
  241. for _, member := range group.GetAttributeValues(ls.GroupMemberUID) {
  242. if member == uid {
  243. isMember = true
  244. }
  245. }
  246. }
  247. if !isMember {
  248. log.Trace("LDAP: Group membership test failed [username: %s, group_member_uid: %s, user_uid: %s", username, ls.GroupMemberUID, uid)
  249. return "", "", "", "", false, false
  250. }
  251. }
  252. isAdmin := false
  253. if len(ls.AdminFilter) > 0 {
  254. log.Trace("Checking admin with filter '%s' and base '%s'", ls.AdminFilter, userDN)
  255. search = ldap.NewSearchRequest(
  256. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  257. []string{ls.AttributeName},
  258. nil)
  259. sr, err = l.Search(search)
  260. if err != nil {
  261. log.Error(2, "LDAP: Admin search failed: %v", err)
  262. } else if len(sr.Entries) < 1 {
  263. log.Error(2, "LDAP: Admin search failed: 0 entries")
  264. } else {
  265. isAdmin = true
  266. }
  267. }
  268. if !directBind && ls.AttributesInBind {
  269. // binds user (checking password) after looking-up attributes in BindDN context
  270. err = bindUser(l, userDN, passwd)
  271. if err != nil {
  272. return "", "", "", "", false, false
  273. }
  274. }
  275. return username, firstname, surname, mail, isAdmin, true
  276. }