security.go 7.0 KB

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