ldap.go 11 KB

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