ldap.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. package ldap
  2. import (
  3. "encoding/json"
  4. "log"
  5. "net/http"
  6. "regexp"
  7. "strconv"
  8. "github.com/go-ldap/ldap"
  9. auth "imuslab.com/arozos/mod/auth"
  10. "imuslab.com/arozos/mod/auth/ldap/ldapreader"
  11. "imuslab.com/arozos/mod/auth/oauth2/syncdb"
  12. reg "imuslab.com/arozos/mod/auth/register"
  13. "imuslab.com/arozos/mod/common"
  14. db "imuslab.com/arozos/mod/database"
  15. permission "imuslab.com/arozos/mod/permission"
  16. "imuslab.com/arozos/mod/user"
  17. )
  18. type ldapHandler struct {
  19. ag *auth.AuthAgent
  20. ldapreader *ldapreader.LdapReader
  21. reg *reg.RegisterHandler
  22. coredb *db.Database
  23. permissionHandler *permission.PermissionHandler
  24. userHandler *user.UserHandler
  25. iconSystem string
  26. syncdb *syncdb.SyncDB
  27. }
  28. type Config struct {
  29. Enabled bool `json:"enabled"`
  30. AutoRedirect bool `json:"auto_redirect"`
  31. BindUsername string `json:"bind_username"`
  32. BindPassword string `json:"bind_password"`
  33. FQDN string `json:"fqdn"`
  34. BaseDN string `json:"base_dn"`
  35. }
  36. type UserAccount struct {
  37. Username string `json:"username"`
  38. Group []string `json:"group"`
  39. EquivGroup []string `json:"equiv_group"`
  40. }
  41. //syncorizeUserReturnInterface not designed to be used outside
  42. type syncorizeUserReturnInterface struct {
  43. Userinfo []UserAccount `json:"userinfo"`
  44. Length int `json:"length"`
  45. Error string `json:"error"`
  46. }
  47. //NewLdapHandler xxx
  48. func NewLdapHandler(authAgent *auth.AuthAgent, register *reg.RegisterHandler, coreDb *db.Database, permissionHandler *permission.PermissionHandler, userHandler *user.UserHandler, iconSystem string) *ldapHandler {
  49. //ldap handler init
  50. log.Println("Starting LDAP client...")
  51. err := coreDb.NewTable("ldap")
  52. if err != nil {
  53. log.Println("Failed to create LDAP database. Terminating.")
  54. panic(err)
  55. }
  56. //key value to be used for LDAP authentication
  57. BindUsername := readSingleConfig("BindUsername", coreDb)
  58. BindPassword := readSingleConfig("BindPassword", coreDb)
  59. FQDN := readSingleConfig("FQDN", coreDb)
  60. BaseDN := readSingleConfig("BaseDN", coreDb)
  61. LDAPHandler := ldapHandler{
  62. ag: authAgent,
  63. ldapreader: ldapreader.NewLDAPReader(BindUsername, BindPassword, FQDN, BaseDN),
  64. reg: register,
  65. coredb: coreDb,
  66. permissionHandler: permissionHandler,
  67. userHandler: userHandler,
  68. iconSystem: iconSystem,
  69. syncdb: syncdb.NewSyncDB(),
  70. }
  71. return &LDAPHandler
  72. }
  73. func (ldap *ldapHandler) ReadConfig(w http.ResponseWriter, r *http.Request) {
  74. //basic components
  75. enabled, err := strconv.ParseBool(ldap.readSingleConfig("enabled"))
  76. if err != nil {
  77. common.SendTextResponse(w, "Invalid config value [key=enabled].")
  78. return
  79. }
  80. autoredirect, err := strconv.ParseBool(ldap.readSingleConfig("autoredirect"))
  81. if err != nil {
  82. common.SendTextResponse(w, "Invalid config value [key=autoredirect].")
  83. return
  84. }
  85. //get the LDAP config from db
  86. BindUsername := ldap.readSingleConfig("BindUsername")
  87. BindPassword := ldap.readSingleConfig("BindPassword")
  88. FQDN := ldap.readSingleConfig("FQDN")
  89. BaseDN := ldap.readSingleConfig("BaseDN")
  90. //marshall it and return
  91. config, err := json.Marshal(Config{
  92. Enabled: enabled,
  93. AutoRedirect: autoredirect,
  94. BindUsername: BindUsername,
  95. BindPassword: BindPassword,
  96. FQDN: FQDN,
  97. BaseDN: BaseDN,
  98. })
  99. if err != nil {
  100. empty, err := json.Marshal(Config{})
  101. if err != nil {
  102. common.SendErrorResponse(w, "Error while marshalling config")
  103. }
  104. common.SendJSONResponse(w, string(empty))
  105. }
  106. common.SendJSONResponse(w, string(config))
  107. }
  108. func (ldap *ldapHandler) WriteConfig(w http.ResponseWriter, r *http.Request) {
  109. //receive the parameter
  110. enabled, err := common.Mv(r, "enabled", true)
  111. if err != nil {
  112. common.SendErrorResponse(w, "enabled field can't be empty")
  113. return
  114. }
  115. //allow empty fields if enabled is false
  116. showError := true
  117. if enabled != "true" {
  118. showError = false
  119. }
  120. //four fields to store the LDAP authentication information
  121. BindUsername, err := common.Mv(r, "bind_username", true)
  122. if err != nil {
  123. if showError {
  124. common.SendErrorResponse(w, "bind_username field can't be empty")
  125. return
  126. }
  127. }
  128. BindPassword, err := common.Mv(r, "bind_password", true)
  129. if err != nil {
  130. if showError {
  131. common.SendErrorResponse(w, "bind_password field can't be empty")
  132. return
  133. }
  134. }
  135. FQDN, err := common.Mv(r, "fqdn", true)
  136. if err != nil {
  137. if showError {
  138. common.SendErrorResponse(w, "fqdn field can't be empty")
  139. return
  140. }
  141. }
  142. BaseDN, err := common.Mv(r, "base_dn", true)
  143. if err != nil {
  144. if showError {
  145. common.SendErrorResponse(w, "base_dn field can't be empty")
  146. return
  147. }
  148. }
  149. //write the data back to db
  150. ldap.coredb.Write("ldap", "enabled", enabled)
  151. ldap.coredb.Write("ldap", "BindUsername", BindUsername)
  152. ldap.coredb.Write("ldap", "BindPassword", BindPassword)
  153. ldap.coredb.Write("ldap", "FQDN", FQDN)
  154. ldap.coredb.Write("ldap", "BaseDN", BaseDN)
  155. //update the new authencation infromation
  156. ldap.ldapreader = ldapreader.NewLDAPReader(BindUsername, BindPassword, FQDN, BaseDN)
  157. //return ok
  158. common.SendOK(w)
  159. }
  160. //@para limit: -1 means unlimited
  161. func (ldap *ldapHandler) getAllUser(limit int) ([]UserAccount, error) {
  162. //read the user account from ldap, if limit is -1 then it will read all USERS
  163. var accounts []UserAccount
  164. result, err := ldap.ldapreader.GetAllUser()
  165. if err != nil {
  166. return []UserAccount{}, err
  167. }
  168. //loop through the result
  169. for i, v := range result {
  170. account := ldap.convertGroup(v)
  171. accounts = append(accounts, account)
  172. if i > limit && limit != -1 {
  173. break
  174. }
  175. }
  176. //check if the return struct is empty, if yes then insert empty
  177. if len(accounts) > 0 {
  178. return accounts[1:], nil
  179. } else {
  180. return []UserAccount{}, nil
  181. }
  182. }
  183. func (ldap *ldapHandler) convertGroup(ldapUser *ldap.Entry) UserAccount {
  184. //check the group belongs
  185. var Group []string
  186. var EquivGroup []string
  187. regexSyntax := regexp.MustCompile("cn=([^,]+),")
  188. for _, v := range ldapUser.GetAttributeValues("memberOf") {
  189. groups := regexSyntax.FindStringSubmatch(v)
  190. if len(groups) > 0 {
  191. //check if the LDAP group is already exists in ArOZOS system
  192. if ldap.permissionHandler.GroupExists(groups[1]) {
  193. EquivGroup = append(EquivGroup, groups[1])
  194. }
  195. //LDAP list
  196. Group = append(Group, groups[1])
  197. }
  198. }
  199. if len(EquivGroup) < 1 {
  200. EquivGroup = append(EquivGroup, ldap.reg.DefaultUserGroup)
  201. }
  202. account := UserAccount{
  203. Username: ldapUser.GetAttributeValue("cn"),
  204. Group: Group,
  205. EquivGroup: EquivGroup,
  206. }
  207. return account
  208. }
  209. func (ldap *ldapHandler) TestConnection(w http.ResponseWriter, r *http.Request) {
  210. //marshall it and return the connection status
  211. userList, err := ldap.getAllUser(10)
  212. log.Println(userList, err)
  213. if err != nil {
  214. empty, err := json.Marshal(syncorizeUserReturnInterface{})
  215. if err != nil {
  216. common.SendErrorResponse(w, "Error while marshalling information")
  217. return
  218. }
  219. common.SendJSONResponse(w, string(empty))
  220. return
  221. }
  222. returnJSON := syncorizeUserReturnInterface{Userinfo: userList, Length: len(userList), Error: ""}
  223. accountJSON, err := json.Marshal(returnJSON)
  224. if err != nil {
  225. empty, err := json.Marshal(syncorizeUserReturnInterface{})
  226. if err != nil {
  227. common.SendErrorResponse(w, "Error while marshalling information")
  228. return
  229. }
  230. common.SendJSONResponse(w, string(empty))
  231. return
  232. }
  233. common.SendJSONResponse(w, string(accountJSON))
  234. }
  235. func (ldap *ldapHandler) checkCurrUserAdmin(w http.ResponseWriter, r *http.Request) bool {
  236. //check current user is admin and new update will remove it or not
  237. currentLoggedInUser, err := ldap.userHandler.GetUserInfoFromRequest(w, r)
  238. if err != nil {
  239. common.SendErrorResponse(w, "Error while getting user info")
  240. return false
  241. }
  242. ldapCurrUserInfo, err := ldap.ldapreader.GetUser(currentLoggedInUser.Username)
  243. if err != nil {
  244. common.SendErrorResponse(w, "Error while getting user info from LDAP")
  245. return false
  246. }
  247. isAdmin := false
  248. //get the croups out from LDAP group list
  249. regexSyntax := regexp.MustCompile("cn=([^,]+),")
  250. for _, v := range ldapCurrUserInfo.GetAttributeValues("memberOf") {
  251. //loop through all memberOf's array
  252. groups := regexSyntax.FindStringSubmatch(v)
  253. //if after regex there is still groups exists
  254. if len(groups) > 0 {
  255. //check if the LDAP group is already exists in ArOZOS system
  256. if ldap.permissionHandler.GroupExists(groups[1]) {
  257. if ldap.permissionHandler.GetPermissionGroupByName(groups[1]).IsAdmin {
  258. isAdmin = true
  259. }
  260. }
  261. }
  262. }
  263. return isAdmin
  264. }
  265. func (ldap *ldapHandler) SynchronizeUser(w http.ResponseWriter, r *http.Request) {
  266. //check if suer is admin before executing the command
  267. //if user is admin then check if user will lost him/her's admin access
  268. consistencyCheck := ldap.checkCurrUserAdmin(w, r)
  269. if !consistencyCheck {
  270. common.SendErrorResponse(w, "You will no longer become the admin after synchronizing, synchronize terminated")
  271. return
  272. }
  273. ldapUsersList, err := ldap.getAllUser(-1)
  274. if err != nil {
  275. common.SendErrorResponse(w, err.Error())
  276. }
  277. for _, ldapUser := range ldapUsersList {
  278. //check if user exist in system
  279. if ldap.ag.UserExists(ldapUser.Username) {
  280. //if exists, then check if the user group is the same with ldap's setting
  281. //Get the permission groups by their ids
  282. userinfo, err := ldap.userHandler.GetUserInfoFromUsername(ldapUser.Username)
  283. if err != nil {
  284. common.SendErrorResponse(w, "Error while getting user info")
  285. return
  286. }
  287. newPermissionGroups := ldap.permissionHandler.GetPermissionGroupByNameList(ldapUser.EquivGroup)
  288. //Set the user's permission to these groups
  289. userinfo.SetUserPermissionGroup(newPermissionGroups)
  290. }
  291. }
  292. common.SendOK(w)
  293. }
  294. //LOGIN related function
  295. //functions basically same as arozos's original function
  296. func (ldap *ldapHandler) HandleLoginPage(w http.ResponseWriter, r *http.Request) {
  297. //load the template from file and inject necessary variables
  298. red, _ := common.Mv(r, "redirect", false)
  299. //Append the redirection addr into the template
  300. imgsrc := "./web/" + ldap.iconSystem
  301. if !common.FileExists(imgsrc) {
  302. imgsrc = "./web/img/public/auth_icon.png"
  303. }
  304. imageBase64, _ := common.LoadImageAsBase64(imgsrc)
  305. parsedPage, err := common.Templateload("web/login.system", map[string]interface{}{
  306. "redirection_addr": red,
  307. "usercount": strconv.Itoa(ldap.ag.GetUserCounts()),
  308. "service_logo": imageBase64,
  309. "login_addr": "system/auth/ldap/login",
  310. })
  311. if err != nil {
  312. panic("Error. Unable to parse login page. Is web directory data exists?")
  313. }
  314. w.Header().Add("Content-Type", "text/html; charset=UTF-8")
  315. w.Write([]byte(parsedPage))
  316. }
  317. func (ldap *ldapHandler) HandleNewPasswordPage(w http.ResponseWriter, r *http.Request) {
  318. //get the parameter from the request
  319. acc, err := common.Mv(r, "username", false)
  320. if err != nil {
  321. common.SendErrorResponse(w, err.Error())
  322. return
  323. }
  324. displayname, err := common.Mv(r, "displayname", false)
  325. if err != nil {
  326. common.SendErrorResponse(w, err.Error())
  327. return
  328. }
  329. key, err := common.Mv(r, "authkey", false)
  330. if err != nil {
  331. common.SendErrorResponse(w, err.Error())
  332. return
  333. }
  334. //init the web interface
  335. imgsrc := "./web/" + ldap.iconSystem
  336. if !common.FileExists(imgsrc) {
  337. imgsrc = "./web/img/public/auth_icon.png"
  338. }
  339. imageBase64, _ := common.LoadImageAsBase64(imgsrc)
  340. template, err := common.Templateload("system/ldap/newPasswordTemplate.html", map[string]interface{}{
  341. "vendor_logo": imageBase64,
  342. "username": acc,
  343. "display_name": displayname,
  344. "key": key,
  345. })
  346. if err != nil {
  347. log.Fatal(err)
  348. }
  349. w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  350. w.Write([]byte(template))
  351. }
  352. func (ldap *ldapHandler) HandleLogin(w http.ResponseWriter, r *http.Request) {
  353. //Get username from request using POST mode
  354. username, err := common.Mv(r, "username", true)
  355. if err != nil {
  356. //Username not defined
  357. log.Println("[System Auth] Someone trying to login with username: " + username)
  358. //Write to log
  359. ldap.ag.Logger.LogAuth(r, false)
  360. common.SendErrorResponse(w, "Username not defined or empty.")
  361. return
  362. }
  363. //Get password from request using POST mode
  364. password, err := common.Mv(r, "password", true)
  365. if err != nil {
  366. //Password not defined
  367. ldap.ag.Logger.LogAuth(r, false)
  368. common.SendErrorResponse(w, "Password not defined or empty.")
  369. return
  370. }
  371. //Get rememberme settings
  372. rememberme := false
  373. rmbme, _ := common.Mv(r, "rmbme", true)
  374. if rmbme == "true" {
  375. rememberme = true
  376. }
  377. //Check the database and see if this user is in the database
  378. passwordCorrect, err := ldap.ldapreader.Authenticate(username, password)
  379. if err != nil {
  380. ldap.ag.Logger.LogAuth(r, false)
  381. common.SendErrorResponse(w, "Unable to connect to LDAP server")
  382. log.Println("LDAP Authentication error, " + err.Error())
  383. return
  384. }
  385. //The database contain this user information. Check its password if it is correct
  386. if passwordCorrect {
  387. //Password correct
  388. //if user not exist then redirect to create pwd screen
  389. if !ldap.ag.UserExists(username) {
  390. authkey := ldap.syncdb.Store(username)
  391. common.SendJSONResponse(w, "{\"redirect\":\"system/auth/ldap/newPassword?username="+username+"&displayname="+username+"&authkey="+authkey+"\"}")
  392. } else {
  393. // Set user as authenticated
  394. ldap.ag.LoginUserByRequest(w, r, username, rememberme)
  395. //Print the login message to console
  396. log.Println(username + " logged in.")
  397. ldap.ag.Logger.LogAuth(r, true)
  398. common.SendOK(w)
  399. }
  400. } else {
  401. //Password incorrect
  402. log.Println(username + " has entered an invalid username or password")
  403. common.SendErrorResponse(w, "Invalid username or password")
  404. ldap.ag.Logger.LogAuth(r, false)
  405. return
  406. }
  407. }
  408. func (ldap *ldapHandler) HandleSetPassword(w http.ResponseWriter, r *http.Request) {
  409. //get paramters from request
  410. username, err := common.Mv(r, "username", true)
  411. if err != nil {
  412. common.SendErrorResponse(w, err.Error())
  413. return
  414. }
  415. password, err := common.Mv(r, "password", true)
  416. if err != nil {
  417. common.SendErrorResponse(w, err.Error())
  418. return
  419. }
  420. authkey, err := common.Mv(r, "authkey", true)
  421. if err != nil {
  422. common.SendErrorResponse(w, err.Error())
  423. return
  424. }
  425. //check if the input key matches the database's username
  426. isValid := ldap.syncdb.Read(authkey) == username
  427. ldap.syncdb.Delete(authkey) // remove the key, aka key is one time use only
  428. //if db data match the username, proceed
  429. if isValid {
  430. //if not exists
  431. if !ldap.ag.UserExists(username) {
  432. //get the user from ldap server
  433. ldapUser, err := ldap.ldapreader.GetUser(username)
  434. if err != nil {
  435. common.SendErrorResponse(w, err.Error())
  436. return
  437. }
  438. //convert the ldap usergroup to arozos usergroup
  439. convertedInfo := ldap.convertGroup(ldapUser)
  440. //create user account and login
  441. ldap.ag.CreateUserAccount(username, password, convertedInfo.EquivGroup)
  442. ldap.ag.Logger.LogAuth(r, true)
  443. ldap.ag.LoginUserByRequest(w, r, username, false)
  444. http.Redirect(w, r, "index.html", 301)
  445. //common.SendOK(w)
  446. return
  447. } else {
  448. //if exist then return error
  449. common.SendErrorResponse(w, "User exists, please contact the system administrator if you believe this is an error.")
  450. return
  451. }
  452. } else {
  453. common.SendErrorResponse(w, "Improper key detected")
  454. log.Println(r.RemoteAddr + " attempted to use invaild key to create new user but failed")
  455. return
  456. }
  457. }