security.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package logic
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "strings"
  7. "github.com/gorilla/mux"
  8. "github.com/gravitl/netmaker/models"
  9. "github.com/gravitl/netmaker/servercfg"
  10. )
  11. const (
  12. MasterUser = "masteradministrator"
  13. Forbidden_Msg = "forbidden"
  14. Forbidden_Err = models.Error(Forbidden_Msg)
  15. Unauthorized_Msg = "unauthorized"
  16. Unauthorized_Err = models.Error(Unauthorized_Msg)
  17. )
  18. func GetSubjectsFromURL(URL string) (rsrcType models.RsrcType, rsrcID models.RsrcID) {
  19. urlSplit := strings.Split(URL, "/")
  20. rsrcType = models.RsrcType(urlSplit[1])
  21. if len(urlSplit) > 1 {
  22. rsrcID = models.RsrcID(urlSplit[2])
  23. }
  24. return
  25. }
  26. func networkPermissionsCheck(username string, r *http.Request) error {
  27. // at this point global checks should be completed
  28. user, err := GetUser(username)
  29. if err != nil {
  30. return err
  31. }
  32. // get info from header to determine the target rsrc
  33. targetRsrc := r.Header.Get("TARGET_RSRC")
  34. targetRsrcID := r.Header.Get("TARGET_RSRC_ID")
  35. netID := r.Header.Get("NET_ID")
  36. if targetRsrc == "" {
  37. return errors.New("target rsrc is missing")
  38. }
  39. if netID == "" {
  40. return errors.New("network id is missing")
  41. }
  42. if r.Method == "" {
  43. r.Method = http.MethodGet
  44. }
  45. // check if user has scope for target resource
  46. // TODO - differentitate between global scope and network scope apis
  47. networkPermissionScope, err := GetRole(user.NetworkRoles[models.NetworkID(netID)].String())
  48. if err != nil {
  49. return errors.New("access denied")
  50. }
  51. if networkPermissionScope.FullAccess {
  52. return nil
  53. }
  54. rsrcPermissionScope, ok := networkPermissionScope.NetworkLevelAccess[models.RsrcType(targetRsrc)]
  55. if !ok {
  56. return fmt.Errorf("access denied to %s rsrc", targetRsrc)
  57. }
  58. if allRsrcsTypePermissionScope, ok := rsrcPermissionScope[models.RsrcID(fmt.Sprintf("all_%s", targetRsrc))]; ok {
  59. return checkPermissionScopeWithReqMethod(allRsrcsTypePermissionScope, r.Method)
  60. }
  61. if targetRsrcID == "" {
  62. return errors.New("target rsrc is missing")
  63. }
  64. if scope, ok := rsrcPermissionScope[models.RsrcID(targetRsrcID)]; ok {
  65. return checkPermissionScopeWithReqMethod(scope, r.Method)
  66. }
  67. return errors.New("access denied")
  68. }
  69. func globalPermissionsCheck(username string, r *http.Request) error {
  70. user, err := GetUser(username)
  71. if err != nil {
  72. return err
  73. }
  74. userRole, err := GetRole(user.PlatformRoleID.String())
  75. if err != nil {
  76. return errors.New("access denied")
  77. }
  78. if userRole.FullAccess {
  79. return nil
  80. }
  81. targetRsrc := r.Header.Get("TARGET_RSRC")
  82. targetRsrcID := r.Header.Get("TARGET_RSRC_ID")
  83. if targetRsrc == "" {
  84. return errors.New("target rsrc is missing")
  85. }
  86. if r.Method == "" {
  87. r.Method = http.MethodGet
  88. }
  89. rsrcPermissionScope, ok := userRole.GlobalLevelAccess[models.RsrcType(targetRsrc)]
  90. if !ok {
  91. return fmt.Errorf("access denied to %s rsrc", targetRsrc)
  92. }
  93. if allRsrcsTypePermissionScope, ok := rsrcPermissionScope[models.RsrcID(fmt.Sprintf("all_%s", targetRsrc))]; ok {
  94. return checkPermissionScopeWithReqMethod(allRsrcsTypePermissionScope, r.Method)
  95. }
  96. if targetRsrcID == "" {
  97. return errors.New("target rsrc id is missing")
  98. }
  99. if scope, ok := rsrcPermissionScope[models.RsrcID(targetRsrcID)]; ok {
  100. return checkPermissionScopeWithReqMethod(scope, r.Method)
  101. }
  102. return errors.New("access denied")
  103. }
  104. func checkPermissionScopeWithReqMethod(scope models.RsrcPermissionScope, reqmethod string) error {
  105. if reqmethod == http.MethodGet && scope.Read {
  106. return nil
  107. }
  108. if (reqmethod == http.MethodPatch || reqmethod == http.MethodPut) && scope.Update {
  109. return nil
  110. }
  111. if reqmethod == http.MethodDelete && scope.Delete {
  112. return nil
  113. }
  114. if reqmethod == http.MethodPost && scope.Create {
  115. return nil
  116. }
  117. return errors.New("operation not permitted")
  118. }
  119. // SecurityCheck - Check if user has appropriate permissions
  120. func SecurityCheck(reqAdmin bool, next http.Handler) http.HandlerFunc {
  121. return func(w http.ResponseWriter, r *http.Request) {
  122. r.Header.Set("ismaster", "no")
  123. bearerToken := r.Header.Get("Authorization")
  124. isGlobalAccesss := r.Header.Get("IS_GLOBAL_ACCESS") == "yes"
  125. username, err := UserPermissions(reqAdmin, bearerToken)
  126. if err != nil {
  127. ReturnErrorResponse(w, r, FormatError(err, err.Error()))
  128. return
  129. }
  130. // detect masteradmin
  131. if username == MasterUser {
  132. r.Header.Set("ismaster", "yes")
  133. } else {
  134. if isGlobalAccesss {
  135. globalPermissionsCheck(username, r)
  136. } else {
  137. networkPermissionsCheck(username, r)
  138. }
  139. }
  140. r.Header.Set("user", username)
  141. next.ServeHTTP(w, r)
  142. }
  143. }
  144. // UserPermissions - checks token stuff
  145. func UserPermissions(reqAdmin bool, token string) (string, error) {
  146. var tokenSplit = strings.Split(token, " ")
  147. var authToken = ""
  148. if len(tokenSplit) < 2 {
  149. return "", Unauthorized_Err
  150. } else {
  151. authToken = tokenSplit[1]
  152. }
  153. //all endpoints here require master so not as complicated
  154. if authenticateMaster(authToken) {
  155. // TODO log in as an actual admin user
  156. return MasterUser, nil
  157. }
  158. username, issuperadmin, isadmin, err := VerifyUserToken(authToken)
  159. if err != nil {
  160. return username, Unauthorized_Err
  161. }
  162. if reqAdmin && !(issuperadmin || isadmin) {
  163. return username, Forbidden_Err
  164. }
  165. return username, nil
  166. }
  167. // Consider a more secure way of setting master key
  168. func authenticateMaster(tokenString string) bool {
  169. return tokenString == servercfg.GetMasterKey() && servercfg.GetMasterKey() != ""
  170. }
  171. func ContinueIfUserMatch(next http.Handler) http.HandlerFunc {
  172. return func(w http.ResponseWriter, r *http.Request) {
  173. var errorResponse = models.ErrorResponse{
  174. Code: http.StatusForbidden, Message: Forbidden_Msg,
  175. }
  176. var params = mux.Vars(r)
  177. var requestedUser = params["username"]
  178. if requestedUser != r.Header.Get("user") {
  179. ReturnErrorResponse(w, r, errorResponse)
  180. return
  181. }
  182. next.ServeHTTP(w, r)
  183. }
  184. }