1
0

config.go 11 KB

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