ldap.go 10 KB

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