security.go 6.7 KB

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