ldap.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. log.Println("EXCEC")
  212. userList, err := ldap.getAllUser(10)
  213. log.Println(userList)
  214. if err != nil {
  215. empty, err := json.Marshal(syncorizeUserReturnInterface{})
  216. if err != nil {
  217. common.SendErrorResponse(w, "Error while marshalling information")
  218. return
  219. }
  220. common.SendJSONResponse(w, string(empty))
  221. return
  222. }
  223. returnJSON := syncorizeUserReturnInterface{Userinfo: userList, Length: len(userList), Error: ""}
  224. accountJSON, err := json.Marshal(returnJSON)
  225. if err != nil {
  226. empty, err := json.Marshal(syncorizeUserReturnInterface{})
  227. if err != nil {
  228. common.SendErrorResponse(w, "Error while marshalling information")
  229. return
  230. }
  231. common.SendJSONResponse(w, string(empty))
  232. return
  233. }
  234. common.SendJSONResponse(w, string(accountJSON))
  235. }
  236. func (ldap *ldapHandler) checkCurrUserAdmin(w http.ResponseWriter, r *http.Request) bool {
  237. //check current user is admin and new update will remove it or not
  238. currentLoggedInUser, err := ldap.userHandler.GetUserInfoFromRequest(w, r)
  239. if err != nil {
  240. common.SendErrorResponse(w, "Error while getting user info")
  241. return false
  242. }
  243. ldapCurrUserInfo, err := ldap.ldapreader.GetUser(currentLoggedInUser.Username)
  244. if err != nil {
  245. common.SendErrorResponse(w, "Error while getting user info from LDAP")
  246. return false
  247. }
  248. isAdmin := false
  249. //get the croups out from LDAP group list
  250. regexSyntax := regexp.MustCompile("cn=([^,]+),")
  251. for _, v := range ldapCurrUserInfo.GetAttributeValues("memberOf") {
  252. //loop through all memberOf's array
  253. groups := regexSyntax.FindStringSubmatch(v)
  254. //if after regex there is still groups exists
  255. if len(groups) > 0 {
  256. //check if the LDAP group is already exists in ArOZOS system
  257. if ldap.permissionHandler.GroupExists(groups[1]) {
  258. if ldap.permissionHandler.GetPermissionGroupByName(groups[1]).IsAdmin {
  259. isAdmin = true
  260. }
  261. }
  262. }
  263. }
  264. return isAdmin
  265. }
  266. func (ldap *ldapHandler) SynchronizeUser(w http.ResponseWriter, r *http.Request) {
  267. //check if suer is admin before executing the command
  268. //if user is admin then check if user will lost him/her's admin access
  269. consistencyCheck := ldap.checkCurrUserAdmin(w, r)
  270. if !consistencyCheck {
  271. common.SendErrorResponse(w, "You will no longer become the admin after synchronizing, synchronize terminated")
  272. return
  273. }
  274. ldapUsersList, err := ldap.getAllUser(-1)
  275. if err != nil {
  276. common.SendErrorResponse(w, err.Error())
  277. }
  278. for _, ldapUser := range ldapUsersList {
  279. //check if user exist in system
  280. if ldap.ag.UserExists(ldapUser.Username) {
  281. //if exists, then check if the user group is the same with ldap's setting
  282. //Get the permission groups by their ids
  283. userinfo, err := ldap.userHandler.GetUserInfoFromUsername(ldapUser.Username)
  284. if err != nil {
  285. common.SendErrorResponse(w, "Error while getting user info")
  286. return
  287. }
  288. newPermissionGroups := ldap.permissionHandler.GetPermissionGroupByNameList(ldapUser.EquivGroup)
  289. //Set the user's permission to these groups
  290. userinfo.SetUserPermissionGroup(newPermissionGroups)
  291. }
  292. }
  293. common.SendOK(w)
  294. }
  295. //LOGIN related function
  296. //functions basically same as arozos's original function
  297. func (ldap *ldapHandler) HandleLoginPage(w http.ResponseWriter, r *http.Request) {
  298. //load the template from file and inject necessary variables
  299. red, _ := common.Mv(r, "redirect", false)
  300. //Append the redirection addr into the template
  301. imgsrc := "./web/" + ldap.iconSystem
  302. if !common.FileExists(imgsrc) {
  303. imgsrc = "./web/img/public/auth_icon.png"
  304. }
  305. imageBase64, _ := common.LoadImageAsBase64(imgsrc)
  306. parsedPage, err := common.Templateload("web/login.system", map[string]interface{}{
  307. "redirection_addr": red,
  308. "usercount": strconv.Itoa(ldap.ag.GetUserCounts()),
  309. "service_logo": imageBase64,
  310. "login_addr": "system/auth/ldap/login",
  311. })
  312. if err != nil {
  313. panic("Error. Unable to parse login page. Is web directory data exists?")
  314. }
  315. w.Header().Add("Content-Type", "text/html; charset=UTF-8")
  316. w.Write([]byte(parsedPage))
  317. }
  318. func (ldap *ldapHandler) HandleNewPasswordPage(w http.ResponseWriter, r *http.Request) {
  319. //get the parameter from the request
  320. acc, err := common.Mv(r, "username", false)
  321. if err != nil {
  322. common.SendErrorResponse(w, err.Error())
  323. return
  324. }
  325. displayname, err := common.Mv(r, "displayname", false)
  326. if err != nil {
  327. common.SendErrorResponse(w, err.Error())
  328. return
  329. }
  330. key, err := common.Mv(r, "authkey", false)
  331. if err != nil {
  332. common.SendErrorResponse(w, err.Error())
  333. return
  334. }
  335. //init the web interface
  336. imgsrc := "./web/" + ldap.iconSystem
  337. if !common.FileExists(imgsrc) {
  338. imgsrc = "./web/img/public/auth_icon.png"
  339. }
  340. imageBase64, _ := common.LoadImageAsBase64(imgsrc)
  341. template, err := common.Templateload("system/ldap/newPasswordTemplate.html", map[string]interface{}{
  342. "vendor_logo": imageBase64,
  343. "username": acc,
  344. "display_name": displayname,
  345. "key": key,
  346. })
  347. if err != nil {
  348. log.Fatal(err)
  349. }
  350. w.Header().Set("Content-Type", "text/html; charset=UTF-8")
  351. w.Write([]byte(template))
  352. }
  353. func (ldap *ldapHandler) HandleLogin(w http.ResponseWriter, r *http.Request) {
  354. //Get username from request using POST mode
  355. username, err := common.Mv(r, "username", true)
  356. if err != nil {
  357. //Username not defined
  358. log.Println("[System Auth] Someone trying to login with username: " + username)
  359. //Write to log
  360. ldap.ag.Logger.LogAuth(r, false)
  361. common.SendErrorResponse(w, "Username not defined or empty.")
  362. return
  363. }
  364. //Get password from request using POST mode
  365. password, err := common.Mv(r, "password", true)
  366. if err != nil {
  367. //Password not defined
  368. ldap.ag.Logger.LogAuth(r, false)
  369. common.SendErrorResponse(w, "Password not defined or empty.")
  370. return
  371. }
  372. //Get rememberme settings
  373. rememberme := false
  374. rmbme, _ := common.Mv(r, "rmbme", true)
  375. if rmbme == "true" {
  376. rememberme = true
  377. }
  378. //Check the database and see if this user is in the database
  379. passwordCorrect, err := ldap.ldapreader.Authenticate(username, password)
  380. if err != nil {
  381. ldap.ag.Logger.LogAuth(r, false)
  382. common.SendErrorResponse(w, "Unable to connect to LDAP server")
  383. log.Println("LDAP Authentication error, " + err.Error())
  384. return
  385. }
  386. //The database contain this user information. Check its password if it is correct
  387. if passwordCorrect {
  388. //Password correct
  389. //if user not exist then redirect to create pwd screen
  390. if !ldap.ag.UserExists(username) {
  391. authkey := ldap.syncdb.Store(username)
  392. common.SendJSONResponse(w, "{\"redirect\":\"system/auth/ldap/newPassword?username="+username+"&displayname="+username+"&authkey="+authkey+"\"}")
  393. } else {
  394. // Set user as authenticated
  395. ldap.ag.LoginUserByRequest(w, r, username, rememberme)
  396. //Print the login message to console
  397. log.Println(username + " logged in.")
  398. ldap.ag.Logger.LogAuth(r, true)
  399. common.SendOK(w)
  400. }
  401. } else {
  402. //Password incorrect
  403. log.Println(username + " has entered an invalid username or password")
  404. common.SendErrorResponse(w, "Invalid username or password")
  405. ldap.ag.Logger.LogAuth(r, false)
  406. return
  407. }
  408. }
  409. func (ldap *ldapHandler) HandleSetPassword(w http.ResponseWriter, r *http.Request) {
  410. //get paramters from request
  411. username, err := common.Mv(r, "username", true)
  412. if err != nil {
  413. common.SendErrorResponse(w, err.Error())
  414. return
  415. }
  416. password, err := common.Mv(r, "password", true)
  417. if err != nil {
  418. common.SendErrorResponse(w, err.Error())
  419. return
  420. }
  421. authkey, err := common.Mv(r, "authkey", true)
  422. if err != nil {
  423. common.SendErrorResponse(w, err.Error())
  424. return
  425. }
  426. //check if the input key matches the database's username
  427. isValid := ldap.syncdb.Read(authkey) == username
  428. ldap.syncdb.Delete(authkey) // remove the key, aka key is one time use only
  429. //if db data match the username, proceed
  430. if isValid {
  431. //if not exists
  432. if !ldap.ag.UserExists(username) {
  433. //get the user from ldap server
  434. ldapUser, err := ldap.ldapreader.GetUser(username)
  435. if err != nil {
  436. common.SendErrorResponse(w, err.Error())
  437. return
  438. }
  439. //convert the ldap usergroup to arozos usergroup
  440. convertedInfo := ldap.convertGroup(ldapUser)
  441. //create user account and login
  442. ldap.ag.CreateUserAccount(username, password, convertedInfo.EquivGroup)
  443. ldap.ag.Logger.LogAuth(r, true)
  444. ldap.ag.LoginUserByRequest(w, r, username, false)
  445. http.Redirect(w, r, "index.html", 301)
  446. //common.SendOK(w)
  447. return
  448. } else {
  449. //if exist then return error
  450. common.SendErrorResponse(w, "User exists, please contact the system administrator if you believe this is an error.")
  451. return
  452. }
  453. } else {
  454. common.SendErrorResponse(w, "Improper key detected")
  455. log.Println(r.RemoteAddr + " attempted to use invaild key to create new user but failed")
  456. return
  457. }
  458. }