config.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. ldap "github.com/go-ldap/ldap/v3"
  12. log "unknwon.dev/clog/v2"
  13. )
  14. // SecurityProtocol is the security protocol when the authenticate provider talks to LDAP directory.
  15. type SecurityProtocol int
  16. // ⚠️ WARNING: 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. // SecurityProtocolName returns the human-readable name for given security protocol.
  23. func SecurityProtocolName(protocol SecurityProtocol) string {
  24. return map[SecurityProtocol]string{
  25. SecurityProtocolUnencrypted: "Unencrypted",
  26. SecurityProtocolLDAPS: "LDAPS",
  27. SecurityProtocolStartTLS: "StartTLS",
  28. }[protocol]
  29. }
  30. // Config contains configuration for LDAP authentication.
  31. //
  32. // ⚠️ WARNING: Change to the field name must preserve the INI key name for backward compatibility.
  33. type Config struct {
  34. Host string // LDAP host
  35. Port int // Port number
  36. SecurityProtocol SecurityProtocol
  37. SkipVerify bool
  38. BindDN string `ini:"bind_dn,omitempty"` // DN to bind with
  39. BindPassword string `ini:",omitempty"` // Bind DN password
  40. UserBase string `ini:",omitempty"` // Base search path for users
  41. UserDN string `ini:"user_dn,omitempty"` // Template for the DN of the user for simple auth
  42. AttributeUsername string // Username attribute
  43. AttributeName string // First name attribute
  44. AttributeSurname string // Surname attribute
  45. AttributeMail string // Email attribute
  46. AttributesInBind bool // Fetch attributes in bind context (not user)
  47. Filter string // Query filter to validate entry
  48. AdminFilter string // Query filter to check if user is admin
  49. GroupEnabled bool // Whether the group checking is enabled
  50. GroupDN string `ini:"group_dn"` // Group search base
  51. GroupFilter string // Group name filter
  52. GroupMemberUID string `ini:"group_member_uid"` // Group Attribute containing array of UserUID
  53. UserUID string `ini:"user_uid"` // User Attribute listed in group
  54. }
  55. func (c *Config) SecurityProtocolName() string {
  56. return SecurityProtocolName(c.SecurityProtocol)
  57. }
  58. func (c *Config) sanitizedUserQuery(username string) (string, bool) {
  59. // See http://tools.ietf.org/search/rfc4515
  60. badCharacters := "\x00()*\\"
  61. if strings.ContainsAny(username, badCharacters) {
  62. log.Trace("LDAP: Username contains invalid query characters: %s", username)
  63. return "", false
  64. }
  65. return strings.ReplaceAll(c.Filter, "%s", username), true
  66. }
  67. func (c *Config) sanitizedUserDN(username string) (string, bool) {
  68. // See http://tools.ietf.org/search/rfc4514: "special characters"
  69. badCharacters := "\x00()*\\,='\"#+;<>"
  70. if strings.ContainsAny(username, badCharacters) || strings.HasPrefix(username, " ") || strings.HasSuffix(username, " ") {
  71. log.Trace("LDAP: Username contains invalid query characters: %s", username)
  72. return "", false
  73. }
  74. return strings.ReplaceAll(c.UserDN, "%s", username), true
  75. }
  76. func (*Config) sanitizedGroupFilter(group string) (string, bool) {
  77. // See http://tools.ietf.org/search/rfc4515
  78. badCharacters := "\x00*\\"
  79. if strings.ContainsAny(group, badCharacters) {
  80. log.Trace("LDAP: Group filter invalid query characters: %s", group)
  81. return "", false
  82. }
  83. return group, true
  84. }
  85. func (*Config) sanitizedGroupDN(groupDn string) (string, bool) {
  86. // See http://tools.ietf.org/search/rfc4514: "special characters"
  87. badCharacters := "\x00()*\\'\"#+;<>"
  88. if strings.ContainsAny(groupDn, badCharacters) || strings.HasPrefix(groupDn, " ") || strings.HasSuffix(groupDn, " ") {
  89. log.Trace("LDAP: Group DN contains invalid query characters: %s", groupDn)
  90. return "", false
  91. }
  92. return groupDn, true
  93. }
  94. func (c *Config) findUserDN(l *ldap.Conn, name string) (string, bool) {
  95. log.Trace("Search for LDAP user: %s", name)
  96. if len(c.BindDN) > 0 && len(c.BindPassword) > 0 {
  97. // Replace placeholders with username
  98. bindDN := strings.ReplaceAll(c.BindDN, "%s", name)
  99. err := l.Bind(bindDN, c.BindPassword)
  100. if err != nil {
  101. log.Trace("LDAP: Failed to bind as BindDN '%s': %v", bindDN, err)
  102. return "", false
  103. }
  104. log.Trace("LDAP: Bound as BindDN: %s", bindDN)
  105. } else {
  106. log.Trace("LDAP: Proceeding with anonymous LDAP search")
  107. }
  108. // A search for the user.
  109. userFilter, ok := c.sanitizedUserQuery(name)
  110. if !ok {
  111. return "", false
  112. }
  113. log.Trace("LDAP: Searching for DN using filter %q and base %q", userFilter, c.UserBase)
  114. search := ldap.NewSearchRequest(
  115. c.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  116. false, userFilter, []string{}, nil)
  117. // Ensure we found a user
  118. sr, err := l.Search(search)
  119. if err != nil || len(sr.Entries) < 1 {
  120. log.Trace("LDAP: Failed to search using filter %q: %v", userFilter, err)
  121. return "", false
  122. } else if len(sr.Entries) > 1 {
  123. log.Trace("LDAP: Filter %q returned more than one user", userFilter)
  124. return "", false
  125. }
  126. userDN := sr.Entries[0].DN
  127. if userDN == "" {
  128. log.Error("LDAP: Search was successful, but found no DN!")
  129. return "", false
  130. }
  131. return userDN, true
  132. }
  133. func dial(ls *Config) (*ldap.Conn, error) {
  134. log.Trace("LDAP: Dialing with security protocol '%v' without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
  135. tlsCfg := &tls.Config{
  136. ServerName: ls.Host,
  137. InsecureSkipVerify: ls.SkipVerify,
  138. }
  139. if ls.SecurityProtocol == SecurityProtocolLDAPS {
  140. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
  141. }
  142. conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  143. if err != nil {
  144. return nil, fmt.Errorf("Dial: %v", err)
  145. }
  146. if ls.SecurityProtocol == SecurityProtocolStartTLS {
  147. if err = conn.StartTLS(tlsCfg); err != nil {
  148. conn.Close()
  149. return nil, fmt.Errorf("StartTLS: %v", err)
  150. }
  151. }
  152. return conn, nil
  153. }
  154. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  155. log.Trace("Binding with userDN: %s", userDN)
  156. err := l.Bind(userDN, passwd)
  157. if err != nil {
  158. log.Trace("LDAP authentication failed for '%s': %v", userDN, err)
  159. return err
  160. }
  161. log.Trace("Bound successfully with userDN: %s", userDN)
  162. return err
  163. }
  164. // searchEntry searches an LDAP source if an entry (name, passwd) is valid and in the specific filter.
  165. func (c *Config) searchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  166. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  167. if passwd == "" {
  168. log.Trace("authentication failed for '%s' with empty password", name)
  169. return "", "", "", "", false, false
  170. }
  171. l, err := dial(c)
  172. if err != nil {
  173. log.Error("LDAP connect failed for '%s': %v", c.Host, err)
  174. return "", "", "", "", false, false
  175. }
  176. defer l.Close()
  177. var userDN string
  178. if directBind {
  179. log.Trace("LDAP will bind directly via UserDN template: %s", c.UserDN)
  180. var ok bool
  181. userDN, ok = c.sanitizedUserDN(name)
  182. if !ok {
  183. return "", "", "", "", false, false
  184. }
  185. } else {
  186. log.Trace("LDAP will use BindDN")
  187. var found bool
  188. userDN, found = c.findUserDN(l, name)
  189. if !found {
  190. return "", "", "", "", false, false
  191. }
  192. }
  193. if directBind || !c.AttributesInBind {
  194. // binds user (checking password) before looking-up attributes in user context
  195. err = bindUser(l, userDN, passwd)
  196. if err != nil {
  197. return "", "", "", "", false, false
  198. }
  199. }
  200. userFilter, ok := c.sanitizedUserQuery(name)
  201. if !ok {
  202. return "", "", "", "", false, false
  203. }
  204. log.Trace("Fetching attributes %q, %q, %q, %q, %q with user filter %q and user DN %q",
  205. c.AttributeUsername, c.AttributeName, c.AttributeSurname, c.AttributeMail, c.UserUID, userFilter, userDN)
  206. search := ldap.NewSearchRequest(
  207. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  208. []string{c.AttributeUsername, c.AttributeName, c.AttributeSurname, c.AttributeMail, c.UserUID},
  209. nil)
  210. sr, err := l.Search(search)
  211. if err != nil {
  212. log.Error("LDAP: User search failed: %v", err)
  213. return "", "", "", "", false, false
  214. } else if len(sr.Entries) < 1 {
  215. if directBind {
  216. log.Trace("LDAP: User filter inhibited user login")
  217. } else {
  218. log.Trace("LDAP: User search failed: 0 entries")
  219. }
  220. return "", "", "", "", false, false
  221. }
  222. username := sr.Entries[0].GetAttributeValue(c.AttributeUsername)
  223. firstname := sr.Entries[0].GetAttributeValue(c.AttributeName)
  224. surname := sr.Entries[0].GetAttributeValue(c.AttributeSurname)
  225. mail := sr.Entries[0].GetAttributeValue(c.AttributeMail)
  226. uid := sr.Entries[0].GetAttributeValue(c.UserUID)
  227. // Check group membership
  228. if c.GroupEnabled {
  229. groupFilter, ok := c.sanitizedGroupFilter(c.GroupFilter)
  230. if !ok {
  231. return "", "", "", "", false, false
  232. }
  233. groupDN, ok := c.sanitizedGroupDN(c.GroupDN)
  234. if !ok {
  235. return "", "", "", "", false, false
  236. }
  237. log.Trace("LDAP: Fetching groups '%v' with filter '%s' and base '%s'", c.GroupMemberUID, groupFilter, groupDN)
  238. groupSearch := ldap.NewSearchRequest(
  239. groupDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, groupFilter,
  240. []string{c.GroupMemberUID},
  241. nil)
  242. srg, err := l.Search(groupSearch)
  243. if err != nil {
  244. log.Error("LDAP: Group search failed: %v", err)
  245. return "", "", "", "", false, false
  246. } else if len(srg.Entries) < 1 {
  247. log.Trace("LDAP: Group search returned no entries")
  248. return "", "", "", "", false, false
  249. }
  250. isMember := false
  251. if c.UserUID == "dn" {
  252. for _, group := range srg.Entries {
  253. for _, member := range group.GetAttributeValues(c.GroupMemberUID) {
  254. if member == sr.Entries[0].DN {
  255. isMember = true
  256. }
  257. }
  258. }
  259. } else {
  260. for _, group := range srg.Entries {
  261. for _, member := range group.GetAttributeValues(c.GroupMemberUID) {
  262. if member == uid {
  263. isMember = true
  264. }
  265. }
  266. }
  267. }
  268. if !isMember {
  269. log.Trace("LDAP: Group membership test failed [username: %s, group_member_uid: %s, user_uid: %s", username, c.GroupMemberUID, uid)
  270. return "", "", "", "", false, false
  271. }
  272. }
  273. isAdmin := false
  274. if len(c.AdminFilter) > 0 {
  275. log.Trace("Checking admin with filter '%s' and base '%s'", c.AdminFilter, userDN)
  276. search = ldap.NewSearchRequest(
  277. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, c.AdminFilter,
  278. []string{c.AttributeName},
  279. nil)
  280. sr, err = l.Search(search)
  281. if err != nil {
  282. log.Error("LDAP: Admin search failed: %v", err)
  283. } else if len(sr.Entries) < 1 {
  284. log.Trace("LDAP: Admin search returned no entries")
  285. } else {
  286. isAdmin = true
  287. }
  288. }
  289. if !directBind && c.AttributesInBind {
  290. // binds user (checking password) after looking-up attributes in BindDN context
  291. err = bindUser(l, userDN, passwd)
  292. if err != nil {
  293. return "", "", "", "", false, false
  294. }
  295. }
  296. return username, firstname, surname, mail, isAdmin, true
  297. }