You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ldap.go 9.4 kB

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