security.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. netRoles := user.NetworkRoles[models.NetworkID(netID)]
  48. for netRoleID := range netRoles {
  49. networkPermissionScope, err := GetRole(netRoleID)
  50. if err != nil {
  51. continue
  52. }
  53. if networkPermissionScope.FullAccess {
  54. return nil
  55. }
  56. rsrcPermissionScope, ok := networkPermissionScope.NetworkLevelAccess[models.RsrcType(targetRsrc)]
  57. if !ok {
  58. continue
  59. }
  60. if allRsrcsTypePermissionScope, ok := rsrcPermissionScope[models.RsrcID(fmt.Sprintf("all_%s", targetRsrc))]; ok {
  61. err = checkPermissionScopeWithReqMethod(allRsrcsTypePermissionScope, r.Method)
  62. if err == nil {
  63. return nil
  64. }
  65. }
  66. if targetRsrcID == "" {
  67. continue
  68. }
  69. if scope, ok := rsrcPermissionScope[models.RsrcID(targetRsrcID)]; ok {
  70. err = checkPermissionScopeWithReqMethod(scope, r.Method)
  71. if err == nil {
  72. return nil
  73. }
  74. }
  75. }
  76. return errors.New("access denied")
  77. }
  78. func globalPermissionsCheck(username string, r *http.Request) error {
  79. user, err := GetUser(username)
  80. if err != nil {
  81. return err
  82. }
  83. userRole, err := GetRole(user.PlatformRoleID)
  84. if err != nil {
  85. return errors.New("access denied")
  86. }
  87. if userRole.FullAccess {
  88. return nil
  89. }
  90. targetRsrc := r.Header.Get("TARGET_RSRC")
  91. targetRsrcID := r.Header.Get("TARGET_RSRC_ID")
  92. if targetRsrc == "" {
  93. return errors.New("target rsrc is missing")
  94. }
  95. if r.Method == "" {
  96. r.Method = http.MethodGet
  97. }
  98. rsrcPermissionScope, ok := userRole.GlobalLevelAccess[models.RsrcType(targetRsrc)]
  99. if !ok {
  100. return fmt.Errorf("access denied to %s rsrc", targetRsrc)
  101. }
  102. if allRsrcsTypePermissionScope, ok := rsrcPermissionScope[models.RsrcID(fmt.Sprintf("all_%s", targetRsrc))]; ok {
  103. return checkPermissionScopeWithReqMethod(allRsrcsTypePermissionScope, r.Method)
  104. }
  105. if targetRsrcID == "" {
  106. return errors.New("target rsrc id is missing")
  107. }
  108. if scope, ok := rsrcPermissionScope[models.RsrcID(targetRsrcID)]; ok {
  109. return checkPermissionScopeWithReqMethod(scope, r.Method)
  110. }
  111. return errors.New("access denied")
  112. }
  113. func checkPermissionScopeWithReqMethod(scope models.RsrcPermissionScope, reqmethod string) error {
  114. if reqmethod == http.MethodGet && scope.Read {
  115. return nil
  116. }
  117. if (reqmethod == http.MethodPatch || reqmethod == http.MethodPut) && scope.Update {
  118. return nil
  119. }
  120. if reqmethod == http.MethodDelete && scope.Delete {
  121. return nil
  122. }
  123. if reqmethod == http.MethodPost && scope.Create {
  124. return nil
  125. }
  126. return errors.New("operation not permitted")
  127. }
  128. // SecurityCheck - Check if user has appropriate permissions
  129. func SecurityCheck(reqAdmin bool, next http.Handler) http.HandlerFunc {
  130. return func(w http.ResponseWriter, r *http.Request) {
  131. r.Header.Set("ismaster", "no")
  132. bearerToken := r.Header.Get("Authorization")
  133. isGlobalAccesss := r.Header.Get("IS_GLOBAL_ACCESS") == "yes"
  134. username, err := GetUserNameFromToken(bearerToken)
  135. if err != nil {
  136. ReturnErrorResponse(w, r, FormatError(err, err.Error()))
  137. return
  138. }
  139. // detect masteradmin
  140. if username == MasterUser {
  141. r.Header.Set("ismaster", "yes")
  142. } else {
  143. if isGlobalAccesss {
  144. err = globalPermissionsCheck(username, r)
  145. } else {
  146. err = networkPermissionsCheck(username, r)
  147. }
  148. }
  149. w.Header().Set("TARGET_RSRC", r.Header.Get("TARGET_RSRC"))
  150. w.Header().Set("TARGET_RSRC_ID", r.Header.Get("TARGET_RSRC_ID"))
  151. w.Header().Set("RSRC_TYPE", r.Header.Get("RSRC_TYPE"))
  152. w.Header().Set("IS_GLOBAL_ACCESS", r.Header.Get("IS_GLOBAL_ACCESS"))
  153. if err != nil {
  154. w.Header().Set("ACCESS_PERM", err.Error())
  155. ReturnErrorResponse(w, r, FormatError(err, "forbidden"))
  156. return
  157. }
  158. r.Header.Set("user", username)
  159. next.ServeHTTP(w, r)
  160. }
  161. }
  162. // UserPermissions - checks token stuff
  163. func UserPermissions(reqAdmin bool, token string) (string, error) {
  164. var tokenSplit = strings.Split(token, " ")
  165. var authToken = ""
  166. if len(tokenSplit) < 2 {
  167. return "", Unauthorized_Err
  168. } else {
  169. authToken = tokenSplit[1]
  170. }
  171. //all endpoints here require master so not as complicated
  172. if authenticateMaster(authToken) {
  173. // TODO log in as an actual admin user
  174. return MasterUser, nil
  175. }
  176. username, issuperadmin, isadmin, err := VerifyUserToken(authToken)
  177. if err != nil {
  178. return username, Unauthorized_Err
  179. }
  180. if reqAdmin && !(issuperadmin || isadmin) {
  181. return username, Forbidden_Err
  182. }
  183. return username, nil
  184. }
  185. // Consider a more secure way of setting master key
  186. func authenticateMaster(tokenString string) bool {
  187. return tokenString == servercfg.GetMasterKey() && servercfg.GetMasterKey() != ""
  188. }
  189. func ContinueIfUserMatch(next http.Handler) http.HandlerFunc {
  190. return func(w http.ResponseWriter, r *http.Request) {
  191. var errorResponse = models.ErrorResponse{
  192. Code: http.StatusForbidden, Message: Forbidden_Msg,
  193. }
  194. var params = mux.Vars(r)
  195. var requestedUser = params["username"]
  196. if requestedUser != r.Header.Get("user") {
  197. ReturnErrorResponse(w, r, errorResponse)
  198. return
  199. }
  200. next.ServeHTTP(w, r)
  201. }
  202. }