ldap.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. package service
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "net/url"
  8. "os"
  9. "strconv"
  10. "strings"
  11. "github.com/go-ldap/ldap/v3"
  12. "github.com/lejianwen/rustdesk-api/v2/config"
  13. "github.com/lejianwen/rustdesk-api/v2/model"
  14. )
  15. var (
  16. ErrUrlParseFailed = errors.New("UrlParseFailed")
  17. ErrFileReadFailed = errors.New("FileReadFailed")
  18. ErrLdapNotEnabled = errors.New("LdapNotEnabled")
  19. ErrLdapUserDisabled = errors.New("UserDisabledAtLdap")
  20. ErrLdapUserNotFound = errors.New("UserNotFound")
  21. ErrLdapMailNotMatch = errors.New("MailNotMatch")
  22. ErrLdapConnectFailed = errors.New("LdapConnectFailed")
  23. ErrLdapSearchFailed = errors.New("LdapSearchRequestFailed")
  24. ErrLdapTlsFailed = errors.New("LdapStartTLSFailed")
  25. ErrLdapBindService = errors.New("LdapBindServiceFailed")
  26. ErrLdapBindFailed = errors.New("LdapBindFailed")
  27. ErrLdapToLocalUserFailed = errors.New("LdapToLocalUserFailed")
  28. ErrLdapCreateUserFailed = errors.New("LdapCreateUserFailed")
  29. ErrLdapPasswordNotMatch = errors.New("PasswordNotMatch")
  30. )
  31. // LdapService is responsible for LDAP authentication and user synchronization.
  32. type LdapService struct {
  33. }
  34. // LdapUser represents the user attributes retrieved from LDAP.
  35. type LdapUser struct {
  36. Dn string
  37. Username string
  38. Email string
  39. FirstName string
  40. LastName string
  41. MemberOf []string
  42. EnableAttrValue string
  43. Enabled bool
  44. }
  45. // Name returns the full name of an LDAP user.
  46. func (lu *LdapUser) Name() string {
  47. return fmt.Sprintf("%s %s", lu.FirstName, lu.LastName)
  48. }
  49. // ToUser merges the LdapUser data into a provided *model.User.
  50. // If 'u' is nil, it creates and returns a new *model.User.
  51. func (lu *LdapUser) ToUser(u *model.User) *model.User {
  52. if u == nil {
  53. u = &model.User{}
  54. }
  55. u.Username = lu.Username
  56. u.Email = lu.Email
  57. u.Nickname = lu.Name()
  58. if lu.Enabled {
  59. u.Status = model.COMMON_STATUS_ENABLE
  60. } else {
  61. u.Status = model.COMMON_STATUS_DISABLED
  62. }
  63. return u
  64. }
  65. // connectAndBind creates an LDAP connection, optionally starts TLS, and then binds using the provided credentials.
  66. func (ls *LdapService) connectAndBind(cfg *config.Ldap, username, password string) (*ldap.Conn, error) {
  67. u, err := url.Parse(cfg.Url)
  68. if err != nil {
  69. return nil, errors.Join(ErrUrlParseFailed, err)
  70. }
  71. var conn *ldap.Conn
  72. if u.Scheme == "ldaps" {
  73. // WARNING: InsecureSkipVerify: true is not recommended for production
  74. tlsConfig := &tls.Config{InsecureSkipVerify: !cfg.TlsVerify}
  75. if cfg.TlsCaFile != "" {
  76. caCert, err := os.ReadFile(cfg.TlsCaFile)
  77. if err != nil {
  78. return nil, errors.Join(ErrFileReadFailed, err)
  79. }
  80. caCertPool := x509.NewCertPool()
  81. if !caCertPool.AppendCertsFromPEM(caCert) {
  82. return nil, errors.Join(ErrLdapTlsFailed, errors.New("failed to append CA certificate"))
  83. }
  84. tlsConfig.RootCAs = caCertPool
  85. }
  86. conn, err = ldap.DialURL(cfg.Url, ldap.DialWithTLSConfig(tlsConfig))
  87. } else {
  88. conn, err = ldap.DialURL(cfg.Url)
  89. }
  90. if err != nil {
  91. return nil, errors.Join(ErrLdapConnectFailed, err)
  92. }
  93. // Bind as the "service" user
  94. if err = conn.Bind(username, password); err != nil {
  95. fmt.Println("Bind failed")
  96. conn.Close()
  97. return nil, errors.Join(ErrLdapBindService, err)
  98. }
  99. return conn, nil
  100. }
  101. // connectAndBindAdmin creates an LDAP connection, optionally starts TLS, and then binds using the admin credentials.
  102. func (ls *LdapService) connectAndBindAdmin(cfg *config.Ldap) (*ldap.Conn, error) {
  103. return ls.connectAndBind(cfg, cfg.BindDn, cfg.BindPassword)
  104. }
  105. // verifyCredentials checks the provided username and password against LDAP.
  106. func (ls *LdapService) verifyCredentials(cfg *config.Ldap, username, password string) error {
  107. ldapConn, err := ls.connectAndBind(cfg, username, password)
  108. if err != nil {
  109. return ErrLdapPasswordNotMatch
  110. }
  111. defer ldapConn.Close()
  112. return nil
  113. }
  114. // Authenticate checks the provided username and password against LDAP.
  115. // Returns the corresponding *model.User if successful, or an error if not.
  116. func (ls *LdapService) Authenticate(username, password string) (*model.User, error) {
  117. ldapUser, err := ls.GetUserInfoByUsernameLdap(username)
  118. if err != nil {
  119. return nil, err
  120. }
  121. if !ldapUser.Enabled {
  122. return nil, ErrLdapUserDisabled
  123. }
  124. cfg := &Config.Ldap
  125. err = ls.verifyCredentials(cfg, ldapUser.Dn, password)
  126. if err != nil {
  127. return nil, err
  128. }
  129. user, err := ls.mapToLocalUser(cfg, ldapUser)
  130. if err != nil {
  131. return nil, errors.Join(ErrLdapToLocalUserFailed, err)
  132. }
  133. return user, nil
  134. }
  135. // mapToLocalUser checks whether the user exists locally; if not, creates one.
  136. // If the user exists and Ldap.Sync is enabled, it updates local info.
  137. func (ls *LdapService) mapToLocalUser(cfg *config.Ldap, lu *LdapUser) (*model.User, error) {
  138. userService := &UserService{}
  139. localUser := userService.InfoByUsername(lu.Username)
  140. isAdmin := ls.isUserAdmin(cfg, lu)
  141. // If the user doesn't exist in local DB, create a new one
  142. if localUser.Id == 0 {
  143. newUser := lu.ToUser(nil)
  144. // Typically, you don’t store LDAP user passwords locally.
  145. // If needed, you can set a random password here.
  146. newUser.IsAdmin = &isAdmin
  147. newUser.GroupId = 1
  148. if err := DB.Create(newUser).Error; err != nil {
  149. return nil, errors.Join(ErrLdapCreateUserFailed, err)
  150. }
  151. return userService.InfoByUsername(lu.Username), nil
  152. }
  153. // If the user already exists and sync is enabled, update local info
  154. if cfg.User.Sync {
  155. originalEmail := localUser.Email
  156. originalNickname := localUser.Nickname
  157. originalIsAdmin := localUser.IsAdmin
  158. originalStatus := localUser.Status
  159. lu.ToUser(localUser) // merges LDAP data into the existing user
  160. localUser.IsAdmin = &isAdmin
  161. if err := userService.Update(localUser); err != nil {
  162. // If the update fails, revert to original data
  163. localUser.Email = originalEmail
  164. localUser.Nickname = originalNickname
  165. localUser.IsAdmin = originalIsAdmin
  166. localUser.Status = originalStatus
  167. }
  168. }
  169. return localUser, nil
  170. }
  171. // IsUsernameExists checks if a username exists in LDAP (can be useful for local registration checks).
  172. func (ls *LdapService) IsUsernameExists(username string) bool {
  173. cfg := &Config.Ldap
  174. if !cfg.Enable {
  175. return false
  176. }
  177. sr, err := ls.usernameSearchResult(cfg, username)
  178. if err != nil {
  179. return false
  180. }
  181. return len(sr.Entries) > 0
  182. }
  183. // IsEmailExists checks if an email exists in LDAP (can be useful for local registration checks).
  184. func (ls *LdapService) IsEmailExists(email string) bool {
  185. cfg := &Config.Ldap
  186. if !cfg.Enable {
  187. return false
  188. }
  189. sr, err := ls.emailSearchResult(cfg, email)
  190. if err != nil {
  191. return false
  192. }
  193. return len(sr.Entries) > 0
  194. }
  195. // GetUserInfoByUsernameLdap returns the user info from LDAP for the given username.
  196. func (ls *LdapService) GetUserInfoByUsernameLdap(username string) (*LdapUser, error) {
  197. cfg := &Config.Ldap
  198. if !cfg.Enable {
  199. return nil, ErrLdapNotEnabled
  200. }
  201. sr, err := ls.usernameSearchResult(cfg, username)
  202. if err != nil {
  203. return nil, errors.Join(ErrLdapSearchFailed, err)
  204. }
  205. if len(sr.Entries) != 1 {
  206. return nil, ErrLdapUserNotFound
  207. }
  208. return ls.userResultToLdapUser(cfg, sr.Entries[0]), nil
  209. }
  210. // GetUserInfoByUsernameLocal returns the user info from LDAP for the given username. If the user exists, it will sync the user info to the local database.
  211. func (ls *LdapService) GetUserInfoByUsernameLocal(username string) (*model.User, error) {
  212. ldapUser, err := ls.GetUserInfoByUsernameLdap(username)
  213. if err != nil {
  214. return &model.User{}, err
  215. }
  216. return ls.mapToLocalUser(&Config.Ldap, ldapUser)
  217. }
  218. // GetUserInfoByEmailLdap returns the user info from LDAP for the given email.
  219. func (ls *LdapService) GetUserInfoByEmailLdap(email string) (*LdapUser, error) {
  220. cfg := &Config.Ldap
  221. if !cfg.Enable {
  222. return nil, ErrLdapNotEnabled
  223. }
  224. sr, err := ls.emailSearchResult(cfg, email)
  225. if err != nil {
  226. return nil, errors.Join(ErrLdapSearchFailed, err)
  227. }
  228. if len(sr.Entries) != 1 {
  229. return nil, ErrLdapUserNotFound
  230. }
  231. return ls.userResultToLdapUser(cfg, sr.Entries[0]), nil
  232. }
  233. // GetUserInfoByEmailLocal returns the user info from LDAP for the given email. if the user exists, it will synchronize the user information to local database.
  234. func (ls *LdapService) GetUserInfoByEmailLocal(email string) (*model.User, error) {
  235. ldapUser, err := ls.GetUserInfoByEmailLdap(email)
  236. if err != nil {
  237. return &model.User{}, err
  238. }
  239. return ls.mapToLocalUser(&Config.Ldap, ldapUser)
  240. }
  241. // usernameSearchResult returns the search result for the given username.
  242. func (ls *LdapService) usernameSearchResult(cfg *config.Ldap, username string) (*ldap.SearchResult, error) {
  243. // Build the combined filter for the username
  244. filter := ls.filterField(ls.fieldUsername(cfg), username)
  245. // Create the *ldap.SearchRequest
  246. searchRequest := ls.buildUserSearchRequest(cfg, filter)
  247. return ls.searchResult(cfg, searchRequest)
  248. }
  249. // emailSearchResult returns the search result for the given email.
  250. func (ls *LdapService) emailSearchResult(cfg *config.Ldap, email string) (*ldap.SearchResult, error) {
  251. filter := ls.filterField(ls.fieldEmail(cfg), email)
  252. searchRequest := ls.buildUserSearchRequest(cfg, filter)
  253. return ls.searchResult(cfg, searchRequest)
  254. }
  255. func (ls *LdapService) searchResult(cfg *config.Ldap, searchRequest *ldap.SearchRequest) (*ldap.SearchResult, error) {
  256. ldapConn, err := ls.connectAndBindAdmin(cfg)
  257. if err != nil {
  258. return nil, err
  259. }
  260. defer ldapConn.Close()
  261. return ldapConn.Search(searchRequest)
  262. }
  263. // buildUserSearchRequest constructs an LDAP SearchRequest for users given a filter.
  264. func (ls *LdapService) buildUserSearchRequest(cfg *config.Ldap, filter string) *ldap.SearchRequest {
  265. baseDn := ls.baseDnUser(cfg) // user-specific base DN, or fallback
  266. filterConfig := cfg.User.Filter
  267. if filterConfig == "" {
  268. filterConfig = "(cn=*)"
  269. }
  270. // Combine the default filter with our field filter, e.g. (&(cn=*)(uid=jdoe))
  271. combinedFilter := fmt.Sprintf("(&%s%s)", filterConfig, filter)
  272. attributes := ls.buildUserAttributes(cfg)
  273. return ldap.NewSearchRequest(
  274. baseDn,
  275. ldap.ScopeWholeSubtree,
  276. ldap.NeverDerefAliases,
  277. 0, // unlimited search results
  278. 0, // no server-side time limit
  279. false, // typesOnly
  280. combinedFilter,
  281. attributes,
  282. nil,
  283. )
  284. }
  285. // buildUserAttributes returns the list of attributes we want from LDAP user searches.
  286. func (ls *LdapService) buildUserAttributes(cfg *config.Ldap) []string {
  287. return []string{
  288. "dn",
  289. ls.fieldUsername(cfg),
  290. ls.fieldEmail(cfg),
  291. ls.fieldFirstName(cfg),
  292. ls.fieldLastName(cfg),
  293. ls.fieldMemberOf(),
  294. ls.fieldUserEnableAttr(cfg),
  295. }
  296. }
  297. // userResultToLdapUser maps an *ldap.Entry to our LdapUser struct.
  298. func (ls *LdapService) userResultToLdapUser(cfg *config.Ldap, entry *ldap.Entry) *LdapUser {
  299. lu := &LdapUser{
  300. Dn: entry.DN,
  301. Username: entry.GetAttributeValue(ls.fieldUsername(cfg)),
  302. Email: entry.GetAttributeValue(ls.fieldEmail(cfg)),
  303. FirstName: entry.GetAttributeValue(ls.fieldFirstName(cfg)),
  304. LastName: entry.GetAttributeValue(ls.fieldLastName(cfg)),
  305. MemberOf: entry.GetAttributeValues(ls.fieldMemberOf()),
  306. EnableAttrValue: entry.GetAttributeValue(ls.fieldUserEnableAttr(cfg)),
  307. }
  308. // Check if the user is enabled based on the LDAP configuration
  309. ls.isUserEnabled(cfg, lu)
  310. return lu
  311. }
  312. // filterField helps build simple attribute filters, e.g. (uid=username).
  313. func (ls *LdapService) filterField(field, value string) string {
  314. return fmt.Sprintf("(%s=%s)", field, value)
  315. }
  316. // fieldUsername returns the configured username attribute or "uid" if not set.
  317. func (ls *LdapService) fieldUsername(cfg *config.Ldap) string {
  318. if cfg.User.Username == "" {
  319. return "uid"
  320. }
  321. return cfg.User.Username
  322. }
  323. // fieldEmail returns the configured email attribute or "mail" if not set.
  324. func (ls *LdapService) fieldEmail(cfg *config.Ldap) string {
  325. if cfg.User.Email == "" {
  326. return "mail"
  327. }
  328. return cfg.User.Email
  329. }
  330. // fieldFirstName returns the configured first name attribute or "givenName" if not set.
  331. func (ls *LdapService) fieldFirstName(cfg *config.Ldap) string {
  332. if cfg.User.FirstName == "" {
  333. return "givenName"
  334. }
  335. return cfg.User.FirstName
  336. }
  337. // fieldLastName returns the configured last name attribute or "sn" if not set.
  338. func (ls *LdapService) fieldLastName(cfg *config.Ldap) string {
  339. if cfg.User.LastName == "" {
  340. return "sn"
  341. }
  342. return cfg.User.LastName
  343. }
  344. func (ls *LdapService) fieldMemberOf() string {
  345. return "memberOf"
  346. }
  347. func (ls *LdapService) fieldUserEnableAttr(cfg *config.Ldap) string {
  348. if cfg.User.EnableAttr == "" {
  349. return "userAccountControl"
  350. }
  351. return cfg.User.EnableAttr
  352. }
  353. // baseDnUser returns the user-specific base DN or the global base DN if none is set.
  354. func (ls *LdapService) baseDnUser(cfg *config.Ldap) string {
  355. if cfg.User.BaseDn == "" {
  356. return cfg.BaseDn
  357. }
  358. return cfg.User.BaseDn
  359. }
  360. // isUserAdmin checks if the user is a member of the admin group.
  361. func (ls *LdapService) isUserAdmin(cfg *config.Ldap, ldapUser *LdapUser) bool {
  362. // Check if the admin group is configured
  363. adminGroup := cfg.User.AdminGroup
  364. if adminGroup == "" {
  365. return false
  366. }
  367. // Check "memberOf" directly
  368. if len(ldapUser.MemberOf) > 0 {
  369. for _, group := range ldapUser.MemberOf {
  370. if strings.EqualFold(group, adminGroup) {
  371. return true
  372. }
  373. }
  374. return false
  375. }
  376. // For "member" attribute, perform a reverse search on the group
  377. member := "member"
  378. userDN := ldap.EscapeFilter(ldapUser.Dn)
  379. adminGroupDn := ldap.EscapeFilter(adminGroup)
  380. groupFilter := fmt.Sprintf("(%s=%s)", member, userDN)
  381. // Create the LDAP search request
  382. groupSearchRequest := ldap.NewSearchRequest(
  383. adminGroupDn,
  384. ldap.ScopeWholeSubtree,
  385. ldap.NeverDerefAliases,
  386. 0, // Unlimited search results
  387. 0, // No time limit
  388. false, // Return both attributes and DN
  389. groupFilter,
  390. []string{"dn"},
  391. nil,
  392. )
  393. // Perform the group search
  394. groupResult, err := ls.searchResult(cfg, groupSearchRequest)
  395. if err != nil {
  396. return false
  397. }
  398. // If any results are returned, the user is part of the admin group
  399. if len(groupResult.Entries) > 0 {
  400. return true
  401. }
  402. return false
  403. }
  404. // isUserEnabled checks if the user is enabled based on the LDAP configuration.
  405. // If no enable attribute or value is set, all users are considered enabled by default.
  406. func (ls *LdapService) isUserEnabled(cfg *config.Ldap, ldapUser *LdapUser) bool {
  407. // Retrieve the enable attribute and expected value from the configuration
  408. enableAttr := cfg.User.EnableAttr
  409. enableAttrValue := cfg.User.EnableAttrValue
  410. // If no enable attribute or value is configured, consider all users as enabled
  411. if enableAttr == "" || enableAttrValue == "" {
  412. ldapUser.Enabled = true
  413. return true
  414. }
  415. // Normalize the enable attribute for comparison
  416. enableAttr = strings.ToLower(enableAttr)
  417. // Handle Active Directory's userAccountControl attribute
  418. if enableAttr == "useraccountcontrol" {
  419. // Parse the userAccountControl value
  420. userAccountControl, err := strconv.Atoi(ldapUser.EnableAttrValue)
  421. if err != nil {
  422. fmt.Printf("[ERROR] Invalid userAccountControl value: %v\n", err)
  423. ldapUser.Enabled = false
  424. return false
  425. }
  426. // Account is disabled if the ACCOUNTDISABLE flag (0x2) is set
  427. const ACCOUNTDISABLE = 0x2
  428. ldapUser.Enabled = userAccountControl&ACCOUNTDISABLE == 0
  429. return ldapUser.Enabled
  430. }
  431. // For other attributes, perform a direct comparison with the expected value
  432. ldapUser.Enabled = ldapUser.EnableAttrValue == enableAttrValue
  433. return ldapUser.Enabled
  434. }
  435. // getAttrOfDn retrieves the value of an attribute for a given DN.
  436. func (ls *LdapService) getAttrOfDn(cfg *config.Ldap, dn, attr string) string {
  437. searchRequest := ldap.NewSearchRequest(
  438. ldap.EscapeFilter(dn),
  439. ldap.ScopeBaseObject,
  440. ldap.NeverDerefAliases,
  441. 0, // unlimited search results
  442. 0, // no server-side time limit
  443. false, // typesOnly
  444. "(objectClass=*)",
  445. []string{attr},
  446. nil,
  447. )
  448. sr, err := ls.searchResult(cfg, searchRequest)
  449. if err != nil {
  450. return ""
  451. }
  452. if len(sr.Entries) == 0 {
  453. return ""
  454. }
  455. return sr.Entries[0].GetAttributeValue(attr)
  456. }