ldap.go 15 KB

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