ldap.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. Host string // LDAP host
  24. Port int // port number
  25. SecurityProtocol SecurityProtocol
  26. SkipVerify bool
  27. BindDN string `ini:"bind_dn,omitempty"` // DN to bind with
  28. BindPassword string `ini:",omitempty"` // Bind DN password
  29. UserBase string `ini:",omitempty"` // Base search path for users
  30. UserDN string `ini:"user_dn,omitempty"` // Template for the DN of the user for simple auth
  31. AttributeUsername string // Username attribute
  32. AttributeName string // First name attribute
  33. AttributeSurname string // Surname attribute
  34. AttributeMail string // E-mail attribute
  35. AttributesInBind bool // fetch attributes in bind context (not user)
  36. Filter string // Query filter to validate entry
  37. AdminFilter string // Query filter to check if user is admin
  38. GroupEnabled bool // if the group checking is enabled
  39. GroupDN string `ini:"group_dn"` // Group Search Base
  40. GroupFilter string // Group Name Filter
  41. GroupMemberUID string `ini:"group_member_uid"` // Group Attribute containing array of UserUID
  42. UserUID string `ini:"user_uid"` // User Attribute listed in Group
  43. }
  44. func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
  45. // See http://tools.ietf.org/search/rfc4515
  46. badCharacters := "\x00()*\\"
  47. if strings.ContainsAny(username, badCharacters) {
  48. log.Trace("LDAP: Username contains invalid query characters: %s", username)
  49. return "", false
  50. }
  51. return strings.Replace(ls.Filter, "%s", username, -1), true
  52. }
  53. func (ls *Source) sanitizedUserDN(username string) (string, bool) {
  54. // See http://tools.ietf.org/search/rfc4514: "special characters"
  55. badCharacters := "\x00()*\\,='\"#+;<>"
  56. if strings.ContainsAny(username, badCharacters) || strings.HasPrefix(username, " ") || strings.HasSuffix(username, " ") {
  57. log.Trace("LDAP: Username contains invalid query characters: %s", username)
  58. return "", false
  59. }
  60. return strings.Replace(ls.UserDN, "%s", username, -1), true
  61. }
  62. func (ls *Source) sanitizedGroupFilter(group string) (string, bool) {
  63. // See http://tools.ietf.org/search/rfc4515
  64. badCharacters := "\x00*\\"
  65. if strings.ContainsAny(group, badCharacters) {
  66. log.Trace("LDAP: Group filter invalid query characters: %s", group)
  67. return "", false
  68. }
  69. return group, true
  70. }
  71. func (ls *Source) sanitizedGroupDN(groupDn string) (string, bool) {
  72. // See http://tools.ietf.org/search/rfc4514: "special characters"
  73. badCharacters := "\x00()*\\'\"#+;<>"
  74. if strings.ContainsAny(groupDn, badCharacters) || strings.HasPrefix(groupDn, " ") || strings.HasSuffix(groupDn, " ") {
  75. log.Trace("LDAP: Group DN contains invalid query characters: %s", groupDn)
  76. return "", false
  77. }
  78. return groupDn, true
  79. }
  80. func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  81. log.Trace("Search for LDAP user: %s", name)
  82. if len(ls.BindDN) > 0 && len(ls.BindPassword) > 0 {
  83. // Replace placeholders with username
  84. bindDN := strings.Replace(ls.BindDN, "%s", name, -1)
  85. err := l.Bind(bindDN, ls.BindPassword)
  86. if err != nil {
  87. log.Trace("LDAP: Failed to bind as BindDN '%s': %v", bindDN, err)
  88. return "", false
  89. }
  90. log.Trace("LDAP: Bound as BindDN: %s", 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", name)
  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. return "", "", "", "", false, false
  161. }
  162. defer l.Close()
  163. var userDN string
  164. if directBind {
  165. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  166. var ok bool
  167. userDN, ok = ls.sanitizedUserDN(name)
  168. if !ok {
  169. return "", "", "", "", false, false
  170. }
  171. } else {
  172. log.Trace("LDAP will use BindDN")
  173. var found bool
  174. userDN, found = ls.findUserDN(l, name)
  175. if !found {
  176. return "", "", "", "", false, false
  177. }
  178. }
  179. if directBind || !ls.AttributesInBind {
  180. // binds user (checking password) before looking-up attributes in user context
  181. err = bindUser(l, userDN, passwd)
  182. if err != nil {
  183. return "", "", "", "", false, false
  184. }
  185. }
  186. userFilter, ok := ls.sanitizedUserQuery(name)
  187. if !ok {
  188. return "", "", "", "", false, false
  189. }
  190. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v' with filter '%s' and base '%s'",
  191. ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.UserUID, userFilter, userDN)
  192. search := ldap.NewSearchRequest(
  193. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  194. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.UserUID},
  195. nil)
  196. sr, err := l.Search(search)
  197. if err != nil {
  198. log.Error(2, "LDAP: User search failed: %v", err)
  199. return "", "", "", "", false, false
  200. } else if len(sr.Entries) < 1 {
  201. if directBind {
  202. log.Trace("LDAP: User filter inhibited user login")
  203. } else {
  204. log.Trace("LDAP: User search failed: 0 entries")
  205. }
  206. return "", "", "", "", false, false
  207. }
  208. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  209. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  210. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  211. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  212. uid := sr.Entries[0].GetAttributeValue(ls.UserUID)
  213. // Check group membership
  214. if ls.GroupEnabled {
  215. groupFilter, ok := ls.sanitizedGroupFilter(ls.GroupFilter)
  216. if !ok {
  217. return "", "", "", "", false, false
  218. }
  219. groupDN, ok := ls.sanitizedGroupDN(ls.GroupDN)
  220. if !ok {
  221. return "", "", "", "", false, false
  222. }
  223. log.Trace("LDAP: Fetching groups '%v' with filter '%s' and base '%s'", ls.GroupMemberUID, groupFilter, groupDN)
  224. groupSearch := ldap.NewSearchRequest(
  225. groupDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, groupFilter,
  226. []string{ls.GroupMemberUID},
  227. nil)
  228. srg, err := l.Search(groupSearch)
  229. if err != nil {
  230. log.Error(2, "LDAP: Group search failed: %v", err)
  231. return "", "", "", "", false, false
  232. } else if len(srg.Entries) < 1 {
  233. log.Error(2, "LDAP: Group search failed: 0 entries")
  234. return "", "", "", "", false, false
  235. }
  236. isMember := false
  237. if ls.UserUID == "dn" {
  238. for _, group := range srg.Entries {
  239. for _, member := range group.GetAttributeValues(ls.GroupMemberUID) {
  240. if member == sr.Entries[0].DN {
  241. isMember = true
  242. }
  243. }
  244. }
  245. } else {
  246. for _, group := range srg.Entries {
  247. for _, member := range group.GetAttributeValues(ls.GroupMemberUID) {
  248. if member == uid {
  249. isMember = true
  250. }
  251. }
  252. }
  253. }
  254. if !isMember {
  255. log.Trace("LDAP: Group membership test failed [username: %s, group_member_uid: %s, user_uid: %s", username, ls.GroupMemberUID, uid)
  256. return "", "", "", "", false, false
  257. }
  258. }
  259. isAdmin := false
  260. if len(ls.AdminFilter) > 0 {
  261. log.Trace("Checking admin with filter '%s' and base '%s'", ls.AdminFilter, userDN)
  262. search = ldap.NewSearchRequest(
  263. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  264. []string{ls.AttributeName},
  265. nil)
  266. sr, err = l.Search(search)
  267. if err != nil {
  268. log.Error(2, "LDAP: Admin search failed: %v", err)
  269. } else if len(sr.Entries) < 1 {
  270. log.Error(2, "LDAP: Admin search failed: 0 entries")
  271. } else {
  272. isAdmin = true
  273. }
  274. }
  275. if !directBind && ls.AttributesInBind {
  276. // binds user (checking password) after looking-up attributes in BindDN context
  277. err = bindUser(l, userDN, passwd)
  278. if err != nil {
  279. return "", "", "", "", false, false
  280. }
  281. }
  282. return username, firstname, surname, mail, isAdmin, true
  283. }