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 12KB

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