gitea源码

source_search.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package ldap
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "net"
  9. "strconv"
  10. "strings"
  11. "code.gitea.io/gitea/modules/container"
  12. "code.gitea.io/gitea/modules/log"
  13. "github.com/go-ldap/ldap/v3"
  14. )
  15. // SearchResult : user data
  16. type SearchResult struct {
  17. Username string // Username
  18. Name string // Name
  19. Surname string // Surname
  20. Mail string // E-mail address
  21. SSHPublicKey []string // SSH Public Key
  22. IsAdmin bool // if user is administrator
  23. IsRestricted bool // if user is restricted
  24. LowerName string // LowerName
  25. Avatar []byte
  26. Groups container.Set[string]
  27. }
  28. func (source *Source) sanitizedUserQuery(username string) (string, bool) {
  29. // See http://tools.ietf.org/search/rfc4515
  30. badCharacters := "\x00()*\\"
  31. if strings.ContainsAny(username, badCharacters) {
  32. log.Debug("'%s' contains invalid query characters. Aborting.", username)
  33. return "", false
  34. }
  35. return fmt.Sprintf(source.Filter, username), true
  36. }
  37. func (source *Source) sanitizedUserDN(username string) (string, bool) {
  38. // See http://tools.ietf.org/search/rfc4514: "special characters"
  39. badCharacters := "\x00()*\\,='\"#+;<>"
  40. if strings.ContainsAny(username, badCharacters) {
  41. log.Debug("'%s' contains invalid DN characters. Aborting.", username)
  42. return "", false
  43. }
  44. return fmt.Sprintf(source.UserDN, username), true
  45. }
  46. func (source *Source) sanitizedGroupFilter(group string) (string, bool) {
  47. // See http://tools.ietf.org/search/rfc4515
  48. badCharacters := "\x00*\\"
  49. if strings.ContainsAny(group, badCharacters) {
  50. log.Trace("Group filter invalid query characters: %s", group)
  51. return "", false
  52. }
  53. return group, true
  54. }
  55. func (source *Source) sanitizedGroupDN(groupDn string) (string, bool) {
  56. // See http://tools.ietf.org/search/rfc4514: "special characters"
  57. badCharacters := "\x00()*\\'\"#+;<>"
  58. if strings.ContainsAny(groupDn, badCharacters) || strings.HasPrefix(groupDn, " ") || strings.HasSuffix(groupDn, " ") {
  59. log.Trace("Group DN contains invalid query characters: %s", groupDn)
  60. return "", false
  61. }
  62. return groupDn, true
  63. }
  64. func (source *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  65. log.Trace("Search for LDAP user: %s", name)
  66. // A search for the user.
  67. userFilter, ok := source.sanitizedUserQuery(name)
  68. if !ok {
  69. return "", false
  70. }
  71. log.Trace("Searching for DN using filter %s and base %s", userFilter, source.UserBase)
  72. search := ldap.NewSearchRequest(
  73. source.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  74. false, userFilter, []string{}, nil)
  75. // Ensure we found a user
  76. sr, err := l.Search(search)
  77. if err != nil || len(sr.Entries) < 1 {
  78. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  79. return "", false
  80. } else if len(sr.Entries) > 1 {
  81. log.Debug("Filter '%s' returned more than one user.", userFilter)
  82. return "", false
  83. }
  84. userDN := sr.Entries[0].DN
  85. if userDN == "" {
  86. log.Error("LDAP search was successful, but found no DN!")
  87. return "", false
  88. }
  89. return userDN, true
  90. }
  91. func dial(source *Source) (*ldap.Conn, error) {
  92. log.Trace("Dialing LDAP with security protocol (%v) without verifying: %v", source.SecurityProtocol, source.SkipVerify)
  93. tlsConfig := &tls.Config{
  94. ServerName: source.Host,
  95. InsecureSkipVerify: source.SkipVerify,
  96. }
  97. if source.SecurityProtocol == SecurityProtocolLDAPS {
  98. return ldap.DialTLS("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port)), tlsConfig) //nolint:staticcheck // DialTLS is deprecated
  99. }
  100. conn, err := ldap.Dial("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port))) //nolint:staticcheck // Dial is deprecated
  101. if err != nil {
  102. return nil, fmt.Errorf("error during Dial: %w", err)
  103. }
  104. if source.SecurityProtocol == SecurityProtocolStartTLS {
  105. if err = conn.StartTLS(tlsConfig); err != nil {
  106. conn.Close()
  107. return nil, fmt.Errorf("error during StartTLS: %w", err)
  108. }
  109. }
  110. return conn, nil
  111. }
  112. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  113. log.Trace("Binding with userDN: %s", userDN)
  114. err := l.Bind(userDN, passwd)
  115. if err != nil {
  116. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  117. return err
  118. }
  119. log.Trace("Bound successfully with userDN: %s", userDN)
  120. return err
  121. }
  122. func checkAdmin(l *ldap.Conn, ls *Source, userDN string) bool {
  123. if ls.AdminFilter == "" {
  124. return false
  125. }
  126. log.Trace("Checking admin with filter %s and base %s", ls.AdminFilter, userDN)
  127. search := ldap.NewSearchRequest(
  128. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  129. []string{ls.AttributeName},
  130. nil)
  131. sr, err := l.Search(search)
  132. if err != nil {
  133. log.Error("LDAP Admin Search with filter %s for %s failed unexpectedly! (%v)", ls.AdminFilter, userDN, err)
  134. } else if len(sr.Entries) < 1 {
  135. log.Trace("LDAP Admin Search found no matching entries.")
  136. } else {
  137. return true
  138. }
  139. return false
  140. }
  141. func checkRestricted(l *ldap.Conn, ls *Source, userDN string) bool {
  142. if ls.RestrictedFilter == "" {
  143. return false
  144. }
  145. if ls.RestrictedFilter == "*" {
  146. return true
  147. }
  148. log.Trace("Checking restricted with filter %s and base %s", ls.RestrictedFilter, userDN)
  149. search := ldap.NewSearchRequest(
  150. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.RestrictedFilter,
  151. []string{ls.AttributeName},
  152. nil)
  153. sr, err := l.Search(search)
  154. if err != nil {
  155. log.Error("LDAP Restrictred Search with filter %s for %s failed unexpectedly! (%v)", ls.RestrictedFilter, userDN, err)
  156. } else if len(sr.Entries) < 1 {
  157. log.Trace("LDAP Restricted Search found no matching entries.")
  158. } else {
  159. return true
  160. }
  161. return false
  162. }
  163. // List all group memberships of a user
  164. func (source *Source) listLdapGroupMemberships(l *ldap.Conn, uid string, applyGroupFilter bool) container.Set[string] {
  165. ldapGroups := make(container.Set[string])
  166. groupFilter, ok := source.sanitizedGroupFilter(source.GroupFilter)
  167. if !ok {
  168. return ldapGroups
  169. }
  170. groupDN, ok := source.sanitizedGroupDN(source.GroupDN)
  171. if !ok {
  172. return ldapGroups
  173. }
  174. var searchFilter string
  175. if applyGroupFilter && groupFilter != "" {
  176. searchFilter = fmt.Sprintf("(&(%s)(%s=%s))", groupFilter, source.GroupMemberUID, ldap.EscapeFilter(uid))
  177. } else {
  178. searchFilter = fmt.Sprintf("(%s=%s)", source.GroupMemberUID, ldap.EscapeFilter(uid))
  179. }
  180. result, err := l.Search(ldap.NewSearchRequest(
  181. groupDN,
  182. ldap.ScopeWholeSubtree,
  183. ldap.NeverDerefAliases,
  184. 0,
  185. 0,
  186. false,
  187. searchFilter,
  188. []string{},
  189. nil,
  190. ))
  191. if err != nil {
  192. log.Error("Failed group search in LDAP with filter [%s]: %v", searchFilter, err)
  193. return ldapGroups
  194. }
  195. for _, entry := range result.Entries {
  196. if entry.DN == "" {
  197. log.Error("LDAP search was successful, but found no DN!")
  198. continue
  199. }
  200. ldapGroups.Add(entry.DN)
  201. }
  202. return ldapGroups
  203. }
  204. func (source *Source) getUserAttributeListedInGroup(entry *ldap.Entry) string {
  205. if strings.EqualFold(source.UserUID, "dn") {
  206. return entry.DN
  207. }
  208. return entry.GetAttributeValue(source.UserUID)
  209. }
  210. // SearchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  211. func (source *Source) SearchEntry(name, passwd string, directBind bool) *SearchResult {
  212. if MockedSearchEntry != nil {
  213. return MockedSearchEntry(source, name, passwd, directBind)
  214. }
  215. return realSearchEntry(source, name, passwd, directBind)
  216. }
  217. var MockedSearchEntry func(source *Source, name, passwd string, directBind bool) *SearchResult
  218. func realSearchEntry(source *Source, name, passwd string, directBind bool) *SearchResult {
  219. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  220. if passwd == "" {
  221. log.Debug("Auth. failed for %s, password cannot be empty", name)
  222. return nil
  223. }
  224. l, err := dial(source)
  225. if err != nil {
  226. log.Error("LDAP Connect error, %s:%v", source.Host, err)
  227. source.Enabled = false
  228. return nil
  229. }
  230. defer l.Close()
  231. var userDN string
  232. if directBind {
  233. log.Trace("LDAP will bind directly via UserDN template: %s", source.UserDN)
  234. var ok bool
  235. userDN, ok = source.sanitizedUserDN(name)
  236. if !ok {
  237. return nil
  238. }
  239. err = bindUser(l, userDN, passwd)
  240. if err != nil {
  241. return nil
  242. }
  243. if source.UserBase != "" {
  244. // not everyone has a CN compatible with input name so we need to find
  245. // the real userDN in that case
  246. userDN, ok = source.findUserDN(l, name)
  247. if !ok {
  248. return nil
  249. }
  250. }
  251. } else {
  252. log.Trace("LDAP will use BindDN.")
  253. var found bool
  254. if source.BindDN != "" && source.BindPassword != "" {
  255. err := l.Bind(source.BindDN, source.BindPassword)
  256. if err != nil {
  257. log.Debug("Failed to bind as BindDN[%s]: %v", source.BindDN, err)
  258. return nil
  259. }
  260. log.Trace("Bound as BindDN %s", source.BindDN)
  261. } else {
  262. log.Trace("Proceeding with anonymous LDAP search.")
  263. }
  264. userDN, found = source.findUserDN(l, name)
  265. if !found {
  266. return nil
  267. }
  268. }
  269. if !source.AttributesInBind {
  270. // binds user (checking password) before looking-up attributes in user context
  271. err = bindUser(l, userDN, passwd)
  272. if err != nil {
  273. return nil
  274. }
  275. }
  276. userFilter, ok := source.sanitizedUserQuery(name)
  277. if !ok {
  278. return nil
  279. }
  280. isAttributeSSHPublicKeySet := strings.TrimSpace(source.AttributeSSHPublicKey) != ""
  281. isAttributeAvatarSet := strings.TrimSpace(source.AttributeAvatar) != ""
  282. attribs := []string{source.AttributeUsername, source.AttributeName, source.AttributeSurname, source.AttributeMail}
  283. if strings.TrimSpace(source.UserUID) != "" {
  284. attribs = append(attribs, source.UserUID)
  285. }
  286. if isAttributeSSHPublicKeySet {
  287. attribs = append(attribs, source.AttributeSSHPublicKey)
  288. }
  289. if isAttributeAvatarSet {
  290. attribs = append(attribs, source.AttributeAvatar)
  291. }
  292. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v', '%v', '%v' with filter '%s' and base '%s'", source.AttributeUsername, source.AttributeName, source.AttributeSurname, source.AttributeMail, source.AttributeSSHPublicKey, source.AttributeAvatar, source.UserUID, userFilter, userDN)
  293. search := ldap.NewSearchRequest(
  294. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  295. attribs, nil)
  296. sr, err := l.Search(search)
  297. if err != nil {
  298. log.Error("LDAP Search failed unexpectedly! (%v)", err)
  299. return nil
  300. } else if len(sr.Entries) < 1 {
  301. if directBind {
  302. log.Trace("User filter inhibited user login.")
  303. } else {
  304. log.Trace("LDAP Search found no matching entries.")
  305. }
  306. return nil
  307. }
  308. var sshPublicKey []string
  309. var Avatar []byte
  310. username := sr.Entries[0].GetAttributeValue(source.AttributeUsername)
  311. firstname := sr.Entries[0].GetAttributeValue(source.AttributeName)
  312. surname := sr.Entries[0].GetAttributeValue(source.AttributeSurname)
  313. mail := sr.Entries[0].GetAttributeValue(source.AttributeMail)
  314. if isAttributeSSHPublicKeySet {
  315. sshPublicKey = sr.Entries[0].GetAttributeValues(source.AttributeSSHPublicKey)
  316. }
  317. isAdmin := checkAdmin(l, source, userDN)
  318. var isRestricted bool
  319. if !isAdmin {
  320. isRestricted = checkRestricted(l, source, userDN)
  321. }
  322. if isAttributeAvatarSet {
  323. Avatar = sr.Entries[0].GetRawAttributeValue(source.AttributeAvatar)
  324. }
  325. // Check group membership
  326. var usersLdapGroups container.Set[string]
  327. if source.GroupsEnabled {
  328. userAttributeListedInGroup := source.getUserAttributeListedInGroup(sr.Entries[0])
  329. usersLdapGroups = source.listLdapGroupMemberships(l, userAttributeListedInGroup, true)
  330. if source.GroupFilter != "" && len(usersLdapGroups) == 0 {
  331. return nil
  332. }
  333. }
  334. if !directBind && source.AttributesInBind {
  335. // binds user (checking password) after looking-up attributes in BindDN context
  336. err = bindUser(l, userDN, passwd)
  337. if err != nil {
  338. return nil
  339. }
  340. }
  341. return &SearchResult{
  342. LowerName: strings.ToLower(username),
  343. Username: username,
  344. Name: firstname,
  345. Surname: surname,
  346. Mail: mail,
  347. SSHPublicKey: sshPublicKey,
  348. IsAdmin: isAdmin,
  349. IsRestricted: isRestricted,
  350. Avatar: Avatar,
  351. Groups: usersLdapGroups,
  352. }
  353. }
  354. // UsePagedSearch returns if need to use paged search
  355. func (source *Source) UsePagedSearch() bool {
  356. return source.SearchPageSize > 0
  357. }
  358. // SearchEntries : search an LDAP source for all users matching userFilter
  359. func (source *Source) SearchEntries() ([]*SearchResult, error) {
  360. l, err := dial(source)
  361. if err != nil {
  362. log.Error("LDAP Connect error, %s:%v", source.Host, err)
  363. source.Enabled = false
  364. return nil, err
  365. }
  366. defer l.Close()
  367. if source.BindDN != "" && source.BindPassword != "" {
  368. err := l.Bind(source.BindDN, source.BindPassword)
  369. if err != nil {
  370. log.Debug("Failed to bind as BindDN[%s]: %v", source.BindDN, err)
  371. return nil, err
  372. }
  373. log.Trace("Bound as BindDN %s", source.BindDN)
  374. } else {
  375. log.Trace("Proceeding with anonymous LDAP search.")
  376. }
  377. userFilter := fmt.Sprintf(source.Filter, "*")
  378. isAttributeSSHPublicKeySet := strings.TrimSpace(source.AttributeSSHPublicKey) != ""
  379. isAttributeAvatarSet := strings.TrimSpace(source.AttributeAvatar) != ""
  380. attribs := []string{source.AttributeUsername, source.AttributeName, source.AttributeSurname, source.AttributeMail, source.UserUID}
  381. if isAttributeSSHPublicKeySet {
  382. attribs = append(attribs, source.AttributeSSHPublicKey)
  383. }
  384. if isAttributeAvatarSet {
  385. attribs = append(attribs, source.AttributeAvatar)
  386. }
  387. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v', '%v' with filter %s and base %s", source.AttributeUsername, source.AttributeName, source.AttributeSurname, source.AttributeMail, source.AttributeSSHPublicKey, source.AttributeAvatar, userFilter, source.UserBase)
  388. search := ldap.NewSearchRequest(
  389. source.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  390. attribs, nil)
  391. var sr *ldap.SearchResult
  392. if source.UsePagedSearch() {
  393. sr, err = l.SearchWithPaging(search, source.SearchPageSize)
  394. } else {
  395. sr, err = l.Search(search)
  396. }
  397. if err != nil {
  398. log.Error("LDAP Search failed unexpectedly! (%v)", err)
  399. return nil, err
  400. }
  401. result := make([]*SearchResult, 0, len(sr.Entries))
  402. for _, v := range sr.Entries {
  403. var usersLdapGroups container.Set[string]
  404. if source.GroupsEnabled {
  405. userAttributeListedInGroup := source.getUserAttributeListedInGroup(v)
  406. if source.GroupFilter != "" {
  407. usersLdapGroups = source.listLdapGroupMemberships(l, userAttributeListedInGroup, true)
  408. if len(usersLdapGroups) == 0 {
  409. continue
  410. }
  411. }
  412. if source.GroupTeamMap != "" || source.GroupTeamMapRemoval {
  413. usersLdapGroups = source.listLdapGroupMemberships(l, userAttributeListedInGroup, false)
  414. }
  415. }
  416. user := &SearchResult{
  417. Username: v.GetAttributeValue(source.AttributeUsername),
  418. Name: v.GetAttributeValue(source.AttributeName),
  419. Surname: v.GetAttributeValue(source.AttributeSurname),
  420. Mail: v.GetAttributeValue(source.AttributeMail),
  421. IsAdmin: checkAdmin(l, source, v.DN),
  422. Groups: usersLdapGroups,
  423. }
  424. if !user.IsAdmin {
  425. user.IsRestricted = checkRestricted(l, source, v.DN)
  426. }
  427. if isAttributeSSHPublicKeySet {
  428. user.SSHPublicKey = v.GetAttributeValues(source.AttributeSSHPublicKey)
  429. }
  430. if isAttributeAvatarSet {
  431. user.Avatar = v.GetRawAttributeValue(source.AttributeAvatar)
  432. }
  433. user.LowerName = strings.ToLower(user.Username)
  434. result = append(result, user)
  435. }
  436. return result, nil
  437. }