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

ldap.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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. "code.gitea.io/gitea/modules/log"
  12. ldap "gopkg.in/ldap.v3"
  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. // A search for the user.
  74. userFilter, ok := ls.sanitizedUserQuery(name)
  75. if !ok {
  76. return "", false
  77. }
  78. log.Trace("Searching for DN using filter %s and base %s", userFilter, ls.UserBase)
  79. search := ldap.NewSearchRequest(
  80. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  81. false, userFilter, []string{}, nil)
  82. // Ensure we found a user
  83. sr, err := l.Search(search)
  84. if err != nil || len(sr.Entries) < 1 {
  85. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  86. return "", false
  87. } else if len(sr.Entries) > 1 {
  88. log.Debug("Filter '%s' returned more than one user.", userFilter)
  89. return "", false
  90. }
  91. userDN := sr.Entries[0].DN
  92. if userDN == "" {
  93. log.Error("LDAP search was successful, but found no DN!")
  94. return "", false
  95. }
  96. return userDN, true
  97. }
  98. func dial(ls *Source) (*ldap.Conn, error) {
  99. log.Trace("Dialing LDAP with security protocol (%v) without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
  100. tlsCfg := &tls.Config{
  101. ServerName: ls.Host,
  102. InsecureSkipVerify: ls.SkipVerify,
  103. }
  104. if ls.SecurityProtocol == SecurityProtocolLDAPS {
  105. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
  106. }
  107. conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  108. if err != nil {
  109. return nil, fmt.Errorf("Dial: %v", err)
  110. }
  111. if ls.SecurityProtocol == SecurityProtocolStartTLS {
  112. if err = conn.StartTLS(tlsCfg); err != nil {
  113. conn.Close()
  114. return nil, fmt.Errorf("StartTLS: %v", err)
  115. }
  116. }
  117. return conn, nil
  118. }
  119. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  120. log.Trace("Binding with userDN: %s", userDN)
  121. err := l.Bind(userDN, passwd)
  122. if err != nil {
  123. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  124. return err
  125. }
  126. log.Trace("Bound successfully with userDN: %s", userDN)
  127. return err
  128. }
  129. func checkAdmin(l *ldap.Conn, ls *Source, userDN string) bool {
  130. if len(ls.AdminFilter) > 0 {
  131. log.Trace("Checking admin with filter %s and base %s", ls.AdminFilter, userDN)
  132. search := ldap.NewSearchRequest(
  133. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  134. []string{ls.AttributeName},
  135. nil)
  136. sr, err := l.Search(search)
  137. if err != nil {
  138. log.Error("LDAP Admin Search failed unexpectedly! (%v)", err)
  139. } else if len(sr.Entries) < 1 {
  140. log.Trace("LDAP Admin Search found no matching entries.")
  141. } else {
  142. return true
  143. }
  144. }
  145. return false
  146. }
  147. // SearchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  148. func (ls *Source) SearchEntry(name, passwd string, directBind bool) *SearchResult {
  149. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  150. if len(passwd) == 0 {
  151. log.Debug("Auth. failed for %s, password cannot be empty", name)
  152. return nil
  153. }
  154. l, err := dial(ls)
  155. if err != nil {
  156. log.Error("LDAP Connect error, %s:%v", ls.Host, err)
  157. ls.Enabled = false
  158. return nil
  159. }
  160. defer l.Close()
  161. var userDN string
  162. if directBind {
  163. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  164. var ok bool
  165. userDN, ok = ls.sanitizedUserDN(name)
  166. if !ok {
  167. return nil
  168. }
  169. err = bindUser(l, userDN, passwd)
  170. if err != nil {
  171. return nil
  172. }
  173. if ls.UserBase != "" {
  174. // not everyone has a CN compatible with input name so we need to find
  175. // the real userDN in that case
  176. userDN, ok = ls.findUserDN(l, name)
  177. if !ok {
  178. return nil
  179. }
  180. }
  181. } else {
  182. log.Trace("LDAP will use BindDN.")
  183. var found bool
  184. if ls.BindDN != "" && ls.BindPassword != "" {
  185. err := l.Bind(ls.BindDN, ls.BindPassword)
  186. if err != nil {
  187. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  188. return nil
  189. }
  190. log.Trace("Bound as BindDN %s", ls.BindDN)
  191. } else {
  192. log.Trace("Proceeding with anonymous LDAP search.")
  193. }
  194. userDN, found = ls.findUserDN(l, name)
  195. if !found {
  196. return nil
  197. }
  198. }
  199. if !ls.AttributesInBind {
  200. // binds user (checking password) before looking-up attributes in user context
  201. err = bindUser(l, userDN, passwd)
  202. if err != nil {
  203. return nil
  204. }
  205. }
  206. userFilter, ok := ls.sanitizedUserQuery(name)
  207. if !ok {
  208. return nil
  209. }
  210. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0
  211. attribs := []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail}
  212. if isAttributeSSHPublicKeySet {
  213. attribs = append(attribs, ls.AttributeSSHPublicKey)
  214. }
  215. 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, userDN)
  216. search := ldap.NewSearchRequest(
  217. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  218. attribs, nil)
  219. sr, err := l.Search(search)
  220. if err != nil {
  221. log.Error("LDAP Search failed unexpectedly! (%v)", err)
  222. return nil
  223. } else if len(sr.Entries) < 1 {
  224. if directBind {
  225. log.Trace("User filter inhibited user login.")
  226. } else {
  227. log.Trace("LDAP Search found no matching entries.")
  228. }
  229. return nil
  230. }
  231. var sshPublicKey []string
  232. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  233. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  234. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  235. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  236. if isAttributeSSHPublicKeySet {
  237. sshPublicKey = sr.Entries[0].GetAttributeValues(ls.AttributeSSHPublicKey)
  238. }
  239. isAdmin := checkAdmin(l, ls, userDN)
  240. if !directBind && ls.AttributesInBind {
  241. // binds user (checking password) after looking-up attributes in BindDN context
  242. err = bindUser(l, userDN, passwd)
  243. if err != nil {
  244. return nil
  245. }
  246. }
  247. return &SearchResult{
  248. Username: username,
  249. Name: firstname,
  250. Surname: surname,
  251. Mail: mail,
  252. SSHPublicKey: sshPublicKey,
  253. IsAdmin: isAdmin,
  254. }
  255. }
  256. // UsePagedSearch returns if need to use paged search
  257. func (ls *Source) UsePagedSearch() bool {
  258. return ls.SearchPageSize > 0
  259. }
  260. // SearchEntries : search an LDAP source for all users matching userFilter
  261. func (ls *Source) SearchEntries() ([]*SearchResult, error) {
  262. l, err := dial(ls)
  263. if err != nil {
  264. log.Error("LDAP Connect error, %s:%v", ls.Host, err)
  265. ls.Enabled = false
  266. return nil, err
  267. }
  268. defer l.Close()
  269. if ls.BindDN != "" && ls.BindPassword != "" {
  270. err := l.Bind(ls.BindDN, ls.BindPassword)
  271. if err != nil {
  272. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  273. return nil, err
  274. }
  275. log.Trace("Bound as BindDN %s", ls.BindDN)
  276. } else {
  277. log.Trace("Proceeding with anonymous LDAP search.")
  278. }
  279. userFilter := fmt.Sprintf(ls.Filter, "*")
  280. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0
  281. attribs := []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail}
  282. if isAttributeSSHPublicKeySet {
  283. attribs = append(attribs, ls.AttributeSSHPublicKey)
  284. }
  285. 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)
  286. search := ldap.NewSearchRequest(
  287. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  288. attribs, nil)
  289. var sr *ldap.SearchResult
  290. if ls.UsePagedSearch() {
  291. sr, err = l.SearchWithPaging(search, ls.SearchPageSize)
  292. } else {
  293. sr, err = l.Search(search)
  294. }
  295. if err != nil {
  296. log.Error("LDAP Search failed unexpectedly! (%v)", err)
  297. return nil, err
  298. }
  299. result := make([]*SearchResult, len(sr.Entries))
  300. for i, v := range sr.Entries {
  301. result[i] = &SearchResult{
  302. Username: v.GetAttributeValue(ls.AttributeUsername),
  303. Name: v.GetAttributeValue(ls.AttributeName),
  304. Surname: v.GetAttributeValue(ls.AttributeSurname),
  305. Mail: v.GetAttributeValue(ls.AttributeMail),
  306. IsAdmin: checkAdmin(l, ls, v.DN),
  307. }
  308. if isAttributeSSHPublicKeySet {
  309. result[i].SSHPublicKey = v.GetAttributeValues(ls.AttributeSSHPublicKey)
  310. }
  311. }
  312. return result, nil
  313. }