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 10 kB

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