client_security.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. // Copyright 2015 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package etcdhttp
  15. import (
  16. "encoding/json"
  17. "log"
  18. "net/http"
  19. "path"
  20. "strings"
  21. "github.com/coreos/etcd/etcdserver"
  22. "github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
  23. "github.com/coreos/etcd/etcdserver/security"
  24. "github.com/coreos/etcd/pkg/netutil"
  25. )
  26. type securityHandler struct {
  27. sec *security.Store
  28. clusterInfo etcdserver.ClusterInfo
  29. }
  30. func hasWriteRootAccess(sec *security.Store, r *http.Request) bool {
  31. if r.Method == "GET" || r.Method == "HEAD" {
  32. return true
  33. }
  34. return hasRootAccess(sec, r)
  35. }
  36. func hasRootAccess(sec *security.Store, r *http.Request) bool {
  37. if sec == nil {
  38. // No store means no security available, eg, tests.
  39. return true
  40. }
  41. if !sec.SecurityEnabled() {
  42. return true
  43. }
  44. username, password, ok := netutil.BasicAuth(r)
  45. if !ok {
  46. return false
  47. }
  48. rootUser, err := sec.GetUser(username)
  49. if err != nil {
  50. return false
  51. }
  52. ok = rootUser.CheckPassword(password)
  53. if !ok {
  54. log.Printf("security: Wrong password for user %s", username)
  55. return false
  56. }
  57. for _, role := range rootUser.Roles {
  58. if role == security.RootRoleName {
  59. return true
  60. }
  61. }
  62. log.Printf("security: User %s does not have the %s role for resource %s.", username, security.RootRoleName, r.URL.Path)
  63. return false
  64. }
  65. func hasKeyPrefixAccess(sec *security.Store, r *http.Request, key string, recursive bool) bool {
  66. if sec == nil {
  67. // No store means no security available, eg, tests.
  68. return true
  69. }
  70. if !sec.SecurityEnabled() {
  71. return true
  72. }
  73. username, password, ok := netutil.BasicAuth(r)
  74. if !ok {
  75. return hasGuestAccess(sec, r, key)
  76. }
  77. user, err := sec.GetUser(username)
  78. if err != nil {
  79. log.Printf("security: No such user: %s.", username)
  80. return false
  81. }
  82. authAsUser := user.CheckPassword(password)
  83. if !authAsUser {
  84. log.Printf("security: Incorrect password for user: %s.", username)
  85. return false
  86. }
  87. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  88. for _, roleName := range user.Roles {
  89. role, err := sec.GetRole(roleName)
  90. if err != nil {
  91. continue
  92. }
  93. if recursive {
  94. return role.HasRecursiveAccess(key, writeAccess)
  95. }
  96. return role.HasKeyAccess(key, writeAccess)
  97. }
  98. log.Printf("security: Invalid access for user %s on key %s.", username, key)
  99. return false
  100. }
  101. func hasGuestAccess(sec *security.Store, r *http.Request, key string) bool {
  102. writeAccess := r.Method != "GET" && r.Method != "HEAD"
  103. role, err := sec.GetRole(security.GuestRoleName)
  104. if err != nil {
  105. return false
  106. }
  107. if role.HasKeyAccess(key, writeAccess) {
  108. return true
  109. }
  110. log.Printf("security: Invalid access for unauthenticated user on resource %s.", key)
  111. return false
  112. }
  113. func writeNoAuth(w http.ResponseWriter) {
  114. herr := httptypes.NewHTTPError(http.StatusUnauthorized, "Insufficient credentials")
  115. herr.WriteTo(w)
  116. }
  117. func handleSecurity(mux *http.ServeMux, sh *securityHandler) {
  118. mux.HandleFunc(securityPrefix+"/roles", sh.baseRoles)
  119. mux.HandleFunc(securityPrefix+"/roles/", sh.handleRoles)
  120. mux.HandleFunc(securityPrefix+"/users", sh.baseUsers)
  121. mux.HandleFunc(securityPrefix+"/users/", sh.handleUsers)
  122. mux.HandleFunc(securityPrefix+"/enable", sh.enableDisable)
  123. }
  124. func (sh *securityHandler) baseRoles(w http.ResponseWriter, r *http.Request) {
  125. if !allowMethod(w, r.Method, "GET") {
  126. return
  127. }
  128. if !hasRootAccess(sh.sec, r) {
  129. writeNoAuth(w)
  130. return
  131. }
  132. w.Header().Set("X-Etcd-Cluster-ID", sh.clusterInfo.ID().String())
  133. w.Header().Set("Content-Type", "application/json")
  134. var rolesCollections struct {
  135. Roles []string `json:"roles"`
  136. }
  137. roles, err := sh.sec.AllRoles()
  138. if err != nil {
  139. writeError(w, err)
  140. return
  141. }
  142. if roles == nil {
  143. roles = make([]string, 0)
  144. }
  145. rolesCollections.Roles = roles
  146. err = json.NewEncoder(w).Encode(rolesCollections)
  147. if err != nil {
  148. log.Println("etcdhttp: baseRoles error encoding on", r.URL)
  149. }
  150. }
  151. func (sh *securityHandler) handleRoles(w http.ResponseWriter, r *http.Request) {
  152. subpath := path.Clean(r.URL.Path[len(securityPrefix):])
  153. // Split "/roles/rolename/command".
  154. // First item is an empty string, second is "roles"
  155. pieces := strings.Split(subpath, "/")
  156. if len(pieces) == 2 {
  157. sh.baseRoles(w, r)
  158. return
  159. }
  160. if len(pieces) != 3 {
  161. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  162. return
  163. }
  164. sh.forRole(w, r, pieces[2])
  165. }
  166. func (sh *securityHandler) forRole(w http.ResponseWriter, r *http.Request, role string) {
  167. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  168. return
  169. }
  170. if !hasRootAccess(sh.sec, r) {
  171. writeNoAuth(w)
  172. return
  173. }
  174. w.Header().Set("X-Etcd-Cluster-ID", sh.clusterInfo.ID().String())
  175. switch r.Method {
  176. case "GET":
  177. w.Header().Set("Content-Type", "application/json")
  178. data, err := sh.sec.GetRole(role)
  179. if err != nil {
  180. writeError(w, err)
  181. return
  182. }
  183. err = json.NewEncoder(w).Encode(data)
  184. if err != nil {
  185. log.Println("etcdhttp: forRole error encoding on", r.URL)
  186. return
  187. }
  188. return
  189. case "PUT":
  190. var in security.Role
  191. err := json.NewDecoder(r.Body).Decode(&in)
  192. if err != nil {
  193. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  194. return
  195. }
  196. if in.Role != role {
  197. writeError(w, httptypes.NewHTTPError(401, "Role JSON name does not match the name in the URL"))
  198. return
  199. }
  200. newrole, created, err := sh.sec.CreateOrUpdateRole(in)
  201. if err != nil {
  202. writeError(w, err)
  203. return
  204. }
  205. if created {
  206. w.WriteHeader(http.StatusCreated)
  207. } else {
  208. w.WriteHeader(http.StatusOK)
  209. }
  210. err = json.NewEncoder(w).Encode(newrole)
  211. if err != nil {
  212. log.Println("etcdhttp: forRole error encoding on", r.URL)
  213. return
  214. }
  215. return
  216. case "DELETE":
  217. err := sh.sec.DeleteRole(role)
  218. if err != nil {
  219. writeError(w, err)
  220. return
  221. }
  222. }
  223. }
  224. func (sh *securityHandler) baseUsers(w http.ResponseWriter, r *http.Request) {
  225. if !allowMethod(w, r.Method, "GET") {
  226. return
  227. }
  228. if !hasRootAccess(sh.sec, r) {
  229. writeNoAuth(w)
  230. return
  231. }
  232. w.Header().Set("X-Etcd-Cluster-ID", sh.clusterInfo.ID().String())
  233. w.Header().Set("Content-Type", "application/json")
  234. var usersCollections struct {
  235. Users []string `json:"users"`
  236. }
  237. users, err := sh.sec.AllUsers()
  238. if err != nil {
  239. writeError(w, err)
  240. return
  241. }
  242. if users == nil {
  243. users = make([]string, 0)
  244. }
  245. usersCollections.Users = users
  246. err = json.NewEncoder(w).Encode(usersCollections)
  247. if err != nil {
  248. log.Println("etcdhttp: baseUsers error encoding on", r.URL)
  249. }
  250. }
  251. func (sh *securityHandler) handleUsers(w http.ResponseWriter, r *http.Request) {
  252. subpath := path.Clean(r.URL.Path[len(securityPrefix):])
  253. // Split "/users/username".
  254. // First item is an empty string, second is "users"
  255. pieces := strings.Split(subpath, "/")
  256. if len(pieces) == 2 {
  257. sh.baseUsers(w, r)
  258. return
  259. }
  260. if len(pieces) != 3 {
  261. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid path"))
  262. return
  263. }
  264. sh.forUser(w, r, pieces[2])
  265. }
  266. func (sh *securityHandler) forUser(w http.ResponseWriter, r *http.Request, user string) {
  267. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  268. return
  269. }
  270. if !hasRootAccess(sh.sec, r) {
  271. writeNoAuth(w)
  272. return
  273. }
  274. w.Header().Set("X-Etcd-Cluster-ID", sh.clusterInfo.ID().String())
  275. switch r.Method {
  276. case "GET":
  277. w.Header().Set("Content-Type", "application/json")
  278. u, err := sh.sec.GetUser(user)
  279. if err != nil {
  280. writeError(w, err)
  281. return
  282. }
  283. u.Password = ""
  284. err = json.NewEncoder(w).Encode(u)
  285. if err != nil {
  286. log.Println("etcdhttp: forUser error encoding on", r.URL)
  287. return
  288. }
  289. return
  290. case "PUT":
  291. var u security.User
  292. err := json.NewDecoder(r.Body).Decode(&u)
  293. if err != nil {
  294. writeError(w, httptypes.NewHTTPError(http.StatusBadRequest, "Invalid JSON in request body."))
  295. return
  296. }
  297. if u.User != user {
  298. writeError(w, httptypes.NewHTTPError(400, "User JSON name does not match the name in the URL"))
  299. return
  300. }
  301. newuser, created, err := sh.sec.CreateOrUpdateUser(u)
  302. if err != nil {
  303. writeError(w, err)
  304. return
  305. }
  306. if u.Password == "" {
  307. newuser.Password = ""
  308. }
  309. if created {
  310. w.WriteHeader(http.StatusCreated)
  311. } else {
  312. w.WriteHeader(http.StatusOK)
  313. }
  314. err = json.NewEncoder(w).Encode(newuser)
  315. if err != nil {
  316. log.Println("etcdhttp: forUser error encoding on", r.URL)
  317. return
  318. }
  319. return
  320. case "DELETE":
  321. err := sh.sec.DeleteUser(user)
  322. if err != nil {
  323. writeError(w, err)
  324. return
  325. }
  326. }
  327. }
  328. type enabled struct {
  329. Enabled bool `json:"enabled"`
  330. }
  331. func (sh *securityHandler) enableDisable(w http.ResponseWriter, r *http.Request) {
  332. if !allowMethod(w, r.Method, "GET", "PUT", "DELETE") {
  333. return
  334. }
  335. if !hasWriteRootAccess(sh.sec, r) {
  336. writeNoAuth(w)
  337. return
  338. }
  339. w.Header().Set("X-Etcd-Cluster-ID", sh.clusterInfo.ID().String())
  340. w.Header().Set("Content-Type", "application/json")
  341. isEnabled := sh.sec.SecurityEnabled()
  342. switch r.Method {
  343. case "GET":
  344. jsonDict := enabled{isEnabled}
  345. err := json.NewEncoder(w).Encode(jsonDict)
  346. if err != nil {
  347. log.Println("etcdhttp: error encoding security state on", r.URL)
  348. }
  349. case "PUT":
  350. err := sh.sec.EnableSecurity()
  351. if err != nil {
  352. writeError(w, err)
  353. return
  354. }
  355. case "DELETE":
  356. err := sh.sec.DisableSecurity()
  357. if err != nil {
  358. writeError(w, err)
  359. return
  360. }
  361. }
  362. }